diff --git a/.gitattributes b/.gitattributes index b13776f5445d633e2ffcafd736b6bbdc056d4abe..36ffc453b02d3ad34ee08e5136697651d7182b93 100644 --- a/.gitattributes +++ b/.gitattributes @@ -305,3 +305,5 @@ python_embeded/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd filter=lfs dif python_embeded/Lib/site-packages/tests/data/scotland_pitie.png filter=lfs diff=lfs merge=lfs -text python_embeded/Lib/site-packages/tests/data/scotland_house.png filter=lfs diff=lfs merge=lfs -text python_embeded/Lib/site-packages/pythonwin/win32ui.pyd filter=lfs diff=lfs merge=lfs -text +python_embeded/Lib/site-packages/sklearn/.libs/msvcp140.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/Lib/site-packages/sklearn/.libs/vcomp140.dll filter=lfs diff=lfs merge=lfs -text diff --git a/python_embeded/Lib/site-packages/scipy/_lib/__init__.py b/python_embeded/Lib/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0e84889f1b1b1bde4778558a9dd88ddd9cb477 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_array_api.py b/python_embeded/Lib/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7a93e5480e8d1f59ac9c7d872b0faad9faba8560 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_array_api_no_0d.py b/python_embeded/Lib/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..2d997be2644381142b6a5d14bcaf97228b5b330a --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_bunch.py b/python_embeded/Lib/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..139e31e2ef620a43461166186f218caace4b9bfd --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_ccallback.py b/python_embeded/Lib/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e2aaea3fbdf68c8c14d786b40ce4329f9f9e2126 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..9c5fb62407c3d94ced088870fb0fdcbcd68e018a Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/_ccallback_c.cp312-win_amd64.dll.a differ diff --git a/python_embeded/Lib/site-packages/scipy/_lib/_disjoint_set.py b/python_embeded/Lib/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d4eecdecf8b2eb41230c93a246b4734779ee58 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_docscrape.py b/python_embeded/Lib/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..c8468e948e5f6e6b1ab173988e0ddd7ba9790d51 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py b/python_embeded/Lib/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..0e7316913b19b1de9d04dd902705c2834ab5207f --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_finite_differences.py b/python_embeded/Lib/site-packages/scipy/_lib/_finite_differences.py new file mode 100644 index 0000000000000000000000000000000000000000..891a99f83271c6e3c5f6ad62189c752723cddfc6 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a new file mode 100644 index 0000000000000000000000000000000000000000..bf3144af76bf9db3f10c7350957627aed23235fb Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/_fpumode.cp312-win_amd64.dll.a differ diff --git a/python_embeded/Lib/site-packages/scipy/_lib/_gcutils.py b/python_embeded/Lib/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..c08d35c48985aced8c73c93d92e89616850e270a --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_pep440.py b/python_embeded/Lib/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..aee9f2757ce9cbd825a67a8a06a8f110b2a8b720 --- /dev/null +++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..e6da45b673b9e1df808776375dd3577474943def
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/_test_ccallback.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..f968b2a667725a1d412e8bc30cb5fedcec11906f
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_call.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..e248eb737d07fe5e49912d7e2b0ea04dfd24d8ea
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/_test_deprecation_def.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/_lib/_testutils.py b/python_embeded/Lib/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1eec9d32e86270a900fc976354fc988aeff35df
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_threadsafety.py b/python_embeded/Lib/site-packages/scipy/_lib/_threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea5b40bb02c9e48b799de3b7384a365f1d5c2aad
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_tmpdirs.py b/python_embeded/Lib/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d863b78dfaf027e4729f3e782edaec81dcb3077
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/_util.py b/python_embeded/Lib/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f2e8d1a42c90ae7a8f6ecc4002012ad2e5f42da
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py b/python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d4aeb2785fdda9f4adf8bf9695c687ed0e9d9a0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py b/python_embeded/Lib/site-packages/scipy/_lib/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..15f1a654de35004d8d424f0ccd229cc68f35df55
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py b/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..845a081fa8abc8138c57935a1e77cc1cbce46956
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_funcs.py b/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..172db59bb5518c201f04b2eaa439457ef134f0ce
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_typing.py b/python_embeded/Lib/site-packages/scipy/_lib/array_api_extra/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e681154ba8beadf8ed1f839c38fd1bb3dfff08e8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/framework.py b/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/framework.py
new file mode 100644
index 0000000000000000000000000000000000000000..59b8ea0442c81af1f39ff12381bc993e83dbb0f5
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/main.py b/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8fd966e40bb5fc93248f0b62cb64ccfd0f3e90
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/models.py b/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..8917e594e6d13921185f27e9b34167845aa89371
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/problem.py b/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/problem.py
new file mode 100644
index 0000000000000000000000000000000000000000..046441a76486eab3d665af26147f6843d8bfaef2
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/settings.py b/python_embeded/Lib/site-packages/scipy/_lib/cobyqa/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..fec9a091c40f7da974c8752e2143c67922483c77
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/decorator.py b/python_embeded/Lib/site-packages/scipy/_lib/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f819d555c3aba07dd79f6d3a656785f2714d49f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/deprecation.py b/python_embeded/Lib/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..731194a8700e0f46b5b3540d534b5744a9d25672
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/doccer.py b/python_embeded/Lib/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..726ef5b72ecf8780136560510ebd3dac5c44d6cb
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..309af4033a96ffb61530a069862d9736129ee5b9
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/_lib/messagestream.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/_lib/uarray.py b/python_embeded/Lib/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1d37be3ff9a7817de00bfa557f7a01c78440510
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/cluster/__init__.py b/python_embeded/Lib/site-packages/scipy/cluster/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..93a68daf892e865a9d949a77d8857b1d1b68c1f3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..76348a16eff8e7f00c38cbd0141d6bc623f8a36c
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/cluster/_hierarchy.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..b6754eb8b513de3bb4dcfe43e186cb7362bc7694
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/cluster/_optimal_leaf_ordering.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..2d9e55f98c05d40904b6b951669c83c8e0f67f11
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/cluster/_vq.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/hierarchy.py b/python_embeded/Lib/site-packages/scipy/cluster/hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..9de6befccdb002c4280789da09c51aa55da7b07f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/cluster/vq.py b/python_embeded/Lib/site-packages/scipy/cluster/vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d779c13903649779cf3ce8f72b0665712ab267b
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/constants/__init__.py b/python_embeded/Lib/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec4ed081f9ed1dfc3adb382793d322c9d400f794
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/constants/_codata.py b/python_embeded/Lib/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..03fb5bc0a5715610e67972937a404261c9c481eb
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/constants/_constants.py b/python_embeded/Lib/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f508081e946f89261f0678a7c44543574a5ca2c
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/constants/codata.py b/python_embeded/Lib/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1f946e1bdfa13ffc485157d15b4284e5b14994b
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/constants/constants.py b/python_embeded/Lib/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..2615486c1e1f6715dc4f44b6a8217794b7640d82
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/datasets/__init__.py b/python_embeded/Lib/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab63e3ae2a680e7e9d767c85bfdcc41669f3822
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/datasets/_download_all.py b/python_embeded/Lib/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..4acc02709090857a8c377c21fc3c26068ec0c3a4
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/datasets/_fetchers.py b/python_embeded/Lib/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2985690468095e345ebc2750df420fdb86cc4e21
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/datasets/_registry.py b/python_embeded/Lib/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..9df4cf4de4d23ebdd8c036b26daee004663dfe0f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/datasets/_utils.py b/python_embeded/Lib/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ab1b4037a9f6eca22eea495b02878323be93c35
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/differentiate/__init__.py b/python_embeded/Lib/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..940cd71abc0b7ea954f04433ca261d542e664b25
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/differentiate/_differentiate.py b/python_embeded/Lib/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..5637f066eab178f77a1ebbe7304e174f6497747f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fft/__init__.py b/python_embeded/Lib/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c68df69e8a7ff6fedb6cf30dc852b60b006c639b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/__init__.py
@@ -0,0 +1,114 @@
+"""
+==============================================
+Discrete Fourier transforms (:mod:`scipy.fft`)
+==============================================
+
+.. currentmodule:: 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
+   rfft2 - 2-D FFT of real sequence
+   irfft2 - Inverse of rfft2
+   rfftn - N-D FFT of real sequence
+   irfftn - Inverse of rfftn
+   hfft - FFT of a Hermitian sequence (real spectrum)
+   ihfft - Inverse of hfft
+   hfft2 - 2-D FFT of a Hermitian sequence
+   ihfft2 - Inverse of hfft2
+   hfftn - N-D FFT of a Hermitian sequence
+   ihfftn - Inverse of hfftn
+
+Discrete Sin and Cosine Transforms (DST and DCT)
+================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   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
+
+Fast Hankel Transforms
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   fht - Fast Hankel transform
+   ifht - Inverse of fht
+
+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)
+   fhtoffset - Compute an optimal offset for the Fast Hankel Transform
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+   prev_fast_len - Find the maximum slice length that results in a fast FFT
+   set_workers - Context manager to set default number of workers
+   get_workers - Get the current default number of workers
+
+Backend control
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   set_backend - Context manager to set the backend within a fixed scope
+   skip_backend - Context manager to skip a backend within a fixed scope
+   set_global_backend - Sets the global fft backend
+   register_backend - Register a backend for permanent use
+
+"""
+
+from ._basic import (
+    fft, ifft, fft2, ifft2, fftn, ifftn,
+    rfft, irfft, rfft2, irfft2, rfftn, irfftn,
+    hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
+from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
+from ._fftlog import fht, ifht, fhtoffset
+from ._helper import (
+    next_fast_len, prev_fast_len, fftfreq,
+    rfftfreq, fftshift, ifftshift)
+from ._backend import (set_backend, skip_backend, set_global_backend,
+                       register_backend)
+from ._pocketfft.helper import set_workers, get_workers
+
+__all__ = [
+    'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
+    'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
+    'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
+    'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
+    'next_fast_len', 'prev_fast_len',
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
+    'fht', 'ifht',
+    'fhtoffset',
+    'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
+    'get_workers', 'set_workers']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_backend.py b/python_embeded/Lib/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..94d03a4c825ca3fcf1b1d07cf6da932d4e0664db
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,196 @@
+import scipy._lib.uarray as ua
+from . import _basic_backend
+from . import _realtransforms_backend
+from . import _fftlog_backend
+
+
+class _ScipyBackend:
+    """The default backend for fft calculations
+
+    Notes
+    -----
+    We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
+    treats the domain as a hierarchy. This means the user can install a single
+    backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
+    """
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+
+        fn = getattr(_basic_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_realtransforms_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_fftlog_backend, method.__name__, None)
+        if fn is None:
+            return NotImplemented
+        return fn(*args, **kwargs)
+
+
+_named_backends = {
+    'scipy': _ScipyBackend,
+}
+
+
+def _backend_from_arg(backend):
+    """Maps strings to known backends and validates the backend"""
+
+    if isinstance(backend, str):
+        try:
+            backend = _named_backends[backend]
+        except KeyError as e:
+            raise ValueError(f'Unknown backend {backend}') from e
+
+    if backend.__ua_domain__ != 'numpy.scipy.fft':
+        raise ValueError('Backend does not implement "numpy.scipy.fft"')
+
+    return backend
+
+
+def set_global_backend(backend, coerce=False, only=False, try_last=False):
+    """Sets the global fft backend
+
+    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.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    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.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Notes
+    -----
+    This will overwrite the previously set global backend, which, by default, is
+    the SciPy implementation.
+
+    Examples
+    --------
+    We can set the global fft backend:
+
+    >>> from scipy.fft import fft, set_global_backend
+    >>> set_global_backend("scipy")  # Sets global backend (default is "scipy").
+    >>> fft([1])  # Calls the global backend
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
+
+
+def register_backend(backend):
+    """
+    Register a backend for permanent use.
+
+    Registered backends have the lowest priority and will be tried after the
+    global backend.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Examples
+    --------
+    We can register a new fft backend:
+
+    >>> from scipy.fft import fft, register_backend, set_global_backend
+    >>> class NoopBackend:  # Define an invalid Backend
+    ...     __ua_domain__ = "numpy.scipy.fft"
+    ...     def __ua_function__(self, func, args, kwargs):
+    ...          return NotImplemented
+    >>> set_global_backend(NoopBackend())  # Set the invalid backend as global
+    >>> register_backend("scipy")  # Register a new backend
+    # The registered backend is called because
+    # the global backend returns `NotImplemented`
+    >>> fft([1])
+    array([1.+0.j])
+    >>> set_global_backend("scipy")  # Restore global backend to default
+
+    """
+    backend = _backend_from_arg(backend)
+    ua.register_backend(backend)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """Context manager to set the backend within a fixed scope.
+
+    Upon entering the ``with`` statement, the given backend will be added to
+    the list of available backends with the highest priority. Upon exit, the
+    backend is reset to the state before entering the scope.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool, optional
+        Whether to allow expensive conversions for the ``x`` parameter. e.g.,
+        copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
+    only : bool, optional
+        If only is ``True`` and this backend returns ``NotImplemented``, then a
+        BackendNotImplemented error will be raised immediately. Ignoring any
+        lower priority backends.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> with fft.set_backend('scipy', only=True):
+    ...     fft.fft([1])  # Always calls the scipy implementation
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    return ua.set_backend(backend, coerce=coerce, only=only)
+
+
+def skip_backend(backend):
+    """Context manager to skip a backend within a fixed scope.
+
+    Within the context of a ``with`` statement, the given backend will not be
+    called. This covers backends registered both locally and globally. Upon
+    exit, the backend will again be considered.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to skip.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> fft.fft([1])  # Calls default SciPy backend
+    array([1.+0.j])
+    >>> with fft.skip_backend('scipy'):  # We explicitly skip the SciPy backend
+    ...     fft.fft([1])                 # leaving no implementation available
+    Traceback (most recent call last):
+        ...
+    BackendNotImplementedError: No selected backends had an implementation ...
+    """
+    backend = _backend_from_arg(backend)
+    return ua.skip_backend(backend)
+
+
+set_global_backend('scipy', try_last=True)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_basic.py b/python_embeded/Lib/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..44c61d0a6557381edaebdcc36288d0625e7ab257
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1630 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+import numpy as np
+
+
+def _x_replacer(args, kwargs, dispatchables):
+    """
+    uarray argument replacer to replace the transform input array (``x``)
+    """
+    if len(args) > 0:
+        return (dispatchables[0],) + args[1:], kwargs
+    kw = kwargs.copy()
+    kw['x'] = dispatchables[0]
+    return args, kw
+
+
+def _dispatch(func):
+    """
+    Function annotation that creates a uarray multimethod from the function
+    """
+    return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
+
+
+@_dispatch
+def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+        plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) with the efficient Fast Fourier Transform (FFT)
+    algorithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode. Default is "backward", meaning no normalization on
+        the forward transforms and scaling by ``1/n`` on the `ifft`.
+        "forward" instead applies the ``1/n`` factor on the forward transform.
+        For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
+
+        .. versionadded:: 1.6.0
+           ``norm={"forward", "backward"}`` options were added
+
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See the notes below for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``. See below for more
+        details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        if `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    ifft : The inverse of `fft`.
+    fft2 : The 2-D FFT.
+    fftn : The N-D FFT.
+    rfftn : The N-D FFT of real input.
+    fftfreq : Frequency bins for given FFT parameters.
+    next_fast_len : Size to pad input to for most efficient transforms
+
+    Notes
+    -----
+    FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
+    (DFT) can be calculated efficiently, by using symmetries in the calculated
+    terms. The symmetry is highest when `n` is a power of 2, and the transform
+    is therefore most efficient for these sizes. For poorly factorizable sizes,
+    `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
+    O(`n` log `n`). Further performance improvements may be seen by zero-padding
+    the input using `next_fast_len`.
+
+    If ``x`` is a 1d array, then the `fft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
+
+    The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
+    the Nyquist frequency and wrap around to the negative-frequency terms. 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`.
+
+    Transforms can be done in single, double, or extended precision (long
+    double) floating point. Half precision inputs will be converted to single
+    precision and non-floating-point inputs will be converted to double
+    precision.
+
+    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 are both real and
+    symmetrical, the `dct` can again double the efficiency, by generating
+    half of the spectrum from half of the signal.
+
+    When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
+    be used by the implementation in any way. This may include reusing the
+    memory for the result, but this is in no way guaranteed. You should not
+    rely on the contents of ``x`` after the transform as this may change in
+    future without warning.
+
+    The ``workers`` argument specifies the maximum number of parallel jobs to
+    split the FFT computation into. This will execute independent 1-D
+    FFTs within ``x``. So, ``x`` must be at least 2-D and the
+    non-transformed axes must be large enough to split into chunks. If ``x`` is
+    too small, fewer jobs may be used than requested.
+
+    References
+    ----------
+    .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+           machine calculation of complex Fourier series," *Math. Comput.*
+           19: 297-301.
+    .. [2] Bluestein, L., 1970, "A linear filtering approach to the
+           computation of discrete Fourier transform". *IEEE Transactions on
+           Audio and Electroacoustics.* 18 (4): 451-455.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
+    array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
+            2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
+           -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
+            1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
+
+    In this example, real input has an FFT which is Hermitian, i.e., symmetric
+    in the real part and anti-symmetric in the imaginary part:
+
+    >>> from scipy.fft import fft, fftfreq, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> t = np.arange(256)
+    >>> sp = fftshift(fft(np.sin(t)))
+    >>> freq = fftshift(fftfreq(t.shape[-1]))
+    >>> plt.plot(freq, sp.real, freq, sp.imag)
+    [,
+     ]
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier transform computed by `fft`.  In other words,
+    ``ifft(fft(x)) == x`` to within numerical accuracy.
+
+    The input should be ordered in the same way as is returned by `fft`,
+    i.e.,
+
+    * ``x[0]`` should contain the zero frequency term,
+    * ``x[1:n//2]`` should contain the positive-frequency terms,
+    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
+      increasing order starting from the most negative frequency.
+
+    For an even number of input points, ``x[n//2]`` represents the sum of
+    the values at the positive and negative Nyquist frequencies, as the two
+    are aliased together. See `fft` for details.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+        See notes about padding issues.
+    axis : int, optional
+        Axis over which to compute the inverse DFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        If `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
+    ifft2 : The 2-D inverse FFT.
+    ifftn : The N-D inverse FFT.
+
+    Notes
+    -----
+    If the input parameter `n` is larger than the size of the input, the input
+    is padded by appending zeros at the end. Even though this is the common
+    approach, it might lead to surprising results. If a different padding is
+    desired, it must be performed before calling `ifft`.
+
+    If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
+
+    As with `fft`, `ifft` has support for all floating point types and is
+    optimized for real input.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.ifft([0, 4, 0, 0])
+    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
+
+    Create and plot a band-limited signal with random phases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> t = np.arange(400)
+    >>> n = np.zeros((400,), dtype=complex)
+    >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
+    >>> s = scipy.fft.ifft(n)
+    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+    [, ]
+    >>> plt.legend(('real', 'imaginary'))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform for real input.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) of a real-valued array by means of an efficient algorithm
+    called the Fast Fourier Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array
+    n : int, optional
+        Number of points along transformation axis in the input to use.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
+        If `n` is odd, the length is ``(n+1)/2``.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    irfft : The inverse of `rfft`.
+    fft : The 1-D FFT of general (complex) input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+    rfftn : The N-D FFT of real input.
+
+    Notes
+    -----
+    When the DFT is computed for purely real input, the output is
+    Hermitian-symmetric, i.e., the negative frequency terms are just the complex
+    conjugates of the corresponding positive-frequency terms, and the
+    negative-frequency terms are therefore redundant. This function does not
+    compute the negative frequency terms, and the length of the transformed
+    axis of the output is therefore ``n//2 + 1``.
+
+    When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
+    the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
+
+    If `n` is even, ``A[-1]`` contains the term representing both positive
+    and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
+    real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
+    the largest positive frequency (fs/2*(n-1)/n), and is complex in the
+    general case.
+
+    If the input `a` contains an imaginary part, it is silently discarded.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.fft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
+    >>> scipy.fft.rfft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
+
+    Notice how the final element of the `fft` output is the complex conjugate
+    of the second element, for real input. For `rfft`, this symmetry is
+    exploited to compute only the non-negative frequency terms.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Computes the inverse of `rfft`.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier Transform of real input computed by `rfft`.
+    In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
+    accuracy. (See Notes below for why ``len(a)`` is necessary here.)
+
+    The input is expected to be in the form returned by `rfft`, i.e., the
+    real zero-frequency term followed by the complex positive frequency terms
+    in order of increasing frequency. Since the discrete Fourier Transform of
+    real input is Hermitian-symmetric, the negative frequency terms are taken
+    to be the complex conjugates of the corresponding positive frequency terms.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output.
+        For `n` output points, ``n//2+1`` input points are necessary. If the
+        input is longer than this, it is cropped. If it is shorter than this,
+        it is padded with zeros. If `n` is not given, it is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along the axis
+        specified by `axis`.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
+        input. To get an odd number of output points, `n` must be specified.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    rfft : The 1-D FFT of real input, of which `irfft` is inverse.
+    fft : The 1-D FFT.
+    irfft2 : The inverse of the 2-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    Returns the real valued `n`-point inverse discrete Fourier transform
+    of `x`, where `x` contains the non-negative frequency terms of a
+    Hermitian-symmetric sequence. `n` is the length of the result, not the
+    input.
+
+    If you specify an `n` such that `a` must be zero-padded or truncated, the
+    extra/removed values will be added/removed at high frequencies. One can
+    thus resample a series to `m` points via Fourier interpolation by:
+    ``a_resamp = irfft(rfft(a), m)``.
+
+    The default value of `n` assumes an even output length. By the Hermitian
+    symmetry, the last imaginary component must be 0 and so is ignored. To
+    avoid losing information, the correct length of the real input *must* be
+    given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.ifft([1, -1j, -1, 1j])
+    array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
+    >>> scipy.fft.irfft([1, -1j, -1])
+    array([0.,  1.,  0.,  0.])
+
+    Notice how the last term in the input to the ordinary `ifft` is the
+    complex conjugate of the second term, and the output has zero imaginary
+    part everywhere. When calling `irfft`, the negative frequencies are not
+    specified, and the output array is purely real.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
+    spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output. For `n` output
+        points, ``n//2 + 1`` input points are necessary. If the input is
+        longer than this, it is cropped. If it is shorter than this, it is
+        padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
+        where ``m`` is the length of the input along the axis specified by
+        `axis`.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*m - 2``, where ``m`` is the length of the transformed axis of
+        the input. To get an odd number of output points, `n` must be
+        specified, for instance, as ``2*m - 1`` in the typical case,
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    rfft : Compute the 1-D FFT for real input.
+    ihfft : The inverse of `hfft`.
+    hfftn : Compute the N-D FFT of a Hermitian signal.
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd.
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import fft, hfft
+    >>> import numpy as np
+    >>> a = 2 * np.pi * np.arange(10) / 10
+    >>> signal = np.cos(a) + 3j * np.sin(3 * a)
+    >>> fft(signal).round(10)
+    array([ -0.+0.j,   5.+0.j,  -0.+0.j,  15.-0.j,   0.+0.j,   0.+0.j,
+            -0.+0.j, -15.-0.j,   0.+0.j,   5.+0.j])
+    >>> hfft(signal[:6]).round(10) # Input first half of signal
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    >>> hfft(signal, 10)  # Input entire signal and truncate
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the inverse FFT of a signal that has Hermitian symmetry.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    n : int, optional
+        Length of the inverse FFT, the number of points along
+        transformation axis in the input to use.  If `n` is smaller than
+        the length of the input, the input is cropped. If it is larger,
+        the input is padded with zeros. If `n` is not given, the length of
+        the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is ``n//2 + 1``.
+
+    See Also
+    --------
+    hfft, irfft
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here, the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd:
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import ifft, ihfft
+    >>> import numpy as np
+    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
+    >>> ifft(spectrum)
+    array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
+    >>> ihfft(spectrum)
+    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the N-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D array by means of the Fast Fourier
+    Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifftn : The inverse of `fftn`, the inverse N-D FFT.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfftn : The N-D FFT of real input.
+    fft2 : The 2-D FFT.
+    fftshift : Shifts zero-frequency terms to centre of array.
+
+    Notes
+    -----
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of all axes, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:3, :3, :3][0]
+    >>> scipy.fft.fftn(x, axes=(1, 2))
+    array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[ 9.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[18.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]]])
+    >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
+    array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
+            [ 0.+0.j,  0.+0.j,  0.+0.j]],
+           [[-2.+0.j, -2.+0.j, -2.+0.j],
+            [ 0.+0.j,  0.+0.j,  0.+0.j]]])
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
+    ...                      2 * np.pi * np.arange(200) / 34)
+    >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
+    >>> FS = scipy.fft.fftn(S)
+    >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform over any number of axes in an M-D array by
+    means of the Fast Fourier Transform (FFT).  In other words,
+    ``ifftn(fftn(x)) == x`` to within numerical accuracy.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fftn`, i.e., it should have the term for zero frequency
+    in all axes in the low-order corner, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``ifft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used. See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the IFFT.  If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fftn : The forward N-D FFT, of which `ifftn` is the inverse.
+    ifft : The 1-D inverse FFT.
+    ifft2 : The 2-D inverse FFT.
+    ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
+        of array.
+
+    Notes
+    -----
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifftn` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.eye(4)
+    >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
+
+
+    Create and plot an image with band-limited frequency content:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> n = np.zeros((200,200), dtype=complex)
+    >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
+    >>> im = scipy.fft.ifftn(n).real
+    >>> plt.imshow(im)
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 2-D discrete Fourier Transform
+
+    This function computes the N-D discrete Fourier Transform
+    over any axes in an M-D array by means of the
+    Fast Fourier Transform (FFT). By default, the transform is computed over
+    the last two axes of the input array, i.e., a 2-dimensional FFT.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two axes are
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifft2 : The inverse 2-D FFT.
+    fft : The 1-D FFT.
+    fftn : The N-D FFT.
+    fftshift : Shifts zero-frequency terms to the center of the array.
+        For 2-D input, swaps first and third quadrants, and second
+        and fourth quadrants.
+
+    Notes
+    -----
+    `fft2` is just `fftn` with a different default for `axes`.
+
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of the transformed axes, the positive frequency terms
+    in the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    the axes, in order of decreasingly negative frequency.
+
+    See `fftn` for details and a plotting example, and `fft` for
+    definitions and conventions used.
+
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:5, :5][0]
+    >>> scipy.fft.fft2(x)
+    array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 2-D discrete Fourier
+    Transform over any number of axes in an M-D array by means of
+    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
+    to within numerical accuracy. By default, the inverse transform is
+    computed over the last two axes of the input array.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fft2`, i.e., it should have the term for zero frequency
+    in the low-order corner of the two axes, the positive frequency terms in
+    the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    both axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
+        ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.  See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two
+        axes are used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
+    ifftn : The inverse of the N-D FFT.
+    fft : The 1-D FFT.
+    ifft : The 1-D inverse FFT.
+
+    Notes
+    -----
+    `ifft2` is just `ifftn` with a different default for `axes`.
+
+    See `ifftn` for details and a plotting example, and `fft` for
+    definition and conventions used.
+
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifft2` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = 4 * np.eye(4)
+    >>> scipy.fft.ifft2(x)
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D discrete Fourier Transform for real input.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining
+    transforms are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
+        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
+         of real input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : The 1-D FFT of real input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `rfft`, then the transform over the remaining axes is
+    performed as by `fftn`. The order of the output is as for `rfft` for the
+    final transformation axis, and as for `fftn` for the remaining
+    transformation axes.
+
+    See `fft` for details, definitions and conventions used.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.rfftn(x)
+    array([[[8.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    >>> scipy.fft.rfftn(x, axes=(2, 0))
+    array([[[4.+0.j,  0.+0.j], # may vary
+            [4.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a real array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape of the FFT.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the real 2-D FFT.
+
+    See Also
+    --------
+    irfft2 : The inverse of the 2-D FFT of real input.
+    rfft : The 1-D FFT of real input.
+    rfftn : Compute the N-D discrete Fourier Transform for real
+            input.
+
+    Notes
+    -----
+    This is really just `rfftn` with different default behavior.
+    For more details see `rfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfftn`
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform for real input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In
+    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
+    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
+    and for the same reason.)
+
+    The input should be ordered in the same way as is returned by `rfftn`,
+    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
+    along all the other axes.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given. In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
+        length of the final transformed axis of the input. To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    rfftn : The forward N-D FFT of real input,
+            of which `ifftn` is the inverse.
+    fft : The 1-D FFT, with definitions and conventions used.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfft2 : The inverse of the 2-D FFT of real input.
+
+    Notes
+    -----
+    See `fft` for definitions and conventions used.
+
+    See `rfft` for definitions and conventions used for real input.
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.zeros((3, 2, 2))
+    >>> x[0, 0, 0] = 3 * 2 * 2
+    >>> scipy.fft.irfftn(x)
+    array([[[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfft2`
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real output to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    rfft2 : The 2-D FFT of real input.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    This is really `irfftn` with different defaults.
+    For more details see `irfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
+    signal with a real spectrum.
+
+    This function computes the N-D discrete Fourier Transform for a
+    Hermitian symmetric complex input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In other
+    words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
+    here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
+    for the same reason ``x.shape`` would be necessary for `irfft`.)
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)`` where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given.  In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
+        length of the final transformed axis of the input.  To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : Forward FFT of real input.
+
+    Notes
+    -----
+    For a 1-D signal ``x`` to have a real spectrum, it must satisfy
+    the Hermitian property::
+
+        x[i] == np.conj(x[-i]) for all i
+
+    This generalizes into higher dimensions by reflecting over each axis in
+    turn::
+
+        x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
+
+    This should not be confused with a Hermitian matrix, for which the
+    transpose is its own conjugate::
+
+        x[i, j] == np.conj(x[j, i]) for all i, j
+
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((3, 2, 2))
+    >>> scipy.fft.hfftn(x)
+    array([[[12.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a Hermitian complex array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be Hermitian complex.
+    s : sequence of ints, optional
+        Shape of the real output.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The real result of the 2-D Hermitian complex real FFT.
+
+    See Also
+    --------
+    hfftn : Compute the N-D discrete Fourier Transform for Hermitian
+            complex input.
+
+    Notes
+    -----
+    This is really just `hfftn` with different default behavior.
+    For more details see `hfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform for a real
+    spectrum.
+
+    This function computes the N-D inverse discrete Fourier Transform
+    over any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining transforms
+    are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    hfftn : The forward N-D FFT of Hermitian input.
+    hfft : The 1-D FFT of Hermitian input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    fftn : The N-D FFT.
+    hfft2 : The 2-D FFT of Hermitian input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `ihfft`, then the transform over the remaining axes is
+    performed as by `ifftn`. The order of the output is the positive part of
+    the Hermitian output signal, in the same format as `rfft`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.ihfftn(x)
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+    >>> scipy.fft.ihfftn(x, axes=(2, 0))
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [1.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the 2-D inverse FFT of a real spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real input to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
+
+    Notes
+    -----
+    This is really `ihfftn` with different defaults.
+    For more details see `ihfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_basic_backend.py b/python_embeded/Lib/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..d01e075b4fff2d837ecf51465967f7ff38e15272
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_basic_backend.py
@@ -0,0 +1,197 @@
+from scipy._lib._array_api import (
+    array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex
+)
+from . import _pocketfft
+import numpy as np
+
+
+def _validate_fft_args(workers, plan, norm):
+    if workers is not None:
+        raise ValueError(xp_unsupported_param_msg("workers"))
+    if plan is not None:
+        raise ValueError(xp_unsupported_param_msg("plan"))
+    if norm is None:
+        norm = 'backward'
+    return norm
+
+
+# these functions expect complex input in the fft standard extension
+complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'}
+
+# pocketfft is used whenever SCIPY_ARRAY_API is not set,
+# or x is a NumPy array or array-like.
+# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
+# PyTorch arrays and other array API standard supporting objects.
+# If xp.fft does not exist, we attempt to convert to np and back to use pocketfft.
+
+def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, n=n, axis=axis, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            return res
+        return xp_func(x, n=n, axis=axis, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, n=n, axis=axis, norm=norm)
+    return xp.asarray(y)
+
+
+def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+    
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, s=s, axes=axes, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            return res
+        return xp_func(x, s=s, axes=axes, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, s=s, axes=axes, norm=norm)
+    return xp.asarray(y)
+
+
+def fft(x, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def hfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ihfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fftn(x, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+
+def ifftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ifft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def rfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def irfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def _swap_direction(norm):
+    if norm in (None, 'backward'):
+        norm = 'forward'
+    elif norm == 'forward':
+        norm = 'backward'
+    elif norm != 'ortho':
+        raise ValueError(f'Invalid norm value {norm}; should be "backward", '
+                         '"ortho", or "forward".')
+    return norm
+
+
+def hfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    if is_complex(x, xp):
+        x = xp.conj(x)
+    return irfftn(x, s, axes, _swap_direction(norm),
+                  overwrite_x, workers, plan=plan)
+
+
+def hfft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ihfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
+                         overwrite_x, workers, plan=plan))
+
+def ihfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_debug_backends.py b/python_embeded/Lib/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a09866e5b4f647c7de3c5292afece0a7a0d3378
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_debug_backends.py
@@ -0,0 +1,22 @@
+import numpy as np
+
+class NumPyBackend:
+    """Backend that uses numpy.fft"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        kwargs.pop("overwrite_x", None)
+
+        fn = getattr(np.fft, method.__name__, None)
+        return (NotImplemented if fn is None
+                else fn(*args, **kwargs))
+
+
+class EchoBackend:
+    """Backend that just prints the __ua_function__ arguments"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        print(method, args, kwargs, sep='\n')
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_fftlog.py b/python_embeded/Lib/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..c05a2700bc060967e687716f32c648a6e655fbc5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,223 @@
+"""Fast Hankel transforms using the FFTLog algorithm.
+
+The implementation closely follows the Fortran code of Hamilton (2000).
+
+added: 14/11/2020 Nicolas Tessore 
+"""
+
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from ._fftlog_backend import fhtoffset
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@_dispatch
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    r'''Compute the fast Hankel transform.
+
+    Computes the discrete Hankel transform of a logarithmically spaced periodic
+    sequence using the FFTLog algorithm [1]_, [2]_.
+
+    Parameters
+    ----------
+    a : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    A : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    ifht : The inverse of `fht`.
+    fhtoffset : Return an optimal offset for `fht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative.  Note that the
+    numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
+    mathematical Hankel transform is commonly defined using :math:`r \, dr`.
+
+    The input array `a` is a periodic sequence of length :math:`n`, uniformly
+    logarithmically spaced with spacing `dln`,
+
+    .. math::
+
+        a_j = a(r_j) \;, \quad
+        r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`r_c`.  Note that the central index
+    :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
+    :math:`r_c` falls between two input elements.  Similarly, the output
+    array `A` is a periodic sequence of length :math:`n`, also uniformly
+    logarithmically spaced with spacing `dln`
+
+    .. math::
+
+       A_j = A(k_j) \;, \quad
+       k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`k_c`.
+
+    The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
+    be chosen arbitrarily, but it would be usual to choose the product
+    :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity.  This can be
+    changed using the `offset` parameter, which controls the logarithmic offset
+    :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
+    Choosing an optimal value for `offset` may reduce ringing of the discrete
+    Hankel transform.
+
+    If the `bias` parameter is nonzero, this function computes a discrete
+    version of the biased Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
+
+    where :math:`q` is the value of `bias`, and a power law bias
+    :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
+    Biasing the transform can help approximate the continuous transform of
+    :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
+    close to a periodic sequence, in which case the resulting :math:`A(k)` will
+    be close to the continuous transform.
+
+    References
+    ----------
+    .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
+    .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    Examples
+    --------
+
+    This example is the adapted version of ``fftlogtest.f`` which is provided
+    in [2]_. It evaluates the integral
+
+    .. math::
+
+        \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr
+        = k^{\mu+1} \exp(-k^2/2) .
+
+    >>> import numpy as np
+    >>> from scipy import fft
+    >>> import matplotlib.pyplot as plt
+
+    Parameters for the transform.
+
+    >>> mu = 0.0                     # Order mu of Bessel function
+    >>> r = np.logspace(-7, 1, 128)  # Input evaluation points
+    >>> dln = np.log(r[1]/r[0])      # Step size
+    >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
+    >>> k = np.exp(offset)/r[::-1]   # Output evaluation points
+
+    Define the analytical function.
+
+    >>> def f(x, mu):
+    ...     """Analytical function: x^(mu+1) exp(-x^2/2)."""
+    ...     return x**(mu + 1)*np.exp(-x**2/2)
+
+    Evaluate the function at ``r`` and compute the corresponding values at
+    ``k`` using FFTLog.
+
+    >>> a_r = f(r, mu)
+    >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
+
+    For this example we can actually compute the analytical response (which in
+    this case is the same as the input function) for comparison and compute the
+    relative error.
+
+    >>> a_k = f(k, mu)
+    >>> rel_err = abs((fht-a_k)/a_k)
+
+    Plot the result.
+
+    >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
+    >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
+    >>> ax1.loglog(r, a_r, 'k', lw=2)
+    >>> ax1.set_xlabel('r')
+    >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
+    >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
+    >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
+    >>> ax2.set_xlabel('k')
+    >>> ax2.legend(loc=3, framealpha=1)
+    >>> ax2.set_ylim([1e-10, 1e1])
+    >>> ax2b = ax2.twinx()
+    >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
+    >>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
+    >>> ax2b.tick_params(axis='y', labelcolor='C0')
+    >>> ax2b.legend(loc=4, framealpha=1)
+    >>> ax2b.set_ylim([1e-9, 1e-3])
+    >>> plt.show()
+
+    '''
+    return (Dispatchable(a, np.ndarray),)
+
+
+@_dispatch
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    r"""Compute the inverse fast Hankel transform.
+
+    Computes the discrete inverse Hankel transform of a logarithmically spaced
+    periodic sequence. This is the inverse operation to `fht`.
+
+    Parameters
+    ----------
+    A : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    a : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+    fhtoffset : Return an optimal offset for `ifht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative. Note that the
+    numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
+    mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
+
+    See `fht` for further details.
+    """
+    return (Dispatchable(A, np.ndarray),)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_fftlog_backend.py b/python_embeded/Lib/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..b16579002893481fad867560725408c646fa08ee
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,200 @@
+import numpy as np
+from warnings import warn
+from ._basic import rfft, irfft
+from ..special import loggamma, poch
+
+from scipy._lib._array_api import array_namespace
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+# constants
+LN_2 = np.log(2)
+
+
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+
+    # size of transform
+    n = a.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # a_q(r) = a(r) (r/r_c)^{-q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        a = a * xp.exp(-bias*(j - j_c)*dln)
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
+
+    # transform
+    A = _fhtq(a, u, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
+        A *= xp.exp(-bias*((j - j_c)*dln + offset))
+
+    return A
+
+
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(A)
+    A = xp.asarray(A)
+
+    # size of transform
+    n = A.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        A = A * xp.exp(bias*((j - j_c)*dln + offset))
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
+
+    # transform
+    a = _fhtq(A, u, inverse=True, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # a(r) = a_q(r) (r/r_c)^{q}
+        a /= xp.exp(-bias*(j - j_c)*dln)
+
+    return a
+
+
+def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
+    """Compute the coefficient array for a fast Hankel transform."""
+    lnkr, q = offset, bias
+
+    # Hankel transform coefficients
+    # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
+    # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
+    u = np.empty(n//2+1, dtype=complex)
+    v = np.empty(n//2+1, dtype=complex)
+    u.imag[:] = y
+    u.real[:] = xm
+    loggamma(u, out=v)
+    u.real[:] = xp
+    loggamma(u, out=u)
+    y *= 2*(LN_2 - lnkr)
+    u.real -= v.real
+    u.real += LN_2*q
+    u.imag += v.imag
+    u.imag += y
+    np.exp(u, out=u)
+
+    # fix last coefficient to be real
+    if n % 2 == 0:
+        u.imag[-1] = 0
+
+    # deal with special cases
+    if not np.isfinite(u[0]):
+        # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
+        # poch() handles special cases for negative integers correctly
+        u[0] = 2**q * poch(xm, xp-xm)
+        # the coefficient may be inf or 0, meaning the transform or the
+        # inverse transform, respectively, is singular
+
+    # check for singular transform or singular inverse transform
+    if np.isinf(u[0]) and not inverse:
+        warn('singular transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) transform anyway
+        u = np.copy(u)
+        u[0] = 0
+    elif u[0] == 0 and inverse:
+        warn('singular inverse transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) inverse anyway
+        u = np.copy(u)
+        u[0] = np.inf
+
+    return u
+
+
+def fhtoffset(dln, mu, initial=0.0, bias=0.0):
+    """Return optimal offset for a fast Hankel transform.
+
+    Returns an offset close to `initial` that fulfils the low-ringing
+    condition of [1]_ for the fast Hankel transform `fht` with logarithmic
+    spacing `dln`, order `mu` and bias `bias`.
+
+    Parameters
+    ----------
+    dln : float
+        Uniform logarithmic spacing of the transform.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    initial : float, optional
+        Initial value for the offset. Returns the closest value that fulfils
+        the low-ringing condition.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    offset : float
+        Optimal offset of the uniform logarithmic spacing of the transform that
+        fulfils a low-ringing condition.
+
+    Examples
+    --------
+    >>> from scipy.fft import fhtoffset
+    >>> dln = 0.1
+    >>> mu = 2.0
+    >>> initial = 0.5
+    >>> bias = 0.0
+    >>> offset = fhtoffset(dln, mu, initial, bias)
+    >>> offset
+    0.5454581477676637
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+
+    References
+    ----------
+    .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    """
+
+    lnkr, q = initial, bias
+
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.pi/(2*dln)
+    zp = loggamma(xp + 1j*y)
+    zm = loggamma(xm + 1j*y)
+    arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
+    return lnkr + (arg - np.round(arg))*dln
+
+
+def _fhtq(a, u, inverse=False, *, xp=None):
+    """Compute the biased fast Hankel transform.
+
+    This is the basic FFTLog routine.
+    """
+    if xp is None:
+        xp = np
+
+    # size of transform
+    n = a.shape[-1]
+
+    # biased fast Hankel transform via real FFT
+    A = rfft(a, axis=-1)
+    if not inverse:
+        # forward transform
+        A *= u
+    else:
+        # backward transform
+        A /= xp.conj(u)
+    A = irfft(A, n, axis=-1)
+    A = xp.flip(A, axis=-1)
+
+    return A
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_helper.py b/python_embeded/Lib/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e2426e9f087d4f55e4cd9e51d7e59ed3fbb14f2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,379 @@
+from functools import update_wrapper, lru_cache
+import inspect
+
+from ._pocketfft import helper as _helper
+
+import numpy as np
+from scipy._lib._array_api import array_namespace
+
+
+def next_fast_len(target, real=False):
+    """Find the next fast size of input data to ``fft``, for zero-padding, etc.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The smallest fast length greater than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 11.4 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fft.fft(a)
+
+    Zero-padding to the next regular length reduces computation time to
+    1.6 ms, a speedup of 7.3 times:
+
+    >>> fft.next_fast_len(min_len, real=True)
+    93312
+    >>> b = fft.fft(a, 93312)
+
+    Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
+    compute; 1.9 times longer than the size given by ``next_fast_len``:
+
+    >>> b = fft.fft(a, 131072)
+
+    """
+    pass
+
+
+# Directly wrap the c-function good_size but take the docstring etc., from the
+# next_fast_len function above
+_sig = inspect.signature(next_fast_len)
+next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
+next_fast_len.__wrapped__ = _helper.good_size
+next_fast_len.__signature__ = _sig
+
+
+def prev_fast_len(target, real=False):
+    """Find the previous fast size of input data to ``fft``.
+    Useful for discarding a minimal number of samples before FFT.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Maximum length to search until. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The largest fast length less than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    In the current implementation, prev_fast_len assumes radices of
+    2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 16.2 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> max_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(max_len)
+    >>> b = fft.fft(a)
+
+    Performing FFT on the maximum fast length less than max_len
+    reduces the computation time to 1.5 ms, a speedup of 10.5 times:
+
+    >>> fft.prev_fast_len(max_len, real=True)
+    92160
+    >>> c = fft.fft(a[:92160]) # discard last 899 samples
+
+    """
+    pass
+
+
+# Directly wrap the c-function prev_good_size but take the docstring etc.,
+# from the prev_fast_len function above
+_sig_prev_fast_len = inspect.signature(prev_fast_len)
+prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
+prev_fast_len.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+def _init_nd_shape_and_axes(x, shape, axes):
+    """Handle shape and axes arguments for N-D transforms.
+
+    Returns the shape and axes in a standard form, taking into account negative
+    values and checking for various potential errors.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    shape : int or array_like of ints or None
+        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` is -1, the size of the corresponding dimension of `x` is
+        used.
+    axes : int or array_like of ints or None
+        Axes along which the calculation is computed.
+        The default is over all axes.
+        Negative indices are automatically converted to their positive
+        counterparts.
+
+    Returns
+    -------
+    shape : tuple
+        The shape of the result as a tuple of integers.
+    axes : list
+        Axes along which the calculation is computed, as a list of integers.
+
+    """
+    x = np.asarray(x)
+    return _helper._init_nd_shape_and_axes(x, shape, axes)
+
+
+def fftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies.
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.fftfreq` implements the device parameter.
+     
+    Returns
+    -------
+    f : ndarray
+        Array of length `n` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> fourier = scipy.fft.fft(signal)
+    >>> n = signal.size
+    >>> timestep = 0.1
+    >>> freq = scipy.fft.fftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.fftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.fftfreq(n, d=d)
+
+
+def rfftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies
+    (for usage with rfft, irfft).
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
+
+    Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
+    the Nyquist frequency component is considered to be positive.
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.rfftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length ``n//2 + 1`` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
+    >>> fourier = scipy.fft.rfft(signal)
+    >>> n = signal.size
+    >>> sample_rate = 100
+    >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20., ..., -30., -20., -10.])
+    >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20.,  30.,  40.,  50.])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.rfftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.rfftfreq(n, d=d)
+
+
+def fftshift(x, axes=None):
+    """Shift the zero-frequency component to the center of the spectrum.
+
+    This function swaps half-spaces for all axes listed (defaults to all).
+    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to shift.  Default is None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    ifftshift : The inverse of `fftshift`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(10, 0.1)
+    >>> freqs
+    array([ 0.,  1.,  2., ..., -3., -2., -1.])
+    >>> np.fft.fftshift(freqs)
+    array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+
+    Shift the zero-frequency component only along the second axis:
+
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.fftshift(freqs, axes=(1,))
+    array([[ 2.,  0.,  1.],
+           [-4.,  3.,  4.],
+           [-1., -3., -2.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.fftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.fftshift(x, axes=axes)
+    return xp.asarray(y)
+
+
+def ifftshift(x, axes=None):
+    """The inverse of `fftshift`. Although identical for even-length `x`, the
+    functions differ by one sample for odd-length `x`.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to calculate.  Defaults to None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    fftshift : Shift zero-frequency component to the center of the spectrum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.ifftshift(np.fft.fftshift(freqs))
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.ifftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.ifftshift(x, axes=axes)
+    return xp.asarray(y)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_realtransforms.py b/python_embeded/Lib/site-packages/scipy/fft/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c0b2ddef3c36048490330983d372e7c46302206
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_realtransforms.py
@@ -0,0 +1,693 @@
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+import numpy as np
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+@_dispatch
+def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, orthogonalize=None):
+    """
+    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.
+    s : int or array_like of ints or None, optional
+        The shape of the result. If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse 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.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are
+        None, `s` is ``x.shape``; if `s` is None but `axes` is
+        not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    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.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[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 over which the DST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse 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.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    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 : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the DCT matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
+    ``norm="forward"`` the ``1/N`` normalization is applied to the forward
+    `dct` instead and the `idct` is unnormalized.
+
+    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="backward"``)
+
+    .. 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 ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
+    scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
+    by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    .. 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="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
+    when combined with ``norm="ortho"``, 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="backward"``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
+    :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    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="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    ``orthogonalize`` has no effect here, as the DCT-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    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.fft 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 (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    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 : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    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)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform. To
+                 recover it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the IDCT matrix (see `dct` for the full
+    definitions).
+
+    'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
+
+    The IDCT is equivalent to a normal DCT except for the normalization and
+    type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
+    other's inverses.
+
+    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.fft 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)
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    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 : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
+
+    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="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
+    :math:`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 :math:`2(N+1)`.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    ``orthogonalize`` has no effect here, as the DST-I matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
+    :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`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 ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
+    combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
+    even around :math:`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)
+
+    If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
+    which, when combined with ``norm="ortho"``, makes the corresponding matrix
+    of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and
+    even around :math:`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)
+
+    ``orthogonalize`` has no effect here, as the DST-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    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 : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see `dst` for the full
+    definitions).
+
+    'The' IDST is the IDST-II, which is the same as the normalized DST-III.
+
+    The IDST is equivalent to a normal DST except for the normalization and
+    type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
+    other's inverses.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_realtransforms_backend.py b/python_embeded/Lib/site-packages/scipy/fft/_realtransforms_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..96f6f14de702da8387990ba77153651f180b6515
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_realtransforms_backend.py
@@ -0,0 +1,63 @@
+from scipy._lib._array_api import array_namespace
+import numpy as np
+from . import _pocketfft
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+def _execute(pocketfft_func, x, type, s, axes, norm, 
+             overwrite_x, workers, orthogonalize):
+    xp = array_namespace(x)
+    x = np.asarray(x)
+    y = pocketfft_func(x, type, s, axes, norm,
+                       overwrite_x=overwrite_x, workers=workers,
+                       orthogonalize=orthogonalize)
+    return xp.asarray(y)
+
+
+def dctn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.dctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idctn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dstn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idstn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/__init__.py b/python_embeded/Lib/site-packages/scipy/fftpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85efa83fd939a01ef8f26e232e69da4843f1886f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/_basic.py b/python_embeded/Lib/site-packages/scipy/fftpack/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb1de9e8ba468e33efe8959e98a7fea9b9ec20d2
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/_helper.py b/python_embeded/Lib/site-packages/scipy/fftpack/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..38cdc97ee379c78e30b6ece43e4c78d3b7ff85cc
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/_pseudo_diffs.py b/python_embeded/Lib/site-packages/scipy/fftpack/_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5cc5cf1e35e7d090ce864aad1447109f09fc4c0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/_realtransforms.py b/python_embeded/Lib/site-packages/scipy/fftpack/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ea2d90ac5aea6b137b979fbc5f032539f52acca
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/basic.py b/python_embeded/Lib/site-packages/scipy/fftpack/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..479eea61de9f1451c26d1fcf2a443c5b9618fe59
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/convolve.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/fftpack/convolve.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..07a40792f619c121a51d53a438eb41763b58b099
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/fftpack/convolve.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/helper.py b/python_embeded/Lib/site-packages/scipy/fftpack/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed7b92403fdf36349abd4bc0d4204baef22fc7df
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/pseudo_diffs.py b/python_embeded/Lib/site-packages/scipy/fftpack/pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d67ffdff0521c5968c30e002c3877e00591f3f3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/fftpack/realtransforms.py b/python_embeded/Lib/site-packages/scipy/fftpack/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dc0ba5cb5538e566afb6ee8d62e3e8535925cb5
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/integrate/__init__.py b/python_embeded/Lib/site-packages/scipy/integrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f50a3d5c7d0a69ebd636daf634edaa793279a788
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/__init__.py
@@ -0,0 +1,122 @@
+"""
+=============================================
+Integration and ODEs (:mod:`scipy.integrate`)
+=============================================
+
+.. currentmodule:: scipy.integrate
+
+Integrating functions, given function object
+============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   quad          -- General purpose integration
+   quad_vec      -- General purpose integration of vector-valued functions
+   cubature      -- General purpose multi-dimensional integration of array-valued functions
+   dblquad       -- General purpose double integration
+   tplquad       -- General purpose triple integration
+   nquad         -- General purpose N-D integration
+   tanhsinh      -- General purpose elementwise integration
+   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
+   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
+   lebedev_rule
+   qmc_quad      -- N-D integration using Quasi-Monte Carlo quadrature
+   IntegrationWarning -- Warning on issues during integration
+
+
+Integrating functions, given fixed samples
+==========================================
+
+.. autosummary::
+   :toctree: generated/
+
+   trapezoid            -- Use trapezoidal rule to compute integral.
+   cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
+   simpson              -- Use Simpson's rule to compute integral from samples.
+   cumulative_simpson   -- Use Simpson's rule to cumulatively compute integral from samples.
+   romb                 -- Use Romberg Integration to compute integral from
+                        -- (2**k + 1) evenly-spaced samples.
+
+.. seealso::
+
+   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
+   quadrature roots and weights for other weighting factors and regions.
+
+Summation
+=========
+
+.. autosummary::
+   :toctree: generated/
+
+   nsum
+
+Solving initial value problems for ODE systems
+==============================================
+
+The solvers are implemented as individual classes, which can be used directly
+(low-level usage) or through a convenience function.
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_ivp     -- Convenient function for ODE integration.
+   RK23          -- Explicit Runge-Kutta solver of order 3(2).
+   RK45          -- Explicit Runge-Kutta solver of order 5(4).
+   DOP853        -- Explicit Runge-Kutta solver of order 8.
+   Radau         -- Implicit Runge-Kutta solver of order 5.
+   BDF           -- Implicit multi-step variable order (1 to 5) solver.
+   LSODA         -- LSODA solver from ODEPACK Fortran package.
+   OdeSolver     -- Base class for ODE solvers.
+   DenseOutput   -- Local interpolant for computing a dense output.
+   OdeSolution   -- Class which represents a continuous ODE solution.
+
+
+Old API
+-------
+
+These are the routines developed earlier for SciPy. They wrap older solvers
+implemented in Fortran (mostly ODEPACK). While the interface to them is not
+particularly convenient and certain features are missing compared to the new
+API, the solvers themselves are of good quality and work fast as compiled
+Fortran code. In some cases, it might be worth using this old API.
+
+.. autosummary::
+   :toctree: generated/
+
+   odeint        -- General integration of ordinary differential equations.
+   ode           -- Integrate ODE using VODE and ZVODE routines.
+   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
+   ODEintWarning -- Warning raised during the execution of `odeint`.
+
+
+Solving boundary value problems for ODE systems
+===============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_bvp     -- Solve a boundary value problem for a system of ODEs.
+"""  # noqa: E501
+
+
+from ._quadrature import *
+from ._odepack_py import *
+from ._quadpack_py import *
+from ._ode import *
+from ._bvp import solve_bvp
+from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
+                   OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
+from ._quad_vec import quad_vec
+from ._tanhsinh import nsum, tanhsinh
+from ._cubature import cubature
+from ._lebedev import lebedev_rule
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import dop, lsoda, vode, odepack, quadpack
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_bvp.py b/python_embeded/Lib/site-packages/scipy/integrate/_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1291fc56ffa98b3b9fbbea750d071fb1d703b7b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_bvp.py
@@ -0,0 +1,1154 @@
+"""Boundary value problem solver."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import pinv
+
+from scipy.sparse import coo_matrix, csc_matrix
+from scipy.sparse.linalg import splu
+from scipy.optimize import OptimizeResult
+
+
+EPS = np.finfo(float).eps
+
+
+def estimate_fun_jac(fun, x, y, p, f0=None):
+    """Estimate derivatives of an ODE system rhs with forward differences.
+
+    Returns
+    -------
+    df_dy : ndarray, shape (n, n, m)
+        Derivatives with respect to y. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q) / d (y_q)_j.
+    df_dp : ndarray with shape (n, k, m) or None
+        Derivatives with respect to p. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
+    """
+    n, m = y.shape
+    if f0 is None:
+        f0 = fun(x, y, p)
+
+    dtype = y.dtype
+
+    df_dy = np.empty((n, n, m), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(y))
+    for i in range(n):
+        y_new = y.copy()
+        y_new[i] += h[i]
+        hi = y_new[i] - y[i]
+        f_new = fun(x, y_new, p)
+        df_dy[:, i, :] = (f_new - f0) / hi
+
+    k = p.shape[0]
+    if k == 0:
+        df_dp = None
+    else:
+        df_dp = np.empty((n, k, m), dtype=dtype)
+        h = EPS**0.5 * (1 + np.abs(p))
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            f_new = fun(x, y, p_new)
+            df_dp[:, i, :] = (f_new - f0) / hi
+
+    return df_dy, df_dp
+
+
+def estimate_bc_jac(bc, ya, yb, p, bc0=None):
+    """Estimate derivatives of boundary conditions with forward differences.
+
+    Returns
+    -------
+    dbc_dya : ndarray, shape (n + k, n)
+        Derivatives with respect to ya. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dyb : ndarray, shape (n + k, n)
+        Derivatives with respect to yb. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dp : ndarray with shape (n + k, k) or None
+        Derivatives with respect to p. An element (i, j) corresponds to
+        d bc_i / d p_j. If `p` is empty, None is returned.
+    """
+    n = ya.shape[0]
+    k = p.shape[0]
+
+    if bc0 is None:
+        bc0 = bc(ya, yb, p)
+
+    dtype = ya.dtype
+
+    dbc_dya = np.empty((n, n + k), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(ya))
+    for i in range(n):
+        ya_new = ya.copy()
+        ya_new[i] += h[i]
+        hi = ya_new[i] - ya[i]
+        bc_new = bc(ya_new, yb, p)
+        dbc_dya[i] = (bc_new - bc0) / hi
+    dbc_dya = dbc_dya.T
+
+    h = EPS**0.5 * (1 + np.abs(yb))
+    dbc_dyb = np.empty((n, n + k), dtype=dtype)
+    for i in range(n):
+        yb_new = yb.copy()
+        yb_new[i] += h[i]
+        hi = yb_new[i] - yb[i]
+        bc_new = bc(ya, yb_new, p)
+        dbc_dyb[i] = (bc_new - bc0) / hi
+    dbc_dyb = dbc_dyb.T
+
+    if k == 0:
+        dbc_dp = None
+    else:
+        h = EPS**0.5 * (1 + np.abs(p))
+        dbc_dp = np.empty((k, n + k), dtype=dtype)
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            bc_new = bc(ya, yb, p_new)
+            dbc_dp[i] = (bc_new - bc0) / hi
+        dbc_dp = dbc_dp.T
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def compute_jac_indices(n, m, k):
+    """Compute indices for the collocation system Jacobian construction.
+
+    See `construct_global_jac` for the explanation.
+    """
+    i_col = np.repeat(np.arange((m - 1) * n), n)
+    j_col = (np.tile(np.arange(n), n * (m - 1)) +
+             np.repeat(np.arange(m - 1) * n, n**2))
+
+    i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
+    j_bc = np.tile(np.arange(n), n + k)
+
+    i_p_col = np.repeat(np.arange((m - 1) * n), k)
+    j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
+
+    i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
+    j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
+
+    i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
+    j = np.hstack((j_col, j_col + n,
+                   j_bc, j_bc + (m - 1) * n,
+                   j_p_col, j_p_bc))
+
+    return i, j
+
+
+def stacked_matmul(a, b):
+    """Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
+
+    Empirical optimization. Use outer Python loop and BLAS for large
+    matrices, otherwise use a single einsum call.
+    """
+    if a.shape[1] > 50:
+        out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
+        for i in range(a.shape[0]):
+            out[i] = np.dot(a[i], b[i])
+        return out
+    else:
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+
+def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
+                         df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
+    """Construct the Jacobian of the collocation system.
+
+    There are n * m + k functions: m - 1 collocations residuals, each
+    containing n components, followed by n + k boundary condition residuals.
+
+    There are n * m + k variables: m vectors of y, each containing n
+    components, followed by k values of vector p.
+
+    For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
+    the following sparsity structure:
+
+        1 1 2 2 0 0 0 0  5
+        1 1 2 2 0 0 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 0 0 1 1 2 2  5
+        0 0 0 0 1 1 2 2  5
+
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+
+    Zeros denote identically zero values, other values denote different kinds
+    of blocks in the matrix (see below). The blank row indicates the separation
+    of collocation residuals from boundary conditions. And the blank column
+    indicates the separation of y values from p values.
+
+    Refer to [1]_  (p. 306) for the formula of n x n blocks for derivatives
+    of collocation residuals with respect to y.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    k : int
+        Number of the unknown parameters.
+    i_jac, j_jac : ndarray
+        Row and column indices returned by `compute_jac_indices`. They
+        represent different blocks in the Jacobian matrix in the following
+        order (see the scheme above):
+
+            * 1: m - 1 diagonal n x n blocks for the collocation residuals.
+            * 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
+            * 3 : (n + k) x n block for the dependency of the boundary
+              conditions on ya.
+            * 4: (n + k) x n block for the dependency of the boundary
+              conditions on yb.
+            * 5: (m - 1) * n x k block for the dependency of the collocation
+              residuals on p.
+            * 6: (n + k) x k block for the dependency of the boundary
+              conditions on p.
+
+    df_dy : ndarray, shape (n, n, m)
+        Jacobian of f with respect to y computed at the mesh nodes.
+    df_dy_middle : ndarray, shape (n, n, m - 1)
+        Jacobian of f with respect to y computed at the middle between the
+        mesh nodes.
+    df_dp : ndarray with shape (n, k, m) or None
+        Jacobian of f with respect to p computed at the mesh nodes.
+    df_dp_middle : ndarray with shape (n, k, m - 1) or None
+        Jacobian of f with respect to p computed at the middle between the
+        mesh nodes.
+    dbc_dya, dbc_dyb : ndarray, shape (n, n)
+        Jacobian of bc with respect to ya and yb.
+    dbc_dp : ndarray with shape (n, k) or None
+        Jacobian of bc with respect to p.
+
+    Returns
+    -------
+    J : csc_matrix, shape (n * m + k, n * m + k)
+        Jacobian of the collocation system in a sparse form.
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    df_dy = np.transpose(df_dy, (2, 0, 1))
+    df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
+
+    h = h[:, np.newaxis, np.newaxis]
+
+    dtype = df_dy.dtype
+
+    # Computing diagonal n x n blocks.
+    dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_0[:] = -np.identity(n)
+    dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[:-1])
+    dPhi_dy_0 -= h**2 / 12 * T
+
+    # Computing off-diagonal n x n blocks.
+    dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_1[:] = np.identity(n)
+    dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[1:])
+    dPhi_dy_1 += h**2 / 12 * T
+
+    values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
+                        dbc_dyb.ravel()))
+
+    if k > 0:
+        df_dp = np.transpose(df_dp, (2, 0, 1))
+        df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
+        T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
+        df_dp_middle += 0.125 * h * T
+        dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
+        values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
+
+    J = coo_matrix((values, (i_jac, j_jac)))
+    return csc_matrix(J)
+
+
+def collocation_fun(fun, y, p, x, h):
+    """Evaluate collocation residuals.
+
+    This function lies in the core of the method. The solution is sought
+    as a cubic C1 continuous spline with derivatives matching the ODE rhs
+    at given nodes `x`. Collocation conditions are formed from the equality
+    of the spline derivatives and rhs of the ODE system in the middle points
+    between nodes.
+
+    Such method is classified to Lobbato IIIA family in ODE literature.
+    Refer to [1]_ for the formula and some discussion.
+
+    Returns
+    -------
+    col_res : ndarray, shape (n, m - 1)
+        Collocation residuals at the middle points of the mesh intervals.
+    y_middle : ndarray, shape (n, m - 1)
+        Values of the cubic spline evaluated at the middle points of the mesh
+        intervals.
+    f : ndarray, shape (n, m)
+        RHS of the ODE system evaluated at the mesh nodes.
+    f_middle : ndarray, shape (n, m - 1)
+        RHS of the ODE system evaluated at the middle points of the mesh
+        intervals (and using `y_middle`).
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    """
+    f = fun(x, y, p)
+    y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
+                0.125 * h * (f[:, 1:] - f[:, :-1]))
+    f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
+    col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
+                                              4 * f_middle)
+
+    return col_res, y_middle, f, f_middle
+
+
+def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
+    """Create the function and the Jacobian for the collocation system."""
+    x_middle = x[:-1] + 0.5 * h
+    i_jac, j_jac = compute_jac_indices(n, m, k)
+
+    def col_fun(y, p):
+        return collocation_fun(fun, y, p, x, h)
+
+    def sys_jac(y, p, y_middle, f, f_middle, bc0):
+        if fun_jac is None:
+            df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
+            df_dy_middle, df_dp_middle = estimate_fun_jac(
+                fun, x_middle, y_middle, p, f_middle)
+        else:
+            df_dy, df_dp = fun_jac(x, y, p)
+            df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
+
+        if bc_jac is None:
+            dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
+                                                       p, bc0)
+        else:
+            dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
+
+        return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
+                                    df_dy_middle, df_dp, df_dp_middle, dbc_dya,
+                                    dbc_dyb, dbc_dp)
+
+    return col_fun, sys_jac
+
+
+def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
+    """Solve the nonlinear collocation system by a Newton method.
+
+    This is a simple Newton method with a backtracking line search. As
+    advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
+    is used, where J is the Jacobian matrix at the current iteration and r is
+    the vector or collocation residuals (values of the system lhs).
+
+    The method alters between full Newton iterations and the fixed-Jacobian
+    iterations based
+
+    There are other tricks proposed in [1]_, but they are not used as they
+    don't seem to improve anything significantly, and even break the
+    convergence on some test problems I tried.
+
+    All important parameters of the algorithm are defined inside the function.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    h : ndarray, shape (m-1,)
+        Mesh intervals.
+    col_fun : callable
+        Function computing collocation residuals.
+    bc : callable
+        Function computing boundary condition residuals.
+    jac : callable
+        Function computing the Jacobian of the whole system (including
+        collocation and boundary condition residuals). It is supposed to
+        return csc_matrix.
+    y : ndarray, shape (n, m)
+        Initial guess for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Initial guess for the unknown parameters.
+    B : ndarray with shape (n, n) or None
+        Matrix to force the S y(a) = 0 condition for a problems with the
+        singular term. If None, the singular term is assumed to be absent.
+    bvp_tol : float
+        Tolerance to which we want to solve a BVP.
+    bc_tol : float
+        Tolerance to which we want to satisfy the boundary conditions.
+
+    Returns
+    -------
+    y : ndarray, shape (n, m)
+        Final iterate for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Final iterate for the unknown parameters.
+    singular : bool
+        True, if the LU decomposition failed because Jacobian turned out
+        to be singular.
+
+    References
+    ----------
+    .. [1]  U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+       Boundary Value Problems for Ordinary Differential Equations"
+    """
+    # We know that the solution residuals at the middle points of the mesh
+    # are connected with collocation residuals  r_middle = 1.5 * col_res / h.
+    # As our BVP solver tries to decrease relative residuals below a certain
+    # tolerance, it seems reasonable to terminated Newton iterations by
+    # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
+    # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
+    # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
+    # should be computed as follows:
+    tol_r = 2/3 * h * 5e-2 * bvp_tol
+
+    # Maximum allowed number of Jacobian evaluation and factorization, in
+    # other words, the maximum number of full Newton iterations. A small value
+    # is recommended in the literature.
+    max_njev = 4
+
+    # Maximum number of iterations, considering that some of them can be
+    # performed with the fixed Jacobian. In theory, such iterations are cheap,
+    # but it's not that simple in Python.
+    max_iter = 8
+
+    # Minimum relative improvement of the criterion function to accept the
+    # step (Armijo constant).
+    sigma = 0.2
+
+    # Step size decrease factor for backtracking.
+    tau = 0.5
+
+    # Maximum number of backtracking steps, the minimum step is then
+    # tau ** n_trial.
+    n_trial = 4
+
+    col_res, y_middle, f, f_middle = col_fun(y, p)
+    bc_res = bc(y[:, 0], y[:, -1], p)
+    res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+    njev = 0
+    singular = False
+    recompute_jac = True
+    for iteration in range(max_iter):
+        if recompute_jac:
+            J = jac(y, p, y_middle, f, f_middle, bc_res)
+            njev += 1
+            try:
+                LU = splu(J)
+            except RuntimeError:
+                singular = True
+                break
+
+            step = LU.solve(res)
+            cost = np.dot(step, step)
+
+        y_step = step[:m * n].reshape((n, m), order='F')
+        p_step = step[m * n:]
+
+        alpha = 1
+        for trial in range(n_trial + 1):
+            y_new = y - alpha * y_step
+            if B is not None:
+                y_new[:, 0] = np.dot(B, y_new[:, 0])
+            p_new = p - alpha * p_step
+
+            col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
+            bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
+            res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+            step_new = LU.solve(res)
+            cost_new = np.dot(step_new, step_new)
+            if cost_new < (1 - 2 * alpha * sigma) * cost:
+                break
+
+            if trial < n_trial:
+                alpha *= tau
+
+        y = y_new
+        p = p_new
+
+        if njev == max_njev:
+            break
+
+        if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
+                np.all(np.abs(bc_res) < bc_tol)):
+            break
+
+        # If the full step was taken, then we are going to continue with
+        # the same Jacobian. This is the approach of BVP_SOLVER.
+        if alpha == 1:
+            step = step_new
+            cost = cost_new
+            recompute_jac = False
+        else:
+            recompute_jac = True
+
+    return y, p, singular
+
+
+def print_iteration_header():
+    print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
+          f"{'Total nodes':^15}{'Nodes added':^15}")
+
+
+def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
+                             nodes_added):
+    print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
+          f"{total_nodes:^15}{nodes_added:^15}")
+
+
+class BVPResult(OptimizeResult):
+    pass
+
+
+TERMINATION_MESSAGES = {
+    0: "The algorithm converged to the desired accuracy.",
+    1: "The maximum number of mesh nodes is exceeded.",
+    2: "A singular Jacobian encountered when solving the collocation system.",
+    3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
+}
+
+
+def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
+    """Estimate rms values of collocation residuals using Lobatto quadrature.
+
+    The residuals are defined as the difference between the derivatives of
+    our solution and rhs of the ODE system. We use relative residuals, i.e.,
+    normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
+    normalized integrals of the squared relative residuals over each interval.
+    Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
+    fact that residuals at the mesh nodes are identically zero.
+
+    In [2] they don't normalize integrals by interval lengths, which gives
+    a higher rate of convergence of the residuals by the factor of h**0.5.
+    I chose to do such normalization for an ease of interpretation of return
+    values as RMS estimates.
+
+    Returns
+    -------
+    rms_res : ndarray, shape (m - 1,)
+        Estimated rms values of the relative residuals over each interval.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
+    .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    x_middle = x[:-1] + 0.5 * h
+    s = 0.5 * h * (3/7)**0.5
+    x1 = x_middle + s
+    x2 = x_middle - s
+    y1 = sol(x1)
+    y2 = sol(x2)
+    y1_prime = sol(x1, 1)
+    y2_prime = sol(x2, 1)
+    f1 = fun(x1, y1, p)
+    f2 = fun(x2, y2, p)
+    r1 = y1_prime - f1
+    r2 = y2_prime - f2
+
+    r_middle /= 1 + np.abs(f_middle)
+    r1 /= 1 + np.abs(f1)
+    r2 /= 1 + np.abs(f2)
+
+    r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
+    r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
+    r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
+
+    return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
+
+
+def create_spline(y, yp, x, h):
+    """Create a cubic spline given values and derivatives.
+
+    Formulas for the coefficients are taken from interpolate.CubicSpline.
+
+    Returns
+    -------
+    sol : PPoly
+        Constructed spline as a PPoly instance.
+    """
+    from scipy.interpolate import PPoly
+
+    n, m = y.shape
+    c = np.empty((4, n, m - 1), dtype=y.dtype)
+    slope = (y[:, 1:] - y[:, :-1]) / h
+    t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
+    c[0] = t / h
+    c[1] = (slope - yp[:, :-1]) / h - t
+    c[2] = yp[:, :-1]
+    c[3] = y[:, :-1]
+    c = np.moveaxis(c, 1, 0)
+
+    return PPoly(c, x, extrapolate=True, axis=1)
+
+
+def modify_mesh(x, insert_1, insert_2):
+    """Insert nodes into a mesh.
+
+    Nodes removal logic is not established, its impact on the solver is
+    presumably negligible. So, only insertion is done in this function.
+
+    Parameters
+    ----------
+    x : ndarray, shape (m,)
+        Mesh nodes.
+    insert_1 : ndarray
+        Intervals to each insert 1 new node in the middle.
+    insert_2 : ndarray
+        Intervals to each insert 2 new nodes, such that divide an interval
+        into 3 equal parts.
+
+    Returns
+    -------
+    x_new : ndarray
+        New mesh nodes.
+
+    Notes
+    -----
+    `insert_1` and `insert_2` should not have common values.
+    """
+    # Because np.insert implementation apparently varies with a version of
+    # NumPy, we use a simple and reliable approach with sorting.
+    return np.sort(np.hstack((
+        x,
+        0.5 * (x[insert_1] + x[insert_1 + 1]),
+        (2 * x[insert_2] + x[insert_2 + 1]) / 3,
+        (x[insert_2] + 2 * x[insert_2 + 1]) / 3
+    )))
+
+
+def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
+    """Wrap functions for unified usage in the solver."""
+    if fun_jac is None:
+        fun_jac_wrapped = None
+
+    if bc_jac is None:
+        bc_jac_wrapped = None
+
+    if k == 0:
+        def fun_p(x, y, _):
+            return np.asarray(fun(x, y), dtype)
+
+        def bc_wrapped(ya, yb, _):
+            return np.asarray(bc(ya, yb), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, _):
+                return np.asarray(fun_jac(x, y), dtype), None
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, _):
+                dbc_dya, dbc_dyb = bc_jac(ya, yb)
+                return (np.asarray(dbc_dya, dtype),
+                        np.asarray(dbc_dyb, dtype), None)
+    else:
+        def fun_p(x, y, p):
+            return np.asarray(fun(x, y, p), dtype)
+
+        def bc_wrapped(x, y, p):
+            return np.asarray(bc(x, y, p), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, p):
+                df_dy, df_dp = fun_jac(x, y, p)
+                return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, p):
+                dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
+                return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
+                        np.asarray(dbc_dp, dtype))
+
+    if S is None:
+        fun_wrapped = fun_p
+    else:
+        def fun_wrapped(x, y, p):
+            f = fun_p(x, y, p)
+            if x[0] == a:
+                f[:, 0] = np.dot(D, f[:, 0])
+                f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
+            else:
+                f += np.dot(S, y) / (x - a)
+            return f
+
+    if fun_jac is not None:
+        if S is None:
+            fun_jac_wrapped = fun_jac_p
+        else:
+            Sr = S[:, :, np.newaxis]
+
+            def fun_jac_wrapped(x, y, p):
+                df_dy, df_dp = fun_jac_p(x, y, p)
+                if x[0] == a:
+                    df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
+                    df_dy[:, :, 1:] += Sr / (x[1:] - a)
+                else:
+                    df_dy += Sr / (x - a)
+
+                return df_dy, df_dp
+
+    return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
+
+
+def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
+              tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
+    """Solve a boundary value problem for a system of ODEs.
+
+    This function numerically solves a first order system of ODEs subject to
+    two-point boundary conditions::
+
+        dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
+        bc(y(a), y(b), p) = 0
+
+    Here x is a 1-D independent variable, y(x) is an n-D
+    vector-valued function and p is a k-D vector of unknown
+    parameters which is to be found along with y(x). For the problem to be
+    determined, there must be n + k boundary conditions, i.e., bc must be an
+    (n + k)-D function.
+
+    The last singular term on the right-hand side of the system is optional.
+    It is defined by an n-by-n matrix S, such that the solution must satisfy
+    S y(a) = 0. This condition will be forced during iterations, so it must not
+    contradict boundary conditions. See [2]_ for the explanation how this term
+    is handled when solving BVPs numerically.
+
+    Problems in a complex domain can be solved as well. In this case, y and p
+    are considered to be complex, and f and bc are assumed to be complex-valued
+    functions, but x stays real. Note that f and bc must be complex
+    differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
+    should rewrite your problem for real and imaginary parts separately. To
+    solve a problem in a complex domain, pass an initial guess for y with a
+    complex data type (see below).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(x, y)``,
+        or ``fun(x, y, p)`` if parameters are present. All arguments are
+        ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
+        ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
+        return value must be an array with shape (n, m) and with the same
+        layout as ``y``.
+    bc : callable
+        Function evaluating residuals of the boundary conditions. The calling
+        signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
+        present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
+        and ``p`` with shape (k,). The return value must be an array with
+        shape (n + k,).
+    x : array_like, shape (m,)
+        Initial mesh. Must be a strictly increasing sequence of real numbers
+        with ``x[0]=a`` and ``x[-1]=b``.
+    y : array_like, shape (n, m)
+        Initial guess for the function values at the mesh nodes, ith column
+        corresponds to ``x[i]``. For problems in a complex domain pass `y`
+        with a complex data type (even if the initial guess is purely real).
+    p : array_like with shape (k,) or None, optional
+        Initial guess for the unknown parameters. If None (default), it is
+        assumed that the problem doesn't depend on any parameters.
+    S : array_like with shape (n, n) or None
+        Matrix defining the singular term. If None (default), the problem is
+        solved without the singular term.
+    fun_jac : callable or None, optional
+        Function computing derivatives of f with respect to y and p. The
+        calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
+        parameters are present. The return must contain 1 or 2 elements in the
+        following order:
+
+            * df_dy : array_like with shape (n, n, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
+            * df_dp : array_like with shape (n, k, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
+
+        Here q numbers nodes at which x and y are defined, whereas i and j
+        number vector components. If the problem is solved without unknown
+        parameters, df_dp should not be returned.
+
+        If `fun_jac` is None (default), the derivatives will be estimated
+        by the forward finite differences.
+    bc_jac : callable or None, optional
+        Function computing derivatives of bc with respect to ya, yb, and p.
+        The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
+        if parameters are present. The return must contain 2 or 3 elements in
+        the following order:
+
+            * dbc_dya : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d ya_j.
+            * dbc_dyb : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d yb_j.
+            * dbc_dp : array_like with shape (n, k), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d p_j.
+
+        If the problem is solved without unknown parameters, dbc_dp should not
+        be returned.
+
+        If `bc_jac` is None (default), the derivatives will be estimated by
+        the forward finite differences.
+    tol : float, optional
+        Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
+        where y is the found solution, then the solver tries to achieve on each
+        mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
+        estimated in a root mean squared sense (using a numerical quadrature
+        formula). Default is 1e-3.
+    max_nodes : int, optional
+        Maximum allowed number of the mesh nodes. If exceeded, the algorithm
+        terminates. Default is 1000.
+    verbose : {0, 1, 2}, optional
+        Level of algorithm's verbosity:
+
+            * 0 (default) : work silently.
+            * 1 : display a termination report.
+            * 2 : display progress during iterations.
+    bc_tol : float, optional
+        Desired absolute tolerance for the boundary condition residuals: `bc`
+        value should satisfy ``abs(bc) < bc_tol`` component-wise.
+        Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
+        tolerance.
+
+    Returns
+    -------
+    Bunch object with the following fields defined:
+    sol : PPoly
+        Found solution for y as `scipy.interpolate.PPoly` instance, a C1
+        continuous cubic spline.
+    p : ndarray or None, shape (k,)
+        Found parameters. None, if the parameters were not present in the
+        problem.
+    x : ndarray, shape (m,)
+        Nodes of the final mesh.
+    y : ndarray, shape (n, m)
+        Solution values at the mesh nodes.
+    yp : ndarray, shape (n, m)
+        Solution derivatives at the mesh nodes.
+    rms_residuals : ndarray, shape (m - 1,)
+        RMS values of the relative residuals over each mesh interval (see the
+        description of `tol` parameter).
+    niter : int
+        Number of completed iterations.
+    status : int
+        Reason for algorithm termination:
+
+            * 0: The algorithm converged to the desired accuracy.
+            * 1: The maximum number of mesh nodes is exceeded.
+            * 2: A singular Jacobian encountered when solving the collocation
+              system.
+
+    message : string
+        Verbal description of the termination reason.
+    success : bool
+        True if the algorithm converged to the desired accuracy (``status=0``).
+
+    Notes
+    -----
+    This function implements a 4th order collocation algorithm with the
+    control of residuals similar to [1]_. A collocation system is solved
+    by a damped Newton method with an affine-invariant criterion function as
+    described in [3]_.
+
+    Note that in [1]_  integral residuals are defined without normalization
+    by interval lengths. So, their definition is different by a multiplier of
+    h**0.5 (h is an interval length) from the definition used here.
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
+           Solver".
+    .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+           Boundary Value Problems for Ordinary Differential Equations".
+    .. [4] `Cauchy-Riemann equations
+            `_ on
+            Wikipedia.
+
+    Examples
+    --------
+    In the first example, we solve Bratu's problem::
+
+        y'' + k * exp(y) = 0
+        y(0) = y(1) = 0
+
+    for k = 1.
+
+    We rewrite the equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -exp(y1)
+
+    >>> import numpy as np
+    >>> def fun(x, y):
+    ...     return np.vstack((y[1], -np.exp(y[0])))
+
+    Implement evaluation of the boundary condition residuals:
+
+    >>> def bc(ya, yb):
+    ...     return np.array([ya[0], yb[0]])
+
+    Define the initial mesh with 5 nodes:
+
+    >>> x = np.linspace(0, 1, 5)
+
+    This problem is known to have two solutions. To obtain both of them, we
+    use two different initial guesses for y. We denote them by subscripts
+    a and b.
+
+    >>> y_a = np.zeros((2, x.size))
+    >>> y_b = np.zeros((2, x.size))
+    >>> y_b[0] = 3
+
+    Now we are ready to run the solver.
+
+    >>> from scipy.integrate import solve_bvp
+    >>> res_a = solve_bvp(fun, bc, x, y_a)
+    >>> res_b = solve_bvp(fun, bc, x, y_b)
+
+    Let's plot the two found solutions. We take an advantage of having the
+    solution in a spline form to produce a smooth plot.
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot_a = res_a.sol(x_plot)[0]
+    >>> y_plot_b = res_b.sol(x_plot)[0]
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x_plot, y_plot_a, label='y_a')
+    >>> plt.plot(x_plot, y_plot_b, label='y_b')
+    >>> plt.legend()
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+
+    We see that the two solutions have similar shape, but differ in scale
+    significantly.
+
+    In the second example, we solve a simple Sturm-Liouville problem::
+
+        y'' + k**2 * y = 0
+        y(0) = y(1) = 0
+
+    It is known that a non-trivial solution y = A * sin(k * x) is possible for
+    k = pi * n, where n is an integer. To establish the normalization constant
+    A = 1 we add a boundary condition::
+
+        y'(0) = k
+
+    Again, we rewrite our equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -k**2 * y1
+
+    >>> def fun(x, y, p):
+    ...     k = p[0]
+    ...     return np.vstack((y[1], -k**2 * y[0]))
+
+    Note that parameters p are passed as a vector (with one element in our
+    case).
+
+    Implement the boundary conditions:
+
+    >>> def bc(ya, yb, p):
+    ...     k = p[0]
+    ...     return np.array([ya[0], yb[0], ya[1] - k])
+
+    Set up the initial mesh and guess for y. We aim to find the solution for
+    k = 2 * pi, to achieve that we set values of y to approximately follow
+    sin(2 * pi * x):
+
+    >>> x = np.linspace(0, 1, 5)
+    >>> y = np.zeros((2, x.size))
+    >>> y[0, 1] = 1
+    >>> y[0, 3] = -1
+
+    Run the solver with 6 as an initial guess for k.
+
+    >>> sol = solve_bvp(fun, bc, x, y, p=[6])
+
+    We see that the found k is approximately correct:
+
+    >>> sol.p[0]
+    6.28329460046
+
+    And, finally, plot the solution to see the anticipated sinusoid:
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot = sol.sol(x_plot)[0]
+    >>> plt.plot(x_plot, y_plot)
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+    """
+    x = np.asarray(x, dtype=float)
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1 dimensional.")
+    h = np.diff(x)
+    if np.any(h <= 0):
+        raise ValueError("`x` must be strictly increasing.")
+    a = x[0]
+
+    y = np.asarray(y)
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+    y = y.astype(dtype, copy=False)
+
+    if y.ndim != 2:
+        raise ValueError("`y` must be 2 dimensional.")
+    if y.shape[1] != x.shape[0]:
+        raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
+                         f"has {y.shape[1]}.")
+
+    if p is None:
+        p = np.array([])
+    else:
+        p = np.asarray(p, dtype=dtype)
+    if p.ndim != 1:
+        raise ValueError("`p` must be 1 dimensional.")
+
+    if tol < 100 * EPS:
+        warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
+        tol = 100 * EPS
+
+    if verbose not in [0, 1, 2]:
+        raise ValueError("`verbose` must be in [0, 1, 2].")
+
+    n = y.shape[0]
+    k = p.shape[0]
+
+    if S is not None:
+        S = np.asarray(S, dtype=dtype)
+        if S.shape != (n, n):
+            raise ValueError(f"`S` is expected to have shape {(n, n)}, "
+                             f"but actually has {S.shape}")
+
+        # Compute I - S^+ S to impose necessary boundary conditions.
+        B = np.identity(n) - np.dot(pinv(S), S)
+
+        y[:, 0] = np.dot(B, y[:, 0])
+
+        # Compute (I - S)^+ to correct derivatives at x=a.
+        D = pinv(np.identity(n) - S)
+    else:
+        B = None
+        D = None
+
+    if bc_tol is None:
+        bc_tol = tol
+
+    # Maximum number of iterations
+    max_iteration = 10
+
+    fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
+        fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
+
+    f = fun_wrapped(x, y, p)
+    if f.shape != y.shape:
+        raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
+                         f"but actually has {f.shape}.")
+
+    bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+    if bc_res.shape != (n + k,):
+        raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
+                         f"but actually has {bc_res.shape}.")
+
+    status = 0
+    iteration = 0
+    if verbose == 2:
+        print_iteration_header()
+
+    while True:
+        m = x.shape[0]
+
+        col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
+                                       fun_jac_wrapped, bc_jac_wrapped, x, h)
+        y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
+                                      y, p, B, tol, bc_tol)
+        iteration += 1
+
+        col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
+                                                         p, x, h)
+        bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+        max_bc_res = np.max(abs(bc_res))
+
+        # This relation is not trivial, but can be verified.
+        r_middle = 1.5 * col_res / h
+        sol = create_spline(y, f, x, h)
+        rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
+                                         r_middle, f_middle)
+        max_rms_res = np.max(rms_res)
+
+        if singular:
+            status = 2
+            break
+
+        insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
+        insert_2, = np.nonzero(rms_res >= 100 * tol)
+        nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
+
+        if m + nodes_added > max_nodes:
+            status = 1
+            if verbose == 2:
+                nodes_added = f"({nodes_added})"
+                print_iteration_progress(iteration, max_rms_res, max_bc_res,
+                                         m, nodes_added)
+            break
+
+        if verbose == 2:
+            print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
+                                     nodes_added)
+
+        if nodes_added > 0:
+            x = modify_mesh(x, insert_1, insert_2)
+            h = np.diff(x)
+            y = sol(x)
+        elif max_bc_res <= bc_tol:
+            status = 0
+            break
+        elif iteration >= max_iteration:
+            status = 3
+            break
+
+    if verbose > 0:
+        if status == 0:
+            print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 1:
+            print(f"Number of nodes is exceeded after iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 2:
+            print("Singular Jacobian encountered when solving the collocation "
+                  f"system on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 3:
+            print("The solver was unable to satisfy boundary conditions "
+                  f"tolerance on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+
+    if p.size == 0:
+        p = None
+
+    return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
+                     niter=iteration, status=status,
+                     message=TERMINATION_MESSAGES[status], success=status == 0)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_cubature.py b/python_embeded/Lib/site-packages/scipy/integrate/_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f52c8c44f089f0fed80bf52fc8c6e1d2620adb1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_cubature.py
@@ -0,0 +1,728 @@
+import math
+import heapq
+import itertools
+
+from dataclasses import dataclass, field
+from types import ModuleType
+from typing import Any, TypeAlias
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_copy,
+    xp_broadcast_promote
+)
+from scipy._lib._util import MapWrapper
+
+from scipy.integrate._rules import (
+    ProductNestedFixed,
+    GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+from scipy.integrate._rules._base import _split_subregion
+
+__all__ = ['cubature']
+
+Array: TypeAlias = Any  # To be changed to an array-api-typing Protocol later
+
+
+@dataclass
+class CubatureRegion:
+    estimate: Array
+    error: Array
+    a: Array
+    b: Array
+    _xp: ModuleType = field(repr=False)
+
+    def __lt__(self, other):
+        # Consider regions with higher error estimates as being "less than" regions with
+        # lower order estimates, so that regions with high error estimates are placed at
+        # the top of the heap.
+
+        this_err = self._xp.max(self._xp.abs(self.error))
+        other_err = self._xp.max(self._xp.abs(other.error))
+
+        return this_err > other_err
+
+
+@dataclass
+class CubatureResult:
+    estimate: Array
+    error: Array
+    status: str
+    regions: list[CubatureRegion]
+    subdivisions: int
+    atol: float
+    rtol: float
+
+
+def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
+             args=(), workers=1, points=None):
+    r"""
+    Adaptive cubature of multidimensional array-valued function.
+
+    Given an arbitrary integration rule, this function returns an estimate of the
+    integral to the requested tolerance over the region defined by the arrays `a` and
+    `b` specifying the corners of a hypercube.
+
+    Convergence is not guaranteed for all integrals.
+
+    Parameters
+    ----------
+    f : callable
+        Function to integrate. `f` must have the signature::
+
+            f(x : ndarray, *args) -> ndarray
+
+        `f` should accept arrays ``x`` of shape::
+
+            (npoints, ndim)
+
+        and output arrays of shape::
+
+            (npoints, output_dim_1, ..., output_dim_n)
+
+        In this case, `cubature` will return arrays of shape::
+
+            (output_dim_1, ..., output_dim_n)
+    a, b : array_like
+        Lower and upper limits of integration as 1D arrays specifying the left and right
+        endpoints of the intervals being integrated over. Limits can be infinite.
+    rule : str, optional
+        Rule used to estimate the integral. If passing a string, the options are
+        "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
+        "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
+        Cartesian product rule is used. "gk21", "gk15" are also supported for
+        compatibility with `quad_vec`. See Notes.
+    rtol, atol : float, optional
+        Relative and absolute tolerances. Iterations are performed until the error is
+        estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
+        relative accuracy (number of correct digits), while `atol` controls absolute
+        accuracy (number of correct decimal places). To achieve the desired `rtol`, set
+        `atol` to be smaller than the smallest value that can be expected from
+        ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
+        larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
+        Conversely, to achieve the desired `atol`, set `rtol` such that
+        ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
+        `rtol` and 0 for `atol`.
+    max_subdivisions : int, optional
+        Upper bound on the number of subdivisions to perform. Default is 10,000.
+    args : tuple, optional
+        Additional positional args passed to `f`, if any.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in parallel
+        subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process. Alternatively, supply a
+        map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
+        evaluating the population in parallel. This evaluation is carried out as
+        ``workers(func, iterable)``.
+    points : list of array_like, optional
+        List of points to avoid evaluating `f` at, under the condition that the rule
+        being used does not evaluate `f` on the boundary of a region (which is the
+        case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
+        a singularity at the specified point. This should be a list of array-likes where
+        each element has length ``ndim``. Default is empty. See Examples.
+
+    Returns
+    -------
+    res : object
+        Object containing the results of the estimation. It has the following
+        attributes:
+
+        estimate : ndarray
+            Estimate of the value of the integral over the overall region specified.
+        error : ndarray
+            Estimate of the error of the approximation over the overall region
+            specified.
+        status : str
+            Whether the estimation was successful. Can be either: "converged",
+            "not_converged".
+        subdivisions : int
+            Number of subdivisions performed.
+        atol, rtol : float
+            Requested tolerances for the approximation.
+        regions: list of object
+            List of objects containing the estimates of the integral over smaller
+            regions of the domain.
+
+        Each object in ``regions`` has the following attributes:
+
+        a, b : ndarray
+            Points describing the corners of the region. If the original integral
+            contained infinite limits or was over a region described by `region`,
+            then `a` and `b` are in the transformed coordinates.
+        estimate : ndarray
+            Estimate of the value of the integral over this region.
+        error : ndarray
+            Estimate of the error of the approximation over this region.
+
+    Notes
+    -----
+    The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
+    implementation of QUADPACK's DQAG* algorithms, implementing global error control and
+    adaptive subdivision.
+
+    The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
+    in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
+    cubature can be found in [2]_.
+
+    The rules currently supported via the `rule` argument are:
+
+    - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
+    - ``"genz-malik"``, n-node Genz-Malik
+
+    If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
+    corresponding Cartesian product rule will be found by taking the Cartesian product
+    of the nodes in the 1D case. This means that the number of nodes scales
+    exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
+    moderate number of dimensions.
+
+    Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
+    so in this situation using "genz-malik" might be preferable.
+
+    Infinite limits are handled with an appropriate variable transformation. Assuming
+    ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427
+        :doi:`10.1016/0771-050X(80)90039-X`
+
+    Examples
+    --------
+    **1D integral with vector output**:
+
+    .. math::
+
+        \int^1_0 \mathbf f(x) \text dx
+
+    Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
+    specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
+    integration with 21 nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, n):
+    ...    # Make sure x and n are broadcastable
+    ...    return x[:, np.newaxis]**n[np.newaxis, :]
+    >>> res = cubature(
+    ...     f,
+    ...     a=[0],
+    ...     b=[1],
+    ...     args=(np.arange(10),),
+    ... )
+    >>> res.estimate
+     array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+            0.16666667, 0.14285714, 0.125     , 0.11111111, 0.1       ])
+
+    **7D integral with arbitrary-shaped array output**::
+
+        f(x) = cos(2*pi*r + alphas @ x)
+
+    for some ``r`` and ``alphas``, and the integral is performed over the unit
+    hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
+    dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
+    avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alphas @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas = alphas[np.newaxis, ...]
+    ...     x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
+    >>> rng = np.random.default_rng()
+    >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...     b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...     rtol=1e-5,
+    ...     rule="genz-malik",
+    ...     args=(r, alphas),
+    ... )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **Parallel computation with** `workers`:
+
+    >>> from concurrent.futures import ThreadPoolExecutor
+    >>> with ThreadPoolExecutor() as executor:
+    ...     res = cubature(
+    ...         f=f,
+    ...         a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...         b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...         rtol=1e-5,
+    ...         rule="genz-malik",
+    ...         args=(r, alphas),
+    ...         workers=executor.map,
+    ...      )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **2D integral with infinite limits**:
+
+    .. math::
+
+        \int^{ \infty }_{ -\infty }
+        \int^{ \infty }_{ -\infty }
+            e^{-x^2-y^2}
+        \text dy
+        \text dx
+
+    >>> def gaussian(x):
+    ...     return np.exp(-np.sum(x**2, axis=-1))
+    >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
+    >>> res.estimate
+     3.1415926
+
+    **1D integral with singularities avoided using** `points`:
+
+    .. math::
+
+        \int^{ 1 }_{ -1 }
+          \frac{\sin(x)}{x}
+        \text dx
+
+    It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
+
+    >>> def sinc(x):
+    ...     return np.sin(x)/x
+    >>> res = cubature(sinc, [-1], [1], points=[[0]])
+    >>> res.estimate
+     1.8921661
+    """
+
+    # It is also possible to use a custom rule, but this is not yet part of the public
+    # API. An example of this can be found in the class scipy.integrate._rules.Rule.
+
+    xp = array_namespace(a, b)
+    max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
+    points = [] if points is None else points
+
+    # Convert a and b to arrays and convert each point in points to an array, promoting
+    # each to a common floating dtype.
+    a, b, *points = xp_broadcast_promote(a, b, *points, force_floating=True)
+    result_dtype = a.dtype
+
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        raise ValueError("`a` and `b` must be nonempty")
+
+    if a.ndim != 1 or b.ndim != 1:
+        raise ValueError("`a` and `b` must be 1D arrays")
+
+    # If the rule is a string, convert to a corresponding product rule
+    if isinstance(rule, str):
+        ndim = xp_size(a)
+
+        if rule == "genz-malik":
+            rule = GenzMalikCubature(ndim, xp=xp)
+        else:
+            quadratues = {
+                "gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
+
+                # Also allow names quad_vec uses:
+                "gk21": GaussKronrodQuadrature(21, xp=xp),
+                "gk15": GaussKronrodQuadrature(15, xp=xp),
+            }
+
+            base_rule = quadratues.get(rule)
+
+            if base_rule is None:
+                raise ValueError(f"unknown rule {rule}")
+
+            rule = ProductNestedFixed([base_rule] * ndim)
+
+    # If any of limits are the wrong way around (a > b), flip them and keep track of
+    # the sign.
+    sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
+
+    a_flipped = xp.min(xp.stack([a, b]), axis=0)
+    b_flipped = xp.max(xp.stack([a, b]), axis=0)
+
+    a, b = a_flipped, b_flipped
+
+    # If any of the limits are infinite, apply a transformation
+    if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
+        f = _InfiniteLimitsTransform(f, a, b, xp=xp)
+        a, b = f.transformed_limits
+
+        # Map points from the original coordinates to the new transformed coordinates.
+        #
+        # `points` is a list of arrays of shape (ndim,), but transformations are applied
+        # to arrays of shape (npoints, ndim).
+        #
+        # It is not possible to combine all the points into one array and then apply
+        # f.inv to all of them at once since `points` needs to remain iterable.
+        # Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
+        # applied, and then each is reshaped back to (ndim,).
+        points = [xp.reshape(point, (1, -1)) for point in points]
+        points = [f.inv(point) for point in points]
+        points = [xp.reshape(point, (-1,)) for point in points]
+
+        # Include any problematic points introduced by the transformation
+        points.extend(f.points)
+
+    # If any problematic points are specified, divide the initial region so that these
+    # points lie on the edge of a subregion.
+    #
+    # This means ``f`` won't be evaluated there if the rule being used has no evaluation
+    # points on the boundary.
+    if len(points) == 0:
+        initial_regions = [(a, b)]
+    else:
+        initial_regions = _split_region_at_points(a, b, points, xp)
+
+    regions = []
+    est = 0.0
+    err = 0.0
+
+    for a_k, b_k in initial_regions:
+        est_k = rule.estimate(f, a_k, b_k, args)
+        err_k = rule.estimate_error(f, a_k, b_k, args)
+        regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
+
+        est += est_k
+        err += err_k
+
+    subdivisions = 0
+    success = True
+
+    with MapWrapper(workers) as mapwrapper:
+        while xp.any(err > atol + rtol * xp.abs(est)):
+            # region_k is the region with highest estimated error
+            region_k = heapq.heappop(regions)
+
+            est_k = region_k.estimate
+            err_k = region_k.error
+
+            a_k, b_k = region_k.a, region_k.b
+
+            # Subtract the estimate of the integral and its error over this region from
+            # the current global estimates, since these will be refined in the loop over
+            # all subregions.
+            est -= est_k
+            err -= err_k
+
+            # Find all 2^ndim subregions formed by splitting region_k along each axis,
+            # e.g. for 1D integrals this splits an estimate over an interval into an
+            # estimate over two subintervals, for 3D integrals this splits an estimate
+            # over a cube into 8 subcubes.
+            #
+            # For each of the new subregions, calculate an estimate for the integral and
+            # the error there, and push these regions onto the heap for potential
+            # further subdividing.
+
+            executor_args = zip(
+                itertools.repeat(f),
+                itertools.repeat(rule),
+                itertools.repeat(args),
+                _split_subregion(a_k, b_k, xp),
+            )
+
+            for subdivision_result in mapwrapper(_process_subregion, executor_args):
+                a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
+
+                est += est_sub
+                err += err_sub
+
+                new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
+
+                heapq.heappush(regions, new_region)
+
+            subdivisions += 1
+
+            if subdivisions >= max_subdivisions:
+                success = False
+                break
+
+        status = "converged" if success else "not_converged"
+
+        # Apply sign change to handle any limits which were initially flipped.
+        est = sign * est
+
+        return CubatureResult(
+            estimate=est,
+            error=err,
+            status=status,
+            subdivisions=subdivisions,
+            regions=regions,
+            atol=atol,
+            rtol=rtol,
+        )
+
+
+def _process_subregion(data):
+    f, rule, args, coord = data
+    a_k_sub, b_k_sub = coord
+
+    est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
+    err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
+
+    return a_k_sub, b_k_sub, est_sub, err_sub
+
+
+def _is_strictly_in_region(a, b, point, xp):
+    if xp.all(point == a) or xp.all(point == b):
+        return False
+
+    return xp.all(a <= point) and xp.all(point <= b)
+
+
+def _split_region_at_points(a, b, points, xp):
+    """
+    Given the integration limits `a` and `b` describing a rectangular region and a list
+    of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
+    initial region into smaller subregion such that no `points` lie strictly inside
+    any of the subregions.
+    """
+
+    regions = [(a, b)]
+
+    for point in points:
+        if xp.any(xp.isinf(point)):
+            # If a point is specified at infinity, ignore.
+            #
+            # This case occurs when points are given by the user to avoid, but after
+            # applying a transformation, they are removed.
+            continue
+
+        new_subregions = []
+
+        for a_k, b_k in regions:
+            if _is_strictly_in_region(a_k, b_k, point, xp):
+                subregions = _split_subregion(a_k, b_k, xp, point)
+
+                for left, right in subregions:
+                    # Skip any zero-width regions.
+                    if xp.any(left == right):
+                        continue
+                    else:
+                        new_subregions.append((left, right))
+
+                new_subregions.extend(subregions)
+
+            else:
+                new_subregions.append((a_k, b_k))
+
+        regions = new_subregions
+
+    return regions
+
+
+class _VariableTransform:
+    """
+    A transformation that can be applied to an integral.
+    """
+
+    @property
+    def transformed_limits(self):
+        """
+        New limits of integration after applying the transformation.
+        """
+
+        raise NotImplementedError
+
+    @property
+    def points(self):
+        """
+        Any problematic points introduced by the transformation.
+
+        These should be specified as points where ``_VariableTransform(f)(self, point)``
+        would be problematic.
+
+        For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
+        univariate integral, then points should return ``[ [1], [-1] ]``.
+        """
+
+        return []
+
+    def inv(self, x):
+        """
+        Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
+        is the function after the transformation is applied, then::
+
+            f(x) = g(self.inv(x))
+        """
+
+        raise NotImplementedError
+
+    def __call__(self, t, *args, **kwargs):
+        """
+        Apply the transformation to ``f`` and multiply by the Jacobian determinant.
+        This should be the new integrand after the transformation has been applied so
+        that the following is satisfied::
+
+            f_transformed = _VariableTransform(f)
+
+            cubature(f, a, b) == cubature(
+                f_transformed,
+                *f_transformed.transformed_limits(a, b),
+            )
+        """
+
+        raise NotImplementedError
+
+
+class _InfiniteLimitsTransform(_VariableTransform):
+    r"""
+    Transformation for handling infinite limits.
+
+    Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+    """
+
+    def __init__(self, f, a, b, xp):
+        self._xp = xp
+
+        self._f = f
+        self._orig_a = a
+        self._orig_b = b
+
+        # (-oo, oo) will be mapped to (-1, 1).
+        self._double_inf_pos = (a == -math.inf) & (b == math.inf)
+
+        # (start, oo) will be mapped to (0, 1).
+        start_inf_mask = (a != -math.inf) & (b == math.inf)
+
+        # (-oo, end) will be mapped to (0, 1).
+        inf_end_mask = (a == -math.inf) & (b != math.inf)
+
+        # This is handled by making the transformation t = -x and reducing it to
+        # the other semi-infinite case.
+        self._semi_inf_pos = start_inf_mask | inf_end_mask
+
+        # Since we flip the limits, we don't need to separately multiply the
+        # integrand by -1.
+        self._orig_a[inf_end_mask] = -b[inf_end_mask]
+        self._orig_b[inf_end_mask] = -a[inf_end_mask]
+
+        self._num_inf = self._xp.sum(
+            self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
+        ).__int__()
+
+    @property
+    def transformed_limits(self):
+        a = xp_copy(self._orig_a)
+        b = xp_copy(self._orig_b)
+
+        a[self._double_inf_pos] = -1
+        b[self._double_inf_pos] = 1
+
+        a[self._semi_inf_pos] = 0
+        b[self._semi_inf_pos] = 1
+
+        return a, b
+
+    @property
+    def points(self):
+        # If there are infinite limits, then the origin becomes a problematic point
+        # due to a division by zero there.
+
+        # If the function using this class only wraps f when a and b contain infinite
+        # limits, this condition will always be met (as is the case with cubature).
+        #
+        # If a and b do not contain infinite limits but f is still wrapped with this
+        # class, then without this condition the initial region of integration will
+        # be split around the origin unnecessarily.
+        if self._num_inf != 0:
+            return [self._xp.zeros(self._orig_a.shape)]
+        else:
+            return []
+
+    def inv(self, x):
+        t = xp_copy(x)
+        npoints = x.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # If any components of x are 0, then this component will be mapped to infinity
+        # under the transformation used for doubly-infinite limits.
+        #
+        # Handle the zero values and non-zero values separately to avoid division by
+        # zero.
+        zero_mask = x[double_inf_mask] == 0
+        non_zero_mask = double_inf_mask & ~zero_mask
+        t[zero_mask] = math.inf
+        t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+        t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
+
+        return t
+
+    def __call__(self, t, *args, **kwargs):
+        x = xp_copy(t)
+        npoints = t.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
+        x[double_inf_mask] = (
+            (1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
+        )
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+
+        # For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
+        x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
+
+        jacobian_det = 1/self._xp.prod(
+            self._xp.reshape(
+                t[semi_inf_mask | double_inf_mask]**2,
+                (-1, self._num_inf),
+            ),
+            axis=-1,
+        )
+
+        f_x = self._f(x, *args, **kwargs)
+        jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
+
+        return f_x * jacobian_det
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_dop.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_dop.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..f91d1fc0fbf9384848bf543701066ad0d91d7bd1
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_dop.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_lebedev.py b/python_embeded/Lib/site-packages/scipy/integrate/_lebedev.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ee3cd41afeed0cb0b7a982409cc4769fc287997
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_lebedev.py
@@ -0,0 +1,5450 @@
+# getLebedevSphere
+# Copyright (c) 2010, Robert Parrish
+# 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
+#
+# 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.
+#
+# Brainlessly translated to Python
+
+import numpy as np
+from numpy import pi, zeros, sqrt
+
+
+__all__ = ['lebedev_rule']
+
+
+def get_lebedev_sphere(degree):
+    # getLebedevSphere
+    # @author Rob Parrish, The Sherrill Group, CCMST Georgia Tech
+    # @email robparrish@gmail.com
+    # @date 03/24/2010
+    #
+    # @description - function to compute normalized points and weights
+    # for Lebedev quadratures on the surface of the unit sphere at double precision.
+    # **********Relative error is generally expected to be ~2.0E-14 [1]********
+    # Lebedev quadratures are superbly accurate and efficient quadrature rules for
+    # approximating integrals of the form $v = \iint_{4\pi}  f(\Omega) \ \ud
+    # \Omega$, where $\Omega is the solid angle on the surface of the unit
+    # sphere. Lebedev quadratures integrate all spherical harmonics up to $l =
+    # order$, where $degree \approx order(order+1)/3$. These grids may be easily
+    # combined with radial quadratures to provide robust cubature formulae. For
+    # example, see 'A. Becke, 1988c, J. Chem. Phys., 88(4), pp. 2547' (The first
+    # paper on tractable molecular Density Functional Theory methods, of which
+    # Lebedev grids and numerical cubature are an intrinsic part).
+    #
+    # @param degree - positive integer specifying number of points in the
+    # requested quadrature. Allowed values are (degree -> order):
+    # degree: { 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302,
+    #   350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074,
+    #   3470, 3890, 4334, 4802, 5294, 5810 }
+    # order: {3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,35,41,47,53,59,65,71,77,
+    #   83,89,95,101,107,113,119,125,131}
+    #
+    #
+    # @return leb_tmp - struct containing fields:
+    #   x - x values of quadrature, constrained to unit sphere
+    #   y - y values of quadrature, constrained to unit sphere
+    #   z - z values of quadrature, constrained to unit sphere
+    #   w - quadrature weights, normalized to $4\pi$.
+    #
+    # @example: $\int_S x^2+y^2-z^2 \ud \Omega = 4.188790204786399$
+    #   f = @(x,y,z) x.^2+y.^2-z.^2
+    #   leb = getLebedevSphere(590)
+    #   v = f(leb.x,leb.y,leb.z)
+    #   int = sum(v.*leb.w)
+    #
+    # @citation - Translated from a Fortran code kindly provided by Christoph van
+    # Wuellen (Ruhr-Universitaet, Bochum, Germany), which in turn came from the
+    # original C routines coded by Dmitri Laikov (Moscow State University,
+    # Moscow, Russia). The MATLAB implementation of this code is designed for
+    # benchmarking of new DFT integration techniques to be implemented in the
+    # open source Psi4 ab initio quantum chemistry program.
+    #
+    # As per Professor Wuellen's request, any papers published using this code
+    # or its derivatives are requested to include the following citation:
+    #
+    # [1] V.I. Lebedev, and D.N. Laikov
+    #    "A quadrature formula for the sphere of the 131st
+    #     algebraic order of accuracy"
+    #    Doklady Mathematics, Vol. 59, No. 3, 1999, pp. 477-481.
+
+    class Leb:
+        x, y, z, w = None, None, None, None
+
+    leb_tmp = Leb()
+
+    leb_tmp.x = zeros(degree)
+    leb_tmp.y = zeros(degree)
+    leb_tmp.z = zeros(degree)
+    leb_tmp.w = zeros(degree)
+
+    start = 0
+    a = 0.0
+    b = 0.0
+
+    match degree:
+
+        case 6:
+
+            v = 0.1666666666666667E+0
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+
+        case 14:
+
+            v = 0.6666666666666667E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7500000000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 26:
+
+            v = 0.4761904761904762E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3809523809523810E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 38:
+
+            v = 0.9523809523809524E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4597008433809831E+0
+            v = 0.2857142857142857E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 50:
+
+            v = 0.1269841269841270E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2257495590828924E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2109375000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3015113445777636E+0
+            v = 0.2017333553791887E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+
+        case 74:
+
+            v = 0.5130671797338464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1660406956574204E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = -0.2958603896103896E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4803844614152614E+0
+            v = 0.2657620708215946E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3207726489807764E+0
+            v = 0.1652217099371571E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 86:
+
+            v = 0.1154401154401154E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1194390908585628E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3696028464541502E+0
+            v = 0.1111055571060340E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6943540066026664E+0
+            v = 0.1187650129453714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3742430390903412E+0
+            v = 0.1181230374690448E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 110:
+
+            v = 0.3828270494937162E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9793737512487512E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1851156353447362E+0
+            v = 0.8211737283191111E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6904210483822922E+0
+            v = 0.9942814891178103E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3956894730559419E+0
+            v = 0.9595471336070963E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4783690288121502E+0
+            v = 0.9694996361663028E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 146:
+
+            v = 0.5996313688621381E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7372999718620756E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.7210515360144488E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6764410400114264E+0
+            v = 0.7116355493117555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4174961227965453E+0
+            v = 0.6753829486314477E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1574676672039082E+0
+            v = 0.7574394159054034E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1403553811713183E+0
+            b = 0.4493328323269557E+0
+            v = 0.6991087353303262E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 170:
+
+            v = 0.5544842902037365E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6071332770670752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6383674773515093E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2551252621114134E+0
+            v = 0.5183387587747790E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6743601460362766E+0
+            v = 0.6317929009813725E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4318910696719410E+0
+            v = 0.6201670006589077E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2613931360335988E+0
+            v = 0.5477143385137348E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4990453161796037E+0
+            b = 0.1446630744325115E+0
+            v = 0.5968383987681156E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 194:
+
+            v = 0.1782340447244611E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5716905949977102E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.5573383178848738E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6712973442695226E+0
+            v = 0.5608704082587997E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2892465627575439E+0
+            v = 0.5158237711805383E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4446933178717437E+0
+            v = 0.5518771467273614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1299335447650067E+0
+            v = 0.4106777028169394E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3457702197611283E+0
+            v = 0.5051846064614808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1590417105383530E+0
+            b = 0.8360360154824589E+0
+            v = 0.5530248916233094E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 230:
+
+            v = -0.5522639919727325E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4450274607445226E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4492044687397611E+0
+            v = 0.4496841067921404E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2520419490210201E+0
+            v = 0.5049153450478750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6981906658447242E+0
+            v = 0.3976408018051883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6587405243460960E+0
+            v = 0.4401400650381014E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4038544050097660E-1
+            v = 0.1724544350544401E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5823842309715585E+0
+            v = 0.4231083095357343E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3545877390518688E+0
+            v = 0.5198069864064399E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2272181808998187E+0
+            b = 0.4864661535886647E+0
+            v = 0.4695720972568883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 266:
+
+            v = -0.1313769127326952E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = -0.2522728704859336E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4186853881700583E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7039373391585475E+0
+            v = 0.5315167977810885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1012526248572414E+0
+            v = 0.4047142377086219E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4647448726420539E+0
+            v = 0.4112482394406990E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3277420654971629E+0
+            v = 0.3595584899758782E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6620338663699974E+0
+            v = 0.4256131351428158E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8506508083520399E+0
+            v = 0.4229582700647240E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3233484542692899E+0
+            b = 0.1153112011009701E+0
+            v = 0.4080914225780505E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2314790158712601E+0
+            b = 0.5244939240922365E+0
+            v = 0.4071467593830964E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 302:
+
+            v = 0.8545911725128148E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3599119285025571E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3515640345570105E+0
+            v = 0.3449788424305883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6566329410219612E+0
+            v = 0.3604822601419882E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4729054132581005E+0
+            v = 0.3576729661743367E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9618308522614784E-1
+            v = 0.2352101413689164E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2219645236294178E+0
+            v = 0.3108953122413675E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7011766416089545E+0
+            v = 0.3650045807677255E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2644152887060663E+0
+            v = 0.2982344963171804E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5718955891878961E+0
+            v = 0.3600820932216460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2510034751770465E+0
+            b = 0.8000727494073952E+0
+            v = 0.3571540554273387E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1233548532583327E+0
+            b = 0.4127724083168531E+0
+            v = 0.3392312205006170E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 350:
+
+            v = 0.3006796749453936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3050627745650771E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7068965463912316E+0
+            v = 0.1621104600288991E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4794682625712025E+0
+            v = 0.3005701484901752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1927533154878019E+0
+            v = 0.2990992529653774E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6930357961327123E+0
+            v = 0.2982170644107595E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3608302115520091E+0
+            v = 0.2721564237310992E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6498486161496169E+0
+            v = 0.3033513795811141E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1932945013230339E+0
+            v = 0.3007949555218533E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3800494919899303E+0
+            v = 0.2881964603055307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2899558825499574E+0
+            b = 0.7934537856582316E+0
+            v = 0.2958357626535696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9684121455103957E-1
+            b = 0.8280801506686862E+0
+            v = 0.3036020026407088E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1833434647041659E+0
+            b = 0.9074658265305127E+0
+            v = 0.2832187403926303E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 434:
+
+            v = 0.5265897968224436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2548219972002607E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2512317418927307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6909346307509111E+0
+            v = 0.2530403801186355E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1774836054609158E+0
+            v = 0.2014279020918528E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4914342637784746E+0
+            v = 0.2501725168402936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6456664707424256E+0
+            v = 0.2513267174597564E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2861289010307638E+0
+            v = 0.2302694782227416E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7568084367178018E-1
+            v = 0.1462495621594614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3927259763368002E+0
+            v = 0.2445373437312980E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8818132877794288E+0
+            v = 0.2417442375638981E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9776428111182649E+0
+            v = 0.1910951282179532E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2054823696403044E+0
+            b = 0.8689460322872412E+0
+            v = 0.2416930044324775E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5905157048925271E+0
+            b = 0.7999278543857286E+0
+            v = 0.2512236854563495E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5550152361076807E+0
+            b = 0.7717462626915901E+0
+            v = 0.2496644054553086E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9371809858553722E+0
+            b = 0.3344363145343455E+0
+            v = 0.2236607760437849E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 590:
+
+            v = 0.3095121295306187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1852379698597489E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7040954938227469E+0
+            v = 0.1871790639277744E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6807744066455243E+0
+            v = 0.1858812585438317E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6372546939258752E+0
+            v = 0.1852028828296213E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5044419707800358E+0
+            v = 0.1846715956151242E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4215761784010967E+0
+            v = 0.1818471778162769E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3317920736472123E+0
+            v = 0.1749564657281154E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2384736701421887E+0
+            v = 0.1617210647254411E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1459036449157763E+0
+            v = 0.1384737234851692E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6095034115507196E-1
+            v = 0.9764331165051050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6116843442009876E+0
+            v = 0.1857161196774078E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3964755348199858E+0
+            v = 0.1705153996395864E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1724782009907724E+0
+            v = 0.1300321685886048E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5610263808622060E+0
+            b = 0.3518280927733519E+0
+            v = 0.1842866472905286E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4742392842551980E+0
+            b = 0.2634716655937950E+0
+            v = 0.1802658934377451E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5984126497885380E+0
+            b = 0.1816640840360209E+0
+            v = 0.1849830560443660E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3791035407695563E+0
+            b = 0.1720795225656878E+0
+            v = 0.1713904507106709E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778673190586244E+0
+            b = 0.8213021581932511E-1
+            v = 0.1555213603396808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5033564271075117E+0
+            b = 0.8999205842074875E-1
+            v = 0.1802239128008525E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 770:
+
+            v = 0.2192942088181184E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1436433617319080E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1421940344335877E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.5087204410502360E-1
+            v = 0.6798123511050502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1228198790178831E+0
+            v = 0.9913184235294912E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2026890814408786E+0
+            v = 0.1180207833238949E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2847745156464294E+0
+            v = 0.1296599602080921E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3656719078978026E+0
+            v = 0.1365871427428316E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4428264886713469E+0
+            v = 0.1402988604775325E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5140619627249735E+0
+            v = 0.1418645563595609E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6306401219166803E+0
+            v = 0.1421376741851662E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6716883332022612E+0
+            v = 0.1423996475490962E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6979792685336881E+0
+            v = 0.1431554042178567E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1446865674195309E+0
+            v = 0.9254401499865368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3390263475411216E+0
+            v = 0.1250239995053509E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5335804651263506E+0
+            v = 0.1394365843329230E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6944024393349413E-1
+            b = 0.2355187894242326E+0
+            v = 0.1127089094671749E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2269004109529460E+0
+            b = 0.4102182474045730E+0
+            v = 0.1345753760910670E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8025574607775339E-1
+            b = 0.6214302417481605E+0
+            v = 0.1424957283316783E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1467999527896572E+0
+            b = 0.3245284345717394E+0
+            v = 0.1261523341237750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1571507769824727E+0
+            b = 0.5224482189696630E+0
+            v = 0.1392547106052696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2365702993157246E+0
+            b = 0.6017546634089558E+0
+            v = 0.1418761677877656E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7714815866765732E-1
+            b = 0.4346575516141163E+0
+            v = 0.1338366684479554E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3062936666210730E+0
+            b = 0.4908826589037616E+0
+            v = 0.1393700862676131E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3822477379524787E+0
+            b = 0.5648768149099500E+0
+            v = 0.1415914757466932E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 974:
+
+            v = 0.1438294190527431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1125772288287004E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4292963545341347E-1
+            v = 0.4948029341949241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1051426854086404E+0
+            v = 0.7357990109125470E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1750024867623087E+0
+            v = 0.8889132771304384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2477653379650257E+0
+            v = 0.9888347838921435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3206567123955957E+0
+            v = 0.1053299681709471E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3916520749849983E+0
+            v = 0.1092778807014578E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4590825874187624E+0
+            v = 0.1114389394063227E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5214563888415861E+0
+            v = 0.1123724788051555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6253170244654199E+0
+            v = 0.1125239325243814E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6637926744523170E+0
+            v = 0.1126153271815905E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910410398498301E+0
+            v = 0.1130286931123841E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7052907007457760E+0
+            v = 0.1134986534363955E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1236686762657990E+0
+            v = 0.6823367927109931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2940777114468387E+0
+            v = 0.9454158160447096E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4697753849207649E+0
+            v = 0.1074429975385679E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6334563241139567E+0
+            v = 0.1129300086569132E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5974048614181342E-1
+            b = 0.2029128752777523E+0
+            v = 0.8436884500901954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1375760408473636E+0
+            b = 0.4602621942484054E+0
+            v = 0.1075255720448885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3391016526336286E+0
+            b = 0.5030673999662036E+0
+            v = 0.1108577236864462E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1271675191439820E+0
+            b = 0.2817606422442134E+0
+            v = 0.9566475323783357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2693120740413512E+0
+            b = 0.4331561291720157E+0
+            v = 0.1080663250717391E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1419786452601918E+0
+            b = 0.6256167358580814E+0
+            v = 0.1126797131196295E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6709284600738255E-1
+            b = 0.3798395216859157E+0
+            v = 0.1022568715358061E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7057738183256172E-1
+            b = 0.5517505421423520E+0
+            v = 0.1108960267713108E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2783888477882155E+0
+            b = 0.6029619156159187E+0
+            v = 0.1122790653435766E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1979578938917407E+0
+            b = 0.3589606329589096E+0
+            v = 0.1032401847117460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2087307061103274E+0
+            b = 0.5348666438135476E+0
+            v = 0.1107249382283854E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4055122137872836E+0
+            b = 0.5674997546074373E+0
+            v = 0.1121780048519972E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1202:
+
+            v = 0.1105189233267572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9205232738090741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.9133159786443561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3712636449657089E-1
+            v = 0.3690421898017899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9140060412262223E-1
+            v = 0.5603990928680660E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1531077852469906E+0
+            v = 0.6865297629282609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2180928891660612E+0
+            v = 0.7720338551145630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2839874532200175E+0
+            v = 0.8301545958894795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3491177600963764E+0
+            v = 0.8686692550179628E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4121431461444309E+0
+            v = 0.8927076285846890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4718993627149127E+0
+            v = 0.9060820238568219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5273145452842337E+0
+            v = 0.9119777254940867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6209475332444019E+0
+            v = 0.9128720138604181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6569722711857291E+0
+            v = 0.9130714935691735E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6841788309070143E+0
+            v = 0.9152873784554116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012604330123631E+0
+            v = 0.9187436274321654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1072382215478166E+0
+            v = 0.5176977312965694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2582068959496968E+0
+            v = 0.7331143682101417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4172752955306717E+0
+            v = 0.8463232836379928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5700366911792503E+0
+            v = 0.9031122694253992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9827986018263947E+0
+            b = 0.1771774022615325E+0
+            v = 0.6485778453163257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9624249230326228E+0
+            b = 0.2475716463426288E+0
+            v = 0.7435030910982369E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9402007994128811E+0
+            b = 0.3354616289066489E+0
+            v = 0.7998527891839054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9320822040143202E+0
+            b = 0.3173615246611977E+0
+            v = 0.8101731497468018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9043674199393299E+0
+            b = 0.4090268427085357E+0
+            v = 0.8483389574594331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8912407560074747E+0
+            b = 0.3854291150669224E+0
+            v = 0.8556299257311812E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8676435628462708E+0
+            b = 0.4932221184851285E+0
+            v = 0.8803208679738260E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8581979986041619E+0
+            b = 0.4785320675922435E+0
+            v = 0.8811048182425720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8396753624049856E+0
+            b = 0.4507422593157064E+0
+            v = 0.8850282341265444E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8165288564022188E+0
+            b = 0.5632123020762100E+0
+            v = 0.9021342299040653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8015469370783529E+0
+            b = 0.5434303569693900E+0
+            v = 0.9010091677105086E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7773563069070351E+0
+            b = 0.5123518486419871E+0
+            v = 0.9022692938426915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7661621213900394E+0
+            b = 0.6394279634749102E+0
+            v = 0.9158016174693465E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7553584143533510E+0
+            b = 0.6269805509024392E+0
+            v = 0.9131578003189435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7344305757559503E+0
+            b = 0.6031161693096310E+0
+            v = 0.9107813579482705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7043837184021765E+0
+            b = 0.5693702498468441E+0
+            v = 0.9105760258970126E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1454:
+
+            v = 0.7777160743261247E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7557646413004701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3229290663413854E-1
+            v = 0.2841633806090617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8036733271462222E-1
+            v = 0.4374419127053555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1354289960531653E+0
+            v = 0.5417174740872172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1938963861114426E+0
+            v = 0.6148000891358593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2537343715011275E+0
+            v = 0.6664394485800705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3135251434752570E+0
+            v = 0.7025039356923220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3721558339375338E+0
+            v = 0.7268511789249627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4286809575195696E+0
+            v = 0.7422637534208629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4822510128282994E+0
+            v = 0.7509545035841214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5320679333566263E+0
+            v = 0.7548535057718401E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6172998195394274E+0
+            v = 0.7554088969774001E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6510679849127481E+0
+            v = 0.7553147174442808E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6777315251687360E+0
+            v = 0.7564767653292297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963109410648741E+0
+            v = 0.7587991808518730E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7058935009831749E+0
+            v = 0.7608261832033027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9955546194091857E+0
+            v = 0.4021680447874916E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9734115901794209E+0
+            v = 0.5804871793945964E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9275693732388626E+0
+            v = 0.6792151955945159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8568022422795103E+0
+            v = 0.7336741211286294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7623495553719372E+0
+            v = 0.7581866300989608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5707522908892223E+0
+            b = 0.4387028039889501E+0
+            v = 0.7538257859800743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5196463388403083E+0
+            b = 0.3858908414762617E+0
+            v = 0.7483517247053123E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4646337531215351E+0
+            b = 0.3301937372343854E+0
+            v = 0.7371763661112059E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4063901697557691E+0
+            b = 0.2725423573563777E+0
+            v = 0.7183448895756934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3456329466643087E+0
+            b = 0.2139510237495250E+0
+            v = 0.6895815529822191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2831395121050332E+0
+            b = 0.1555922309786647E+0
+            v = 0.6480105801792886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197682022925330E+0
+            b = 0.9892878979686097E-1
+            v = 0.5897558896594636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1564696098650355E+0
+            b = 0.4598642910675510E-1
+            v = 0.5095708849247346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6027356673721295E+0
+            b = 0.3376625140173426E+0
+            v = 0.7536906428909755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496032320255096E+0
+            b = 0.2822301309727988E+0
+            v = 0.7472505965575118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4921707755234567E+0
+            b = 0.2248632342592540E+0
+            v = 0.7343017132279698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4309422998598483E+0
+            b = 0.1666224723456479E+0
+            v = 0.7130871582177445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3664108182313672E+0
+            b = 0.1086964901822169E+0
+            v = 0.6817022032112776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2990189057758436E+0
+            b = 0.5251989784120085E-1
+            v = 0.6380941145604121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6268724013144998E+0
+            b = 0.2297523657550023E+0
+            v = 0.7550381377920310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5707324144834607E+0
+            b = 0.1723080607093800E+0
+            v = 0.7478646640144802E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5096360901960365E+0
+            b = 0.1140238465390513E+0
+            v = 0.7335918720601220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4438729938312456E+0
+            b = 0.5611522095882537E-1
+            v = 0.7110120527658118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6419978471082389E+0
+            b = 0.1164174423140873E+0
+            v = 0.7571363978689501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5817218061802611E+0
+            b = 0.5797589531445219E-1
+            v = 0.7489908329079234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1730:
+
+            v = 0.6309049437420976E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6398287705571748E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6357185073530720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2860923126194662E-1
+            v = 0.2221207162188168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7142556767711522E-1
+            v = 0.3475784022286848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1209199540995559E+0
+            v = 0.4350742443589804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1738673106594379E+0
+            v = 0.4978569136522127E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2284645438467734E+0
+            v = 0.5435036221998053E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2834807671701512E+0
+            v = 0.5765913388219542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3379680145467339E+0
+            v = 0.6001200359226003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3911355454819537E+0
+            v = 0.6162178172717512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4422860353001403E+0
+            v = 0.6265218152438485E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4907781568726057E+0
+            v = 0.6323987160974212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5360006153211468E+0
+            v = 0.6350767851540569E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6142105973596603E+0
+            v = 0.6354362775297107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6459300387977504E+0
+            v = 0.6352302462706235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718056125089225E+0
+            v = 0.6358117881417972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910888533186254E+0
+            v = 0.6373101590310117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7030467416823252E+0
+            v = 0.6390428961368665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8354951166354646E-1
+            v = 0.3186913449946576E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2050143009099486E+0
+            v = 0.4678028558591711E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3370208290706637E+0
+            v = 0.5538829697598626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4689051484233963E+0
+            v = 0.6044475907190476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5939400424557334E+0
+            v = 0.6313575103509012E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1394983311832261E+0
+            b = 0.4097581162050343E-1
+            v = 0.4078626431855630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1967999180485014E+0
+            b = 0.8851987391293348E-1
+            v = 0.4759933057812725E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2546183732548967E+0
+            b = 0.1397680182969819E+0
+            v = 0.5268151186413440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3121281074713875E+0
+            b = 0.1929452542226526E+0
+            v = 0.5643048560507316E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3685981078502492E+0
+            b = 0.2467898337061562E+0
+            v = 0.5914501076613073E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4233760321547856E+0
+            b = 0.3003104124785409E+0
+            v = 0.6104561257874195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4758671236059246E+0
+            b = 0.3526684328175033E+0
+            v = 0.6230252860707806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5255178579796463E+0
+            b = 0.4031134861145713E+0
+            v = 0.6305618761760796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5718025633734589E+0
+            b = 0.4509426448342351E+0
+            v = 0.6343092767597889E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2686927772723415E+0
+            b = 0.4711322502423248E-1
+            v = 0.5176268945737826E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3306006819904809E+0
+            b = 0.9784487303942695E-1
+            v = 0.5564840313313692E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3904906850594983E+0
+            b = 0.1505395810025273E+0
+            v = 0.5856426671038980E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4479957951904390E+0
+            b = 0.2039728156296050E+0
+            v = 0.6066386925777091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027076848919780E+0
+            b = 0.2571529941121107E+0
+            v = 0.6208824962234458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5542087392260217E+0
+            b = 0.3092191375815670E+0
+            v = 0.6296314297822907E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020850887375187E+0
+            b = 0.3593807506130276E+0
+            v = 0.6340423756791859E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4019851409179594E+0
+            b = 0.5063389934378671E-1
+            v = 0.5829627677107342E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4635614567449800E+0
+            b = 0.1032422269160612E+0
+            v = 0.6048693376081110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215860931591575E+0
+            b = 0.1566322094006254E+0
+            v = 0.6202362317732461E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5758202499099271E+0
+            b = 0.2098082827491099E+0
+            v = 0.6299005328403779E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6259893683876795E+0
+            b = 0.2618824114553391E+0
+            v = 0.6347722390609353E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5313795124811891E+0
+            b = 0.5263245019338556E-1
+            v = 0.6203778981238834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5893317955931995E+0
+            b = 0.1061059730982005E+0
+            v = 0.6308414671239979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6426246321215801E+0
+            b = 0.1594171564034221E+0
+            v = 0.6362706466959498E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6511904367376113E+0
+            b = 0.5354789536565540E-1
+            v = 0.6375414170333233E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2030:
+
+            v = 0.4656031899197431E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5421549195295507E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2540835336814348E-1
+            v = 0.1778522133346553E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6399322800504915E-1
+            v = 0.2811325405682796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1088269469804125E+0
+            v = 0.3548896312631459E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1570670798818287E+0
+            v = 0.4090310897173364E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2071163932282514E+0
+            v = 0.4493286134169965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2578914044450844E+0
+            v = 0.4793728447962723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3085687558169623E+0
+            v = 0.5015415319164265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3584719706267024E+0
+            v = 0.5175127372677937E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4070135594428709E+0
+            v = 0.5285522262081019E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4536618626222638E+0
+            v = 0.5356832703713962E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4979195686463577E+0
+            v = 0.5397914736175170E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5393075111126999E+0
+            v = 0.5416899441599930E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6115617676843916E+0
+            v = 0.5419308476889938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6414308435160159E+0
+            v = 0.5416936902030596E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6664099412721607E+0
+            v = 0.5419544338703164E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6859161771214913E+0
+            v = 0.5428983656630975E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6993625593503890E+0
+            v = 0.5442286500098193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7062393387719380E+0
+            v = 0.5452250345057301E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7479028168349763E-1
+            v = 0.2568002497728530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1848951153969366E+0
+            v = 0.3827211700292145E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3059529066581305E+0
+            v = 0.4579491561917824E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4285556101021362E+0
+            v = 0.5042003969083574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5468758653496526E+0
+            v = 0.5312708889976025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6565821978343439E+0
+            v = 0.5438401790747117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1253901572367117E+0
+            b = 0.3681917226439641E-1
+            v = 0.3316041873197344E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1775721510383941E+0
+            b = 0.7982487607213301E-1
+            v = 0.3899113567153771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2305693358216114E+0
+            b = 0.1264640966592335E+0
+            v = 0.4343343327201309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2836502845992063E+0
+            b = 0.1751585683418957E+0
+            v = 0.4679415262318919E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3361794746232590E+0
+            b = 0.2247995907632670E+0
+            v = 0.4930847981631031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3875979172264824E+0
+            b = 0.2745299257422246E+0
+            v = 0.5115031867540091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4374019316999074E+0
+            b = 0.3236373482441118E+0
+            v = 0.5245217148457367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4851275843340022E+0
+            b = 0.3714967859436741E+0
+            v = 0.5332041499895321E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5303391803806868E+0
+            b = 0.4175353646321745E+0
+            v = 0.5384583126021542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726197380596287E+0
+            b = 0.4612084406355461E+0
+            v = 0.5411067210798852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2431520732564863E+0
+            b = 0.4258040133043952E-1
+            v = 0.4259797391468714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3002096800895869E+0
+            b = 0.8869424306722721E-1
+            v = 0.4604931368460021E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3558554457457432E+0
+            b = 0.1368811706510655E+0
+            v = 0.4871814878255202E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097782537048887E+0
+            b = 0.1860739985015033E+0
+            v = 0.5072242910074885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4616337666067458E+0
+            b = 0.2354235077395853E+0
+            v = 0.5217069845235350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5110707008417874E+0
+            b = 0.2842074921347011E+0
+            v = 0.5315785966280310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577415286163795E+0
+            b = 0.3317784414984102E+0
+            v = 0.5376833708758905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6013060431366950E+0
+            b = 0.3775299002040700E+0
+            v = 0.5408032092069521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3661596767261781E+0
+            b = 0.4599367887164592E-1
+            v = 0.4842744917904866E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237633153506581E+0
+            b = 0.9404893773654421E-1
+            v = 0.5048926076188130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4786328454658452E+0
+            b = 0.1431377109091971E+0
+            v = 0.5202607980478373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5305702076789774E+0
+            b = 0.1924186388843570E+0
+            v = 0.5309932388325743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5793436224231788E+0
+            b = 0.2411590944775190E+0
+            v = 0.5377419770895208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6247069017094747E+0
+            b = 0.2886871491583605E+0
+            v = 0.5411696331677717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4874315552535204E+0
+            b = 0.4804978774953206E-1
+            v = 0.5197996293282420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5427337322059053E+0
+            b = 0.9716857199366665E-1
+            v = 0.5311120836622945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5943493747246700E+0
+            b = 0.1465205839795055E+0
+            v = 0.5384309319956951E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6421314033564943E+0
+            b = 0.1953579449803574E+0
+            v = 0.5421859504051886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020628374713980E+0
+            b = 0.4916375015738108E-1
+            v = 0.5390948355046314E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529222529856881E+0
+            b = 0.9861621540127005E-1
+            v = 0.5433312705027845E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2354:
+
+            v = 0.3922616270665292E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4703831750854424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4678202801282136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2290024646530589E-1
+            v = 0.1437832228979900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5779086652271284E-1
+            v = 0.2303572493577644E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9863103576375984E-1
+            v = 0.2933110752447454E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1428155792982185E+0
+            v = 0.3402905998359838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1888978116601463E+0
+            v = 0.3759138466870372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2359091682970210E+0
+            v = 0.4030638447899798E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2831228833706171E+0
+            v = 0.4236591432242211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3299495857966693E+0
+            v = 0.4390522656946746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3758840802660796E+0
+            v = 0.4502523466626247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4204751831009480E+0
+            v = 0.4580577727783541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4633068518751051E+0
+            v = 0.4631391616615899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5039849474507313E+0
+            v = 0.4660928953698676E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5421265793440747E+0
+            v = 0.4674751807936953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6092660230557310E+0
+            v = 0.4676414903932920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6374654204984869E+0
+            v = 0.4674086492347870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6615136472609892E+0
+            v = 0.4674928539483207E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6809487285958127E+0
+            v = 0.4680748979686447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6952980021665196E+0
+            v = 0.4690449806389040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041245497695400E+0
+            v = 0.4699877075860818E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6744033088306065E-1
+            v = 0.2099942281069176E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1678684485334166E+0
+            v = 0.3172269150712804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2793559049539613E+0
+            v = 0.3832051358546523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3935264218057639E+0
+            v = 0.4252193818146985E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5052629268232558E+0
+            v = 0.4513807963755000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6107905315437531E+0
+            v = 0.4657797469114178E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1135081039843524E+0
+            b = 0.3331954884662588E-1
+            v = 0.2733362800522836E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1612866626099378E+0
+            b = 0.7247167465436538E-1
+            v = 0.3235485368463559E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2100786550168205E+0
+            b = 0.1151539110849745E+0
+            v = 0.3624908726013453E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2592282009459942E+0
+            b = 0.1599491097143677E+0
+            v = 0.3925540070712828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3081740561320203E+0
+            b = 0.2058699956028027E+0
+            v = 0.4156129781116235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3564289781578164E+0
+            b = 0.2521624953502911E+0
+            v = 0.4330644984623263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035587288240703E+0
+            b = 0.2982090785797674E+0
+            v = 0.4459677725921312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491671196373903E+0
+            b = 0.3434762087235733E+0
+            v = 0.4551593004456795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4928854782917489E+0
+            b = 0.3874831357203437E+0
+            v = 0.4613341462749918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5343646791958988E+0
+            b = 0.4297814821746926E+0
+            v = 0.4651019618269806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5732683216530990E+0
+            b = 0.4699402260943537E+0
+            v = 0.4670249536100625E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2214131583218986E+0
+            b = 0.3873602040643895E-1
+            v = 0.3549555576441708E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2741796504750071E+0
+            b = 0.8089496256902013E-1
+            v = 0.3856108245249010E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3259797439149485E+0
+            b = 0.1251732177620872E+0
+            v = 0.4098622845756882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3765441148826891E+0
+            b = 0.1706260286403185E+0
+            v = 0.4286328604268950E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4255773574530558E+0
+            b = 0.2165115147300408E+0
+            v = 0.4427802198993945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4727795117058430E+0
+            b = 0.2622089812225259E+0
+            v = 0.4530473511488561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5178546895819012E+0
+            b = 0.3071721431296201E+0
+            v = 0.4600805475703138E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5605141192097460E+0
+            b = 0.3508998998801138E+0
+            v = 0.4644599059958017E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6004763319352512E+0
+            b = 0.3929160876166931E+0
+            v = 0.4667274455712508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3352842634946949E+0
+            b = 0.4202563457288019E-1
+            v = 0.4069360518020356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3891971629814670E+0
+            b = 0.8614309758870850E-1
+            v = 0.4260442819919195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4409875565542281E+0
+            b = 0.1314500879380001E+0
+            v = 0.4408678508029063E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4904893058592484E+0
+            b = 0.1772189657383859E+0
+            v = 0.4518748115548597E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5375056138769549E+0
+            b = 0.2228277110050294E+0
+            v = 0.4595564875375116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5818255708669969E+0
+            b = 0.2677179935014386E+0
+            v = 0.4643988774315846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6232334858144959E+0
+            b = 0.3113675035544165E+0
+            v = 0.4668827491646946E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4489485354492058E+0
+            b = 0.4409162378368174E-1
+            v = 0.4400541823741973E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5015136875933150E+0
+            b = 0.8939009917748489E-1
+            v = 0.4514512890193797E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5511300550512623E+0
+            b = 0.1351806029383365E+0
+            v = 0.4596198627347549E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5976720409858000E+0
+            b = 0.1808370355053196E+0
+            v = 0.4648659016801781E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6409956378989354E+0
+            b = 0.2257852192301602E+0
+            v = 0.4675502017157673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5581222330827514E+0
+            b = 0.4532173421637160E-1
+            v = 0.4598494476455523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6074705984161695E+0
+            b = 0.9117488031840314E-1
+            v = 0.4654916955152048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6532272537379033E+0
+            b = 0.1369294213140155E+0
+            v = 0.4684709779505137E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6594761494500487E+0
+            b = 0.4589901487275583E-1
+            v = 0.4691445539106986E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2702:
+
+            v = 0.2998675149888161E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4077860529495355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2065562538818703E-1
+            v = 0.1185349192520667E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5250918173022379E-1
+            v = 0.1913408643425751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8993480082038376E-1
+            v = 0.2452886577209897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1306023924436019E+0
+            v = 0.2862408183288702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1732060388531418E+0
+            v = 0.3178032258257357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2168727084820249E+0
+            v = 0.3422945667633690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2609528309173586E+0
+            v = 0.3612790520235922E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3049252927938952E+0
+            v = 0.3758638229818521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3483484138084404E+0
+            v = 0.3868711798859953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3908321549106406E+0
+            v = 0.3949429933189938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4320210071894814E+0
+            v = 0.4006068107541156E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4715824795890053E+0
+            v = 0.4043192149672723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5091984794078453E+0
+            v = 0.4064947495808078E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5445580145650803E+0
+            v = 0.4075245619813152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6072575796841768E+0
+            v = 0.4076423540893566E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6339484505755803E+0
+            v = 0.4074280862251555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6570718257486958E+0
+            v = 0.4074163756012244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6762557330090709E+0
+            v = 0.4077647795071246E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911161696923790E+0
+            v = 0.4084517552782530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012841911659961E+0
+            v = 0.4092468459224052E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7064559272410020E+0
+            v = 0.4097872687240906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6123554989894765E-1
+            v = 0.1738986811745028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1533070348312393E+0
+            v = 0.2659616045280191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2563902605244206E+0
+            v = 0.3240596008171533E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3629346991663361E+0
+            v = 0.3621195964432943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4683949968987538E+0
+            v = 0.3868838330760539E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5694479240657952E+0
+            v = 0.4018911532693111E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6634465430993955E+0
+            v = 0.4089929432983252E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1033958573552305E+0
+            b = 0.3034544009063584E-1
+            v = 0.2279907527706409E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1473521412414395E+0
+            b = 0.6618803044247135E-1
+            v = 0.2715205490578897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1924552158705967E+0
+            b = 0.1054431128987715E+0
+            v = 0.3057917896703976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381094362890328E+0
+            b = 0.1468263551238858E+0
+            v = 0.3326913052452555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838121707936760E+0
+            b = 0.1894486108187886E+0
+            v = 0.3537334711890037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3291323133373415E+0
+            b = 0.2326374238761579E+0
+            v = 0.3700567500783129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3736896978741460E+0
+            b = 0.2758485808485768E+0
+            v = 0.3825245372589122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4171406040760013E+0
+            b = 0.3186179331996921E+0
+            v = 0.3918125171518296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4591677985256915E+0
+            b = 0.3605329796303794E+0
+            v = 0.3984720419937579E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4994733831718418E+0
+            b = 0.4012147253586509E+0
+            v = 0.4029746003338211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5377731830445096E+0
+            b = 0.4403050025570692E+0
+            v = 0.4057428632156627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5737917830001331E+0
+            b = 0.4774565904277483E+0
+            v = 0.4071719274114857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2027323586271389E+0
+            b = 0.3544122504976147E-1
+            v = 0.2990236950664119E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2516942375187273E+0
+            b = 0.7418304388646328E-1
+            v = 0.3262951734212878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3000227995257181E+0
+            b = 0.1150502745727186E+0
+            v = 0.3482634608242413E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3474806691046342E+0
+            b = 0.1571963371209364E+0
+            v = 0.3656596681700892E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3938103180359209E+0
+            b = 0.1999631877247100E+0
+            v = 0.3791740467794218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4387519590455703E+0
+            b = 0.2428073457846535E+0
+            v = 0.3894034450156905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4820503960077787E+0
+            b = 0.2852575132906155E+0
+            v = 0.3968600245508371E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5234573778475101E+0
+            b = 0.3268884208674639E+0
+            v = 0.4019931351420050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5627318647235282E+0
+            b = 0.3673033321675939E+0
+            v = 0.4052108801278599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5996390607156954E+0
+            b = 0.4061211551830290E+0
+            v = 0.4068978613940934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3084780753791947E+0
+            b = 0.3860125523100059E-1
+            v = 0.3454275351319704E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3589988275920223E+0
+            b = 0.7928938987104867E-1
+            v = 0.3629963537007920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4078628415881973E+0
+            b = 0.1212614643030087E+0
+            v = 0.3770187233889873E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4549287258889735E+0
+            b = 0.1638770827382693E+0
+            v = 0.3878608613694378E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5000278512957279E+0
+            b = 0.2065965798260176E+0
+            v = 0.3959065270221274E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5429785044928199E+0
+            b = 0.2489436378852235E+0
+            v = 0.4015286975463570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5835939850491711E+0
+            b = 0.2904811368946891E+0
+            v = 0.4050866785614717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6216870353444856E+0
+            b = 0.3307941957666609E+0
+            v = 0.4069320185051913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4151104662709091E+0
+            b = 0.4064829146052554E-1
+            v = 0.3760120964062763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4649804275009218E+0
+            b = 0.8258424547294755E-1
+            v = 0.3870969564418064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5124695757009662E+0
+            b = 0.1251841962027289E+0
+            v = 0.3955287790534055E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5574711100606224E+0
+            b = 0.1679107505976331E+0
+            v = 0.4015361911302668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5998597333287227E+0
+            b = 0.2102805057358715E+0
+            v = 0.4053836986719548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6395007148516600E+0
+            b = 0.2518418087774107E+0
+            v = 0.4073578673299117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5188456224746252E+0
+            b = 0.4194321676077518E-1
+            v = 0.3954628379231406E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5664190707942778E+0
+            b = 0.8457661551921499E-1
+            v = 0.4017645508847530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6110464353283153E+0
+            b = 0.1273652932519396E+0
+            v = 0.4059030348651293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6526430302051563E+0
+            b = 0.1698173239076354E+0
+            v = 0.4080565809484880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6167551880377548E+0
+            b = 0.4266398851548864E-1
+            v = 0.4063018753664651E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6607195418355383E+0
+            b = 0.8551925814238349E-1
+            v = 0.4087191292799671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3074:
+
+            v = 0.2599095953754734E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3603134089687541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3586067974412447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1886108518723392E-1
+            v = 0.9831528474385880E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4800217244625303E-1
+            v = 0.1605023107954450E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8244922058397242E-1
+            v = 0.2072200131464099E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1200408362484023E+0
+            v = 0.2431297618814187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1595773530809965E+0
+            v = 0.2711819064496707E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2002635973434064E+0
+            v = 0.2932762038321116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2415127590139982E+0
+            v = 0.3107032514197368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2828584158458477E+0
+            v = 0.3243808058921213E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3239091015338138E+0
+            v = 0.3349899091374030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3643225097962194E+0
+            v = 0.3430580688505218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4037897083691802E+0
+            v = 0.3490124109290343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4420247515194127E+0
+            v = 0.3532148948561955E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4787572538464938E+0
+            v = 0.3559862669062833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5137265251275234E+0
+            v = 0.3576224317551411E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5466764056654611E+0
+            v = 0.3584050533086076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6054859420813535E+0
+            v = 0.3584903581373224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6308106701764562E+0
+            v = 0.3582991879040586E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6530369230179584E+0
+            v = 0.3582371187963125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718609524611158E+0
+            v = 0.3584353631122350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6869676499894013E+0
+            v = 0.3589120166517785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6980467077240748E+0
+            v = 0.3595445704531601E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7048241721250522E+0
+            v = 0.3600943557111074E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5591105222058232E-1
+            v = 0.1456447096742039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1407384078513916E+0
+            v = 0.2252370188283782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2364035438976309E+0
+            v = 0.2766135443474897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3360602737818170E+0
+            v = 0.3110729491500851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4356292630054665E+0
+            v = 0.3342506712303391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5321569415256174E+0
+            v = 0.3491981834026860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6232956305040554E+0
+            v = 0.3576003604348932E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9469870086838469E-1
+            b = 0.2778748387309470E-1
+            v = 0.1921921305788564E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1353170300568141E+0
+            b = 0.6076569878628364E-1
+            v = 0.2301458216495632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1771679481726077E+0
+            b = 0.9703072762711040E-1
+            v = 0.2604248549522893E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197066664231751E+0
+            b = 0.1354112458524762E+0
+            v = 0.2845275425870697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2624783557374927E+0
+            b = 0.1750996479744100E+0
+            v = 0.3036870897974840E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3050969521214442E+0
+            b = 0.2154896907449802E+0
+            v = 0.3188414832298066E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3472252637196021E+0
+            b = 0.2560954625740152E+0
+            v = 0.3307046414722089E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3885610219026360E+0
+            b = 0.2965070050624096E+0
+            v = 0.3398330969031360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4288273776062765E+0
+            b = 0.3363641488734497E+0
+            v = 0.3466757899705373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677662471302948E+0
+            b = 0.3753400029836788E+0
+            v = 0.3516095923230054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5051333589553359E+0
+            b = 0.4131297522144286E+0
+            v = 0.3549645184048486E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5406942145810492E+0
+            b = 0.4494423776081795E+0
+            v = 0.3570415969441392E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5742204122576457E+0
+            b = 0.4839938958841502E+0
+            v = 0.3581251798496118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1865407027225188E+0
+            b = 0.3259144851070796E-1
+            v = 0.2543491329913348E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2321186453689432E+0
+            b = 0.6835679505297343E-1
+            v = 0.2786711051330776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2773159142523882E+0
+            b = 0.1062284864451989E+0
+            v = 0.2985552361083679E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3219200192237254E+0
+            b = 0.1454404409323047E+0
+            v = 0.3145867929154039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3657032593944029E+0
+            b = 0.1854018282582510E+0
+            v = 0.3273290662067609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4084376778363622E+0
+            b = 0.2256297412014750E+0
+            v = 0.3372705511943501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4499004945751427E+0
+            b = 0.2657104425000896E+0
+            v = 0.3448274437851510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4898758141326335E+0
+            b = 0.3052755487631557E+0
+            v = 0.3503592783048583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281547442266309E+0
+            b = 0.3439863920645423E+0
+            v = 0.3541854792663162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5645346989813992E+0
+            b = 0.3815229456121914E+0
+            v = 0.3565995517909428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5988181252159848E+0
+            b = 0.4175752420966734E+0
+            v = 0.3578802078302898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2850425424471603E+0
+            b = 0.3562149509862536E-1
+            v = 0.2958644592860982E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3324619433027876E+0
+            b = 0.7330318886871096E-1
+            v = 0.3119548129116835E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3785848333076282E+0
+            b = 0.1123226296008472E+0
+            v = 0.3250745225005984E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4232891028562115E+0
+            b = 0.1521084193337708E+0
+            v = 0.3355153415935208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4664287050829722E+0
+            b = 0.1921844459223610E+0
+            v = 0.3435847568549328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5078458493735726E+0
+            b = 0.2321360989678303E+0
+            v = 0.3495786831622488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473779816204180E+0
+            b = 0.2715886486360520E+0
+            v = 0.3537767805534621E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5848617133811376E+0
+            b = 0.3101924707571355E+0
+            v = 0.3564459815421428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6201348281584888E+0
+            b = 0.3476121052890973E+0
+            v = 0.3578464061225468E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3852191185387871E+0
+            b = 0.3763224880035108E-1
+            v = 0.3239748762836212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4325025061073423E+0
+            b = 0.7659581935637135E-1
+            v = 0.3345491784174287E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4778486229734490E+0
+            b = 0.1163381306083900E+0
+            v = 0.3429126177301782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5211663693009000E+0
+            b = 0.1563890598752899E+0
+            v = 0.3492420343097421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5623469504853703E+0
+            b = 0.1963320810149200E+0
+            v = 0.3537399050235257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6012718188659246E+0
+            b = 0.2357847407258738E+0
+            v = 0.3566209152659172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6378179206390117E+0
+            b = 0.2743846121244060E+0
+            v = 0.3581084321919782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4836936460214534E+0
+            b = 0.3895902610739024E-1
+            v = 0.3426522117591512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5293792562683797E+0
+            b = 0.7871246819312640E-1
+            v = 0.3491848770121379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726281253100033E+0
+            b = 0.1187963808202981E+0
+            v = 0.3539318235231476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6133658776169068E+0
+            b = 0.1587914708061787E+0
+            v = 0.3570231438458694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6515085491865307E+0
+            b = 0.1983058575227646E+0
+            v = 0.3586207335051714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5778692716064976E+0
+            b = 0.3977209689791542E-1
+            v = 0.3541196205164025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6207904288086192E+0
+            b = 0.7990157592981152E-1
+            v = 0.3574296911573953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6608688171046802E+0
+            b = 0.1199671308754309E+0
+            v = 0.3591993279818963E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6656263089489130E+0
+            b = 0.4015955957805969E-1
+            v = 0.3595855034661997E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3470:
+
+            v = 0.2040382730826330E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3178149703889544E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1721420832906233E-1
+            v = 0.8288115128076110E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4408875374981770E-1
+            v = 0.1360883192522954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7594680813878681E-1
+            v = 0.1766854454542662E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1108335359204799E+0
+            v = 0.2083153161230153E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1476517054388567E+0
+            v = 0.2333279544657158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1856731870860615E+0
+            v = 0.2532809539930247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2243634099428821E+0
+            v = 0.2692472184211158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2633006881662727E+0
+            v = 0.2819949946811885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3021340904916283E+0
+            v = 0.2920953593973030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3405594048030089E+0
+            v = 0.2999889782948352E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3783044434007372E+0
+            v = 0.3060292120496902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4151194767407910E+0
+            v = 0.3105109167522192E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4507705766443257E+0
+            v = 0.3136902387550312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4850346056573187E+0
+            v = 0.3157984652454632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5176950817792470E+0
+            v = 0.3170516518425422E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5485384240820989E+0
+            v = 0.3176568425633755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6039117238943308E+0
+            v = 0.3177198411207062E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6279956655573113E+0
+            v = 0.3175519492394733E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6493636169568952E+0
+            v = 0.3174654952634756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6677644117704504E+0
+            v = 0.3175676415467654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6829368572115624E+0
+            v = 0.3178923417835410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6946195818184121E+0
+            v = 0.3183788287531909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025711542057026E+0
+            v = 0.3188755151918807E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7066004767140119E+0
+            v = 0.3191916889313849E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5132537689946062E-1
+            v = 0.1231779611744508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1297994661331225E+0
+            v = 0.1924661373839880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2188852049401307E+0
+            v = 0.2380881867403424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3123174824903457E+0
+            v = 0.2693100663037885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4064037620738195E+0
+            v = 0.2908673382834366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4984958396944782E+0
+            v = 0.3053914619381535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5864975046021365E+0
+            v = 0.3143916684147777E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6686711634580175E+0
+            v = 0.3187042244055363E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8715738780835950E-1
+            b = 0.2557175233367578E-1
+            v = 0.1635219535869790E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1248383123134007E+0
+            b = 0.5604823383376681E-1
+            v = 0.1968109917696070E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1638062693383378E+0
+            b = 0.8968568601900765E-1
+            v = 0.2236754342249974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2035586203373176E+0
+            b = 0.1254086651976279E+0
+            v = 0.2453186687017181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2436798975293774E+0
+            b = 0.1624780150162012E+0
+            v = 0.2627551791580541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838207507773806E+0
+            b = 0.2003422342683208E+0
+            v = 0.2767654860152220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236787502217692E+0
+            b = 0.2385628026255263E+0
+            v = 0.2879467027765895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3629849554840691E+0
+            b = 0.2767731148783578E+0
+            v = 0.2967639918918702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4014948081992087E+0
+            b = 0.3146542308245309E+0
+            v = 0.3035900684660351E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4389818379260225E+0
+            b = 0.3519196415895088E+0
+            v = 0.3087338237298308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4752331143674377E+0
+            b = 0.3883050984023654E+0
+            v = 0.3124608838860167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5100457318374018E+0
+            b = 0.4235613423908649E+0
+            v = 0.3150084294226743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5432238388954868E+0
+            b = 0.4574484717196220E+0
+            v = 0.3165958398598402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5745758685072442E+0
+            b = 0.4897311639255524E+0
+            v = 0.3174320440957372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1723981437592809E+0
+            b = 0.3010630597881105E-1
+            v = 0.2182188909812599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2149553257844597E+0
+            b = 0.6326031554204694E-1
+            v = 0.2399727933921445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2573256081247422E+0
+            b = 0.9848566980258631E-1
+            v = 0.2579796133514652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2993163751238106E+0
+            b = 0.1350835952384266E+0
+            v = 0.2727114052623535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3407238005148000E+0
+            b = 0.1725184055442181E+0
+            v = 0.2846327656281355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3813454978483264E+0
+            b = 0.2103559279730725E+0
+            v = 0.2941491102051334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4209848104423343E+0
+            b = 0.2482278774554860E+0
+            v = 0.3016049492136107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4594519699996300E+0
+            b = 0.2858099509982883E+0
+            v = 0.3072949726175648E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4965640166185930E+0
+            b = 0.3228075659915428E+0
+            v = 0.3114768142886460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321441655571562E+0
+            b = 0.3589459907204151E+0
+            v = 0.3143823673666223E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5660208438582166E+0
+            b = 0.3939630088864310E+0
+            v = 0.3162269764661535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5980264315964364E+0
+            b = 0.4276029922949089E+0
+            v = 0.3172164663759821E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2644215852350733E+0
+            b = 0.3300939429072552E-1
+            v = 0.2554575398967435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3090113743443063E+0
+            b = 0.6803887650078501E-1
+            v = 0.2701704069135677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3525871079197808E+0
+            b = 0.1044326136206709E+0
+            v = 0.2823693413468940E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3950418005354029E+0
+            b = 0.1416751597517679E+0
+            v = 0.2922898463214289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4362475663430163E+0
+            b = 0.1793408610504821E+0
+            v = 0.3001829062162428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760661812145854E+0
+            b = 0.2170630750175722E+0
+            v = 0.3062890864542953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143551042512103E+0
+            b = 0.2545145157815807E+0
+            v = 0.3108328279264746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5509709026935597E+0
+            b = 0.2913940101706601E+0
+            v = 0.3140243146201245E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5857711030329428E+0
+            b = 0.3274169910910705E+0
+            v = 0.3160638030977130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6186149917404392E+0
+            b = 0.3623081329317265E+0
+            v = 0.3171462882206275E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3586894569557064E+0
+            b = 0.3497354386450040E-1
+            v = 0.2812388416031796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035266610019441E+0
+            b = 0.7129736739757095E-1
+            v = 0.2912137500288045E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4467775312332510E+0
+            b = 0.1084758620193165E+0
+            v = 0.2993241256502206E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4883638346608543E+0
+            b = 0.1460915689241772E+0
+            v = 0.3057101738983822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281908348434601E+0
+            b = 0.1837790832369980E+0
+            v = 0.3105319326251432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5661542687149311E+0
+            b = 0.2212075390874021E+0
+            v = 0.3139565514428167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6021450102031452E+0
+            b = 0.2580682841160985E+0
+            v = 0.3161543006806366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6360520783610050E+0
+            b = 0.2940656362094121E+0
+            v = 0.3172985960613294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4521611065087196E+0
+            b = 0.3631055365867002E-1
+            v = 0.2989400336901431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4959365651560963E+0
+            b = 0.7348318468484350E-1
+            v = 0.3054555883947677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5376815804038283E+0
+            b = 0.1111087643812648E+0
+            v = 0.3104764960807702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5773314480243768E+0
+            b = 0.1488226085145408E+0
+            v = 0.3141015825977616E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6148113245575056E+0
+            b = 0.1862892274135151E+0
+            v = 0.3164520621159896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6500407462842380E+0
+            b = 0.2231909701714456E+0
+            v = 0.3176652305912204E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5425151448707213E+0
+            b = 0.3718201306118944E-1
+            v = 0.3105097161023939E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5841860556907931E+0
+            b = 0.7483616335067346E-1
+            v = 0.3143014117890550E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6234632186851500E+0
+            b = 0.1125990834266120E+0
+            v = 0.3168172866287200E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6602934551848843E+0
+            b = 0.1501303813157619E+0
+            v = 0.3181401865570968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6278573968375105E+0
+            b = 0.3767559930245720E-1
+            v = 0.3170663659156037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6665611711264577E+0
+            b = 0.7548443301360158E-1
+            v = 0.3185447944625510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3890:
+
+            v = 0.1807395252196920E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2848008782238827E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2836065837530581E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1587876419858352E-1
+            v = 0.7013149266673816E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4069193593751206E-1
+            v = 0.1162798021956766E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025888115257997E-1
+            v = 0.1518728583972105E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1027495450028704E+0
+            v = 0.1798796108216934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1371457730893426E+0
+            v = 0.2022593385972785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1727758532671953E+0
+            v = 0.2203093105575464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2091492038929037E+0
+            v = 0.2349294234299855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2458813281751915E+0
+            v = 0.2467682058747003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2826545859450066E+0
+            v = 0.2563092683572224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3191957291799622E+0
+            v = 0.2639253896763318E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552621469299578E+0
+            v = 0.2699137479265108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3906329503406230E+0
+            v = 0.2745196420166739E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4251028614093031E+0
+            v = 0.2779529197397593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4584777520111870E+0
+            v = 0.2803996086684265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4905711358710193E+0
+            v = 0.2820302356715842E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5212011669847385E+0
+            v = 0.2830056747491068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5501878488737995E+0
+            v = 0.2834808950776839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6025037877479342E+0
+            v = 0.2835282339078929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6254572689549016E+0
+            v = 0.2833819267065800E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6460107179528248E+0
+            v = 0.2832858336906784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6639541138154251E+0
+            v = 0.2833268235451244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6790688515667495E+0
+            v = 0.2835432677029253E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911338580371512E+0
+            v = 0.2839091722743049E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6999385956126490E+0
+            v = 0.2843308178875841E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7053037748656896E+0
+            v = 0.2846703550533846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4732224387180115E-1
+            v = 0.1051193406971900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1202100529326803E+0
+            v = 0.1657871838796974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2034304820664855E+0
+            v = 0.2064648113714232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2912285643573002E+0
+            v = 0.2347942745819741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3802361792726768E+0
+            v = 0.2547775326597726E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4680598511056146E+0
+            v = 0.2686876684847025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5528151052155599E+0
+            v = 0.2778665755515867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6329386307803041E+0
+            v = 0.2830996616782929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8056516651369069E-1
+            b = 0.2363454684003124E-1
+            v = 0.1403063340168372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1156476077139389E+0
+            b = 0.5191291632545936E-1
+            v = 0.1696504125939477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1520473382760421E+0
+            b = 0.8322715736994519E-1
+            v = 0.1935787242745390E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1892986699745931E+0
+            b = 0.1165855667993712E+0
+            v = 0.2130614510521968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2270194446777792E+0
+            b = 0.1513077167409504E+0
+            v = 0.2289381265931048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2648908185093273E+0
+            b = 0.1868882025807859E+0
+            v = 0.2418630292816186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3026389259574136E+0
+            b = 0.2229277629776224E+0
+            v = 0.2523400495631193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3400220296151384E+0
+            b = 0.2590951840746235E+0
+            v = 0.2607623973449605E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3768217953335510E+0
+            b = 0.2951047291750847E+0
+            v = 0.2674441032689209E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4128372900921884E+0
+            b = 0.3307019714169930E+0
+            v = 0.2726432360343356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4478807131815630E+0
+            b = 0.3656544101087634E+0
+            v = 0.2765787685924545E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4817742034089257E+0
+            b = 0.3997448951939695E+0
+            v = 0.2794428690642224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143472814653344E+0
+            b = 0.4327667110812024E+0
+            v = 0.2814099002062895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454346213905650E+0
+            b = 0.4645196123532293E+0
+            v = 0.2826429531578994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5748739313170252E+0
+            b = 0.4948063555703345E+0
+            v = 0.2832983542550884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1599598738286342E+0
+            b = 0.2792357590048985E-1
+            v = 0.1886695565284976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1998097412500951E+0
+            b = 0.5877141038139065E-1
+            v = 0.2081867882748234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2396228952566202E+0
+            b = 0.9164573914691377E-1
+            v = 0.2245148680600796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2792228341097746E+0
+            b = 0.1259049641962687E+0
+            v = 0.2380370491511872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3184251107546741E+0
+            b = 0.1610594823400863E+0
+            v = 0.2491398041852455E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3570481164426244E+0
+            b = 0.1967151653460898E+0
+            v = 0.2581632405881230E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3949164710492144E+0
+            b = 0.2325404606175168E+0
+            v = 0.2653965506227417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318617293970503E+0
+            b = 0.2682461141151439E+0
+            v = 0.2710857216747087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677221009931678E+0
+            b = 0.3035720116011973E+0
+            v = 0.2754434093903659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5023417939270955E+0
+            b = 0.3382781859197439E+0
+            v = 0.2786579932519380E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5355701836636128E+0
+            b = 0.3721383065625942E+0
+            v = 0.2809011080679474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5672608451328771E+0
+            b = 0.4049346360466055E+0
+            v = 0.2823336184560987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5972704202540162E+0
+            b = 0.4364538098633802E+0
+            v = 0.2831101175806309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2461687022333596E+0
+            b = 0.3070423166833368E-1
+            v = 0.2221679970354546E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2881774566286831E+0
+            b = 0.6338034669281885E-1
+            v = 0.2356185734270703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3293963604116978E+0
+            b = 0.9742862487067941E-1
+            v = 0.2469228344805590E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3697303822241377E+0
+            b = 0.1323799532282290E+0
+            v = 0.2562726348642046E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4090663023135127E+0
+            b = 0.1678497018129336E+0
+            v = 0.2638756726753028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4472819355411712E+0
+            b = 0.2035095105326114E+0
+            v = 0.2699311157390862E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4842513377231437E+0
+            b = 0.2390692566672091E+0
+            v = 0.2746233268403837E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5198477629962928E+0
+            b = 0.2742649818076149E+0
+            v = 0.2781225674454771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5539453011883145E+0
+            b = 0.3088503806580094E+0
+            v = 0.2805881254045684E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5864196762401251E+0
+            b = 0.3425904245906614E+0
+            v = 0.2821719877004913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6171484466668390E+0
+            b = 0.3752562294789468E+0
+            v = 0.2830222502333124E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3350337830565727E+0
+            b = 0.3261589934634747E-1
+            v = 0.2457995956744870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3775773224758284E+0
+            b = 0.6658438928081572E-1
+            v = 0.2551474407503706E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4188155229848973E+0
+            b = 0.1014565797157954E+0
+            v = 0.2629065335195311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4586805892009344E+0
+            b = 0.1368573320843822E+0
+            v = 0.2691900449925075E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4970895714224235E+0
+            b = 0.1724614851951608E+0
+            v = 0.2741275485754276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5339505133960747E+0
+            b = 0.2079779381416412E+0
+            v = 0.2778530970122595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5691665792531440E+0
+            b = 0.2431385788322288E+0
+            v = 0.2805010567646741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6026387682680377E+0
+            b = 0.2776901883049853E+0
+            v = 0.2822055834031040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6342676150163307E+0
+            b = 0.3113881356386632E+0
+            v = 0.2831016901243473E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237951119537067E+0
+            b = 0.3394877848664351E-1
+            v = 0.2624474901131803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4656918683234929E+0
+            b = 0.6880219556291447E-1
+            v = 0.2688034163039377E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5058857069185980E+0
+            b = 0.1041946859721635E+0
+            v = 0.2738932751287636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5443204666713996E+0
+            b = 0.1398039738736393E+0
+            v = 0.2777944791242523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5809298813759742E+0
+            b = 0.1753373381196155E+0
+            v = 0.2806011661660987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156416039447128E+0
+            b = 0.2105215793514010E+0
+            v = 0.2824181456597460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6483801351066604E+0
+            b = 0.2450953312157051E+0
+            v = 0.2833585216577828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5103616577251688E+0
+            b = 0.3485560643800719E-1
+            v = 0.2738165236962878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506738792580681E+0
+            b = 0.7026308631512033E-1
+            v = 0.2778365208203180E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5889573040995292E+0
+            b = 0.1059035061296403E+0
+            v = 0.2807852940418966E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6251641589516930E+0
+            b = 0.1414823925236026E+0
+            v = 0.2827245949674705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6592414921570178E+0
+            b = 0.1767207908214530E+0
+            v = 0.2837342344829828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5930314017533384E+0
+            b = 0.3542189339561672E-1
+            v = 0.2809233907610981E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6309812253390175E+0
+            b = 0.7109574040369549E-1
+            v = 0.2829930809742694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6666296011353230E+0
+            b = 0.1067259792282730E+0
+            v = 0.2841097874111479E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6703715271049922E+0
+            b = 0.3569455268820809E-1
+            v = 0.2843455206008783E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4334:
+
+            v = 0.1449063022537883E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2546377329828424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1462896151831013E-1
+            v = 0.6018432961087496E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3769840812493139E-1
+            v = 0.1002286583263673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6524701904096891E-1
+            v = 0.1315222931028093E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9560543416134648E-1
+            v = 0.1564213746876724E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1278335898929198E+0
+            v = 0.1765118841507736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1613096104466031E+0
+            v = 0.1928737099311080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1955806225745371E+0
+            v = 0.2062658534263270E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2302935218498028E+0
+            v = 0.2172395445953787E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2651584344113027E+0
+            v = 0.2262076188876047E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2999276825183209E+0
+            v = 0.2334885699462397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3343828669718798E+0
+            v = 0.2393355273179203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3683265013750518E+0
+            v = 0.2439559200468863E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4015763206518108E+0
+            v = 0.2475251866060002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4339612026399770E+0
+            v = 0.2501965558158773E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4653180651114582E+0
+            v = 0.2521081407925925E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4954893331080803E+0
+            v = 0.2533881002388081E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5243207068924930E+0
+            v = 0.2541582900848261E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5516590479041704E+0
+            v = 0.2545365737525860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6012371927804176E+0
+            v = 0.2545726993066799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6231574466449819E+0
+            v = 0.2544456197465555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6429416514181271E+0
+            v = 0.2543481596881064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6604124272943595E+0
+            v = 0.2543506451429194E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6753851470408250E+0
+            v = 0.2544905675493763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6876717970626160E+0
+            v = 0.2547611407344429E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6970895061319234E+0
+            v = 0.2551060375448869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7034746912553310E+0
+            v = 0.2554291933816039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067017217542295E+0
+            v = 0.2556255710686343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4382223501131123E-1
+            v = 0.9041339695118195E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1117474077400006E+0
+            v = 0.1438426330079022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1897153252911440E+0
+            v = 0.1802523089820518E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2724023009910331E+0
+            v = 0.2060052290565496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3567163308709902E+0
+            v = 0.2245002248967466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4404784483028087E+0
+            v = 0.2377059847731150E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5219833154161411E+0
+            v = 0.2468118955882525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5998179868977553E+0
+            v = 0.2525410872966528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6727803154548222E+0
+            v = 0.2553101409933397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7476563943166086E-1
+            b = 0.2193168509461185E-1
+            v = 0.1212879733668632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1075341482001416E+0
+            b = 0.4826419281533887E-1
+            v = 0.1472872881270931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1416344885203259E+0
+            b = 0.7751191883575742E-1
+            v = 0.1686846601010828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1766325315388586E+0
+            b = 0.1087558139247680E+0
+            v = 0.1862698414660208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2121744174481514E+0
+            b = 0.1413661374253096E+0
+            v = 0.2007430956991861E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2479669443408145E+0
+            b = 0.1748768214258880E+0
+            v = 0.2126568125394796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2837600452294113E+0
+            b = 0.2089216406612073E+0
+            v = 0.2224394603372113E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3193344933193984E+0
+            b = 0.2431987685545972E+0
+            v = 0.2304264522673135E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3544935442438745E+0
+            b = 0.2774497054377770E+0
+            v = 0.2368854288424087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3890571932288154E+0
+            b = 0.3114460356156915E+0
+            v = 0.2420352089461772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4228581214259090E+0
+            b = 0.3449806851913012E+0
+            v = 0.2460597113081295E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4557387211304052E+0
+            b = 0.3778618641248256E+0
+            v = 0.2491181912257687E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4875487950541643E+0
+            b = 0.4099086391698978E+0
+            v = 0.2513528194205857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5181436529962997E+0
+            b = 0.4409474925853973E+0
+            v = 0.2528943096693220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473824095600661E+0
+            b = 0.4708094517711291E+0
+            v = 0.2538660368488136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751263398976174E+0
+            b = 0.4993275140354637E+0
+            v = 0.2543868648299022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1489515746840028E+0
+            b = 0.2599381993267017E-1
+            v = 0.1642595537825183E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1863656444351767E+0
+            b = 0.5479286532462190E-1
+            v = 0.1818246659849308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2238602880356348E+0
+            b = 0.8556763251425254E-1
+            v = 0.1966565649492420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2612723375728160E+0
+            b = 0.1177257802267011E+0
+            v = 0.2090677905657991E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2984332990206190E+0
+            b = 0.1508168456192700E+0
+            v = 0.2193820409510504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3351786584663333E+0
+            b = 0.1844801892177727E+0
+            v = 0.2278870827661928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3713505522209120E+0
+            b = 0.2184145236087598E+0
+            v = 0.2348283192282090E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4067981098954663E+0
+            b = 0.2523590641486229E+0
+            v = 0.2404139755581477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4413769993687534E+0
+            b = 0.2860812976901373E+0
+            v = 0.2448227407760734E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4749487182516394E+0
+            b = 0.3193686757808996E+0
+            v = 0.2482110455592573E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5073798105075426E+0
+            b = 0.3520226949547602E+0
+            v = 0.2507192397774103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5385410448878654E+0
+            b = 0.3838544395667890E+0
+            v = 0.2524765968534880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5683065353670530E+0
+            b = 0.4146810037640963E+0
+            v = 0.2536052388539425E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5965527620663510E+0
+            b = 0.4443224094681121E+0
+            v = 0.2542230588033068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2299227700856157E+0
+            b = 0.2865757664057584E-1
+            v = 0.1944817013047896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2695752998553267E+0
+            b = 0.5923421684485993E-1
+            v = 0.2067862362746635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3086178716611389E+0
+            b = 0.9117817776057715E-1
+            v = 0.2172440734649114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3469649871659077E+0
+            b = 0.1240593814082605E+0
+            v = 0.2260125991723423E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3845153566319655E+0
+            b = 0.1575272058259175E+0
+            v = 0.2332655008689523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4211600033403215E+0
+            b = 0.1912845163525413E+0
+            v = 0.2391699681532458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4567867834329882E+0
+            b = 0.2250710177858171E+0
+            v = 0.2438801528273928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912829319232061E+0
+            b = 0.2586521303440910E+0
+            v = 0.2475370504260665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245364793303812E+0
+            b = 0.2918112242865407E+0
+            v = 0.2502707235640574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5564369788915756E+0
+            b = 0.3243439239067890E+0
+            v = 0.2522031701054241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5868757697775287E+0
+            b = 0.3560536787835351E+0
+            v = 0.2534511269978784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6157458853519617E+0
+            b = 0.3867480821242581E+0
+            v = 0.2541284914955151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3138461110672113E+0
+            b = 0.3051374637507278E-1
+            v = 0.2161509250688394E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3542495872050569E+0
+            b = 0.6237111233730755E-1
+            v = 0.2248778513437852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3935751553120181E+0
+            b = 0.9516223952401907E-1
+            v = 0.2322388803404617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4317634668111147E+0
+            b = 0.1285467341508517E+0
+            v = 0.2383265471001355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4687413842250821E+0
+            b = 0.1622318931656033E+0
+            v = 0.2432476675019525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5044274237060283E+0
+            b = 0.1959581153836453E+0
+            v = 0.2471122223750674E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5387354077925727E+0
+            b = 0.2294888081183837E+0
+            v = 0.2500291752486870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5715768898356105E+0
+            b = 0.2626031152713945E+0
+            v = 0.2521055942764682E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028627200136111E+0
+            b = 0.2950904075286713E+0
+            v = 0.2534472785575503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6325039812653463E+0
+            b = 0.3267458451113286E+0
+            v = 0.2541599713080121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3981986708423407E+0
+            b = 0.3183291458749821E-1
+            v = 0.2317380975862936E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4382791182133300E+0
+            b = 0.6459548193880908E-1
+            v = 0.2378550733719775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4769233057218166E+0
+            b = 0.9795757037087952E-1
+            v = 0.2428884456739118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5140823911194238E+0
+            b = 0.1316307235126655E+0
+            v = 0.2469002655757292E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496977833862983E+0
+            b = 0.1653556486358704E+0
+            v = 0.2499657574265851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5837047306512727E+0
+            b = 0.1988931724126510E+0
+            v = 0.2521676168486082E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6160349566926879E+0
+            b = 0.2320174581438950E+0
+            v = 0.2535935662645334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6466185353209440E+0
+            b = 0.2645106562168662E+0
+            v = 0.2543356743363214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4810835158795404E+0
+            b = 0.3275917807743992E-1
+            v = 0.2427353285201535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5199925041324341E+0
+            b = 0.6612546183967181E-1
+            v = 0.2468258039744386E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5571717692207494E+0
+            b = 0.9981498331474143E-1
+            v = 0.2500060956440310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5925789250836378E+0
+            b = 0.1335687001410374E+0
+            v = 0.2523238365420979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6261658523859670E+0
+            b = 0.1671444402896463E+0
+            v = 0.2538399260252846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6578811126669331E+0
+            b = 0.2003106382156076E+0
+            v = 0.2546255927268069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5609624612998100E+0
+            b = 0.3337500940231335E-1
+            v = 0.2500583360048449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5979959659984670E+0
+            b = 0.6708750335901803E-1
+            v = 0.2524777638260203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6330523711054002E+0
+            b = 0.1008792126424850E+0
+            v = 0.2540951193860656E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6660960998103972E+0
+            b = 0.1345050343171794E+0
+            v = 0.2549524085027472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6365384364585819E+0
+            b = 0.3372799460737052E-1
+            v = 0.2542569507009158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6710994302899275E+0
+            b = 0.6755249309678028E-1
+            v = 0.2552114127580376E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4802:
+
+            v = 0.9687521879420705E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2307897895367918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2297310852498558E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2335728608887064E-1
+            v = 0.7386265944001919E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4352987836550653E-1
+            v = 0.8257977698542210E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6439200521088801E-1
+            v = 0.9706044762057630E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9003943631993181E-1
+            v = 0.1302393847117003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1196706615548473E+0
+            v = 0.1541957004600968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1511715412838134E+0
+            v = 0.1704459770092199E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1835982828503801E+0
+            v = 0.1827374890942906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2165081259155405E+0
+            v = 0.1926360817436107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2496208720417563E+0
+            v = 0.2008010239494833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2827200673567900E+0
+            v = 0.2075635983209175E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3156190823994346E+0
+            v = 0.2131306638690909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3481476793749115E+0
+            v = 0.2176562329937335E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3801466086947226E+0
+            v = 0.2212682262991018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4114652119634011E+0
+            v = 0.2240799515668565E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4419598786519751E+0
+            v = 0.2261959816187525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4714925949329543E+0
+            v = 0.2277156368808855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4999293972879466E+0
+            v = 0.2287351772128336E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5271387221431248E+0
+            v = 0.2293490814084085E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5529896780837761E+0
+            v = 0.2296505312376273E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6000856099481712E+0
+            v = 0.2296793832318756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6210562192785175E+0
+            v = 0.2295785443842974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6401165879934240E+0
+            v = 0.2295017931529102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6571144029244334E+0
+            v = 0.2295059638184868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718910821718863E+0
+            v = 0.2296232343237362E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6842845591099010E+0
+            v = 0.2298530178740771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6941353476269816E+0
+            v = 0.2301579790280501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012965242212991E+0
+            v = 0.2304690404996513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7056471428242644E+0
+            v = 0.2307027995907102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4595557643585895E-1
+            v = 0.9312274696671092E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1049316742435023E+0
+            v = 0.1199919385876926E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1773548879549274E+0
+            v = 0.1598039138877690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2559071411236127E+0
+            v = 0.1822253763574900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3358156837985898E+0
+            v = 0.1988579593655040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4155835743763893E+0
+            v = 0.2112620102533307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4937894296167472E+0
+            v = 0.2201594887699007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5691569694793316E+0
+            v = 0.2261622590895036E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6405840854894251E+0
+            v = 0.2296458453435705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7345133894143348E-1
+            b = 0.2177844081486067E-1
+            v = 0.1006006990267000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1009859834044931E+0
+            b = 0.4590362185775188E-1
+            v = 0.1227676689635876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1324289619748758E+0
+            b = 0.7255063095690877E-1
+            v = 0.1467864280270117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1654272109607127E+0
+            b = 0.1017825451960684E+0
+            v = 0.1644178912101232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1990767186776461E+0
+            b = 0.1325652320980364E+0
+            v = 0.1777664890718961E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2330125945523278E+0
+            b = 0.1642765374496765E+0
+            v = 0.1884825664516690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2670080611108287E+0
+            b = 0.1965360374337889E+0
+            v = 0.1973269246453848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3008753376294316E+0
+            b = 0.2290726770542238E+0
+            v = 0.2046767775855328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3344475596167860E+0
+            b = 0.2616645495370823E+0
+            v = 0.2107600125918040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3675709724070786E+0
+            b = 0.2941150728843141E+0
+            v = 0.2157416362266829E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4001000887587812E+0
+            b = 0.3262440400919066E+0
+            v = 0.2197557816920721E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318956350436028E+0
+            b = 0.3578835350611916E+0
+            v = 0.2229192611835437E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4628239056795531E+0
+            b = 0.3888751854043678E+0
+            v = 0.2253385110212775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4927563229773636E+0
+            b = 0.4190678003222840E+0
+            v = 0.2271137107548774E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215687136707969E+0
+            b = 0.4483151836883852E+0
+            v = 0.2283414092917525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5491402346984905E+0
+            b = 0.4764740676087880E+0
+            v = 0.2291161673130077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5753520160126075E+0
+            b = 0.5034021310998277E+0
+            v = 0.2295313908576598E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1388326356417754E+0
+            b = 0.2435436510372806E-1
+            v = 0.1438204721359031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1743686900537244E+0
+            b = 0.5118897057342652E-1
+            v = 0.1607738025495257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2099737037950268E+0
+            b = 0.8014695048539634E-1
+            v = 0.1741483853528379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2454492590908548E+0
+            b = 0.1105117874155699E+0
+            v = 0.1851918467519151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2807219257864278E+0
+            b = 0.1417950531570966E+0
+            v = 0.1944628638070613E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3156842271975842E+0
+            b = 0.1736604945719597E+0
+            v = 0.2022495446275152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3502090945177752E+0
+            b = 0.2058466324693981E+0
+            v = 0.2087462382438514E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3841684849519686E+0
+            b = 0.2381284261195919E+0
+            v = 0.2141074754818308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4174372367906016E+0
+            b = 0.2703031270422569E+0
+            v = 0.2184640913748162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4498926465011892E+0
+            b = 0.3021845683091309E+0
+            v = 0.2219309165220329E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4814146229807701E+0
+            b = 0.3335993355165720E+0
+            v = 0.2246123118340624E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5118863625734701E+0
+            b = 0.3643833735518232E+0
+            v = 0.2266062766915125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5411947455119144E+0
+            b = 0.3943789541958179E+0
+            v = 0.2280072952230796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5692301500357246E+0
+            b = 0.4234320144403542E+0
+            v = 0.2289082025202583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5958857204139576E+0
+            b = 0.4513897947419260E+0
+            v = 0.2294012695120025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2156270284785766E+0
+            b = 0.2681225755444491E-1
+            v = 0.1722434488736947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2532385054909710E+0
+            b = 0.5557495747805614E-1
+            v = 0.1830237421455091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2902564617771537E+0
+            b = 0.8569368062950249E-1
+            v = 0.1923855349997633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3266979823143256E+0
+            b = 0.1167367450324135E+0
+            v = 0.2004067861936271E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3625039627493614E+0
+            b = 0.1483861994003304E+0
+            v = 0.2071817297354263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3975838937548699E+0
+            b = 0.1803821503011405E+0
+            v = 0.2128250834102103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318396099009774E+0
+            b = 0.2124962965666424E+0
+            v = 0.2174513719440102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4651706555732742E+0
+            b = 0.2445221837805913E+0
+            v = 0.2211661839150214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4974752649620969E+0
+            b = 0.2762701224322987E+0
+            v = 0.2240665257813102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5286517579627517E+0
+            b = 0.3075627775211328E+0
+            v = 0.2262439516632620E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5586001195731895E+0
+            b = 0.3382311089826877E+0
+            v = 0.2277874557231869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5872229902021319E+0
+            b = 0.3681108834741399E+0
+            v = 0.2287854314454994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6144258616235123E+0
+            b = 0.3970397446872839E+0
+            v = 0.2293268499615575E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2951676508064861E+0
+            b = 0.2867499538750441E-1
+            v = 0.1912628201529828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3335085485472725E+0
+            b = 0.5867879341903510E-1
+            v = 0.1992499672238701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3709561760636381E+0
+            b = 0.8961099205022284E-1
+            v = 0.2061275533454027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4074722861667498E+0
+            b = 0.1211627927626297E+0
+            v = 0.2119318215968572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4429923648839117E+0
+            b = 0.1530748903554898E+0
+            v = 0.2167416581882652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4774428052721736E+0
+            b = 0.1851176436721877E+0
+            v = 0.2206430730516600E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5107446539535904E+0
+            b = 0.2170829107658179E+0
+            v = 0.2237186938699523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5428151370542935E+0
+            b = 0.2487786689026271E+0
+            v = 0.2260480075032884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5735699292556964E+0
+            b = 0.2800239952795016E+0
+            v = 0.2277098884558542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6029253794562866E+0
+            b = 0.3106445702878119E+0
+            v = 0.2287845715109671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6307998987073145E+0
+            b = 0.3404689500841194E+0
+            v = 0.2293547268236294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3752652273692719E+0
+            b = 0.2997145098184479E-1
+            v = 0.2056073839852528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4135383879344028E+0
+            b = 0.6086725898678011E-1
+            v = 0.2114235865831876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4506113885153907E+0
+            b = 0.9238849548435643E-1
+            v = 0.2163175629770551E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4864401554606072E+0
+            b = 0.1242786603851851E+0
+            v = 0.2203392158111650E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5209708076611709E+0
+            b = 0.1563086731483386E+0
+            v = 0.2235473176847839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5541422135830122E+0
+            b = 0.1882696509388506E+0
+            v = 0.2260024141501235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5858880915113817E+0
+            b = 0.2199672979126059E+0
+            v = 0.2277675929329182E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6161399390603444E+0
+            b = 0.2512165482924867E+0
+            v = 0.2289102112284834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6448296482255090E+0
+            b = 0.2818368701871888E+0
+            v = 0.2295027954625118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4544796274917948E+0
+            b = 0.3088970405060312E-1
+            v = 0.2161281589879992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4919389072146628E+0
+            b = 0.6240947677636835E-1
+            v = 0.2201980477395102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5279313026985183E+0
+            b = 0.9430706144280313E-1
+            v = 0.2234952066593166E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5624169925571135E+0
+            b = 0.1263547818770374E+0
+            v = 0.2260540098520838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5953484627093287E+0
+            b = 0.1583430788822594E+0
+            v = 0.2279157981899988E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266730715339185E+0
+            b = 0.1900748462555988E+0
+            v = 0.2291296918565571E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6563363204278871E+0
+            b = 0.2213599519592567E+0
+            v = 0.2297533752536649E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5314574716585696E+0
+            b = 0.3152508811515374E-1
+            v = 0.2234927356465995E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5674614932298185E+0
+            b = 0.6343865291465561E-1
+            v = 0.2261288012985219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6017706004970264E+0
+            b = 0.9551503504223951E-1
+            v = 0.2280818160923688E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6343471270264178E+0
+            b = 0.1275440099801196E+0
+            v = 0.2293773295180159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6651494599127802E+0
+            b = 0.1593252037671960E+0
+            v = 0.2300528767338634E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6050184986005704E+0
+            b = 0.3192538338496105E-1
+            v = 0.2281893855065666E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6390163550880400E+0
+            b = 0.6402824353962306E-1
+            v = 0.2295720444840727E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6711199107088448E+0
+            b = 0.9609805077002909E-1
+            v = 0.2303227649026753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6741354429572275E+0
+            b = 0.3211853196273233E-1
+            v = 0.2304831913227114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5294:
+
+            v = 0.9080510764308163E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2084824361987793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2303261686261450E-1
+            v = 0.5011105657239616E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3757208620162394E-1
+            v = 0.5942520409683854E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5821912033821852E-1
+            v = 0.9564394826109721E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8403127529194872E-1
+            v = 0.1185530657126338E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1122927798060578E+0
+            v = 0.1364510114230331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1420125319192987E+0
+            v = 0.1505828825605415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1726396437341978E+0
+            v = 0.1619298749867023E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2038170058115696E+0
+            v = 0.1712450504267789E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2352849892876508E+0
+            v = 0.1789891098164999E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2668363354312461E+0
+            v = 0.1854474955629795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2982941279900452E+0
+            v = 0.1908148636673661E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3295002922087076E+0
+            v = 0.1952377405281833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3603094918363593E+0
+            v = 0.1988349254282232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3905857895173920E+0
+            v = 0.2017079807160050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4202005758160837E+0
+            v = 0.2039473082709094E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4490310061597227E+0
+            v = 0.2056360279288953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4769586160311491E+0
+            v = 0.2068525823066865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5038679887049750E+0
+            v = 0.2076724877534488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5296454286519961E+0
+            v = 0.2081694278237885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5541776207164850E+0
+            v = 0.2084157631219326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5990467321921213E+0
+            v = 0.2084381531128593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6191467096294587E+0
+            v = 0.2083476277129307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6375251212901849E+0
+            v = 0.2082686194459732E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6540514381131168E+0
+            v = 0.2082475686112415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6685899064391510E+0
+            v = 0.2083139860289915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6810013009681648E+0
+            v = 0.2084745561831237E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911469578730340E+0
+            v = 0.2087091313375890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6988956915141736E+0
+            v = 0.2089718413297697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041335794868720E+0
+            v = 0.2092003303479793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067754398018567E+0
+            v = 0.2093336148263241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3840368707853623E-1
+            v = 0.7591708117365267E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9835485954117399E-1
+            v = 0.1083383968169186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1665774947612998E+0
+            v = 0.1403019395292510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2405702335362910E+0
+            v = 0.1615970179286436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3165270770189046E+0
+            v = 0.1771144187504911E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3927386145645443E+0
+            v = 0.1887760022988168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4678825918374656E+0
+            v = 0.1973474670768214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5408022024266935E+0
+            v = 0.2033787661234659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6104967445752438E+0
+            v = 0.2072343626517331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6760910702685738E+0
+            v = 0.2091177834226918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6655644120217392E-1
+            b = 0.1936508874588424E-1
+            v = 0.9316684484675566E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9446246161270182E-1
+            b = 0.4252442002115869E-1
+            v = 0.1116193688682976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1242651925452509E+0
+            b = 0.6806529315354374E-1
+            v = 0.1298623551559414E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1553438064846751E+0
+            b = 0.9560957491205369E-1
+            v = 0.1450236832456426E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1871137110542670E+0
+            b = 0.1245931657452888E+0
+            v = 0.1572719958149914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2192612628836257E+0
+            b = 0.1545385828778978E+0
+            v = 0.1673234785867195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2515682807206955E+0
+            b = 0.1851004249723368E+0
+            v = 0.1756860118725188E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838535866287290E+0
+            b = 0.2160182608272384E+0
+            v = 0.1826776290439367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3159578817528521E+0
+            b = 0.2470799012277111E+0
+            v = 0.1885116347992865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3477370882791392E+0
+            b = 0.2781014208986402E+0
+            v = 0.1933457860170574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3790576960890540E+0
+            b = 0.3089172523515731E+0
+            v = 0.1973060671902064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097938317810200E+0
+            b = 0.3393750055472244E+0
+            v = 0.2004987099616311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4398256572859637E+0
+            b = 0.3693322470987730E+0
+            v = 0.2030170909281499E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4690384114718480E+0
+            b = 0.3986541005609877E+0
+            v = 0.2049461460119080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4973216048301053E+0
+            b = 0.4272112491408562E+0
+            v = 0.2063653565200186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245681526132446E+0
+            b = 0.4548781735309936E+0
+            v = 0.2073507927381027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506733911803888E+0
+            b = 0.4815315355023251E+0
+            v = 0.2079764593256122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5755339829522475E+0
+            b = 0.5070486445801855E+0
+            v = 0.2083150534968778E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1305472386056362E+0
+            b = 0.2284970375722366E-1
+            v = 0.1262715121590664E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1637327908216477E+0
+            b = 0.4812254338288384E-1
+            v = 0.1414386128545972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1972734634149637E+0
+            b = 0.7531734457511935E-1
+            v = 0.1538740401313898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2308694653110130E+0
+            b = 0.1039043639882017E+0
+            v = 0.1642434942331432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2643899218338160E+0
+            b = 0.1334526587117626E+0
+            v = 0.1729790609237496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2977171599622171E+0
+            b = 0.1636414868936382E+0
+            v = 0.1803505190260828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3307293903032310E+0
+            b = 0.1942195406166568E+0
+            v = 0.1865475350079657E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3633069198219073E+0
+            b = 0.2249752879943753E+0
+            v = 0.1917182669679069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3953346955922727E+0
+            b = 0.2557218821820032E+0
+            v = 0.1959851709034382E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4267018394184914E+0
+            b = 0.2862897925213193E+0
+            v = 0.1994529548117882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4573009622571704E+0
+            b = 0.3165224536636518E+0
+            v = 0.2022138911146548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4870279559856109E+0
+            b = 0.3462730221636496E+0
+            v = 0.2043518024208592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5157819581450322E+0
+            b = 0.3754016870282835E+0
+            v = 0.2059450313018110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5434651666465393E+0
+            b = 0.4037733784993613E+0
+            v = 0.2070685715318472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5699823887764627E+0
+            b = 0.4312557784139123E+0
+            v = 0.2077955310694373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5952403350947741E+0
+            b = 0.4577175367122110E+0
+            v = 0.2081980387824712E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2025152599210369E+0
+            b = 0.2520253617719557E-1
+            v = 0.1521318610377956E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381066653274425E+0
+            b = 0.5223254506119000E-1
+            v = 0.1622772720185755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2732823383651612E+0
+            b = 0.8060669688588620E-1
+            v = 0.1710498139420709E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3080137692611118E+0
+            b = 0.1099335754081255E+0
+            v = 0.1785911149448736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3422405614587601E+0
+            b = 0.1399120955959857E+0
+            v = 0.1850125313687736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3758808773890420E+0
+            b = 0.1702977801651705E+0
+            v = 0.1904229703933298E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4088458383438932E+0
+            b = 0.2008799256601680E+0
+            v = 0.1949259956121987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4410450550841152E+0
+            b = 0.2314703052180836E+0
+            v = 0.1986161545363960E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4723879420561312E+0
+            b = 0.2618972111375892E+0
+            v = 0.2015790585641370E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027843561874343E+0
+            b = 0.2920013195600270E+0
+            v = 0.2038934198707418E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321453674452458E+0
+            b = 0.3216322555190551E+0
+            v = 0.2056334060538251E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5603839113834030E+0
+            b = 0.3506456615934198E+0
+            v = 0.2068705959462289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5874150706875146E+0
+            b = 0.3789007181306267E+0
+            v = 0.2076753906106002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6131559381660038E+0
+            b = 0.4062580170572782E+0
+            v = 0.2081179391734803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778497016394506E+0
+            b = 0.2696271276876226E-1
+            v = 0.1700345216228943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3143733562261912E+0
+            b = 0.5523469316960465E-1
+            v = 0.1774906779990410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3501485810261827E+0
+            b = 0.8445193201626464E-1
+            v = 0.1839659377002642E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3851430322303653E+0
+            b = 0.1143263119336083E+0
+            v = 0.1894987462975169E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4193013979470415E+0
+            b = 0.1446177898344475E+0
+            v = 0.1941548809452595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4525585960458567E+0
+            b = 0.1751165438438091E+0
+            v = 0.1980078427252384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4848447779622947E+0
+            b = 0.2056338306745660E+0
+            v = 0.2011296284744488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5160871208276894E+0
+            b = 0.2359965487229226E+0
+            v = 0.2035888456966776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5462112185696926E+0
+            b = 0.2660430223139146E+0
+            v = 0.2054516325352142E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751425068101757E+0
+            b = 0.2956193664498032E+0
+            v = 0.2067831033092635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028073872853596E+0
+            b = 0.3245763905312779E+0
+            v = 0.2076485320284876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6291338275278409E+0
+            b = 0.3527670026206972E+0
+            v = 0.2081141439525255E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3541797528439391E+0
+            b = 0.2823853479435550E-1
+            v = 0.1834383015469222E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3908234972074657E+0
+            b = 0.5741296374713106E-1
+            v = 0.1889540591777677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4264408450107590E+0
+            b = 0.8724646633650199E-1
+            v = 0.1936677023597375E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4609949666553286E+0
+            b = 0.1175034422915616E+0
+            v = 0.1976176495066504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4944389496536006E+0
+            b = 0.1479755652628428E+0
+            v = 0.2008536004560983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5267194884346086E+0
+            b = 0.1784740659484352E+0
+            v = 0.2034280351712291E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577787810220990E+0
+            b = 0.2088245700431244E+0
+            v = 0.2053944466027758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875563763536670E+0
+            b = 0.2388628136570763E+0
+            v = 0.2068077642882360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6159910016391269E+0
+            b = 0.2684308928769185E+0
+            v = 0.2077250949661599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6430219602956268E+0
+            b = 0.2973740761960252E+0
+            v = 0.2082062440705320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4300647036213646E+0
+            b = 0.2916399920493977E-1
+            v = 0.1934374486546626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4661486308935531E+0
+            b = 0.5898803024755659E-1
+            v = 0.1974107010484300E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5009658555287261E+0
+            b = 0.8924162698525409E-1
+            v = 0.2007129290388658E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5344824270447704E+0
+            b = 0.1197185199637321E+0
+            v = 0.2033736947471293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5666575997416371E+0
+            b = 0.1502300756161382E+0
+            v = 0.2054287125902493E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5974457471404752E+0
+            b = 0.1806004191913564E+0
+            v = 0.2069184936818894E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6267984444116886E+0
+            b = 0.2106621764786252E+0
+            v = 0.2078883689808782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6546664713575417E+0
+            b = 0.2402526932671914E+0
+            v = 0.2083886366116359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5042711004437253E+0
+            b = 0.2982529203607657E-1
+            v = 0.2006593275470817E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5392127456774380E+0
+            b = 0.6008728062339922E-1
+            v = 0.2033728426135397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726819437668618E+0
+            b = 0.9058227674571398E-1
+            v = 0.2055008781377608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6046469254207278E+0
+            b = 0.1211219235803400E+0
+            v = 0.2070651783518502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6350716157434952E+0
+            b = 0.1515286404791580E+0
+            v = 0.2080953335094320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6639177679185454E+0
+            b = 0.1816314681255552E+0
+            v = 0.2086284998988521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5757276040972253E+0
+            b = 0.3026991752575440E-1
+            v = 0.2055549387644668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6090265823139755E+0
+            b = 0.6078402297870770E-1
+            v = 0.2071871850267654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6406735344387661E+0
+            b = 0.9135459984176636E-1
+            v = 0.2082856600431965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6706397927793709E+0
+            b = 0.1218024155966590E+0
+            v = 0.2088705858819358E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6435019674426665E+0
+            b = 0.3052608357660639E-1
+            v = 0.2083995867536322E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747218676375681E+0
+            b = 0.6112185773983089E-1
+            v = 0.2090509712889637E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5810:
+
+            v = 0.9735347946175486E-5
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1907581241803167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1901059546737578E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1182361662400277E-1
+            v = 0.3926424538919212E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3062145009138958E-1
+            v = 0.6667905467294382E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5329794036834243E-1
+            v = 0.8868891315019135E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7848165532862220E-1
+            v = 0.1066306000958872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1054038157636201E+0
+            v = 0.1214506743336128E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1335577797766211E+0
+            v = 0.1338054681640871E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1625769955502252E+0
+            v = 0.1441677023628504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1921787193412792E+0
+            v = 0.1528880200826557E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2221340534690548E+0
+            v = 0.1602330623773609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2522504912791132E+0
+            v = 0.1664102653445244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2823610860679697E+0
+            v = 0.1715845854011323E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3123173966267560E+0
+            v = 0.1758901000133069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3419847036953789E+0
+            v = 0.1794382485256736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3712386456999758E+0
+            v = 0.1823238106757407E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3999627649876828E+0
+            v = 0.1846293252959976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4280466458648093E+0
+            v = 0.1864284079323098E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4553844360185711E+0
+            v = 0.1877882694626914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4818736094437834E+0
+            v = 0.1887716321852025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5074138709260629E+0
+            v = 0.1894381638175673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5319061304570707E+0
+            v = 0.1898454899533629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5552514978677286E+0
+            v = 0.1900497929577815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5981009025246183E+0
+            v = 0.1900671501924092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6173990192228116E+0
+            v = 0.1899837555533510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6351365239411131E+0
+            v = 0.1899014113156229E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6512010228227200E+0
+            v = 0.1898581257705106E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6654758363948120E+0
+            v = 0.1898804756095753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6778410414853370E+0
+            v = 0.1899793610426402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6881760887484110E+0
+            v = 0.1901464554844117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963645267094598E+0
+            v = 0.1903533246259542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7023010617153579E+0
+            v = 0.1905556158463228E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7059004636628753E+0
+            v = 0.1907037155663528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552470312472575E-1
+            v = 0.5992997844249967E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9151176620841283E-1
+            v = 0.9749059382456978E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1566197930068980E+0
+            v = 0.1241680804599158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2265467599271907E+0
+            v = 0.1437626154299360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2988242318581361E+0
+            v = 0.1584200054793902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3717482419703886E+0
+            v = 0.1694436550982744E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4440094491758889E+0
+            v = 0.1776617014018108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5145337096756642E+0
+            v = 0.1836132434440077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5824053672860230E+0
+            v = 0.1876494727075983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6468283961043370E+0
+            v = 0.1899906535336482E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6095964259104373E-1
+            b = 0.1787828275342931E-1
+            v = 0.8143252820767350E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8811962270959388E-1
+            b = 0.3953888740792096E-1
+            v = 0.9998859890887728E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1165936722428831E+0
+            b = 0.6378121797722990E-1
+            v = 0.1156199403068359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1460232857031785E+0
+            b = 0.8985890813745037E-1
+            v = 0.1287632092635513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1761197110181755E+0
+            b = 0.1172606510576162E+0
+            v = 0.1398378643365139E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2066471190463718E+0
+            b = 0.1456102876970995E+0
+            v = 0.1491876468417391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2374076026328152E+0
+            b = 0.1746153823011775E+0
+            v = 0.1570855679175456E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2682305474337051E+0
+            b = 0.2040383070295584E+0
+            v = 0.1637483948103775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2989653312142369E+0
+            b = 0.2336788634003698E+0
+            v = 0.1693500566632843E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3294762752772209E+0
+            b = 0.2633632752654219E+0
+            v = 0.1740322769393633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3596390887276086E+0
+            b = 0.2929369098051601E+0
+            v = 0.1779126637278296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3893383046398812E+0
+            b = 0.3222592785275512E+0
+            v = 0.1810908108835412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4184653789358347E+0
+            b = 0.3512004791195743E+0
+            v = 0.1836529132600190E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4469172319076166E+0
+            b = 0.3796385677684537E+0
+            v = 0.1856752841777379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4745950813276976E+0
+            b = 0.4074575378263879E+0
+            v = 0.1872270566606832E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5014034601410262E+0
+            b = 0.4345456906027828E+0
+            v = 0.1883722645591307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5272493404551239E+0
+            b = 0.4607942515205134E+0
+            v = 0.1891714324525297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5520413051846366E+0
+            b = 0.4860961284181720E+0
+            v = 0.1896827480450146E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5756887237503077E+0
+            b = 0.5103447395342790E+0
+            v = 0.1899628417059528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1225039430588352E+0
+            b = 0.2136455922655793E-1
+            v = 0.1123301829001669E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1539113217321372E+0
+            b = 0.4520926166137188E-1
+            v = 0.1253698826711277E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1856213098637712E+0
+            b = 0.7086468177864818E-1
+            v = 0.1366266117678531E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2174998728035131E+0
+            b = 0.9785239488772918E-1
+            v = 0.1462736856106918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2494128336938330E+0
+            b = 0.1258106396267210E+0
+            v = 0.1545076466685412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2812321562143480E+0
+            b = 0.1544529125047001E+0
+            v = 0.1615096280814007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3128372276456111E+0
+            b = 0.1835433512202753E+0
+            v = 0.1674366639741759E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3441145160177973E+0
+            b = 0.2128813258619585E+0
+            v = 0.1724225002437900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3749567714853510E+0
+            b = 0.2422913734880829E+0
+            v = 0.1765810822987288E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4052621732015610E+0
+            b = 0.2716163748391453E+0
+            v = 0.1800104126010751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4349335453522385E+0
+            b = 0.3007127671240280E+0
+            v = 0.1827960437331284E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4638776641524965E+0
+            b = 0.3294470677216479E+0
+            v = 0.1850140300716308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4920046410462687E+0
+            b = 0.3576932543699155E+0
+            v = 0.1867333507394938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5192273554861704E+0
+            b = 0.3853307059757764E+0
+            v = 0.1880178688638289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454609081136522E+0
+            b = 0.4122425044452694E+0
+            v = 0.1889278925654758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5706220661424140E+0
+            b = 0.4383139587781027E+0
+            v = 0.1895213832507346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5946286755181518E+0
+            b = 0.4634312536300553E+0
+            v = 0.1898548277397420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1905370790924295E+0
+            b = 0.2371311537781979E-1
+            v = 0.1349105935937341E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2242518717748009E+0
+            b = 0.4917878059254806E-1
+            v = 0.1444060068369326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2577190808025936E+0
+            b = 0.7595498960495142E-1
+            v = 0.1526797390930008E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2908724534927187E+0
+            b = 0.1036991083191100E+0
+            v = 0.1598208771406474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236354020056219E+0
+            b = 0.1321348584450234E+0
+            v = 0.1659354368615331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3559267359304543E+0
+            b = 0.1610316571314789E+0
+            v = 0.1711279910946440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3876637123676956E+0
+            b = 0.1901912080395707E+0
+            v = 0.1754952725601440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4187636705218842E+0
+            b = 0.2194384950137950E+0
+            v = 0.1791247850802529E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491449019883107E+0
+            b = 0.2486155334763858E+0
+            v = 0.1820954300877716E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4787270932425445E+0
+            b = 0.2775768931812335E+0
+            v = 0.1844788524548449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5074315153055574E+0
+            b = 0.3061863786591120E+0
+            v = 0.1863409481706220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5351810507738336E+0
+            b = 0.3343144718152556E+0
+            v = 0.1877433008795068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5619001025975381E+0
+            b = 0.3618362729028427E+0
+            v = 0.1887444543705232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875144035268046E+0
+            b = 0.3886297583620408E+0
+            v = 0.1894009829375006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6119507308734495E+0
+            b = 0.4145742277792031E+0
+            v = 0.1897683345035198E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2619733870119463E+0
+            b = 0.2540047186389353E-1
+            v = 0.1517327037467653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2968149743237949E+0
+            b = 0.5208107018543989E-1
+            v = 0.1587740557483543E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3310451504860488E+0
+            b = 0.7971828470885599E-1
+            v = 0.1649093382274097E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3646215567376676E+0
+            b = 0.1080465999177927E+0
+            v = 0.1701915216193265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3974916785279360E+0
+            b = 0.1368413849366629E+0
+            v = 0.1746847753144065E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4295967403772029E+0
+            b = 0.1659073184763559E+0
+            v = 0.1784555512007570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4608742854473447E+0
+            b = 0.1950703730454614E+0
+            v = 0.1815687562112174E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912598858949903E+0
+            b = 0.2241721144376724E+0
+            v = 0.1840864370663302E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5206882758945558E+0
+            b = 0.2530655255406489E+0
+            v = 0.1860676785390006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5490940914019819E+0
+            b = 0.2816118409731066E+0
+            v = 0.1875690583743703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5764123302025542E+0
+            b = 0.3096780504593238E+0
+            v = 0.1886453236347225E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6025786004213506E+0
+            b = 0.3371348366394987E+0
+            v = 0.1893501123329645E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6275291964794956E+0
+            b = 0.3638547827694396E+0
+            v = 0.1897366184519868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3348189479861771E+0
+            b = 0.2664841935537443E-1
+            v = 0.1643908815152736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3699515545855295E+0
+            b = 0.5424000066843495E-1
+            v = 0.1696300350907768E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4042003071474669E+0
+            b = 0.8251992715430854E-1
+            v = 0.1741553103844483E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4375320100182624E+0
+            b = 0.1112695182483710E+0
+            v = 0.1780015282386092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4699054490335947E+0
+            b = 0.1402964116467816E+0
+            v = 0.1812116787077125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5012739879431952E+0
+            b = 0.1694275117584291E+0
+            v = 0.1838323158085421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5315874883754966E+0
+            b = 0.1985038235312689E+0
+            v = 0.1859113119837737E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5607937109622117E+0
+            b = 0.2273765660020893E+0
+            v = 0.1874969220221698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5888393223495521E+0
+            b = 0.2559041492849764E+0
+            v = 0.1886375612681076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156705979160163E+0
+            b = 0.2839497251976899E+0
+            v = 0.1893819575809276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6412338809078123E+0
+            b = 0.3113791060500690E+0
+            v = 0.1897794748256767E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4076051259257167E+0
+            b = 0.2757792290858463E-1
+            v = 0.1738963926584846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4423788125791520E+0
+            b = 0.5584136834984293E-1
+            v = 0.1777442359873466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760480917328258E+0
+            b = 0.8457772087727143E-1
+            v = 0.1810010815068719E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5085838725946297E+0
+            b = 0.1135975846359248E+0
+            v = 0.1836920318248129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5399513637391218E+0
+            b = 0.1427286904765053E+0
+            v = 0.1858489473214328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5701118433636380E+0
+            b = 0.1718112740057635E+0
+            v = 0.1875079342496592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5990240530606021E+0
+            b = 0.2006944855985351E+0
+            v = 0.1887080239102310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266452685139695E+0
+            b = 0.2292335090598907E+0
+            v = 0.1894905752176822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529320971415942E+0
+            b = 0.2572871512353714E+0
+            v = 0.1898991061200695E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4791583834610126E+0
+            b = 0.2826094197735932E-1
+            v = 0.1809065016458791E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5130373952796940E+0
+            b = 0.5699871359683649E-1
+            v = 0.1836297121596799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5456252429628476E+0
+            b = 0.8602712528554394E-1
+            v = 0.1858426916241869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5768956329682385E+0
+            b = 0.1151748137221281E+0
+            v = 0.1875654101134641E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6068186944699046E+0
+            b = 0.1442811654136362E+0
+            v = 0.1888240751833503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6353622248024907E+0
+            b = 0.1731930321657680E+0
+            v = 0.1896497383866979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6624927035731797E+0
+            b = 0.2017619958756061E+0
+            v = 0.1900775530219121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5484933508028488E+0
+            b = 0.2874219755907391E-1
+            v = 0.1858525041478814E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5810207682142106E+0
+            b = 0.5778312123713695E-1
+            v = 0.1876248690077947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6120955197181352E+0
+            b = 0.8695262371439526E-1
+            v = 0.1889404439064607E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6416944284294319E+0
+            b = 0.1160893767057166E+0
+            v = 0.1898168539265290E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6697926391731260E+0
+            b = 0.1450378826743251E+0
+            v = 0.1902779940661772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6147594390585488E+0
+            b = 0.2904957622341456E-1
+            v = 0.1890125641731815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6455390026356783E+0
+            b = 0.5823809152617197E-1
+            v = 0.1899434637795751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747258588365477E+0
+            b = 0.8740384899884715E-1
+            v = 0.1904520856831751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6772135750395347E+0
+            b = 0.2919946135808105E-1
+            v = 0.1905534498734563E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case _:
+            raise Exception('Angular grid unrecognized, choices are 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810')  # noqa: E501
+
+    leb_tmp.n = degree
+    return leb_tmp
+
+
+def get_lebedev_recurrence_points(type_, start, a, b, v, leb):
+    c = 0.0
+
+    match type_:
+
+        case 1:
+            a = 1.0
+
+            leb.x[start] = a
+            leb.y[start] = 0.0
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = 0.0
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = 0.0
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = 0.0
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+            start = start + 6
+
+        case 2:
+            a = sqrt(0.5)
+            leb.x[start] = 0.0
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = 0.0
+            leb.y[start + 1] = -a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = -a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = a
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = 0.0
+            leb.z[start + 6] = a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = 0.0
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = a
+            leb.z[start + 8] = 0.0
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = a
+            leb.z[start + 9] = 0.0
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = 0.0
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -a
+            leb.z[start + 11] = 0.0
+            leb.w[start + 11] = 4.0 * pi * v
+            start = start + 12
+
+        case 3:
+            a = sqrt(1.0 / 3.0)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -a
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = a
+            leb.z[start + 6] = -a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+            start = start + 8
+
+        case 4:
+            # /* In this case A is inputed */
+            b = sqrt(1.0 - 2.0 * a * a)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = b
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = b
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = b
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -b
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = b
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -a
+            leb.y[start + 5] = a
+            leb.z[start + 5] = -b
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = a
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = -b
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -b
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = -a
+            leb.y[start + 8] = b
+            leb.z[start + 8] = a
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = a
+            leb.y[start + 9] = -b
+            leb.z[start + 9] = a
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = b
+            leb.z[start + 10] = -a
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -b
+            leb.z[start + 11] = a
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -a
+            leb.y[start + 12] = b
+            leb.z[start + 12] = -a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = a
+            leb.y[start + 13] = -b
+            leb.z[start + 13] = -a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -a
+            leb.y[start + 14] = -b
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = a
+            leb.y[start + 15] = b
+            leb.z[start + 15] = a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = b
+            leb.y[start + 16] = a
+            leb.z[start + 16] = a
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -b
+            leb.y[start + 17] = a
+            leb.z[start + 17] = a
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = b
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = a
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = b
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -a
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -b
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = -b
+            leb.y[start + 21] = a
+            leb.z[start + 21] = -a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = b
+            leb.y[start + 22] = -a
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -b
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 5:
+            # /* A is inputed in this case as well*/
+            b = sqrt(1 - a * a)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = -a
+            leb.y[start + 3] = -b
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = b
+            leb.y[start + 4] = a
+            leb.z[start + 4] = 0.0
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -b
+            leb.y[start + 5] = a
+            leb.z[start + 5] = 0.0
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = b
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = 0.0
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -b
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = 0.0
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = 0.0
+            leb.z[start + 8] = b
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = 0.0
+            leb.z[start + 9] = b
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = 0.0
+            leb.z[start + 10] = -b
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = 0.0
+            leb.z[start + 11] = -b
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = b
+            leb.y[start + 12] = 0.0
+            leb.z[start + 12] = a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = -b
+            leb.y[start + 13] = 0.0
+            leb.z[start + 13] = a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = b
+            leb.y[start + 14] = 0.0
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = 0.0
+            leb.z[start + 15] = -a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = 0.0
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = 0.0
+            leb.y[start + 17] = -a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = 0.0
+            leb.y[start + 18] = a
+            leb.z[start + 18] = -b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = 0.0
+            leb.y[start + 19] = -a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = 0.0
+            leb.y[start + 20] = b
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = 0.0
+            leb.y[start + 21] = -b
+            leb.z[start + 21] = a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = 0.0
+            leb.y[start + 22] = b
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = 0.0
+            leb.y[start + 23] = -b
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 6:
+            # /* both A and B are inputed in this case */
+            c = sqrt(1.0 - a * a - b * b)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = c
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = c
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = c
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = b
+            leb.z[start + 3] = -c
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -b
+            leb.z[start + 4] = c
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -b
+            leb.z[start + 5] = -c
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = b
+            leb.z[start + 6] = -c
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -b
+            leb.z[start + 7] = -c
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = b
+            leb.y[start + 8] = a
+            leb.z[start + 8] = c
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -b
+            leb.y[start + 9] = a
+            leb.z[start + 9] = c
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = b
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = c
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = b
+            leb.y[start + 11] = a
+            leb.z[start + 11] = -c
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -b
+            leb.y[start + 12] = -a
+            leb.z[start + 12] = c
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = b
+            leb.y[start + 13] = -a
+            leb.z[start + 13] = -c
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -b
+            leb.y[start + 14] = a
+            leb.z[start + 14] = -c
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = -a
+            leb.z[start + 15] = -c
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = c
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -c
+            leb.y[start + 17] = a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = c
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = c
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -c
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = b
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = c
+            leb.y[start + 21] = -a
+            leb.z[start + 21] = -b
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = -c
+            leb.y[start + 22] = a
+            leb.z[start + 22] = -b
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -c
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -b
+            leb.w[start + 23] = 4.0 * pi * v
+
+            leb.x[start + 24] = c
+            leb.y[start + 24] = b
+            leb.z[start + 24] = a
+            leb.w[start + 24] = 4.0 * pi * v
+
+            leb.x[start + 25] = -c
+            leb.y[start + 25] = b
+            leb.z[start + 25] = a
+            leb.w[start + 25] = 4.0 * pi * v
+
+            leb.x[start + 26] = c
+            leb.y[start + 26] = -b
+            leb.z[start + 26] = a
+            leb.w[start + 26] = 4.0 * pi * v
+
+            leb.x[start + 27] = c
+            leb.y[start + 27] = b
+            leb.z[start + 27] = -a
+            leb.w[start + 27] = 4.0 * pi * v
+
+            leb.x[start + 28] = -c
+            leb.y[start + 28] = -b
+            leb.z[start + 28] = a
+            leb.w[start + 28] = 4.0 * pi * v
+
+            leb.x[start + 29] = c
+            leb.y[start + 29] = -b
+            leb.z[start + 29] = -a
+            leb.w[start + 29] = 4.0 * pi * v
+
+            leb.x[start + 30] = -c
+            leb.y[start + 30] = b
+            leb.z[start + 30] = -a
+            leb.w[start + 30] = 4.0 * pi * v
+
+            leb.x[start + 31] = -c
+            leb.y[start + 31] = -b
+            leb.z[start + 31] = -a
+            leb.w[start + 31] = 4.0 * pi * v
+
+            leb.x[start + 32] = a
+            leb.y[start + 32] = c
+            leb.z[start + 32] = b
+            leb.w[start + 32] = 4.0 * pi * v
+
+            leb.x[start + 33] = -a
+            leb.y[start + 33] = c
+            leb.z[start + 33] = b
+            leb.w[start + 33] = 4.0 * pi * v
+
+            leb.x[start + 34] = a
+            leb.y[start + 34] = -c
+            leb.z[start + 34] = b
+            leb.w[start + 34] = 4.0 * pi * v
+
+            leb.x[start + 35] = a
+            leb.y[start + 35] = c
+            leb.z[start + 35] = -b
+            leb.w[start + 35] = 4.0 * pi * v
+
+            leb.x[start + 36] = -a
+            leb.y[start + 36] = -c
+            leb.z[start + 36] = b
+            leb.w[start + 36] = 4.0 * pi * v
+
+            leb.x[start + 37] = a
+            leb.y[start + 37] = -c
+            leb.z[start + 37] = -b
+            leb.w[start + 37] = 4.0 * pi * v
+
+            leb.x[start + 38] = -a
+            leb.y[start + 38] = c
+            leb.z[start + 38] = -b
+            leb.w[start + 38] = 4.0 * pi * v
+
+            leb.x[start + 39] = -a
+            leb.y[start + 39] = -c
+            leb.z[start + 39] = -b
+            leb.w[start + 39] = 4.0 * pi * v
+
+            leb.x[start + 40] = b
+            leb.y[start + 40] = c
+            leb.z[start + 40] = a
+            leb.w[start + 40] = 4.0 * pi * v
+
+            leb.x[start + 41] = -b
+            leb.y[start + 41] = c
+            leb.z[start + 41] = a
+            leb.w[start + 41] = 4.0 * pi * v
+
+            leb.x[start + 42] = b
+            leb.y[start + 42] = -c
+            leb.z[start + 42] = a
+            leb.w[start + 42] = 4.0 * pi * v
+
+            leb.x[start + 43] = b
+            leb.y[start + 43] = c
+            leb.z[start + 43] = -a
+            leb.w[start + 43] = 4.0 * pi * v
+
+            leb.x[start + 44] = -b
+            leb.y[start + 44] = -c
+            leb.z[start + 44] = a
+            leb.w[start + 44] = 4.0 * pi * v
+
+            leb.x[start + 45] = b
+            leb.y[start + 45] = -c
+            leb.z[start + 45] = -a
+            leb.w[start + 45] = 4.0 * pi * v
+
+            leb.x[start + 46] = -b
+            leb.y[start + 46] = c
+            leb.z[start + 46] = -a
+            leb.w[start + 46] = 4.0 * pi * v
+
+            leb.x[start + 47] = -b
+            leb.y[start + 47] = -c
+            leb.z[start + 47] = -a
+            leb.w[start + 47] = 4.0 * pi * v
+            start = start + 48
+
+        case _:
+            raise Exception('Bad grid order')
+
+    return leb, start
+
+
+def lebedev_rule(n):
+    r"""Lebedev quadrature.
+
+    Compute the sample points and weights for Lebedev quadrature [1]_
+    for integration of a function over the surface of a unit sphere.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order. See Notes for supported values.
+
+    Returns
+    -------
+    x : ndarray of shape ``(3, m)``
+        Sample points on the unit sphere in Cartesian coordinates.
+        ``m`` is the "degree" corresponding with the specified order; see Notes.
+    w : ndarray of shape ``(m,)``
+        Weights
+
+    Notes
+    -----
+    Implemented by translating the Matlab code of [2]_ to Python.
+
+    The available orders (argument `n`) are::
+
+        3, 5, 7, 9, 11, 13, 15, 17,
+        19, 21, 23, 25, 27, 29, 31, 35,
+        41, 47, 53, 59, 65, 71, 77, 83,
+        89, 95, 101, 107, 113, 119, 125, 131
+
+    The corresponding degrees ``m`` are::
+
+        6, 14, 26, 38, 50, 74, 86, 110,
+        146, 170, 194, 230, 266, 302, 350, 434,
+        590, 770, 974, 1202, 1454, 1730, 2030, 2354,
+        2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810
+
+    References
+    ----------
+    .. [1] V.I. Lebedev, and D.N. Laikov. "A quadrature formula for the sphere of
+           the 131st algebraic order of accuracy". Doklady Mathematics, Vol. 59,
+           No. 3, 1999, pp. 477-481.
+    .. [2] R. Parrish. ``getLebedevSphere``. Matlab Central File Exchange.
+           https://www.mathworks.com/matlabcentral/fileexchange/27097-getlebedevsphere.
+    .. [3] Bellet, Jean-Baptiste, Matthieu Brachet, and Jean-Pierre Croisille.
+           "Quadrature and symmetry on the Cubed Sphere." Journal of Computational and
+           Applied Mathematics 409 (2022): 114142. :doi:`10.1016/j.cam.2022.114142`.
+
+    Examples
+    --------
+    An example given in [3]_ is integration of :math:`f(x, y, z) = \exp(x)` over a
+    sphere of radius :math:`1`; the reference there is ``14.7680137457653``.
+    Show the convergence to the expected result as the order increases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> from scipy.integrate import lebedev_rule
+    >>>
+    >>> def f(x):
+    ...     return np.exp(x[0])
+    >>>
+    >>> res = []
+    >>> orders = np.arange(3, 20, 2)
+    >>> for n in orders:
+    ...     x, w = lebedev_rule(n)
+    ...     res.append(w @ f(x))
+    >>>
+    >>> ref = np.full_like(res, 14.7680137457653)
+    >>> err = abs(res - ref)/abs(ref)
+    >>> plt.semilogy(orders, err)
+    >>> plt.xlabel('order $n$')
+    >>> plt.ylabel('relative error')
+    >>> plt.title(r'Convergence for $f(x, y, z) = \exp(x)$')
+    >>> plt.show()
+
+    """
+    degree = [6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350,
+              434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470,
+              3890, 4334, 4802, 5294, 5810]
+    order = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 35, 41, 47,
+             53, 59, 65, 71, 77, 83, 89, 95, 101, 107, 113, 119, 125, 131]
+    order_degree_map = dict(zip(order, degree))
+
+    if n not in order_degree_map:
+        message = f"Order {n=} not available. Available orders are {order}."
+        raise NotImplementedError(message)
+
+    degree = order_degree_map[n]
+    res = get_lebedev_sphere(degree)
+    x = np.stack((res.x, res.y, res.z))
+    w = res.w
+
+    return x, w
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_lsoda.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_lsoda.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..5e1a664ad2aa76e914ddf60ffca5d36b9f7426fe
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_lsoda.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ode.py b/python_embeded/Lib/site-packages/scipy/integrate/_ode.py
new file mode 100644
index 0000000000000000000000000000000000000000..570b51f458b6944d458418869872fe76716d0a9e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ode.py
@@ -0,0 +1,1388 @@
+# Authors: Pearu Peterson, Pauli Virtanen, John Travers
+"""
+First-order ODE integrators.
+
+User-friendly interface to various numerical integrators for solving a
+system of first order ODEs with prescribed initial conditions::
+
+    d y(t)[i]
+    ---------  = f(t,y(t))[i],
+       d t
+
+    y(t=0)[i] = y0[i],
+
+where::
+
+    i = 0, ..., len(y0) - 1
+
+class ode
+---------
+
+A generic interface class to numeric integrators. It has the following
+methods::
+
+    integrator = ode(f, jac=None)
+    integrator = integrator.set_integrator(name, **params)
+    integrator = integrator.set_initial_value(y0, t0=0.0)
+    integrator = integrator.set_f_params(*args)
+    integrator = integrator.set_jac_params(*args)
+    y1 = integrator.integrate(t1, step=False, relax=False)
+    flag = integrator.successful()
+
+class complex_ode
+-----------------
+
+This class has the same generic interface as ode, except it can handle complex
+f, y and Jacobians by transparently translating them into the equivalent
+real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
+an alternative to ode with the zvode solver, sometimes performing better.
+"""
+# XXX: Integrators must have:
+# ===========================
+# cvode - C version of vode and vodpk with many improvements.
+#   Get it from http://www.netlib.org/ode/cvode.tar.gz.
+#   To wrap cvode to Python, one must write the extension module by
+#   hand. Its interface is too much 'advanced C' that using f2py
+#   would be too complicated (or impossible).
+#
+# How to define a new integrator:
+# ===============================
+#
+# class myodeint(IntegratorBase):
+#
+#     runner =  or None
+#
+#     def __init__(self,...):                           # required
+#         
+#
+#     def reset(self,n,has_jac):                        # optional
+#         # n - the size of the problem (number of equations)
+#         # has_jac - whether user has supplied its own routine for Jacobian
+#         
+#
+#     def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
+#         # this method is called to integrate from t=t0 to t=t1
+#         # with initial condition y0. f and jac are user-supplied functions
+#         # that define the problem. f_params,jac_params are additional
+#         # arguments
+#         # to these functions.
+#         
+#         if :
+#             self.success = 0
+#         return t1,y1
+#
+#     # In addition, one can define step() and run_relax() methods (they
+#     # take the same arguments as run()) if the integrator can support
+#     # these features (see IntegratorBase doc strings).
+#
+# if myodeint.runner:
+#     IntegratorBase.integrator_classes.append(myodeint)
+
+__all__ = ['ode', 'complex_ode']
+
+import re
+import threading
+import warnings
+
+from numpy import asarray, array, zeros, isscalar, real, imag, vstack
+
+from . import _vode
+from . import _dop
+from . import _lsoda
+
+
+_dop_int_dtype = _dop.types.intvar.dtype
+_vode_int_dtype = _vode.types.intvar.dtype
+_lsoda_int_dtype = _lsoda.types.intvar.dtype
+
+
+# lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
+# zvode; they share the `def run` implementation
+LSODA_LOCK = threading.Lock()
+VODE_LOCK = threading.Lock()
+
+
+# ------------------------------------------------------------------------------
+# User interface
+# ------------------------------------------------------------------------------
+
+
+class ode:
+    """
+    A generic interface class to numeric integrators.
+
+    Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
+
+    *Note*: The first two arguments of ``f(t, y, ...)`` are in the
+    opposite order of the arguments in the system definition function used
+    by `scipy.integrate.odeint`.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Right-hand side of the differential equation. t is a scalar,
+        ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+        `f` should return a scalar, array or list (not a tuple).
+    jac : callable ``jac(t, y, *jac_args)``, optional
+        Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_jac_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    See also
+    --------
+    odeint : an integrator with a simpler interface based on lsoda from ODEPACK
+    quad : for finding the area under a curve
+
+    Notes
+    -----
+    Available integrators are listed below. They can be selected using
+    the `set_integrator` method.
+
+    "vode"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/vode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "vode" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
+          dimension of the matrix must be (lband+uband+1, len(y)).
+        - method: 'adams' or 'bdf'
+          Which solver to use, Adams (non-stiff) or BDF (stiff)
+        - with_jacobian : bool
+          This option is only considered when the user has not supplied a
+          Jacobian function and has not indicated (by setting either band)
+          that the Jacobian is banded. In this case, `with_jacobian` specifies
+          whether the iteration method of the ODE solver's correction step is
+          chord iteration with an internally generated full Jacobian or
+          functional iteration with no Jacobian.
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - order : int
+          Maximum order used by the integrator,
+          order <= 12 for Adams, <= 5 for BDF.
+
+    "zvode"
+
+        Complex-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/zvode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "zvode" integrator at the same time.
+
+        This integrator accepts the same parameters in `set_integrator`
+        as the "vode" solver.
+
+        .. note::
+
+            When using ZVODE for a stiff system, it should only be used for
+            the case in which the function f is analytic, that is, when each f(i)
+            is an analytic function of each y(j). Analyticity means that the
+            partial derivative df(i)/dy(j) is a unique complex number, and this
+            fact is critical in the way ZVODE solves the dense or banded linear
+            systems that arise in the stiff case. For a complex stiff ODE system
+            in which f is not analytic, ZVODE is likely to have convergence
+            failures, and for this problem one should instead use DVODE on the
+            equivalent real system (in the real and imaginary parts of y).
+
+    "lsoda"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        automatic method switching between implicit Adams method (for non-stiff
+        problems) and a method based on backward differentiation formulas (BDF)
+        (for stiff problems).
+
+        Source: http://www.netlib.org/odepack
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "lsoda" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j].
+        - with_jacobian : bool
+          *Not used.*
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - max_order_ns : int
+          Maximum order used in the nonstiff case (default 12).
+        - max_order_s : int
+          Maximum order used in the stiff case (default 5).
+        - max_hnil : int
+          Maximum number of messages reporting too small step size (t + h = t)
+          (default 0)
+        - ixpr : int
+          Whether to generate extra printing at method switches (default False).
+
+    "dopri5"
+
+        This is an explicit runge-kutta method of order (4)5 due to Dormand &
+        Prince (with stepsize control and dense output).
+
+        Authors:
+
+            E. Hairer and G. Wanner
+            Universite de Geneve, Dept. de Mathematiques
+            CH-1211 Geneve 24, Switzerland
+            e-mail:  ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
+
+        This code is described in [HNW93]_.
+
+        This integrator accepts the following parameters in set_integrator()
+        method of the ode class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - max_step : float
+        - safety : float
+          Safety factor on new step selection (default 0.9)
+        - ifactor : float
+        - dfactor : float
+          Maximum factor to increase/decrease step size by in one step
+        - beta : float
+          Beta parameter for stabilised step size control.
+        - verbosity : int
+          Switch for printing messages (< 0 for no messages).
+
+    "dop853"
+
+        This is an explicit runge-kutta method of order 8(5,3) due to Dormand
+        & Prince (with stepsize control and dense output).
+
+        Options and references the same as "dopri5".
+
+    Examples
+    --------
+
+    A problem to integrate and the corresponding jacobian:
+
+    >>> from scipy.integrate import ode
+    >>>
+    >>> y0, t0 = [1.0j, 2.0], 0
+    >>>
+    >>> def f(t, y, arg1):
+    ...     return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
+    >>> def jac(t, y, arg1):
+    ...     return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
+
+    The integration:
+
+    >>> r = ode(f, jac).set_integrator('zvode', method='bdf')
+    >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
+    >>> t1 = 10
+    >>> dt = 1
+    >>> while r.successful() and r.t < t1:
+    ...     print(r.t+dt, r.integrate(r.t+dt))
+    1 [-0.71038232+0.23749653j  0.40000271+0.j        ]
+    2.0 [0.19098503-0.52359246j 0.22222356+0.j        ]
+    3.0 [0.47153208+0.52701229j 0.15384681+0.j        ]
+    4.0 [-0.61905937+0.30726255j  0.11764744+0.j        ]
+    5.0 [0.02340997-0.61418799j 0.09523835+0.j        ]
+    6.0 [0.58643071+0.339819j 0.08000018+0.j      ]
+    7.0 [-0.52070105+0.44525141j  0.06896565+0.j        ]
+    8.0 [-0.15986733-0.61234476j  0.06060616+0.j        ]
+    9.0 [0.64850462+0.15048982j 0.05405414+0.j        ]
+    10.0 [-0.38404699+0.56382299j  0.04878055+0.j        ]
+
+    References
+    ----------
+    .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
+        Differential Equations i. Nonstiff Problems. 2nd edition.
+        Springer Series in Computational Mathematics,
+        Springer-Verlag (1993)
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.stiff = 0
+        self.f = f
+        self.jac = jac
+        self.f_params = ()
+        self.jac_params = ()
+        self._y = []
+
+    @property
+    def y(self):
+        return self._y
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        if isscalar(y):
+            y = [y]
+        n_prev = len(self._y)
+        if not n_prev:
+            self.set_integrator('')  # find first available integrator
+        self._y = asarray(y, self._integrator.scalar)
+        self.t = t
+        self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator.
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        integrator = find_integrator(name)
+        if integrator is None:
+            # FIXME: this really should be raise an exception. Will that break
+            # any code?
+            message = f'No integrator name match with {name!r} or is not available.'
+            warnings.warn(message, stacklevel=2)
+        else:
+            self._integrator = integrator(**integrator_params)
+            if not len(self._y):
+                self.t = 0.0
+                self._y = array([0.0], self._integrator.scalar)
+            self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        if step and self._integrator.supports_step:
+            mth = self._integrator.step
+        elif relax and self._integrator.supports_run_relax:
+            mth = self._integrator.run_relax
+        else:
+            mth = self._integrator.run
+
+        try:
+            self._y, self.t = mth(self.f, self.jac or (lambda: None),
+                                  self._y, self.t, t,
+                                  self.f_params, self.jac_params)
+        except SystemError as e:
+            # f2py issue with tuple returns, see ticket 1187.
+            raise ValueError(
+                'Function to integrate must not return a tuple.'
+            ) from e
+
+        return self._y
+
+    def successful(self):
+        """Check if integration was successful."""
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.success == 1
+
+    def get_return_code(self):
+        """Extracts the return code for the integration to enable better control
+        if the integration fails.
+
+        In general, a return code > 0 implies success, while a return code < 0
+        implies failure.
+
+        Notes
+        -----
+        This section describes possible return codes and their meaning, for available
+        integrators that can be selected by `set_integrator` method.
+
+        "vode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "zvode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "dopri5"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "dop853"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "lsoda"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call (perhaps wrong Dfun type).
+        -2           Excess accuracy requested (tolerances too small).
+        -3           Illegal input detected (internal error).
+        -4           Repeated error test failures (internal error).
+        -5           Repeated convergence failures (perhaps bad Jacobian or tolerances).
+        -6           Error weight became zero during problem.
+        -7           Internal workspace insufficient to finish (internal error).
+        ===========  =======
+        """
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.istate
+
+    def set_f_params(self, *args):
+        """Set extra parameters for user-supplied function f."""
+        self.f_params = args
+        return self
+
+    def set_jac_params(self, *args):
+        """Set extra parameters for user-supplied function jac."""
+        self.jac_params = args
+        return self
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout)
+            if self._y is not None:
+                self._integrator.reset(len(self._y), self.jac is not None)
+        else:
+            raise ValueError("selected integrator does not support solout,"
+                             " choose another one")
+
+
+def _transform_banded_jac(bjac):
+    """
+    Convert a real matrix of the form (for example)
+
+        [0 0 A B]        [0 0 0 B]
+        [0 0 C D]        [0 0 A D]
+        [E F G H]   to   [0 F C H]
+        [I J K L]        [E J G L]
+                         [I 0 K 0]
+
+    That is, every other column is shifted up one.
+    """
+    # Shift every other column.
+    newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
+    newjac[1:, ::2] = bjac[:, ::2]
+    newjac[:-1, 1::2] = bjac[:, 1::2]
+    return newjac
+
+
+class complex_ode(ode):
+    """
+    A wrapper of ode for complex systems.
+
+    This functions similarly as `ode`, but re-maps a complex-valued
+    equation system to a real-valued one before using the integrators.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+    jac : callable ``jac(t, y, *jac_args)``
+        Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_f_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    Examples
+    --------
+    For usage examples, see `ode`.
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.cf = f
+        self.cjac = jac
+        if jac is None:
+            ode.__init__(self, self._wrap, None)
+        else:
+            ode.__init__(self, self._wrap, self._wrap_jac)
+
+    def _wrap(self, t, y, *f_args):
+        f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
+        # self.tmp is a real-valued array containing the interleaved
+        # real and imaginary parts of f.
+        self.tmp[::2] = real(f)
+        self.tmp[1::2] = imag(f)
+        return self.tmp
+
+    def _wrap_jac(self, t, y, *jac_args):
+        # jac is the complex Jacobian computed by the user-defined function.
+        jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
+
+        # jac_tmp is the real version of the complex Jacobian.  Each complex
+        # entry in jac, say 2+3j, becomes a 2x2 block of the form
+        #     [2 -3]
+        #     [3  2]
+        jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
+        jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
+        jac_tmp[1::2, ::2] = imag(jac)
+        jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
+
+        ml = getattr(self._integrator, 'ml', None)
+        mu = getattr(self._integrator, 'mu', None)
+        if ml is not None or mu is not None:
+            # Jacobian is banded.  The user's Jacobian function has computed
+            # the complex Jacobian in packed format.  The corresponding
+            # real-valued version has every other column shifted up.
+            jac_tmp = _transform_banded_jac(jac_tmp)
+
+        return jac_tmp
+
+    @property
+    def y(self):
+        return self._y[::2] + 1j * self._y[1::2]
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        if name == 'zvode':
+            raise ValueError("zvode must be used with ode, not complex_ode")
+
+        lband = integrator_params.get('lband')
+        uband = integrator_params.get('uband')
+        if lband is not None or uband is not None:
+            # The Jacobian is banded.  Override the user-supplied bandwidths
+            # (which are for the complex Jacobian) with the bandwidths of
+            # the corresponding real-valued Jacobian wrapper of the complex
+            # Jacobian.
+            integrator_params['lband'] = 2 * (lband or 0) + 1
+            integrator_params['uband'] = 2 * (uband or 0) + 1
+
+        return ode.set_integrator(self, name, **integrator_params)
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        y = asarray(y)
+        self.tmp = zeros(y.size * 2, 'float')
+        self.tmp[::2] = real(y)
+        self.tmp[1::2] = imag(y)
+        return ode.set_initial_value(self, self.tmp, t)
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        y = ode.integrate(self, t, step, relax)
+        return y[::2] + 1j * y[1::2]
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout, complex=True)
+        else:
+            raise TypeError("selected integrator does not support solouta, "
+                            "choose another one")
+
+
+# ------------------------------------------------------------------------------
+# ODE integrators
+# ------------------------------------------------------------------------------
+
+def find_integrator(name):
+    for cl in IntegratorBase.integrator_classes:
+        if re.match(name, cl.__name__, re.I):
+            return cl
+    return None
+
+
+class IntegratorConcurrencyError(RuntimeError):
+    """
+    Failure due to concurrent usage of an integrator that can be used
+    only for a single problem at a time.
+
+    """
+
+    def __init__(self, name):
+        msg = (f"Integrator `{name}` can be used to solve only a single problem "
+                "at a time. If you want to integrate multiple problems, "
+                "consider using a different integrator (see `ode.set_integrator`)")
+        RuntimeError.__init__(self, msg)
+
+
+class IntegratorBase:
+    runner = None  # runner is None => integrator is not available
+    success = None  # success==1 if integrator was called successfully
+    istate = None  # istate > 0 means success, istate < 0 means failure
+    supports_run_relax = None
+    supports_step = None
+    supports_solout = False
+    integrator_classes = []
+    scalar = float
+
+    def acquire_new_handle(self):
+        # Some of the integrators have internal state (ancient
+        # Fortran...), and so only one instance can use them at a time.
+        # We keep track of this, and fail when concurrent usage is tried.
+        self.__class__.active_global_handle += 1
+        self.handle = self.__class__.active_global_handle
+
+    def check_handle(self):
+        if self.handle is not self.__class__.active_global_handle:
+            raise IntegratorConcurrencyError(self.__class__.__name__)
+
+    def reset(self, n, has_jac):
+        """Prepare integrator for call: allocate memory, set flags, etc.
+        n - number of equations.
+        has_jac - if user has supplied function for evaluating Jacobian.
+        """
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t=t1 using y0 as an initial condition.
+        Return 2-tuple (y1,t1) where y1 is the result and t=t1
+        defines the stoppage coordinate of the result.
+        """
+        raise NotImplementedError('all integrators must define '
+                                  'run(f, jac, t0, t1, y0, f_params, jac_params)')
+
+    def step(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Make one integration step and return (y1,t1)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support step() method')
+
+    def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t>=t1 and return (y1,t)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support run_relax() method')
+
+    # XXX: __str__ method for getting visual state of the integrator
+
+
+def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
+    """
+    Wrap a banded Jacobian function with a function that pads
+    the Jacobian with `ml` rows of zeros.
+    """
+
+    def jac_wrapper(t, y):
+        jac = asarray(jacfunc(t, y, *jac_params))
+        padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
+        return padded_jac
+
+    return jac_wrapper
+
+
+class vode(IntegratorBase):
+    runner = getattr(_vode, 'dvode', None)
+
+    messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
+                -2: 'Excess accuracy requested. (Tolerances too small.)',
+                -3: 'Illegal input detected. (See printed message.)',
+                -4: 'Repeated error test failures. (Check all input.)',
+                -5: 'Repeated convergence failures. (Perhaps bad'
+                    ' Jacobian supplied or wrong choice of MF or tolerances.)',
+                -6: 'Error weight became zero during problem. (Solution'
+                    ' component i vanished, and ATOL or ATOL(i) = 0.)'
+                }
+    supports_run_relax = 1
+    supports_step = 1
+    active_global_handle = 0
+
+    def __init__(self,
+                 method='adams',
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 order=12,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ):
+
+        if re.match(method, r'adams', re.I):
+            self.meth = 1
+        elif re.match(method, r'bdf', re.I):
+            self.meth = 2
+        else:
+            raise ValueError(f'Unknown integration method {method}')
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.order = order
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.success = 1
+
+        self.initialized = False
+
+    def _determine_mf_and_set_bands(self, has_jac):
+        """
+        Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
+
+        In the Fortran code, the legal values of `MF` are:
+            10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
+            -11, -12, -14, -15, -21, -22, -24, -25
+        but this Python wrapper does not use negative values.
+
+        Returns
+
+            mf  = 10*self.meth + miter
+
+        self.meth is the linear multistep method:
+            self.meth == 1:  method="adams"
+            self.meth == 2:  method="bdf"
+
+        miter is the correction iteration method:
+            miter == 0:  Functional iteration; no Jacobian involved.
+            miter == 1:  Chord iteration with user-supplied full Jacobian.
+            miter == 2:  Chord iteration with internally computed full Jacobian.
+            miter == 3:  Chord iteration with internally computed diagonal Jacobian.
+            miter == 4:  Chord iteration with user-supplied banded Jacobian.
+            miter == 5:  Chord iteration with internally computed banded Jacobian.
+
+        Side effects: If either self.mu or self.ml is not None and the other is None,
+        then the one that is None is set to 0.
+        """
+
+        jac_is_banded = self.mu is not None or self.ml is not None
+        if jac_is_banded:
+            if self.mu is None:
+                self.mu = 0
+            if self.ml is None:
+                self.ml = 0
+
+        # has_jac is True if the user provided a Jacobian function.
+        if has_jac:
+            if jac_is_banded:
+                miter = 4
+            else:
+                miter = 1
+        else:
+            if jac_is_banded:
+                if self.ml == self.mu == 0:
+                    miter = 3  # Chord iteration with internal diagonal Jacobian.
+                else:
+                    miter = 5  # Chord iteration with internal banded Jacobian.
+            else:
+                # self.with_jacobian is set by the user in
+                # the call to ode.set_integrator.
+                if self.with_jacobian:
+                    miter = 2  # Chord iteration with internal full Jacobian.
+                else:
+                    miter = 0  # Functional iteration; no Jacobian involved.
+
+        mf = 10 * self.meth + miter
+        return mf
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf == 10:
+            lrw = 20 + 16 * n
+        elif mf in [11, 12]:
+            lrw = 22 + 16 * n + 2 * n * n
+        elif mf == 13:
+            lrw = 22 + 17 * n
+        elif mf in [14, 15]:
+            lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf == 20:
+            lrw = 20 + 9 * n
+        elif mf in [21, 22]:
+            lrw = 22 + 9 * n + 2 * n * n
+        elif mf == 23:
+            lrw = 22 + 10 * n
+        elif mf in [24, 25]:
+            lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
+        else:
+            raise ValueError(f'Unexpected mf={mf}')
+
+        if mf % 10 in [0, 3]:
+            liw = 30
+        else:
+            liw = 30 + n
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+
+        if self.ml is not None and self.ml > 0:
+            # Banded Jacobian. Wrap the user-provided function with one
+            # that pads the Jacobian array with the extra `self.ml` rows
+            # required by the f2py-generated wrapper.
+            jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
+
+        args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
+                (f_params, jac_params))
+
+        with VODE_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if vode.runner is not None:
+    IntegratorBase.integrator_classes.append(vode)
+
+
+class zvode(vode):
+    runner = getattr(_vode, 'zvode', None)
+
+    supports_run_relax = 1
+    supports_step = 1
+    scalar = complex
+    active_global_handle = 0
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf in (10,):
+            lzw = 15 * n
+        elif mf in (11, 12):
+            lzw = 15 * n + 2 * n ** 2
+        elif mf in (-11, -12):
+            lzw = 15 * n + n ** 2
+        elif mf in (13,):
+            lzw = 16 * n
+        elif mf in (14, 15):
+            lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-14, -15):
+            lzw = 16 * n + (2 * self.ml + self.mu) * n
+        elif mf in (20,):
+            lzw = 8 * n
+        elif mf in (21, 22):
+            lzw = 8 * n + 2 * n ** 2
+        elif mf in (-21, -22):
+            lzw = 8 * n + n ** 2
+        elif mf in (23,):
+            lzw = 9 * n
+        elif mf in (24, 25):
+            lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-24, -25):
+            lzw = 9 * n + (2 * self.ml + self.mu) * n
+
+        lrw = 20 + n
+
+        if mf % 10 in (0, 3):
+            liw = 30
+        else:
+            liw = 30 + n
+
+        zwork = zeros((lzw,), complex)
+        self.zwork = zwork
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.zwork, self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+
+if zvode.runner is not None:
+    IntegratorBase.integrator_classes.append(zvode)
+
+
+class dopri5(IntegratorBase):
+    runner = getattr(_dop, 'dopri5', None)
+    name = 'dopri5'
+    supports_solout = True
+
+    messages = {1: 'computation successful',
+                2: 'computation successful (interrupted by solout)',
+                -1: 'input is not consistent',
+                -2: 'larger nsteps is needed',
+                -3: 'step size becomes too small',
+                -4: 'problem is probably stiff (interrupted)',
+                }
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=10.0,
+                 dfactor=0.2,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        self.rtol = rtol
+        self.atol = atol
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.first_step = first_step
+        self.safety = safety
+        self.ifactor = ifactor
+        self.dfactor = dfactor
+        self.beta = beta
+        self.verbosity = verbosity
+        self.success = 1
+        self.set_solout(None)
+
+    def set_solout(self, solout, complex=False):
+        self.solout = solout
+        self.solout_cmplx = complex
+        if solout is None:
+            self.iout = 0
+        else:
+            self.iout = 1
+
+    def reset(self, n, has_jac):
+        work = zeros((8 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
+                                          tuple(self.call_args) + (f_params,)))
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        return y, x
+
+    def _solout(self, nr, xold, x, y, nd, icomp, con):
+        if self.solout is not None:
+            if self.solout_cmplx:
+                y = y[::2] + 1j * y[1::2]
+            return self.solout(x, y)
+        else:
+            return 1
+
+
+if dopri5.runner is not None:
+    IntegratorBase.integrator_classes.append(dopri5)
+
+
+class dop853(dopri5):
+    runner = getattr(_dop, 'dop853', None)
+    name = 'dop853'
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=6.0,
+                 dfactor=0.3,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
+                         ifactor, dfactor, beta, method, verbosity)
+
+    def reset(self, n, has_jac):
+        work = zeros((11 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+
+if dop853.runner is not None:
+    IntegratorBase.integrator_classes.append(dop853)
+
+
+class lsoda(IntegratorBase):
+    runner = getattr(_lsoda, 'lsoda', None)
+    active_global_handle = 0
+
+    messages = {
+        2: "Integration successful.",
+        -1: "Excess work done on this call (perhaps wrong Dfun type).",
+        -2: "Excess accuracy requested (tolerances too small).",
+        -3: "Illegal input detected (internal error).",
+        -4: "Repeated error test failures (internal error).",
+        -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+        -6: "Error weight became zero during problem.",
+        -7: "Internal workspace insufficient to finish (internal error)."
+    }
+
+    def __init__(self,
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ixpr=0,
+                 max_hnil=0,
+                 max_order_ns=12,
+                 max_order_s=5,
+                 method=None
+                 ):
+
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.max_order_ns = max_order_ns
+        self.max_order_s = max_order_s
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.ixpr = ixpr
+        self.max_hnil = max_hnil
+        self.success = 1
+
+        self.initialized = False
+
+    def reset(self, n, has_jac):
+        # Calculate parameters for Fortran subroutine dvode.
+        if has_jac:
+            if self.mu is None and self.ml is None:
+                jt = 1
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 4
+        else:
+            if self.mu is None and self.ml is None:
+                jt = 2
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 5
+        lrn = 20 + (self.max_order_ns + 4) * n
+        if jt in [1, 2]:
+            lrs = 22 + (self.max_order_s + 4) * n + n * n
+        elif jt in [4, 5]:
+            lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
+        else:
+            raise ValueError(f'Unexpected jt={jt}')
+        lrw = max(lrn, lrs)
+        liw = 20 + n
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+        iwork = zeros((liw,), _lsoda_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.ixpr
+        iwork[5] = self.nsteps
+        iwork[6] = self.max_hnil
+        iwork[7] = self.max_order_ns
+        iwork[8] = self.max_order_s
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, jt]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+        args = [f, y0, t0, t1] + self.call_args[:-1] + \
+               [jac, self.call_args[-1], f_params, 0, jac_params]
+
+        with LSODA_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if lsoda.runner:
+    IntegratorBase.integrator_classes.append(lsoda)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_odepack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_odepack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..90d758a14dc6332f7f88d23136de045b2cc8a1f0
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_odepack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_odepack_py.py b/python_embeded/Lib/site-packages/scipy/integrate/_odepack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..2288204b8a27b671b63fcf05d6d439458d7784b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_odepack_py.py
@@ -0,0 +1,273 @@
+# Author: Travis Oliphant
+
+__all__ = ['odeint', 'ODEintWarning']
+
+import numpy as np
+from . import _odepack
+from copy import copy
+import warnings
+
+from threading import Lock
+
+
+ODE_LOCK = Lock()
+
+
+class ODEintWarning(Warning):
+    """Warning raised during the execution of `odeint`."""
+    pass
+
+
+_msgs = {2: "Integration successful.",
+         1: "Nothing was done; the integration time was 0.",
+         -1: "Excess work done on this call (perhaps wrong Dfun type).",
+         -2: "Excess accuracy requested (tolerances too small).",
+         -3: "Illegal input detected (internal error).",
+         -4: "Repeated error test failures (internal error).",
+         -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+         -6: "Error weight became zero during problem.",
+         -7: "Internal workspace insufficient to finish (internal error).",
+         -8: "Run terminated (internal error)."
+         }
+
+
+def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
+           ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
+           hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
+           mxords=5, printmessg=0, tfirst=False):
+    """
+    Integrate a system of ordinary differential equations.
+
+    .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
+              differential equation.
+
+    Solve a system of ordinary differential equations using lsoda from the
+    FORTRAN library odepack.
+
+    Solves the initial value problem for stiff or non-stiff systems
+    of first order ode-s::
+
+        dy/dt = func(y, t, ...)  [or func(t, y, ...)]
+
+    where y can be a vector.
+
+    .. note:: By default, the required order of the first two arguments of
+              `func` are in the opposite order of the arguments in the system
+              definition function used by the `scipy.integrate.ode` class and
+              the function `scipy.integrate.solve_ivp`. To use a function with
+              the signature ``func(t, y, ...)``, the argument `tfirst` must be
+              set to ``True``.
+
+    Parameters
+    ----------
+    func : callable(y, t, ...) or callable(t, y, ...)
+        Computes the derivative of y at t.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `func` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    y0 : array
+        Initial condition on y (can be a vector).
+    t : array
+        A sequence of time points for which to solve for y. The initial
+        value point should be the first element of this sequence.
+        This sequence must be monotonically increasing or monotonically
+        decreasing; repeated values are allowed.
+    args : tuple, optional
+        Extra arguments to pass to function.
+    Dfun : callable(y, t, ...) or callable(t, y, ...)
+        Gradient (Jacobian) of `func`.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `Dfun` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    col_deriv : bool, optional
+        True if `Dfun` defines derivatives down columns (faster),
+        otherwise `Dfun` should define derivatives across rows.
+    full_output : bool, optional
+        True if to return a dictionary of optional outputs as the second output
+    printmessg : bool, optional
+        Whether to print the convergence message
+    tfirst : bool, optional
+        If True, the first two arguments of `func` (and `Dfun`, if given)
+        must ``t, y`` instead of the default ``y, t``.
+
+        .. versionadded:: 1.1.0
+
+    Returns
+    -------
+    y : array, shape (len(t), len(y0))
+        Array containing the value of y for each desired time in t,
+        with the initial value `y0` in the first row.
+    infodict : dict, only returned if full_output == True
+        Dictionary containing additional output information
+
+        =======  ============================================================
+        key      meaning
+        =======  ============================================================
+        'hu'     vector of step sizes successfully used for each time step
+        'tcur'   vector with the value of t reached for each time step
+                 (will always be at least as large as the input times)
+        'tolsf'  vector of tolerance scale factors, greater than 1.0,
+                 computed when a request for too much accuracy was detected
+        'tsw'    value of t at the time of the last method switch
+                 (given for each time step)
+        'nst'    cumulative number of time steps
+        'nfe'    cumulative number of function evaluations for each time step
+        'nje'    cumulative number of jacobian evaluations for each time step
+        'nqu'    a vector of method orders for each successful step
+        'imxer'  index of the component of largest magnitude in the
+                 weighted local error vector (e / ewt) on an error return, -1
+                 otherwise
+        'lenrw'  the length of the double work array required
+        'leniw'  the length of integer work array required
+        'mused'  a vector of method indicators for each successful time step:
+                 1: adams (nonstiff), 2: bdf (stiff)
+        =======  ============================================================
+
+    Other Parameters
+    ----------------
+    ml, mu : int, optional
+        If either of these are not None or non-negative, then the
+        Jacobian is assumed to be banded. These give the number of
+        lower and upper non-zero diagonals in this banded matrix.
+        For the banded case, `Dfun` should return a matrix whose
+        rows contain the non-zero bands (starting with the lowest diagonal).
+        Thus, the return matrix `jac` from `Dfun` should have shape
+        ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
+        The data in `jac` must be stored such that ``jac[i - j + mu, j]``
+        holds the derivative of the ``i``\\ th equation with respect to the
+        ``j``\\ th state variable.  If `col_deriv` is True, the transpose of
+        this `jac` must be returned.
+    rtol, atol : float, optional
+        The input parameters `rtol` and `atol` determine the error
+        control performed by the solver.  The solver will control the
+        vector, e, of estimated local errors in y, according to an
+        inequality of the form ``max-norm of (e / ewt) <= 1``,
+        where ewt is a vector of positive error weights computed as
+        ``ewt = rtol * abs(y) + atol``.
+        rtol and atol can be either vectors the same length as y or scalars.
+        Defaults to 1.49012e-8.
+    tcrit : ndarray, optional
+        Vector of critical points (e.g., singularities) where integration
+        care should be taken.
+    h0 : float, (0: solver-determined), optional
+        The step size to be attempted on the first step.
+    hmax : float, (0: solver-determined), optional
+        The maximum absolute step size allowed.
+    hmin : float, (0: solver-determined), optional
+        The minimum absolute step size allowed.
+    ixpr : bool, optional
+        Whether to generate extra printing at method switches.
+    mxstep : int, (0: solver-determined), optional
+        Maximum number of (internally defined) steps allowed for each
+        integration point in t.
+    mxhnil : int, (0: solver-determined), optional
+        Maximum number of messages printed.
+    mxordn : int, (0: solver-determined), optional
+        Maximum order to be allowed for the non-stiff (Adams) method.
+    mxords : int, (0: solver-determined), optional
+        Maximum order to be allowed for the stiff (BDF) method.
+
+    See Also
+    --------
+    solve_ivp : solve an initial value problem for a system of ODEs
+    ode : a more object-oriented integrator based on VODE
+    quad : for finding the area under a curve
+
+    Examples
+    --------
+    The second order differential equation for the angle `theta` of a
+    pendulum acted on by gravity with friction can be written::
+
+        theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
+
+    where `b` and `c` are positive constants, and a prime (') denotes a
+    derivative. To solve this equation with `odeint`, we must first convert
+    it to a system of first order equations. By defining the angular
+    velocity ``omega(t) = theta'(t)``, we obtain the system::
+
+        theta'(t) = omega(t)
+        omega'(t) = -b*omega(t) - c*sin(theta(t))
+
+    Let `y` be the vector [`theta`, `omega`]. We implement this system
+    in Python as:
+
+    >>> import numpy as np
+    >>> def pend(y, t, b, c):
+    ...     theta, omega = y
+    ...     dydt = [omega, -b*omega - c*np.sin(theta)]
+    ...     return dydt
+    ...
+
+    We assume the constants are `b` = 0.25 and `c` = 5.0:
+
+    >>> b = 0.25
+    >>> c = 5.0
+
+    For initial conditions, we assume the pendulum is nearly vertical
+    with `theta(0)` = `pi` - 0.1, and is initially at rest, so
+    `omega(0)` = 0.  Then the vector of initial conditions is
+
+    >>> y0 = [np.pi - 0.1, 0.0]
+
+    We will generate a solution at 101 evenly spaced samples in the interval
+    0 <= `t` <= 10.  So our array of times is:
+
+    >>> t = np.linspace(0, 10, 101)
+
+    Call `odeint` to generate the solution. To pass the parameters
+    `b` and `c` to `pend`, we give them to `odeint` using the `args`
+    argument.
+
+    >>> from scipy.integrate import odeint
+    >>> sol = odeint(pend, y0, t, args=(b, c))
+
+    The solution is an array with shape (101, 2). The first column
+    is `theta(t)`, and the second is `omega(t)`. The following code
+    plots both components.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
+    >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
+    >>> plt.legend(loc='best')
+    >>> plt.xlabel('t')
+    >>> plt.grid()
+    >>> plt.show()
+    """
+
+    if ml is None:
+        ml = -1  # changed to zero inside function call
+    if mu is None:
+        mu = -1  # changed to zero inside function call
+
+    dt = np.diff(t)
+    if not ((dt >= 0).all() or (dt <= 0).all()):
+        raise ValueError("The values in t must be monotonically increasing "
+                         "or monotonically decreasing; repeated values are "
+                         "allowed.")
+
+    t = copy(t)
+    y0 = copy(y0)
+
+    with ODE_LOCK:
+        output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
+                                full_output, rtol, atol, tcrit, h0, hmax, hmin,
+                                ixpr, mxstep, mxhnil, mxordn, mxords,
+                                int(bool(tfirst)))
+    if output[-1] < 0:
+        warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
+                       f"get quantitative information.")
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+    elif printmessg:
+        warning_msg = _msgs[output[-1]]
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+
+    if full_output:
+        output[1]['message'] = _msgs[output[-1]]
+
+    output = output[:-1]
+    if len(output) == 1:
+        return output[0]
+    else:
+        return output
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_quad_vec.py b/python_embeded/Lib/site-packages/scipy/integrate/_quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..70714e97c57f2f5a9faf9c8efbd285f8372e4d91
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_quad_vec.py
@@ -0,0 +1,682 @@
+import sys
+import copy
+import heapq
+import collections
+import functools
+import warnings
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper, _FunctionWrapper
+
+
+class LRUDict(collections.OrderedDict):
+    def __init__(self, max_size):
+        self.__max_size = max_size
+
+    def __setitem__(self, key, value):
+        existing_key = (key in self)
+        super().__setitem__(key, value)
+        if existing_key:
+            self.move_to_end(key)
+        elif len(self) > self.__max_size:
+            self.popitem(last=False)
+
+    def update(self, other):
+        # Not needed below
+        raise NotImplementedError()
+
+
+class SemiInfiniteFunc:
+    """
+    Argument transform from (start, +-oo) to (0, 1)
+    """
+    def __init__(self, func, start, infty):
+        self._func = func
+        self._start = start
+        self._sgn = -1 if infty < 0 else 1
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        z = self._sgn * (x - self._start) + 1
+        if z == 0:
+            # Can happen only if point not in range
+            return np.inf
+        return 1 / z
+
+    def __call__(self, t):
+        if t < self._tmin:
+            return 0.0
+        else:
+            x = self._start + self._sgn * (1 - t) / t
+            f = self._func(x)
+            return self._sgn * (f / t) / t
+
+
+class DoubleInfiniteFunc:
+    """
+    Argument transform from (-oo, oo) to (-1, 1)
+    """
+    def __init__(self, func):
+        self._func = func
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        s = -1 if x < 0 else 1
+        return s / (abs(x) + 1)
+
+    def __call__(self, t):
+        if abs(t) < self._tmin:
+            return 0.0
+        else:
+            x = (1 - abs(t)) / t
+            f = self._func(x)
+            return (f / t) / t
+
+
+def _max_norm(x):
+    return np.amax(abs(x))
+
+
+def _get_sizeof(obj):
+    try:
+        return sys.getsizeof(obj)
+    except TypeError:
+        # occurs on pypy
+        if hasattr(obj, '__sizeof__'):
+            return int(obj.__sizeof__())
+        return 64
+
+
+class _Bunch:
+    def __init__(self, **kwargs):
+        self.__keys = kwargs.keys()
+        self.__dict__.update(**kwargs)
+
+    def __repr__(self):
+        key_value_pairs = ', '.join(
+            f'{k}={repr(self.__dict__[k])}' for k in self.__keys
+        )
+        return f"_Bunch({key_value_pairs})"
+
+
+def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
+             limit=10000, workers=1, points=None, quadrature=None, full_output=False,
+             *, args=()):
+    r"""Adaptive integration of a vector-valued function.
+
+    Parameters
+    ----------
+    f : callable
+        Vector-valued function f(x) to integrate.
+    a : float
+        Initial point.
+    b : float
+        Final point.
+    epsabs : float, optional
+        Absolute tolerance.
+    epsrel : float, optional
+        Relative tolerance.
+    norm : {'max', '2'}, optional
+        Vector norm to use for error estimation.
+    cache_size : int, optional
+        Number of bytes to use for memoization.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in
+        parallel subdivided to this many tasks (using
+        :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process.
+        Alternatively, supply a map-like callable, such as
+        :meth:`python:multiprocessing.pool.Pool.map` for evaluating the
+        population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+    points : list, optional
+        List of additional breakpoints.
+    quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
+        Quadrature rule to use on subintervals.
+        Options: 'gk21' (Gauss-Kronrod 21-point rule),
+        'gk15' (Gauss-Kronrod 15-point rule),
+        'trapezoid' (composite trapezoid rule).
+        Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite
+    full_output : bool, optional
+        Return an additional ``info`` dictionary.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    res : {float, array-like}
+        Estimate for the result
+    err : float
+        Error estimate for the result in the given norm
+    info : dict
+        Returned only when ``full_output=True``.
+        Info dictionary. Is an object with the attributes:
+
+            success : bool
+                Whether integration reached target precision.
+            status : int
+                Indicator for convergence, success (0),
+                failure (1), and failure due to rounding error (2).
+            neval : int
+                Number of function evaluations.
+            intervals : ndarray, shape (num_intervals, 2)
+                Start and end points of subdivision intervals.
+            integrals : ndarray, shape (num_intervals, ...)
+                Integral for each interval.
+                Note that at most ``cache_size`` values are recorded,
+                and the array may contains *nan* for missing items.
+            errors : ndarray, shape (num_intervals,)
+                Estimated integration error for each interval.
+
+    Notes
+    -----
+    The algorithm mainly follows the implementation of QUADPACK's
+    DQAG* algorithms, implementing global error control and adaptive
+    subdivision.
+
+    The algorithm here has some differences to the QUADPACK approach:
+
+    Instead of subdividing one interval at a time, the algorithm
+    subdivides N intervals with largest errors at once. This enables
+    (partial) parallelization of the integration.
+
+    The logic of subdividing "next largest" intervals first is then
+    not implemented, and we rely on the above extension to avoid
+    concentrating on "small" intervals only.
+
+    The Wynn epsilon table extrapolation is not used (QUADPACK uses it
+    for infinite intervals). This is because the algorithm here is
+    supposed to work on vector-valued functions, in an user-specified
+    norm, and the extension of the epsilon algorithm to this case does
+    not appear to be widely agreed. For max-norm, using elementwise
+    Wynn epsilon could be possible, but we do not do this here with
+    the hope that the epsilon extrapolation is mainly useful in
+    special cases.
+
+    References
+    ----------
+    [1] R. Piessens, E. de Doncker, QUADPACK (1983).
+
+    Examples
+    --------
+    We can compute integrations of a vector-valued function:
+
+    >>> from scipy.integrate import quad_vec
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> alpha = np.linspace(0.0, 2.0, num=30)
+    >>> f = lambda x: x**alpha
+    >>> x0, x1 = 0, 2
+    >>> y, err = quad_vec(f, x0, x1)
+    >>> plt.plot(alpha, y)
+    >>> plt.xlabel(r"$\alpha$")
+    >>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
+    >>> plt.show()
+
+    When using the argument `workers`, one should ensure
+    that the main module is import-safe, for instance
+    by rewriting the example above as:
+
+    .. code-block:: python
+
+        from scipy.integrate import quad_vec
+        import numpy as np
+        import matplotlib.pyplot as plt
+
+        alpha = np.linspace(0.0, 2.0, num=30)
+        x0, x1 = 0, 2
+        def f(x):
+            return x**alpha
+
+        if __name__ == "__main__":
+            y, err = quad_vec(f, x0, x1, workers=2)
+    """
+    a = float(a)
+    b = float(b)
+
+    if args:
+        if not isinstance(args, tuple):
+            args = (args,)
+
+        # create a wrapped function to allow the use of map and Pool.map
+        f = _FunctionWrapper(f, args)
+
+    # Use simple transformations to deal with integrals over infinite
+    # intervals.
+    kwargs = dict(epsabs=epsabs,
+                  epsrel=epsrel,
+                  norm=norm,
+                  cache_size=cache_size,
+                  limit=limit,
+                  workers=workers,
+                  points=points,
+                  quadrature='gk15' if quadrature is None else quadrature,
+                  full_output=full_output)
+    if np.isfinite(a) and np.isinf(b):
+        f2 = SemiInfiniteFunc(f, start=a, infty=b)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        return quad_vec(f2, 0, 1, **kwargs)
+    elif np.isfinite(b) and np.isinf(a):
+        f2 = SemiInfiniteFunc(f, start=b, infty=a)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        res = quad_vec(f2, 0, 1, **kwargs)
+        return (-res[0],) + res[1:]
+    elif np.isinf(a) and np.isinf(b):
+        sgn = -1 if b < a else 1
+
+        # NB. explicitly split integral at t=0, which separates
+        # the positive and negative sides
+        f2 = DoubleInfiniteFunc(f)
+        if points is not None:
+            kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
+        else:
+            kwargs['points'] = (0,)
+
+        if a != b:
+            res = quad_vec(f2, -1, 1, **kwargs)
+        else:
+            res = quad_vec(f2, 1, 1, **kwargs)
+
+        return (res[0]*sgn,) + res[1:]
+    elif not (np.isfinite(a) and np.isfinite(b)):
+        raise ValueError(f"invalid integration bounds a={a}, b={b}")
+
+    norm_funcs = {
+        None: _max_norm,
+        'max': _max_norm,
+        '2': np.linalg.norm
+    }
+    if callable(norm):
+        norm_func = norm
+    else:
+        norm_func = norm_funcs[norm]
+
+    parallel_count = 128
+    min_intervals = 2
+
+    try:
+        _quadrature = {None: _quadrature_gk21,
+                       'gk21': _quadrature_gk21,
+                       'gk15': _quadrature_gk15,
+                       'trapz': _quadrature_trapezoid,  # alias for backcompat
+                       'trapezoid': _quadrature_trapezoid}[quadrature]
+    except KeyError as e:
+        raise ValueError(f"unknown quadrature {quadrature!r}") from e
+
+    if quadrature == "trapz":
+        msg = ("`quadrature='trapz'` is deprecated in favour of "
+               "`quadrature='trapezoid' and will raise an error from SciPy 1.16.0 "
+               "onwards.")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
+    # Initial interval set
+    if points is None:
+        initial_intervals = [(a, b)]
+    else:
+        prev = a
+        initial_intervals = []
+        for p in sorted(points):
+            p = float(p)
+            if not (a < p < b) or p == prev:
+                continue
+            initial_intervals.append((prev, p))
+            prev = p
+        initial_intervals.append((prev, b))
+
+    global_integral = None
+    global_error = None
+    rounding_error = None
+    interval_cache = None
+    intervals = []
+    neval = 0
+
+    for x1, x2 in initial_intervals:
+        ig, err, rnd = _quadrature(x1, x2, f, norm_func)
+        neval += _quadrature.num_eval
+
+        if global_integral is None:
+            if isinstance(ig, (float, complex)):
+                # Specialize for scalars
+                if norm_func in (_max_norm, np.linalg.norm):
+                    norm_func = abs
+
+            global_integral = ig
+            global_error = float(err)
+            rounding_error = float(rnd)
+
+            cache_count = cache_size // _get_sizeof(ig)
+            interval_cache = LRUDict(cache_count)
+        else:
+            global_integral += ig
+            global_error += err
+            rounding_error += rnd
+
+        interval_cache[(x1, x2)] = copy.copy(ig)
+        intervals.append((-err, x1, x2))
+
+    heapq.heapify(intervals)
+
+    CONVERGED = 0
+    NOT_CONVERGED = 1
+    ROUNDING_ERROR = 2
+    NOT_A_NUMBER = 3
+
+    status_msg = {
+        CONVERGED: "Target precision reached.",
+        NOT_CONVERGED: "Target precision not reached.",
+        ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
+        NOT_A_NUMBER: "Non-finite values encountered."
+    }
+
+    # Process intervals
+    with MapWrapper(workers) as mapwrapper:
+        ier = NOT_CONVERGED
+
+        while intervals and len(intervals) < limit:
+            # Select intervals with largest errors for subdivision
+            tol = max(epsabs, epsrel*norm_func(global_integral))
+
+            to_process = []
+            err_sum = 0
+
+            for j in range(parallel_count):
+                if not intervals:
+                    break
+
+                if j > 0 and err_sum > global_error - tol/8:
+                    # avoid unnecessary parallel splitting
+                    break
+
+                interval = heapq.heappop(intervals)
+
+                neg_old_err, a, b = interval
+                old_int = interval_cache.pop((a, b), None)
+                to_process.append(
+                    ((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
+                )
+                err_sum += -neg_old_err
+
+            # Subdivide intervals
+            for parts in mapwrapper(_subdivide_interval, to_process):
+                dint, derr, dround_err, subint, dneval = parts
+                neval += dneval
+                global_integral += dint
+                global_error += derr
+                rounding_error += dround_err
+                for x in subint:
+                    x1, x2, ig, err = x
+                    interval_cache[(x1, x2)] = ig
+                    heapq.heappush(intervals, (-err, x1, x2))
+
+            # Termination check
+            if len(intervals) >= min_intervals:
+                tol = max(epsabs, epsrel*norm_func(global_integral))
+                if global_error < tol/8:
+                    ier = CONVERGED
+                    break
+                if global_error < rounding_error:
+                    ier = ROUNDING_ERROR
+                    break
+
+            if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
+                ier = NOT_A_NUMBER
+                break
+
+    res = global_integral
+    err = global_error + rounding_error
+
+    if full_output:
+        res_arr = np.asarray(res)
+        dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
+        integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
+                                      for z in intervals], dtype=res_arr.dtype)
+        errors = np.array([-z[0] for z in intervals])
+        intervals = np.array([[z[1], z[2]] for z in intervals])
+
+        info = _Bunch(neval=neval,
+                      success=(ier == CONVERGED),
+                      status=ier,
+                      message=status_msg[ier],
+                      intervals=intervals,
+                      integrals=integrals,
+                      errors=errors)
+        return (res, err, info)
+    else:
+        return (res, err)
+
+
+def _subdivide_interval(args):
+    interval, f, norm_func, _quadrature = args
+    old_err, a, b, old_int = interval
+
+    c = 0.5 * (a + b)
+
+    # Left-hand side
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        f = functools.lru_cache(_quadrature.cache_size)(f)
+
+    s1, err1, round1 = _quadrature(a, c, f, norm_func)
+    dneval = _quadrature.num_eval
+    s2, err2, round2 = _quadrature(c, b, f, norm_func)
+    dneval += _quadrature.num_eval
+    if old_int is None:
+        old_int, _, _ = _quadrature(a, b, f, norm_func)
+        dneval += _quadrature.num_eval
+
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        dneval = f.cache_info().misses
+
+    dint = s1 + s2 - old_int
+    derr = err1 + err2 - old_err
+    dround_err = round1 + round2
+
+    subintervals = ((a, c, s1, err1), (c, b, s2, err2))
+    return dint, derr, dround_err, subintervals, dneval
+
+
+def _quadrature_trapezoid(x1, x2, f, norm_func):
+    """
+    Composite trapezoid quadrature
+    """
+    x3 = 0.5*(x1 + x2)
+    f1 = f(x1)
+    f2 = f(x2)
+    f3 = f(x3)
+
+    s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
+
+    round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
+                                       + 2*float(norm_func(f3))
+                                       + float(norm_func(f2))) * 2e-16
+
+    s1 = 0.5 * (x2 - x1) * (f1 + f2)
+    err = 1/3 * float(norm_func(s1 - s2))
+    return s2, err, round_err
+
+
+_quadrature_trapezoid.cache_size = 3 * 3
+_quadrature_trapezoid.num_eval = 3
+
+
+def _quadrature_gk(a, b, f, norm_func, x, w, v):
+    """
+    Generic Gauss-Kronrod quadrature
+    """
+
+    fv = [0.0]*len(x)
+
+    c = 0.5 * (a + b)
+    h = 0.5 * (b - a)
+
+    # Gauss-Kronrod
+    s_k = 0.0
+    s_k_abs = 0.0
+    for i in range(len(x)):
+        ff = f(c + h*x[i])
+        fv[i] = ff
+
+        vv = v[i]
+
+        # \int f(x)
+        s_k += vv * ff
+        # \int |f(x)|
+        s_k_abs += vv * abs(ff)
+
+    # Gauss
+    s_g = 0.0
+    for i in range(len(w)):
+        s_g += w[i] * fv[2*i + 1]
+
+    # Quadrature of abs-deviation from average
+    s_k_dabs = 0.0
+    y0 = s_k / 2.0
+    for i in range(len(x)):
+        # \int |f(x) - y0|
+        s_k_dabs += v[i] * abs(fv[i] - y0)
+
+    # Use similar error estimation as quadpack
+    err = float(norm_func((s_k - s_g) * h))
+    dabs = float(norm_func(s_k_dabs * h))
+    if dabs != 0 and err != 0:
+        err = dabs * min(1.0, (200 * err / dabs)**1.5)
+
+    eps = sys.float_info.epsilon
+    round_err = float(norm_func(50 * eps * h * s_k_abs))
+
+    if round_err > sys.float_info.min:
+        err = max(err, round_err)
+
+    return h * s_k, err, round_err
+
+
+def _quadrature_gk21(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 21 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.995657163025808080735527280689003,
+         0.973906528517171720077964012084452,
+         0.930157491355708226001207180059508,
+         0.865063366688984510732096688423493,
+         0.780817726586416897063717578345042,
+         0.679409568299024406234327365114874,
+         0.562757134668604683339000099272694,
+         0.433395394129247190799265943165784,
+         0.294392862701460198131126603103866,
+         0.148874338981631210884826001129720,
+         0,
+         -0.148874338981631210884826001129720,
+         -0.294392862701460198131126603103866,
+         -0.433395394129247190799265943165784,
+         -0.562757134668604683339000099272694,
+         -0.679409568299024406234327365114874,
+         -0.780817726586416897063717578345042,
+         -0.865063366688984510732096688423493,
+         -0.930157491355708226001207180059508,
+         -0.973906528517171720077964012084452,
+         -0.995657163025808080735527280689003)
+
+    # 10-point weights
+    w = (0.066671344308688137593568809893332,
+         0.149451349150580593145776339657697,
+         0.219086362515982043995534934228163,
+         0.269266719309996355091226921569469,
+         0.295524224714752870173892994651338,
+         0.295524224714752870173892994651338,
+         0.269266719309996355091226921569469,
+         0.219086362515982043995534934228163,
+         0.149451349150580593145776339657697,
+         0.066671344308688137593568809893332)
+
+    # 21-point weights
+    v = (0.011694638867371874278064396062192,
+         0.032558162307964727478818972459390,
+         0.054755896574351996031381300244580,
+         0.075039674810919952767043140916190,
+         0.093125454583697605535065465083366,
+         0.109387158802297641899210590325805,
+         0.123491976262065851077958109831074,
+         0.134709217311473325928054001771707,
+         0.142775938577060080797094273138717,
+         0.147739104901338491374841515972068,
+         0.149445554002916905664936468389821,
+         0.147739104901338491374841515972068,
+         0.142775938577060080797094273138717,
+         0.134709217311473325928054001771707,
+         0.123491976262065851077958109831074,
+         0.109387158802297641899210590325805,
+         0.093125454583697605535065465083366,
+         0.075039674810919952767043140916190,
+         0.054755896574351996031381300244580,
+         0.032558162307964727478818972459390,
+         0.011694638867371874278064396062192)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk21.num_eval = 21
+
+
+def _quadrature_gk15(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 15 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.991455371120812639206854697526329,
+         0.949107912342758524526189684047851,
+         0.864864423359769072789712788640926,
+         0.741531185599394439863864773280788,
+         0.586087235467691130294144838258730,
+         0.405845151377397166906606412076961,
+         0.207784955007898467600689403773245,
+         0.000000000000000000000000000000000,
+         -0.207784955007898467600689403773245,
+         -0.405845151377397166906606412076961,
+         -0.586087235467691130294144838258730,
+         -0.741531185599394439863864773280788,
+         -0.864864423359769072789712788640926,
+         -0.949107912342758524526189684047851,
+         -0.991455371120812639206854697526329)
+
+    # 7-point weights
+    w = (0.129484966168869693270611432679082,
+         0.279705391489276667901467771423780,
+         0.381830050505118944950369775488975,
+         0.417959183673469387755102040816327,
+         0.381830050505118944950369775488975,
+         0.279705391489276667901467771423780,
+         0.129484966168869693270611432679082)
+
+    # 15-point weights
+    v = (0.022935322010529224963732008058970,
+         0.063092092629978553290700663189204,
+         0.104790010322250183839876322541518,
+         0.140653259715525918745189590510238,
+         0.169004726639267902826583426598550,
+         0.190350578064785409913256402421014,
+         0.204432940075298892414161999234649,
+         0.209482141084727828012999174891714,
+         0.204432940075298892414161999234649,
+         0.190350578064785409913256402421014,
+         0.169004726639267902826583426598550,
+         0.140653259715525918745189590510238,
+         0.104790010322250183839876322541518,
+         0.063092092629978553290700663189204,
+         0.022935322010529224963732008058970)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk15.num_eval = 15
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_quadpack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_quadpack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..ec68b0b80a60c69e04afe21847d127e2e6de55c8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_quadpack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_quadpack_py.py b/python_embeded/Lib/site-packages/scipy/integrate/_quadpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..667fc051859cefd98473879bb895f8320faf1e8d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_quadpack_py.py
@@ -0,0 +1,1279 @@
+# Author: Travis Oliphant 2001
+# Author: Nathan Woods 2013 (nquad &c)
+import sys
+import warnings
+from functools import partial
+
+from . import _quadpack
+import numpy as np
+
+__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
+
+
+class IntegrationWarning(UserWarning):
+    """
+    Warning on issues during integration.
+    """
+    pass
+
+
+def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
+         limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
+         limlst=50, complex_func=False):
+    """
+    Compute a definite integral.
+
+    Integrate func from `a` to `b` (possibly infinite interval) using a
+    technique from the Fortran library QUADPACK.
+
+    Parameters
+    ----------
+    func : {function, scipy.LowLevelCallable}
+        A Python function or method to integrate. If `func` takes many
+        arguments, it is integrated along the axis corresponding to the
+        first argument.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(double x)
+            double func(double x, void *user_data)
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
+        In the call forms with ``xx``,  ``n`` is the length of the ``xx``
+        array which contains ``xx[0] == x`` and the rest of the items are
+        numbers contained in the ``args`` argument of quad.
+
+        In addition, certain ctypes call signatures are supported for
+        backward compatibility, but those should not be used in new code.
+    a : float
+        Lower limit of integration (use -numpy.inf for -infinity).
+    b : float
+        Upper limit of integration (use numpy.inf for +infinity).
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    full_output : int, optional
+        Non-zero to return a dictionary of integration information.
+        If non-zero, warning messages are also suppressed and the
+        message is appended to the output tuple.
+    complex_func : bool, optional
+        Indicate if the function's (`func`) return type is real
+        (``complex_func=False``: default) or complex (``complex_func=True``).
+        In both cases, the function's argument is real.
+        If full_output is also non-zero, the `infodict`, `message`, and
+        `explain` for the real and complex components are returned in
+        a dictionary with keys "real output" and "imag output".
+
+    Returns
+    -------
+    y : float
+        The integral of func from `a` to `b`.
+    abserr : float
+        An estimate of the absolute error in the result.
+    infodict : dict
+        A dictionary containing additional information.
+    message
+        A convergence message.
+    explain
+        Appended only with 'cos' or 'sin' weighting and infinite
+        integration limits, it contains an explanation of the codes in
+        infodict['ierlst']
+
+    Other Parameters
+    ----------------
+    epsabs : float or int, optional
+        Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
+        an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
+        where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
+        numerical approximation. See `epsrel` below.
+    epsrel : float or int, optional
+        Relative error tolerance. Default is 1.49e-8.
+        If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
+        and ``50 * (machine epsilon)``. See `epsabs` above.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    points : (sequence of floats,ints), optional
+        A sequence of break points in the bounded integration interval
+        where local difficulties of the integrand may occur (e.g.,
+        singularities, discontinuities). The sequence does not have
+        to be sorted. Note that this option cannot be used in conjunction
+        with ``weight``.
+    weight : float or int, optional
+        String indicating weighting function. Full explanation for this
+        and the remaining arguments can be found below.
+    wvar : optional
+        Variables for use with weighting functions.
+    wopts : optional
+        Optional input for reusing Chebyshev moments.
+    maxp1 : float or int, optional
+        An upper bound on the number of Chebyshev moments.
+    limlst : int, optional
+        Upper bound on the number of cycles (>=3) for use with a sinusoidal
+        weighting and an infinite end-point.
+
+    See Also
+    --------
+    dblquad : double integral
+    tplquad : triple integral
+    nquad : n-dimensional integrals (uses `quad` recursively)
+    fixed_quad : fixed-order Gaussian quadrature
+    simpson : integrator for sampled data
+    romb : integrator for sampled data
+    scipy.special : for coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Extra information for quad() inputs and outputs**
+
+    If full_output is non-zero, then the third output argument
+    (infodict) is a dictionary with entries as tabulated below. For
+    infinite limits, the range is transformed to (0,1) and the
+    optional outputs are given with respect to this transformed range.
+    Let M be the input argument limit and let K be infodict['last'].
+    The entries are:
+
+    'neval'
+        The number of function evaluations.
+    'last'
+        The number, K, of subintervals produced in the subdivision process.
+    'alist'
+        A rank-1 array of length M, the first K elements of which are the
+        left end points of the subintervals in the partition of the
+        integration range.
+    'blist'
+        A rank-1 array of length M, the first K elements of which are the
+        right end points of the subintervals.
+    'rlist'
+        A rank-1 array of length M, the first K elements of which are the
+        integral approximations on the subintervals.
+    'elist'
+        A rank-1 array of length M, the first K elements of which are the
+        moduli of the absolute error estimates on the subintervals.
+    'iord'
+        A rank-1 integer array of length M, the first L elements of
+        which are pointers to the error estimates over the subintervals
+        with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
+        sequence ``infodict['iord']`` and let E be the sequence
+        ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
+        decreasing sequence.
+
+    If the input argument points is provided (i.e., it is not None),
+    the following additional outputs are placed in the output
+    dictionary. Assume the points sequence is of length P.
+
+    'pts'
+        A rank-1 array of length P+2 containing the integration limits
+        and the break points of the intervals in ascending order.
+        This is an array giving the subintervals over which integration
+        will occur.
+    'level'
+        A rank-1 integer array of length M (=limit), containing the
+        subdivision levels of the subintervals, i.e., if (aa,bb) is a
+        subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
+        are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
+        if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
+    'ndin'
+        A rank-1 integer array of length P+2. After the first integration
+        over the intervals (pts[1], pts[2]), the error estimates over some
+        of the intervals may have been increased artificially in order to
+        put their subdivision forward. This array has ones in slots
+        corresponding to the subintervals for which this happens.
+
+    **Weighting the integrand**
+
+    The input variables, *weight* and *wvar*, are used to weight the
+    integrand by a select list of functions. Different integration
+    methods are used to compute the integral with these weighting
+    functions, and these do not support specifying break points. The
+    possible values of weight and the corresponding weighting functions are.
+
+    ==========  ===================================   =====================
+    ``weight``  Weight function used                  ``wvar``
+    ==========  ===================================   =====================
+    'cos'       cos(w*x)                              wvar = w
+    'sin'       sin(w*x)                              wvar = w
+    'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
+    'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
+    'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
+    'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
+    'cauchy'    1/(x-c)                               wvar = c
+    ==========  ===================================   =====================
+
+    wvar holds the parameter w, (alpha, beta), or c depending on the weight
+    selected. In these expressions, a and b are the integration limits.
+
+    For the 'cos' and 'sin' weighting, additional inputs and outputs are
+    available.
+
+    For finite integration limits, the integration is performed using a
+    Clenshaw-Curtis method which uses Chebyshev moments. For repeated
+    calculations, these moments are saved in the output dictionary:
+
+    'momcom'
+        The maximum level of Chebyshev moments that have been computed,
+        i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
+        computed for intervals of length ``|b-a| * 2**(-l)``,
+        ``l=0,1,...,M_c``.
+    'nnlog'
+        A rank-1 integer array of length M(=limit), containing the
+        subdivision levels of the subintervals, i.e., an element of this
+        array is equal to l if the corresponding subinterval is
+        ``|b-a|* 2**(-l)``.
+    'chebmo'
+        A rank-2 array of shape (25, maxp1) containing the computed
+        Chebyshev moments. These can be passed on to an integration
+        over the same interval by passing this array as the second
+        element of the sequence wopts and passing infodict['momcom'] as
+        the first element.
+
+    If one of the integration limits is infinite, then a Fourier integral is
+    computed (assuming w neq 0). If full_output is 1 and a numerical error
+    is encountered, besides the error message attached to the output tuple,
+    a dictionary is also appended to the output tuple which translates the
+    error codes in the array ``info['ierlst']`` to English messages. The
+    output information dictionary contains the following entries instead of
+    'last', 'alist', 'blist', 'rlist', and 'elist':
+
+    'lst'
+        The number of subintervals needed for the integration (call it ``K_f``).
+    'rslst'
+        A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
+        contain the integral contribution over the interval
+        ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
+        and ``k=1,2,...,K_f``.
+    'erlst'
+        A rank-1 array of length ``M_f`` containing the error estimate
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.
+    'ierlst'
+        A rank-1 integer array of length ``M_f`` containing an error flag
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.  See the explanation dictionary (last entry
+        in the output tuple) for the meaning of the codes.
+
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^b_a \\sin(\\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
+        for user-provided :math:`\\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
+        :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
+        :math:`\\log(x-a)\\log(b-x)`.
+
+        The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    **Integration of Complex Function of a Real Variable**
+
+    A complex valued function, :math:`f`, of a real variable can be written as
+    :math:`f = g + ih`.  Similarly, the integral of :math:`f` can be
+    written as
+
+    .. math::
+        \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
+
+    assuming that the integrals of :math:`g` and :math:`h` exist
+    over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
+    complex-valued functions by integrating the real and imaginary components
+    separately.
+
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    .. [2] McCullough, Thomas; Phillips, Keith (1973).
+           Foundations of Analysis in the Complex Plane.
+           Holt Rinehart Winston.
+           ISBN 0-03-086370-8
+
+    Examples
+    --------
+    Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
+
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x2 = lambda x: x**2
+    >>> integrate.quad(x2, 0, 4)
+    (21.333333333333332, 2.3684757858670003e-13)
+    >>> print(4**3 / 3.)  # analytical result
+    21.3333333333
+
+    Calculate :math:`\\int^\\infty_0 e^{-x} dx`
+
+    >>> invexp = lambda x: np.exp(-x)
+    >>> integrate.quad(invexp, 0, np.inf)
+    (1.0, 5.842605999138044e-11)
+
+    Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
+
+    >>> f = lambda x, a: a*x
+    >>> y, err = integrate.quad(f, 0, 1, args=(1,))
+    >>> y
+    0.5
+    >>> y, err = integrate.quad(f, 0, 1, args=(3,))
+    >>> y
+    1.5
+
+    Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
+    y parameter as 1::
+
+        testlib.c =>
+            double func(int n, double args[n]){
+                return args[0]*args[0] + args[1]*args[1];}
+        compile to library testlib.*
+
+    ::
+
+       from scipy import integrate
+       import ctypes
+       lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
+       lib.func.restype = ctypes.c_double
+       lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
+       integrate.quad(lib.func,0,1,(1))
+       #(1.3333333333333333, 1.4802973661668752e-14)
+       print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
+       # 1.3333333333333333
+
+    Be aware that pulse shapes and other sharp features as compared to the
+    size of the integration interval may not be integrated correctly using
+    this method. A simplified example of this limitation is integrating a
+    y-axis reflected step function with many zero values within the integrals
+    bounds.
+
+    >>> y = lambda x: 1 if x<=0 else 0
+    >>> integrate.quad(y, -1, 1)
+    (1.0, 1.1102230246251565e-14)
+    >>> integrate.quad(y, -1, 100)
+    (1.0000000002199108, 1.0189464580163188e-08)
+    >>> integrate.quad(y, -1, 10000)
+    (0.0, 0.0)
+
+    """
+    if not isinstance(args, tuple):
+        args = (args,)
+
+    # check the limits of integration: \int_a^b, expect a < b
+    flip, a, b = b < a, min(a, b), max(a, b)
+
+    if complex_func:
+        def imfunc(x, *args):
+            return func(x, *args).imag
+
+        def refunc(x, *args):
+            return func(x, *args).real
+
+        re_retval = quad(refunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        im_retval = quad(imfunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        integral = re_retval[0] + 1j*im_retval[0]
+        error_estimate = re_retval[1] + 1j*im_retval[1]
+        retval = integral, error_estimate
+        if full_output:
+            msgexp = {}
+            msgexp["real"] = re_retval[2:]
+            msgexp["imag"] = im_retval[2:]
+            retval = retval + (msgexp,)
+
+        return retval
+
+    if weight is None:
+        retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
+                       points)
+    else:
+        if points is not None:
+            msg = ("Break points cannot be specified when using weighted integrand.\n"
+                   "Continuing, ignoring specified points.")
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+        retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
+                              limlst, limit, maxp1, weight, wvar, wopts)
+
+    if flip:
+        retval = (-retval[0],) + retval[1:]
+
+    ier = retval[-1]
+    if ier == 0:
+        return retval[:-1]
+
+    msgs = {80: "A Python error occurred possibly while calling the function.",
+             1: f"The maximum number of subdivisions ({limit}) has been achieved.\n  "
+                f"If increasing the limit yields no improvement it is advised to "
+                f"analyze \n  the integrand in order to determine the difficulties.  "
+                f"If the position of a \n  local difficulty can be determined "
+                f"(singularity, discontinuity) one will \n  probably gain from "
+                f"splitting up the interval and calling the integrator \n  on the "
+                f"subranges.  Perhaps a special-purpose integrator should be used.",
+             2: "The occurrence of roundoff error is detected, which prevents \n  "
+                "the requested tolerance from being achieved.  "
+                "The error may be \n  underestimated.",
+             3: "Extremely bad integrand behavior occurs at some points of the\n  "
+                "integration interval.",
+             4: "The algorithm does not converge.  Roundoff error is detected\n  "
+                "in the extrapolation table.  It is assumed that the requested "
+                "tolerance\n  cannot be achieved, and that the returned result "
+                "(if full_output = 1) is \n  the best which can be obtained.",
+             5: "The integral is probably divergent, or slowly convergent.",
+             6: "The input is invalid.",
+             7: "Abnormal termination of the routine.  The estimates for result\n  "
+                "and error are less reliable.  It is assumed that the requested "
+                "accuracy\n  has not been achieved.",
+            'unknown': "Unknown error."}
+
+    if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
+        msgs[1] = (
+            "The maximum number of cycles allowed has been achieved., e.e.\n  of "
+            "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n  "
+            "*pi/abs(omega), for k = 1, 2, ..., lst.  "
+            "One can allow more cycles by increasing the value of limlst.  "
+            "Look at info['ierlst'] with full_output=1."
+        )
+        msgs[4] = (
+            "The extrapolation table constructed for convergence acceleration\n  of "
+            "the series formed by the integral contributions over the cycles, \n  does "
+            "not converge to within the requested accuracy.  "
+            "Look at \n  info['ierlst'] with full_output=1."
+        )
+        msgs[7] = (
+            "Bad integrand behavior occurs within one or more of the cycles.\n  "
+            "Location and type of the difficulty involved can be determined from \n  "
+            "the vector info['ierlist'] obtained with full_output=1."
+        )
+        explain = {1: "The maximum number of subdivisions (= limit) has been \n  "
+                      "achieved on this cycle.",
+                   2: "The occurrence of roundoff error is detected and prevents\n  "
+                      "the tolerance imposed on this cycle from being achieved.",
+                   3: "Extremely bad integrand behavior occurs at some points of\n  "
+                      "this cycle.",
+                   4: "The integral over this cycle does not converge (to within the "
+                      "required accuracy) due to roundoff in the extrapolation "
+                      "procedure invoked on this cycle.  It is assumed that the result "
+                      "on this interval is the best which can be obtained.",
+                   5: "The integral over this cycle is probably divergent or "
+                      "slowly convergent."}
+
+    try:
+        msg = msgs[ier]
+    except KeyError:
+        msg = msgs['unknown']
+
+    if ier in [1,2,3,4,5,7]:
+        if full_output:
+            if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
+                return retval[:-1] + (msg, explain)
+            else:
+                return retval[:-1] + (msg,)
+        else:
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+            return retval[:-1]
+
+    elif ier == 6:  # Forensic decision tree when QUADPACK throws ier=6
+        if epsabs <= 0:  # Small error tolerance - applies to all methods
+            if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
+                msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
+                       " 5e-29 and 50*(machine epsilon).")
+            elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
+                msg = ("Sine or cosine weighted integrals with infinite domain"
+                       " must have 'epsabs'>0.")
+
+        elif weight is None:
+            if points is None:  # QAGSE/QAGIE
+                msg = ("Invalid 'limit' argument. There must be"
+                       " at least one subinterval")
+            else:  # QAGPE
+                if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
+                    msg = ("All break points in 'points' must lie within the"
+                           " integration limits.")
+                elif len(points) >= limit:
+                    msg = (f"Number of break points ({len(points):d}) "
+                           f"must be less than subinterval limit ({limit:d})")
+
+        else:
+            if maxp1 < 1:
+                msg = "Chebyshev moment limit maxp1 must be >=1."
+
+            elif weight in ('cos', 'sin') and abs(a+b) == np.inf:  # QAWFE
+                msg = "Cycle limit limlst must be >=3."
+
+            elif weight.startswith('alg'):  # QAWSE
+                if min(wvar) < -1:
+                    msg = "wvar parameters (alpha, beta) must both be >= -1."
+                if b < a:
+                    msg = "Integration limits a, b must satistfy a>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda y, x: x*y**2
+    >>> integrate.dblquad(f, 0, 2, 0, 1)
+        (0.6666666666666667, 7.401486830834377e-15)
+
+    Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
+    \\,dy \\,dx`.
+
+    >>> f = lambda y, x: 1
+    >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
+        (0.41421356237309503, 1.1083280054755938e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
+    for :math:`a=1, 3`.
+
+    >>> f = lambda y, x, a: a*x*y
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
+        (0.33333333333333337, 5.551115123125783e-15)
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
+        (0.9999999999999999, 1.6653345369377348e-14)
+
+    Compute the two-dimensional Gaussian Integral, which is the integral of the
+    Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
+
+    >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
+    >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
+        (3.141592653589777, 2.5173086737433208e-08)
+
+    """
+
+    def temp_ranges(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    return nquad(func, [temp_ranges, [a, b]], args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
+            epsrel=1.49e-8):
+    """
+    Compute a triple (definite) integral.
+
+    Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
+    ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
+
+    Parameters
+    ----------
+    func : function
+        A Python function or method of at least three variables in the
+        order (z, y, x).
+    a, b : float
+        The limits of integration in x: `a` < `b`
+    gfun : function or float
+        The lower boundary curve in y which is a function taking a single
+        floating point argument (x) and returning a floating point result
+        or a float indicating a constant boundary curve.
+    hfun : function or float
+        The upper boundary curve in y (same requirements as `gfun`).
+    qfun : function or float
+        The lower boundary surface in z.  It must be a function that takes
+        two floats in the order (x, y) and returns a float or a float
+        indicating a constant boundary surface.
+    rfun : function or float
+        The upper boundary surface in z. (Same requirements as `qfun`.)
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    epsabs : float, optional
+        Absolute tolerance passed directly to the innermost 1-D quadrature
+        integration. Default is 1.49e-8.
+    epsrel : float, optional
+        Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
+
+    Returns
+    -------
+    y : float
+        The resultant integral.
+    abserr : float
+        An estimate of the error.
+
+    See Also
+    --------
+    quad : Adaptive quadrature using QUADPACK
+    fixed_quad : Fixed-order Gaussian quadrature
+    dblquad : Double integrals
+    nquad : N-dimensional integrals
+    romb : Integrators for sampled data
+    simpson : Integrators for sampled data
+    scipy.special : For coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. For each level of integration, ``qagse``
+    is used for finite limits or ``qagie`` is used, if either limit (or both!)
+    are infinite. The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Compute the triple integral of ``x * y * z``, over ``x`` ranging
+    from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
+    That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
+    \\,dz \\,dy \\,dx`.
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
+    (1.8749999999999998, 3.3246447942574074e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
+    \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
+    Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
+    takes arguments in the order (z, y, x).
+
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
+    (0.05416666666666668, 2.1774196738157757e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
+    a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
+
+    >>> f = lambda z, y, x, a: a*x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
+        (0.125, 5.527033708952211e-15)
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
+        (0.375, 1.6581101126856635e-14)
+
+    Compute the three-dimensional Gaussian Integral, which is the integral of
+    the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
+    \\,dy\\,dx`.
+
+    >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
+    >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
+        (5.568327996830833, 4.4619078828029765e-08)
+
+    """
+    # f(z, y, x)
+    # qfun/rfun(x, y)
+    # gfun/hfun(x)
+    # nquad will hand (y, x, t0, ...) to ranges0
+    # nquad will hand (x, t0, ...) to ranges1
+    # Only qfun / rfun is different API...
+
+    def ranges0(*args):
+        return [qfun(args[1], args[0]) if callable(qfun) else qfun,
+                rfun(args[1], args[0]) if callable(rfun) else rfun]
+
+    def ranges1(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    ranges = [ranges0, ranges1, [a, b]]
+    return nquad(func, ranges, args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def nquad(func, ranges, args=None, opts=None, full_output=False):
+    r"""
+    Integration over multiple variables.
+
+    Wraps `quad` to enable integration over multiple variables.
+    Various options allow improved integration of discontinuous functions, as
+    well as the use of weighted integration, and generally finer control of the
+    integration process.
+
+    Parameters
+    ----------
+    func : {callable, scipy.LowLevelCallable}
+        The function to be integrated. Has arguments of ``x0, ... xn``,
+        ``t0, ... tm``, where integration is carried out over ``x0, ... xn``,
+        which must be floats.  Where ``t0, ... tm`` are extra arguments
+        passed in args.
+        Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
+        Integration is carried out in order.  That is, integration over ``x0``
+        is the innermost integral, and ``xn`` is the outermost.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        where ``n`` is the number of variables and args.  The ``xx`` array
+        contains the coordinates and extra arguments. ``user_data`` is the data
+        contained in the `scipy.LowLevelCallable`.
+    ranges : iterable object
+        Each element of ranges may be either a sequence  of 2 numbers, or else
+        a callable that returns such a sequence. ``ranges[0]`` corresponds to
+        integration over x0, and so on. If an element of ranges is a callable,
+        then it will be called with all of the integration arguments available,
+        as well as any parametric arguments. e.g., if
+        ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
+        either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
+    args : iterable object, optional
+        Additional arguments ``t0, ... tn``, required by ``func``, ``ranges``,
+        and ``opts``.
+    opts : iterable object or dict, optional
+        Options to be passed to `quad`. May be empty, a dict, or
+        a sequence of dicts or functions that return a dict. If empty, the
+        default options from scipy.integrate.quad are used. If a dict, the same
+        options are used for all levels of integraion. If a sequence, then each
+        element of the sequence corresponds to a particular integration. e.g.,
+        ``opts[0]`` corresponds to integration over ``x0``, and so on. If a
+        callable, the signature must be the same as for ``ranges``. The
+        available options together with their default values are:
+
+          - epsabs = 1.49e-08
+          - epsrel = 1.49e-08
+          - limit  = 50
+          - points = None
+          - weight = None
+          - wvar   = None
+          - wopts  = None
+
+        For more information on these options, see `quad`.
+
+    full_output : bool, optional
+        Partial implementation of ``full_output`` from scipy.integrate.quad.
+        The number of integrand function evaluations ``neval`` can be obtained
+        by setting ``full_output=True`` when calling nquad.
+
+    Returns
+    -------
+    result : float
+        The result of the integration.
+    abserr : float
+        The maximum of the estimates of the absolute error in the various
+        integration results.
+    out_dict : dict, optional
+        A dict containing additional information on the integration.
+
+    See Also
+    --------
+    quad : 1-D numerical integration
+    dblquad, tplquad : double and triple integrals
+    fixed_quad : fixed-order Gaussian quadrature
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `nquad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\int^b_a \cos(\omega x)f(x)dx` or
+        :math:`\int^b_a \sin(\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
+        :math:`\int^\infty_a \sin(\omega x)f(x)dx`
+        for user-provided :math:`\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
+        :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
+        :math:`\log(x-a)\log(b-x)`.
+
+        The user specifies :math:`\alpha`, :math:`\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Calculate
+
+    .. math::
+
+        \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
+        f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, x_3) = \begin{cases}
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
+        \end{cases} .
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
+    ...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
+    >>> def opts0(*args, **kwargs):
+    ...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
+    >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
+    ...                 opts=[opts0,{},{},{}], full_output=True)
+    (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
+
+    Calculate
+
+    .. math::
+
+        \int^{t_0+t_1+1}_{t_0+t_1-1}
+        \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
+        \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
+        f(x_0,x_1, x_2,t_0,t_1)
+        \,dx_0 \,dx_1 \,dx_2,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
+          x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
+          x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
+        \end{cases}
+
+    and :math:`(t_0, t_1) = (0, 1)` .
+
+    >>> def func2(x0, x1, x2, t0, t1):
+    ...     return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
+    >>> def lim0(x1, x2, t0, t1):
+    ...     return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
+    >>> def lim1(x2, t0, t1):
+    ...     return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
+    >>> def lim2(t0, t1):
+    ...     return [t0 + t1 - 1, t0 + t1 + 1]
+    >>> def opts0(x1, x2, t0, t1):
+    ...     return {'points' : [t0 - t1*x1]}
+    >>> def opts1(x2, t0, t1):
+    ...     return {}
+    >>> def opts2(t0, t1):
+    ...     return {}
+    >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
+    ...                 opts=[opts0, opts1, opts2])
+    (36.099919226771625, 1.8546948553373528e-07)
+
+    """
+    depth = len(ranges)
+    ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
+    if args is None:
+        args = ()
+    if opts is None:
+        opts = [dict([])] * depth
+
+    if isinstance(opts, dict):
+        opts = [_OptFunc(opts)] * depth
+    else:
+        opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
+    return _NQuad(func, ranges, opts, full_output).integrate(*args)
+
+
+class _RangeFunc:
+    def __init__(self, range_):
+        self.range_ = range_
+
+    def __call__(self, *args):
+        """Return stored value.
+
+        *args needed because range_ can be float or func, and is called with
+        variable number of parameters.
+        """
+        return self.range_
+
+
+class _OptFunc:
+    def __init__(self, opt):
+        self.opt = opt
+
+    def __call__(self, *args):
+        """Return stored dict."""
+        return self.opt
+
+
+class _NQuad:
+    def __init__(self, func, ranges, opts, full_output):
+        self.abserr = 0
+        self.func = func
+        self.ranges = ranges
+        self.opts = opts
+        self.maxdepth = len(ranges)
+        self.full_output = full_output
+        if self.full_output:
+            self.out_dict = {'neval': 0}
+
+    def integrate(self, *args, **kwargs):
+        depth = kwargs.pop('depth', 0)
+        if kwargs:
+            raise ValueError('unexpected kwargs')
+
+        # Get the integration range and options for this depth.
+        ind = -(depth + 1)
+        fn_range = self.ranges[ind]
+        low, high = fn_range(*args)
+        fn_opt = self.opts[ind]
+        opt = dict(fn_opt(*args))
+
+        if 'points' in opt:
+            opt['points'] = [x for x in opt['points'] if low <= x <= high]
+        if depth + 1 == self.maxdepth:
+            f = self.func
+        else:
+            f = partial(self.integrate, depth=depth+1)
+        quad_r = quad(f, low, high, args=args, full_output=self.full_output,
+                      **opt)
+        value = quad_r[0]
+        abserr = quad_r[1]
+        if self.full_output:
+            infodict = quad_r[2]
+            # The 'neval' parameter in full_output returns the total
+            # number of times the integrand function was evaluated.
+            # Therefore, only the innermost integration loop counts.
+            if depth + 1 == self.maxdepth:
+                self.out_dict['neval'] += infodict['neval']
+        self.abserr = max(self.abserr, abserr)
+        if depth > 0:
+            return value
+        else:
+            # Final result of N-D integration with error
+            if self.full_output:
+                return value, self.abserr, self.out_dict
+            else:
+                return value, self.abserr
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_quadrature.py b/python_embeded/Lib/site-packages/scipy/integrate/_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..f13d4ca681a04bd56d6727fd647e3b1a6b26402e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_quadrature.py
@@ -0,0 +1,1336 @@
+import numpy as np
+import numpy.typing as npt
+import math
+import warnings
+from collections import namedtuple
+from collections.abc import Callable
+
+from scipy.special import roots_legendre
+from scipy.special import gammaln, logsumexp
+from scipy._lib._util import _rng_spawn
+from scipy._lib._array_api import _asarray, array_namespace, xp_broadcast_promote
+
+
+__all__ = ['fixed_quad', 'romb',
+           'trapezoid', 'simpson',
+           'cumulative_trapezoid', 'newton_cotes',
+           'qmc_quad', 'cumulative_simpson']
+
+
+def trapezoid(y, x=None, dx=1.0, axis=-1):
+    r"""
+    Integrate along the given axis using the composite trapezoidal rule.
+
+    If `x` is provided, the integration happens in sequence along its
+    elements - they are not sorted.
+
+    Integrate `y` (`x`) along each 1d slice on the given axis, compute
+    :math:`\int y(x) dx`.
+    When `x` is specified, this integrates along the parametric curve,
+    computing :math:`\int_t y(t) dt =
+    \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
+
+    Parameters
+    ----------
+    y : array_like
+        Input array to integrate.
+    x : array_like, optional
+        The sample points corresponding to the `y` values. If `x` is None,
+        the sample points are assumed to be evenly spaced `dx` apart. The
+        default is None.
+    dx : scalar, optional
+        The spacing between sample points when `x` is None. The default is 1.
+    axis : int, optional
+        The axis along which to integrate. The default is the last axis.
+
+    Returns
+    -------
+    trapezoid : float or ndarray
+        Definite integral of `y` = n-dimensional array as approximated along
+        a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
+        then the result is a float. If `n` is greater than 1, then the result
+        is an `n`-1 dimensional array.
+
+    See Also
+    --------
+    cumulative_trapezoid, simpson, romb
+
+    Notes
+    -----
+    Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
+    will be taken from `y` array, by default x-axis distances between
+    points will be 1.0, alternatively they can be provided with `x` array
+    or with `dx` scalar.  Return value will be equal to combined area under
+    the red lines.
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
+
+    .. [2] Illustration image:
+           https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
+
+    Examples
+    --------
+    Use the trapezoidal rule on evenly spaced points:
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> integrate.trapezoid([1, 2, 3])
+    4.0
+
+    The spacing between sample points can be selected by either the
+    ``x`` or ``dx`` arguments:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
+    8.0
+    >>> integrate.trapezoid([1, 2, 3], dx=2)
+    8.0
+
+    Using a decreasing ``x`` corresponds to integrating in reverse:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
+    -8.0
+
+    More generally ``x`` is used to integrate along a parametric curve. We can
+    estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
+
+    >>> x = np.linspace(0, 1, num=50)
+    >>> y = x**2
+    >>> integrate.trapezoid(y, x)
+    0.33340274885464394
+
+    Or estimate the area of a circle, noting we repeat the sample which closes
+    the curve:
+
+    >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
+    >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
+    3.141571941375841
+
+    ``trapezoid`` can be applied along a specified axis to do multiple
+    computations in one call:
+
+    >>> a = np.arange(6).reshape(2, 3)
+    >>> a
+    array([[0, 1, 2],
+           [3, 4, 5]])
+    >>> integrate.trapezoid(a, axis=0)
+    array([1.5, 2.5, 3.5])
+    >>> integrate.trapezoid(a, axis=1)
+    array([2.,  8.])
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, xp=xp, subok=True)
+    # Cannot just use the broadcasted arrays that are returned
+    # because trapezoid does not follow normal broadcasting rules
+    # cf. https://github.com/scipy/scipy/pull/21524#issuecomment-2354105942
+    result_dtype = xp_broadcast_promote(y, force_floating=True, xp=xp)[0].dtype
+    nd = y.ndim
+    slice1 = [slice(None)]*nd
+    slice2 = [slice(None)]*nd
+    slice1[axis] = slice(1, None)
+    slice2[axis] = slice(None, -1)
+    if x is None:
+        d = dx
+    else:
+        x = _asarray(x, xp=xp, subok=True)
+        if x.ndim == 1:
+            d = x[1:] - x[:-1]
+            # make d broadcastable to y
+            slice3 = [None] * nd
+            slice3[axis] = slice(None)
+            d = d[tuple(slice3)]
+        else:
+            # if x is n-D it should be broadcastable to y
+            x = xp.broadcast_to(x, y.shape)
+            d = x[tuple(slice1)] - x[tuple(slice2)]
+    try:
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    except ValueError:
+        # Operations didn't work, cast to ndarray
+        d = xp.asarray(d)
+        y = xp.asarray(y)
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    return ret
+
+
+def _cached_roots_legendre(n):
+    """
+    Cache roots_legendre results to speed up calls of the fixed_quad
+    function.
+    """
+    if n in _cached_roots_legendre.cache:
+        return _cached_roots_legendre.cache[n]
+
+    _cached_roots_legendre.cache[n] = roots_legendre(n)
+    return _cached_roots_legendre.cache[n]
+
+
+_cached_roots_legendre.cache = dict()
+
+
+def fixed_quad(func, a, b, args=(), n=5):
+    """
+    Compute a definite integral using fixed-order Gaussian quadrature.
+
+    Integrate `func` from `a` to `b` using Gaussian quadrature of
+    order `n`.
+
+    Parameters
+    ----------
+    func : callable
+        A Python function or method to integrate (must accept vector inputs).
+        If integrating a vector-valued function, the returned array must have
+        shape ``(..., len(x))``.
+    a : float
+        Lower limit of integration.
+    b : float
+        Upper limit of integration.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+    n : int, optional
+        Order of quadrature integration. Default is 5.
+
+    Returns
+    -------
+    val : float
+        Gaussian quadrature approximation to the integral
+    none : None
+        Statically returned value of None
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> f = lambda x: x**8
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
+    (0.1110884353741496, None)
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
+    (0.11111111111111102, None)
+    >>> print(1/9.0)  # analytical result
+    0.1111111111111111
+
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
+    (0.9999999771971152, None)
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
+    (1.000000000039565, None)
+    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
+    1.0
+
+    """
+    x, w = _cached_roots_legendre(n)
+    x = np.real(x)
+    if np.isinf(a) or np.isinf(b):
+        raise ValueError("Gaussian quadrature is only available for "
+                         "finite limits.")
+    y = (b-a)*(x+1)/2.0 + a
+    return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None
+
+
+def tupleset(t, i, value):
+    l = list(t)
+    l[i] = value
+    return tuple(l)
+
+
+def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None):
+    """
+    Cumulatively integrate y(x) using the composite trapezoidal rule.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate.
+    x : array_like, optional
+        The coordinate to integrate along. If None (default), use spacing `dx`
+        between consecutive elements in `y`.
+    dx : float, optional
+        Spacing between elements of `y`. Only used if `x` is None.
+    axis : int, optional
+        Specifies the axis to cumulate. Default is -1 (last axis).
+    initial : scalar, optional
+        If given, insert this value at the beginning of the returned result.
+        0 or None are the only values accepted. Default is None, which means
+        `res` has one element less than `y` along the axis of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum, numpy.cumprod
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x
+    >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
+    >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
+    >>> plt.show()
+
+    """
+    y = np.asarray(y)
+    if y.shape[axis] == 0:
+        raise ValueError("At least one point is required along `axis`.")
+    if x is None:
+        d = dx
+    else:
+        x = np.asarray(x)
+        if x.ndim == 1:
+            d = np.diff(x)
+            # reshape to correct shape
+            shape = [1] * y.ndim
+            shape[axis] = -1
+            d = d.reshape(shape)
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        else:
+            d = np.diff(x, axis=axis)
+
+        if d.shape[axis] != y.shape[axis] - 1:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    nd = len(y.shape)
+    slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))
+    slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))
+    res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
+
+    if initial is not None:
+        if initial != 0:
+            raise ValueError("`initial` must be `None` or `0`.")
+        if not np.isscalar(initial):
+            raise ValueError("`initial` parameter should be a scalar.")
+
+        shape = list(res.shape)
+        shape[axis] = 1
+        res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],
+                             axis=axis)
+
+    return res
+
+
+def _basic_simpson(y, start, stop, x, dx, axis):
+    nd = len(y.shape)
+    if start is None:
+        start = 0
+    step = 2
+    slice_all = (slice(None),)*nd
+    slice0 = tupleset(slice_all, axis, slice(start, stop, step))
+    slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+    slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))
+
+    if x is None:  # Even-spaced Simpson's rule.
+        result = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
+        result *= dx / 3.0
+    else:
+        # Account for possibly different spacings.
+        #    Simpson's rule changes a bit.
+        h = np.diff(x, axis=axis)
+        sl0 = tupleset(slice_all, axis, slice(start, stop, step))
+        sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+        h0 = h[sl0].astype(float, copy=False)
+        h1 = h[sl1].astype(float, copy=False)
+        hsum = h0 + h1
+        hprod = h0 * h1
+        h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0)
+        tmp = hsum/6.0 * (y[slice0] *
+                          (2.0 - np.true_divide(1.0, h0divh1,
+                                                out=np.zeros_like(h0divh1),
+                                                where=h0divh1 != 0)) +
+                          y[slice1] * (hsum *
+                                       np.true_divide(hsum, hprod,
+                                                      out=np.zeros_like(hsum),
+                                                      where=hprod != 0)) +
+                          y[slice2] * (2.0 - h0divh1))
+        result = np.sum(tmp, axis=axis)
+    return result
+
+
+def simpson(y, x=None, *, dx=1.0, axis=-1):
+    """
+    Integrate y(x) using samples along the given axis and the composite
+    Simpson's rule. If x is None, spacing of dx is assumed.
+
+    Parameters
+    ----------
+    y : array_like
+        Array to be integrated.
+    x : array_like, optional
+        If given, the points at which `y` is sampled.
+    dx : float, optional
+        Spacing of integration points along axis of `x`. Only used when
+        `x` is None. Default is 1.
+    axis : int, optional
+        Axis along which to integrate. Default is the last axis.
+
+    Returns
+    -------
+    float
+        The estimated integral computed with the composite Simpson's rule.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+
+    Notes
+    -----
+    For an odd number of samples that are equally spaced the result is
+    exact if the function is a polynomial of order 3 or less. If
+    the samples are not equally spaced, then the result is exact only
+    if the function is a polynomial of order 2 or less.
+
+    References
+    ----------
+    .. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+           MS Excel and Irregularly-spaced Data. Journal of Mathematical
+           Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(0, 10)
+    >>> y = np.arange(0, 10)
+
+    >>> integrate.simpson(y, x=x)
+    40.5
+
+    >>> y = np.power(x, 3)
+    >>> integrate.simpson(y, x=x)
+    1640.5
+    >>> integrate.quad(lambda x: x**3, 0, 9)[0]
+    1640.25
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    N = y.shape[axis]
+    last_dx = dx
+    returnshape = 0
+    if x is not None:
+        x = np.asarray(x)
+        if len(x.shape) == 1:
+            shapex = [1] * nd
+            shapex[axis] = x.shape[0]
+            saveshape = x.shape
+            returnshape = 1
+            x = x.reshape(tuple(shapex))
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        if x.shape[axis] != N:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    if N % 2 == 0:
+        val = 0.0
+        result = 0.0
+        slice_all = (slice(None),) * nd
+
+        if N == 2:
+            # need at least 3 points in integration axis to form parabolic
+            # segment. If there are two points then any of 'avg', 'first',
+            # 'last' should give the same result.
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            if x is not None:
+                last_dx = x[slice1] - x[slice2]
+            val += 0.5 * last_dx * (y[slice1] + y[slice2])
+        else:
+            # use Simpson's rule on first intervals
+            result = _basic_simpson(y, 0, N-3, x, dx, axis)
+
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            slice3 = tupleset(slice_all, axis, -3)
+
+            h = np.asarray([dx, dx], dtype=np.float64)
+            if x is not None:
+                # grab the last two spacings from the appropriate axis
+                hm2 = tupleset(slice_all, axis, slice(-2, -1, 1))
+                hm1 = tupleset(slice_all, axis, slice(-1, None, 1))
+
+                diffs = np.float64(np.diff(x, axis=axis))
+                h = [np.squeeze(diffs[hm2], axis=axis),
+                     np.squeeze(diffs[hm1], axis=axis)]
+
+            # This is the correction for the last interval according to
+            # Cartwright.
+            # However, I used the equations given at
+            # https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data
+            # A footnote on Wikipedia says:
+            # Cartwright 2017, Equation 8. The equation in Cartwright is
+            # calculating the first interval whereas the equations in the
+            # Wikipedia article are adjusting for the last integral. If the
+            # proper algebraic substitutions are made, the equation results in
+            # the values shown.
+            num = 2 * h[1] ** 2 + 3 * h[0] * h[1]
+            den = 6 * (h[1] + h[0])
+            alpha = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = h[1] ** 2 + 3.0 * h[0] * h[1]
+            den = 6 * h[0]
+            beta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = 1 * h[1] ** 3
+            den = 6 * h[0] * (h[0] + h[1])
+            eta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
+
+        result += val
+    else:
+        result = _basic_simpson(y, 0, N-2, x, dx, axis)
+    if returnshape:
+        x = x.reshape(saveshape)
+    return result
+
+
+def _cumulatively_sum_simpson_integrals(
+    y: np.ndarray, 
+    dx: np.ndarray, 
+    integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
+) -> np.ndarray:
+    """Calculate cumulative sum of Simpson integrals.
+    Takes as input the integration function to be used. 
+    The integration_func is assumed to return the cumulative sum using
+    composite Simpson's rule. Assumes the axis of summation is -1.
+    """
+    sub_integrals_h1 = integration_func(y, dx)
+    sub_integrals_h2 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1]
+    
+    shape = list(sub_integrals_h1.shape)
+    shape[-1] += 1
+    sub_integrals = np.empty(shape)
+    sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2]
+    sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2]
+    # Integral over last subinterval can only be calculated from 
+    # formula for h2
+    sub_integrals[..., -1] = sub_integrals_h2[..., -1]
+    res = np.cumsum(sub_integrals, axis=-1)
+    return res
+
+
+def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming equal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    d = dx[..., :-1]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    # Calculate integral over the subintervals (eqn (10) of Reference [2])
+    return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4)
+
+
+def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming unequal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    x21 = dx[..., :-1]
+    x32 = dx[..., 1:]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    x31 = x21 + x32
+    x21_x31 = x21/x31
+    x21_x32 = x21/x32
+    x21x21_x31x32 = x21_x31 * x21_x32
+
+    # Calculate integral over the subintervals (eqn (8) of Reference [2])
+    coeff1 = 3 - x21_x31
+    coeff2 = 3 + x21x21_x31x32 + x21_x31
+    coeff3 = -x21x21_x31x32
+
+    return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3)
+
+
+def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray:
+    arr = np.asarray(arr)
+    if np.issubdtype(arr.dtype, np.integer):
+        arr = arr.astype(float, copy=False)
+    return arr
+
+
+def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None):
+    r"""
+    Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
+    The integral of the samples at every point is calculated by assuming a 
+    quadratic relationship between each point and the two adjacent points.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate. Requires at least one point along `axis`. If two or fewer
+        points are provided along `axis`, Simpson's integration is not possible and the
+        result is calculated with `cumulative_trapezoid`.
+    x : array_like, optional
+        The coordinate to integrate along. Must have the same shape as `y` or
+        must be 1D with the same length as `y` along `axis`. `x` must also be
+        strictly increasing along `axis`.
+        If `x` is None (default), integration is performed using spacing `dx`
+        between consecutive elements in `y`.
+    dx : scalar or array_like, optional
+        Spacing between elements of `y`. Only used if `x` is None. Can either 
+        be a float, or an array with the same shape as `y`, but of length one along
+        `axis`. Default is 1.0.
+    axis : int, optional
+        Specifies the axis to integrate along. Default is -1 (last axis).
+    initial : scalar or array_like, optional
+        If given, insert this value at the beginning of the returned result,
+        and add it to the rest of the result. Default is None, which means no
+        value at ``x[0]`` is returned and `res` has one element less than `y`
+        along the axis of integration. Can either be a float, or an array with
+        the same shape as `y`, but of length one along `axis`.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum
+    cumulative_trapezoid : cumulative integration using the composite 
+        trapezoidal rule
+    simpson : integrator for sampled data using the Composite Simpson's Rule
+
+    Notes
+    -----
+
+    .. versionadded:: 1.12.0
+
+    The composite Simpson's 1/3 method can be used to approximate the definite 
+    integral of a sampled input function :math:`y(x)` [1]_. The method assumes 
+    a quadratic relationship over the interval containing any three consecutive
+    sampled points.
+
+    Consider three consecutive points: 
+    :math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.
+
+    Assuming a quadratic relationship over the three points, the integral over
+    the subinterval between :math:`x_1` and :math:`x_2` is given by formula
+    (8) of [2]_:
+    
+    .. math::
+        \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
+        \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
+        \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
+        \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
+        - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]
+
+    The integral between :math:`x_2` and :math:`x_3` is given by swapping
+    appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
+    separately for each subinterval and then cumulatively summed to obtain
+    the final result.
+    
+    For samples that are equally spaced, the result is exact if the function
+    is a polynomial of order three or less [1]_ and the number of subintervals
+    is even. Otherwise, the integral is exact for polynomials of order two or
+    less. 
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
+    .. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+            MS Excel and Irregularly-spaced Data. Journal of Mathematical
+            Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x**2
+    >>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
+    >>> ax.grid()
+    >>> plt.show()
+
+    The output of `cumulative_simpson` is similar to that of iteratively
+    calling `simpson` with successively higher upper limits of integration, but
+    not identical.
+
+    >>> def cumulative_simpson_reference(y, x):
+    ...     return np.asarray([integrate.simpson(y[:i], x=x[:i])
+    ...                        for i in range(2, len(y) + 1)])
+    >>>
+    >>> rng = np.random.default_rng(354673834679465)
+    >>> x, y = rng.random(size=(2, 10))
+    >>> x.sort()
+    >>>
+    >>> res = integrate.cumulative_simpson(y, x=x)
+    >>> ref = cumulative_simpson_reference(y, x)
+    >>> equal = np.abs(res - ref) < 1e-15
+    >>> equal  # not equal when `simpson` has even number of subintervals
+    array([False,  True, False,  True, False,  True, False,  True,  True])
+
+    This is expected: because `cumulative_simpson` has access to more
+    information than `simpson`, it can typically produce more accurate
+    estimates of the underlying integral over subintervals.
+
+    """
+    y = _ensure_float_array(y)
+
+    # validate `axis` and standardize to work along the last axis
+    original_y = y
+    original_shape = y.shape
+    try:
+        y = np.swapaxes(y, axis, -1)
+    except IndexError as e:
+        message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`."
+        raise ValueError(message) from e
+    if y.shape[-1] < 3:
+        res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None)
+        res = np.swapaxes(res, axis, -1)
+
+    elif x is not None:
+        x = _ensure_float_array(x)
+        message = ("If given, shape of `x` must be the same as `y` or 1-D with "
+                   "the same length as `y` along `axis`.")
+        if not (x.shape == original_shape
+                or (x.ndim == 1 and len(x) == original_shape[axis])):
+            raise ValueError(message)
+
+        x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1)
+        dx = np.diff(x, axis=-1)
+        if np.any(dx <= 0):
+            raise ValueError("Input x must be strictly increasing.")
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_unequal_intervals
+        )
+
+    else:
+        dx = _ensure_float_array(dx)
+        final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1)
+        alt_input_dx_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `dx` must either be a scalar or have the same "
+                   "shape as `y` but with only 1 point along `axis`.")
+        if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape):
+            raise ValueError(message)
+        dx = np.broadcast_to(dx, final_dx_shape)
+        dx = np.swapaxes(dx, axis, -1)
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_equal_intervals
+        )
+
+    if initial is not None:
+        initial = _ensure_float_array(initial)
+        alt_initial_input_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `initial` must either be a scalar or have the "
+                   "same shape as `y` but with only 1 point along `axis`.")
+        if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape):
+            raise ValueError(message)
+        initial = np.broadcast_to(initial, alt_initial_input_shape)
+        initial = np.swapaxes(initial, axis, -1)
+
+        res += initial
+        res = np.concatenate((initial, res), axis=-1)
+
+    res = np.swapaxes(res, -1, axis)
+    return res
+
+
+def romb(y, dx=1.0, axis=-1, show=False):
+    """
+    Romberg integration using samples of a function.
+
+    Parameters
+    ----------
+    y : array_like
+        A vector of ``2**k + 1`` equally-spaced samples of a function.
+    dx : float, optional
+        The sample spacing. Default is 1.
+    axis : int, optional
+        The axis along which to integrate. Default is -1 (last axis).
+    show : bool, optional
+        When `y` is a single 1-D array, then if this argument is True
+        print the table showing Richardson extrapolation from the
+        samples. Default is False.
+
+    Returns
+    -------
+    romb : ndarray
+        The integrated result for `axis`.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(10, 14.25, 0.25)
+    >>> y = np.arange(3, 12)
+
+    >>> integrate.romb(y)
+    56.0
+
+    >>> y = np.sin(np.power(x, 2.5))
+    >>> integrate.romb(y)
+    -0.742561336672229
+
+    >>> integrate.romb(y, show=True)
+    Richardson Extrapolation Table for Romberg Integration
+    ======================================================
+    -0.81576
+     4.63862  6.45674
+    -1.10581 -3.02062 -3.65245
+    -2.57379 -3.06311 -3.06595 -3.05664
+    -1.34093 -0.92997 -0.78776 -0.75160 -0.74256
+    ======================================================
+    -0.742561336672229  # may vary
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    Nsamps = y.shape[axis]
+    Ninterv = Nsamps-1
+    n = 1
+    k = 0
+    while n < Ninterv:
+        n <<= 1
+        k += 1
+    if n != Ninterv:
+        raise ValueError("Number of samples must be one plus a "
+                         "non-negative power of 2.")
+
+    R = {}
+    slice_all = (slice(None),) * nd
+    slice0 = tupleset(slice_all, axis, 0)
+    slicem1 = tupleset(slice_all, axis, -1)
+    h = Ninterv * np.asarray(dx, dtype=float)
+    R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h
+    slice_R = slice_all
+    start = stop = step = Ninterv
+    for i in range(1, k+1):
+        start >>= 1
+        slice_R = tupleset(slice_R, axis, slice(start, stop, step))
+        step >>= 1
+        R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis))
+        for j in range(1, i+1):
+            prev = R[(i, j-1)]
+            R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)
+        h /= 2.0
+
+    if show:
+        if not np.isscalar(R[(0, 0)]):
+            print("*** Printing table only supported for integrals" +
+                  " of a single data set.")
+        else:
+            try:
+                precis = show[0]
+            except (TypeError, IndexError):
+                precis = 5
+            try:
+                width = show[1]
+            except (TypeError, IndexError):
+                width = 8
+            formstr = "%%%d.%df" % (width, precis)
+
+            title = "Richardson Extrapolation Table for Romberg Integration"
+            print(title, "=" * len(title), sep="\n", end="\n")
+            for i in range(k+1):
+                for j in range(i+1):
+                    print(formstr % R[(i, j)], end=" ")
+                print()
+            print("=" * len(title))
+
+    return R[(k, k)]
+
+
+# Coefficients for Newton-Cotes quadrature
+#
+# These are the points being used
+#  to construct the local interpolating polynomial
+#  a are the weights for Newton-Cotes integration
+#  B is the error coefficient.
+#  error in these coefficients grows as N gets larger.
+#  or as samples are closer and closer together
+
+# You can use maxima to find these rational coefficients
+#  for equally spaced data using the commands
+#  a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N)
+#             / ((N-i)! * i!) * (-1)^(N-i));
+#  Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));
+#  Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));
+#  B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));
+#
+# pre-computed for equally-spaced weights
+#
+# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]
+#
+#  a = num_a*array(int_a)/den_a
+#  B = num_B*1.0 / den_B
+#
+#  integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)
+#    where k = N // 2
+#
+_builtincoeffs = {
+    1: (1,2,[1,1],-1,12),
+    2: (1,3,[1,4,1],-1,90),
+    3: (3,8,[1,3,3,1],-3,80),
+    4: (2,45,[7,32,12,32,7],-8,945),
+    5: (5,288,[19,75,50,50,75,19],-275,12096),
+    6: (1,140,[41,216,27,272,27,216,41],-9,1400),
+    7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),
+    8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],
+        -2368,467775),
+    9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,
+                 15741,2857], -4671, 394240),
+    10: (5,299376,[16067,106300,-48525,272400,-260550,427368,
+                   -260550,272400,-48525,106300,16067],
+         -673175, 163459296),
+    11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,
+                      15493566,15493566,-9595542,25226685,-3237113,
+                      13486539,2171465], -2224234463, 237758976000),
+    12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,
+                      87516288,-87797136,87516288,-51491295,35725120,
+                      -7587864,9903168,1364651], -3012, 875875),
+    13: (13, 402361344000,[8181904909, 56280729661, -31268252574,
+                           156074417954,-151659573325,206683437987,
+                           -43111992612,-43111992612,206683437987,
+                           -151659573325,156074417954,-31268252574,
+                           56280729661,8181904909], -2639651053,
+         344881152000),
+    14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,
+                         -6625093363,12630121616,-16802270373,19534438464,
+                         -16802270373,12630121616,-6625093363,3501442784,
+                         -770720657,710986864,90241897], -3740727473,
+         1275983280000)
+    }
+
+
+def newton_cotes(rn, equal=0):
+    r"""
+    Return weights and error coefficient for Newton-Cotes integration.
+
+    Suppose we have (N+1) samples of f at the positions
+    x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
+    integral between x_0 and x_N is:
+
+    :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
+    + B_N (\Delta x)^{N+2} f^{N+1} (\xi)`
+
+    where :math:`\xi \in [x_0,x_N]`
+    and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.
+
+    If the samples are equally-spaced and N is even, then the error
+    term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.
+
+    Parameters
+    ----------
+    rn : int
+        The integer order for equally-spaced data or the relative positions of
+        the samples with the first sample at 0 and the last at N, where N+1 is
+        the length of `rn`. N is the order of the Newton-Cotes integration.
+    equal : int, optional
+        Set to 1 to enforce equally spaced data.
+
+    Returns
+    -------
+    an : ndarray
+        1-D array of weights to apply to the function at the provided sample
+        positions.
+    B : float
+        Error coefficient.
+
+    Notes
+    -----
+    Normally, the Newton-Cotes rules are used on smaller integration
+    regions and a composite rule is used to return the total integral.
+
+    Examples
+    --------
+    Compute the integral of sin(x) in [0, :math:`\pi`]:
+
+    >>> from scipy.integrate import newton_cotes
+    >>> import numpy as np
+    >>> def f(x):
+    ...     return np.sin(x)
+    >>> a = 0
+    >>> b = np.pi
+    >>> exact = 2
+    >>> for N in [2, 4, 6, 8, 10]:
+    ...     x = np.linspace(a, b, N + 1)
+    ...     an, B = newton_cotes(N, 1)
+    ...     dx = (b - a) / N
+    ...     quad = dx * np.sum(an * f(x))
+    ...     error = abs(quad - exact)
+    ...     print('{:2d}  {:10.9f}  {:.5e}'.format(N, quad, error))
+    ...
+     2   2.094395102   9.43951e-02
+     4   1.998570732   1.42927e-03
+     6   2.000017814   1.78136e-05
+     8   1.999999835   1.64725e-07
+    10   2.000000001   1.14677e-09
+
+    """
+    try:
+        N = len(rn)-1
+        if equal:
+            rn = np.arange(N+1)
+        elif np.all(np.diff(rn) == 1):
+            equal = 1
+    except Exception:
+        N = rn
+        rn = np.arange(N+1)
+        equal = 1
+
+    if equal and N in _builtincoeffs:
+        na, da, vi, nb, db = _builtincoeffs[N]
+        an = na * np.array(vi, dtype=float) / da
+        return an, float(nb)/db
+
+    if (rn[0] != 0) or (rn[-1] != N):
+        raise ValueError("The sample positions must start at 0"
+                         " and end at N")
+    yi = rn / float(N)
+    ti = 2 * yi - 1
+    nvec = np.arange(N+1)
+    C = ti ** nvec[:, np.newaxis]
+    Cinv = np.linalg.inv(C)
+    # improve precision of result
+    for i in range(2):
+        Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)
+    vec = 2.0 / (nvec[::2]+1)
+    ai = Cinv[:, ::2].dot(vec) * (N / 2.)
+
+    if (N % 2 == 0) and equal:
+        BN = N/(N+3.)
+        power = N+2
+    else:
+        BN = N/(N+2.)
+        power = N+1
+
+    BN = BN - np.dot(yi**power, ai)
+    p1 = power+1
+    fac = power*math.log(N) - gammaln(p1)
+    fac = math.exp(fac)
+    return ai, BN*fac
+
+
+def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log):
+
+    # lazy import to avoid issues with partially-initialized submodule
+    if not hasattr(qmc_quad, 'qmc'):
+        from scipy import stats
+        qmc_quad.stats = stats
+    else:
+        stats = qmc_quad.stats
+
+    if not callable(func):
+        message = "`func` must be callable."
+        raise TypeError(message)
+
+    # a, b will be modified, so copy. Oh well if it's copied twice.
+    a = np.atleast_1d(a).copy()
+    b = np.atleast_1d(b).copy()
+    a, b = np.broadcast_arrays(a, b)
+    dim = a.shape[0]
+
+    try:
+        func((a + b) / 2)
+    except Exception as e:
+        message = ("`func` must evaluate the integrand at points within "
+                   "the integration range; e.g. `func( (a + b) / 2)` "
+                   "must return the integrand at the centroid of the "
+                   "integration volume.")
+        raise ValueError(message) from e
+
+    try:
+        func(np.array([a, b]).T)
+        vfunc = func
+    except Exception as e:
+        message = ("Exception encountered when attempting vectorized call to "
+                   f"`func`: {e}. For better performance, `func` should "
+                   "accept two-dimensional array `x` with shape `(len(a), "
+                   "n_points)` and return an array of the integrand value at "
+                   "each of the `n_points.")
+        warnings.warn(message, stacklevel=3)
+
+        def vfunc(x):
+            return np.apply_along_axis(func, axis=-1, arr=x)
+
+    n_points_int = np.int64(n_points)
+    if n_points != n_points_int:
+        message = "`n_points` must be an integer."
+        raise TypeError(message)
+
+    n_estimates_int = np.int64(n_estimates)
+    if n_estimates != n_estimates_int:
+        message = "`n_estimates` must be an integer."
+        raise TypeError(message)
+
+    if qrng is None:
+        qrng = stats.qmc.Halton(dim)
+    elif not isinstance(qrng, stats.qmc.QMCEngine):
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        raise TypeError(message)
+
+    if qrng.d != a.shape[0]:
+        message = ("`qrng` must be initialized with dimensionality equal to "
+                   "the number of variables in `a`, i.e., "
+                   "`qrng.random().shape[-1]` must equal `a.shape[0]`.")
+        raise ValueError(message)
+
+    rng_seed = getattr(qrng, 'rng_seed', None)
+    rng = stats._qmc.check_random_state(rng_seed)
+
+    if log not in {True, False}:
+        message = "`log` must be boolean (`True` or `False`)."
+        raise TypeError(message)
+
+    return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats)
+
+
+QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error'])
+
+
+def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None,
+             log=False):
+    """
+    Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.
+
+    Parameters
+    ----------
+    func : callable
+        The integrand. Must accept a single argument ``x``, an array which
+        specifies the point(s) at which to evaluate the scalar-valued
+        integrand, and return the value(s) of the integrand.
+        For efficiency, the function should be vectorized to accept an array of
+        shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
+        the dimensionality of the function domain) and `n_points` is the number
+        of quadrature points, and return an array of shape ``(n_points,)``,
+        the integrand at each quadrature point.
+    a, b : array-like
+        One-dimensional arrays specifying the lower and upper integration
+        limits, respectively, of each of the ``d`` variables.
+    n_estimates, n_points : int, optional
+        `n_estimates` (default: 8) statistically independent QMC samples, each
+        of `n_points` (default: 1024) points, will be generated by `qrng`.
+        The total number of points at which the integrand `func` will be
+        evaluated is ``n_points * n_estimates``. See Notes for details.
+    qrng : `~scipy.stats.qmc.QMCEngine`, optional
+        An instance of the QMCEngine from which to sample QMC points.
+        The QMCEngine must be initialized to a number of dimensions ``d``
+        corresponding with the number of variables ``x1, ..., xd`` passed to
+        `func`.
+        The provided QMCEngine is used to produce the first integral estimate.
+        If `n_estimates` is greater than one, additional QMCEngines are
+        spawned from the first (with scrambling enabled, if it is an option.)
+        If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
+        will be initialized with the number of dimensions determine from
+        the length of `a`.
+    log : boolean, default: False
+        When set to True, `func` returns the log of the integrand, and
+        the result object contains the log of the integral.
+
+    Returns
+    -------
+    result : object
+        A result object with attributes:
+
+        integral : float
+            The estimate of the integral.
+        standard_error :
+            The error estimate. See Notes for interpretation.
+
+    Notes
+    -----
+    Values of the integrand at each of the `n_points` points of a QMC sample
+    are used to produce an estimate of the integral. This estimate is drawn
+    from a population of possible estimates of the integral, the value of
+    which we obtain depends on the particular points at which the integral
+    was evaluated. We perform this process `n_estimates` times, each time
+    evaluating the integrand at different scrambled QMC points, effectively
+    drawing i.i.d. random samples from the population of integral estimates.
+    The sample mean :math:`m` of these integral estimates is an
+    unbiased estimator of the true value of the integral, and the standard
+    error of the mean :math:`s` of these estimates may be used to generate
+    confidence intervals using the t distribution with ``n_estimates - 1``
+    degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
+    while keeping the total number of function evaluation points
+    ``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
+    increasing `n_estimates` tends to decrease the error estimate.
+
+    Examples
+    --------
+    QMC quadrature is particularly useful for computing integrals in higher
+    dimensions. An example integrand is the probability density function
+    of a multivariate normal distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> dim = 8
+    >>> mean = np.zeros(dim)
+    >>> cov = np.eye(dim)
+    >>> def func(x):
+    ...     # `multivariate_normal` expects the _last_ axis to correspond with
+    ...     # the dimensionality of the space, so `x` must be transposed
+    ...     return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+    To compute the integral over the unit hypercube:
+
+    >>> from scipy.integrate import qmc_quad
+    >>> a = np.zeros(dim)
+    >>> b = np.ones(dim)
+    >>> rng = np.random.default_rng()
+    >>> qrng = stats.qmc.Halton(d=dim, seed=rng)
+    >>> n_estimates = 8
+    >>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
+    >>> res.integral, res.standard_error
+    (0.00018429555666024108, 1.0389431116001344e-07)
+
+    A two-sided, 99% confidence interval for the integral may be estimated
+    as:
+
+    >>> t = stats.t(df=n_estimates-1, loc=res.integral,
+    ...             scale=res.standard_error)
+    >>> t.interval(0.99)
+    (0.0001839319802536469, 0.00018465913306683527)
+
+    Indeed, the value reported by `scipy.stats.multivariate_normal` is
+    within this range.
+
+    >>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+    0.00018430867675187443
+
+    """
+    args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log)
+    func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
+
+    def sum_product(integrands, dA, log=False):
+        if log:
+            return logsumexp(integrands) + np.log(dA)
+        else:
+            return np.sum(integrands * dA)
+
+    def mean(estimates, log=False):
+        if log:
+            return logsumexp(estimates) - np.log(n_estimates)
+        else:
+            return np.mean(estimates)
+
+    def std(estimates, m=None, ddof=0, log=False):
+        m = m or mean(estimates, log)
+        if log:
+            estimates, m = np.broadcast_arrays(estimates, m)
+            temp = np.vstack((estimates, m + np.pi * 1j))
+            diff = logsumexp(temp, axis=0)
+            return np.real(0.5 * (logsumexp(2 * diff)
+                                  - np.log(n_estimates - ddof)))
+        else:
+            return np.std(estimates, ddof=ddof)
+
+    def sem(estimates, m=None, s=None, log=False):
+        m = m or mean(estimates, log)
+        s = s or std(estimates, m, ddof=1, log=log)
+        if log:
+            return s - 0.5*np.log(n_estimates)
+        else:
+            return s / np.sqrt(n_estimates)
+
+    # The sign of the integral depends on the order of the limits. Fix this by
+    # ensuring that lower bounds are indeed lower and setting sign of resulting
+    # integral manually
+    if np.any(a == b):
+        message = ("A lower limit was equal to an upper limit, so the value "
+                   "of the integral is zero by definition.")
+        warnings.warn(message, stacklevel=2)
+        return QMCQuadResult(-np.inf if log else 0, 0)
+
+    i_swap = b < a
+    sign = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+    a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+
+    A = np.prod(b - a)
+    dA = A / n_points
+
+    estimates = np.zeros(n_estimates)
+    rngs = _rng_spawn(qrng.rng, n_estimates)
+    for i in range(n_estimates):
+        # Generate integral estimate
+        sample = qrng.random(n_points)
+        # The rationale for transposing is that this allows users to easily
+        # unpack `x` into separate variables, if desired. This is consistent
+        # with the `xx` array passed into the `scipy.integrate.nquad` `func`.
+        x = stats.qmc.scale(sample, a, b).T  # (n_dim, n_points)
+        integrands = func(x)
+        estimates[i] = sum_product(integrands, dA, log)
+
+        # Get a new, independently-scrambled QRNG for next time
+        qrng = type(qrng)(seed=rngs[i], **qrng._init_quad)
+
+    integral = mean(estimates, log)
+    standard_error = sem(estimates, m=integral, log=log)
+    integral = integral + np.pi*1j if (log and sign < 0) else integral*sign
+    return QMCQuadResult(integral, standard_error)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_tanhsinh.py b/python_embeded/Lib/site-packages/scipy/integrate/_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..2da139a3494b7f89890d6ec4791b432f74773f95
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_tanhsinh.py
@@ -0,0 +1,1384 @@
+# mypy: disable-error-code="attr-defined"
+import math
+import numpy as np
+from scipy import special
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
+                                   xp_real, xp_take_along_axis)
+
+
+__all__ = ['nsum']
+
+
+# todo:
+#  figure out warning situation
+#  address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
+#  without `minweight`, we are also suppressing infinities within the interval.
+#    Is that OK? If so, we can probably get rid of `status=3`.
+#  Add heuristic to stop when improvement is too slow / antithrashing
+#  support singularities? interval subdivision? this feature will be added
+#    eventually, but do we adjust the interface now?
+#  When doing log-integration, should the tolerances control the error of the
+#    log-integral or the error of the integral?  The trouble is that `log`
+#    inherently looses some precision so it may not be possible to refine
+#    the integral further. Example: 7th moment of stats.f(15, 20)
+#  respect function evaluation limit?
+#  make public?
+
+
+def tanhsinh(f, a, b, *, args=(), log=False, maxlevel=None, minlevel=2,
+             atol=None, rtol=None, preserve_shape=False, callback=None):
+    """Evaluate a convergent integral numerically using tanh-sinh quadrature.
+
+    In practice, tanh-sinh quadrature achieves quadratic convergence for
+    many integrands: the number of accurate *digits* scales roughly linearly
+    with the number of function evaluations [1]_.
+
+    Either or both of the limits of integration may be infinite, and
+    singularities at the endpoints are acceptable. Divergent integrals and
+    integrands with non-finite derivatives or singularities within an interval
+    are out of scope, but the latter may be evaluated be calling `tanhsinh` on
+    each sub-interval separately.
+
+    Parameters
+    ----------
+    f : callable
+        The function to be integrated. 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: see documentation of parameter
+        `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
+        in ``argsi``.
+        If ``f`` returns a value with complex dtype when evaluated at
+        either endpoint, subsequent arguments ``x`` will have complex dtype
+        (but zero imaginary part).
+    a, b : float array_like
+        Real lower and upper limits of integration. Must be broadcastable with one
+        another and with arrays in `args`. Elements may be infinite.
+    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 `a` and `b`.
+        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``.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the integrand
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the integral and error. This is useful for integrands for which
+        numerical underflow or overflow would lead to inaccuracies.
+        When ``log=True``, the integrand (the exponential of `f`) must be real,
+        but it may be negative, in which case the log of the integrand is a
+        complex number with an imaginary part that is an odd multiple of π.
+    maxlevel : int, default: 10
+        The maximum refinement level of the algorithm.
+
+        At the zeroth level, `f` is called once, performing 16 function
+        evaluations. At each subsequent level, `f` is called once more,
+        approximately doubling the number of function evaluations that have
+        been performed. Accordingly, for many integrands, each successive level
+        will double the number of accurate digits in the result (up to the
+        limits of floating point precision).
+
+        The algorithm will terminate after completing level `maxlevel` or after
+        another termination condition is satisfied, whichever comes first.
+    minlevel : int, default: 2
+        The level at which to begin iteration (default: 2). This does not
+        change the total number of function evaluations or the abscissae at
+        which the function is evaluated; it changes only the *number of times*
+        `f` is called. If ``minlevel=k``, then the integrand is evaluated at
+        all abscissae from levels ``0`` through ``k`` in a single call.
+        Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
+        ignored, and `minlevel` is set equal to `maxlevel`.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
+        the result dtype), respectively.  Iteration will stop when
+        ``res.error < atol`` or  ``res.error < res.integral * rtol``. The error
+        estimate is as described in [1]_ Section 5 but with a lower bound of
+        ``eps * res.integral``. While not theoretically rigorous or
+        conservative, it is said to work well in practice. Must be non-negative
+        and finite if `log` is False, and must be expressed as the log of a
+        non-negative and finite number if `log` is True.
+    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 `a`, `b`, 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 `_differentiate` (but containing the
+        current iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `tanhsinh` will return a result object. `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`` when 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`` : (unused)
+            ``-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).
+
+        integral : float array
+            An estimate of the integral.
+        error : float array
+            An estimate of the error. Only available if level two or higher
+            has been completed; otherwise NaN.
+        maxlevel : int array
+            The maximum refinement level used.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    quad
+
+    Notes
+    -----
+    Implements the algorithm as described in [1]_ with minor adaptations for
+    finite-precision arithmetic, including some described by [2]_ and [3]_. The
+    tanh-sinh scheme was originally introduced in [4]_.
+
+    Due to floating-point error in the abscissae, the function may be evaluated
+    at the endpoints of the interval during iterations, but the values returned by
+    the function at the endpoints will be ignored.
+
+    References
+    ----------
+    .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
+           three high-precision quadrature schemes." Experimental Mathematics 14.3
+           (2005): 317-329.
+    .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
+           single and multiple integration using floating-point arithmetic."
+           arXiv preprint arXiv:2007.15057 (2020).
+    .. [3] van Engelen, Robert A.  "Improving the Double Exponential Quadrature
+           Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
+           https://www.genivia.com/files/qthsh.pdf
+    .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
+           numerical integration." Publications of the Research Institute for
+           Mathematical Sciences 9.3 (1974): 721-741.
+
+    Examples
+    --------
+    Evaluate the Gaussian integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import tanhsinh
+    >>> def f(x):
+    ...     return np.exp(-x**2)
+    >>> res = tanhsinh(f, -np.inf, np.inf)
+    >>> res.integral  # true value is np.sqrt(np.pi), 1.7724538509055159
+    1.7724538509055159
+    >>> res.error  # actual error is 0
+    4.0007963937534104e-16
+
+    The value of the Gaussian function (bell curve) is nearly zero for
+    arguments sufficiently far from zero, so the value of the integral
+    over a finite interval is nearly the same.
+
+    >>> tanhsinh(f, -20, 20).integral
+    1.772453850905518
+
+    However, with unfavorable integration limits, the integration scheme
+    may not be able to find the important region.
+
+    >>> tanhsinh(f, -np.inf, 1000).integral
+    4.500490856616431
+
+    In such cases, or when there are singularities within the interval,
+    break the integral into parts with endpoints at the important points.
+
+    >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
+    1.772453850905404
+
+    For integration involving very large or very small magnitudes, use
+    log-integration. (For illustrative purposes, the following example shows a
+    case in which both regular and log-integration work, but for more extreme
+    limits of integration, log-integration would avoid the underflow
+    experienced when evaluating the integral normally.)
+
+    >>> res = tanhsinh(f, 20, 30, rtol=1e-10)
+    >>> res.integral, res.error
+    (4.7819613911309014e-176, 4.670364401645202e-187)
+    >>> def log_f(x):
+    ...     return -x**2
+    >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
+    >>> np.exp(res.integral), np.exp(res.error)
+    (4.7819613911306924e-176, 4.670364401645093e-187)
+
+    The limits of integration and elements of `args` may be broadcastable
+    arrays, and integration is performed elementwise.
+
+    >>> from scipy import stats
+    >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
+    >>> a, b = dist.support()
+    >>> x = np.linspace(a, b, 100)
+    >>> res = tanhsinh(dist.pdf, a, x)
+    >>> ref = dist.cdf(x)
+    >>> np.allclose(res.integral, ref)
+    True
+
+    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, 10, 30, 100]
+    >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
+    >>> shapes
+    [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `tanhsinh` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the integrand more complicated,
+    so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([ 67, 131, 259, 515], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    integrand 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
+    integrand at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function double the total number of abscissae at
+    which the function has been evaluated. However, in later function
+    evaluations, the integrand is evaluated at fewer frequencies because
+    the corresponding integral 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" integrands, such as those written for use with
+    `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
+
+    This integrand is not compatible with `tanhsinh` 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(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
+    >>>
+    >>> a = np.zeros(4)
+    >>> res = tanhsinh(f, a, 1, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
+
+    Here, the broadcasted shape of `a` and `b` 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.
+
+    """
+    maxfun = None  # unused right now
+    (f, a, b, log, maxfun, maxlevel, minlevel,
+     atol, rtol, args, preserve_shape, callback, xp) = _tanhsinh_iv(
+        f, a, b, log, maxfun, maxlevel, minlevel, atol,
+        rtol, args, preserve_shape, callback)
+
+    # Initialization
+    # `eim._initialize` does several important jobs, including
+    # ensuring that limits, each of the `args`, and the output of `f`
+    # broadcast correctly and are of consistent types. To save a function
+    # evaluation, I pass the midpoint of the integration interval. This comes
+    # at a cost of some gymnastics to ensure that the midpoint has the right
+    # shape and dtype. Did you know that 0d and >0d arrays follow different
+    # type promotion rules?
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
+        inf_a, inf_b = xp.isinf(a), xp.isinf(b)
+        c[inf_a] = b[inf_a] - 1.  # takes care of infinite a
+        c[inf_b] = a[inf_b] + 1.  # takes care of infinite b
+        c[inf_a & inf_b] = 0.  # takes care of infinite a and b
+        temp = eim._initialize(f, (c,), args, complex_ok=True,
+                               preserve_shape=preserve_shape, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = temp
+    a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
+    b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
+
+    # Transform improper integrals
+    a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
+
+    # Define variables we'll need
+    nit, nfev = 0, 1  # one function evaluation performed above
+    zero = -xp.inf if log else 0
+    pi = xp.asarray(xp.pi, dtype=dtype)[()]
+    maxiter = maxlevel - minlevel + 1
+    eps = xp.finfo(dtype).eps
+    if rtol is None:
+        rtol = 0.75*math.log(eps) if log else eps**0.75
+
+    Sn = xp_ravel(xp.full(shape, zero, dtype=dtype))  # latest integral estimate
+    Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
+    Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0]  # all integral estimates
+    aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))  # absolute error
+    status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
+    h0 = _get_base_step(dtype, xp)
+    h0 = xp_real(h0) # base step
+
+    # For term `d4` of error estimate ([1] Section 5), we need to keep the
+    # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
+    # sum. Here, we initialize these variables.
+    xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
+    fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
+    fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
+
+    work = _RichResult(
+        Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
+        a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)),  # integration limits
+        n=minlevel, nit=nit, nfev=nfev, status=status,  # iter/eval counts
+        xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4,  # err est
+        ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)),  # transforms
+        # Store the xjc/wj pair cache in an object so they can't get compressed
+        # Using RichResult to allow dot notation, but a dictionary would suffice
+        pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None))  # pair cache
+
+    # Constant scalars don't need to be put in `work` unless they need to be
+    # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
+
+    # Correspondence between terms in the `work` object and the result
+    res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
+                      ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
+
+    def pre_func_eval(work):
+        # Determine abscissae at which to evaluate `f`
+        work.h = h0 / 2**work.n
+        xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
+                             inclusive=(work.n == minlevel), xp=xp, work=work)
+        work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
+
+        # Perform abscissae substitutions for infinite limits of integration
+        xj = xp_copy(work.xj)
+        # use xp_real here to avoid cupy/cupy#8434
+        xj[work.abinf] = xj[work.abinf] / (1 - xp_real(xj[work.abinf])**2)
+        xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
+        xj[work.ainf] *= -1
+        return xj
+
+    def post_func_eval(x, fj, work):
+        # Weight integrand as required by substitutions for infinite limits
+        if work.log:
+            fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
+                               - 2*xp.log(1 - work.xj[work.abinf]**2))
+            fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
+        else:
+            fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
+                               (1 - work.xj[work.abinf]**2)**2)
+            fj[work.binf] *= work.xj[work.binf]**-2.
+
+        # Estimate integral with Euler-Maclaurin Sum
+        fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
+        if work.Sk.shape[-1]:
+            Snm1 = work.Sk[:, -1]
+            Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
+                  else Snm1 / 2 + Sn)
+
+        work.fjwj = fjwj
+        work.Sn = Sn
+
+    def check_termination(work):
+        """Terminate due to convergence or encountering non-finite values"""
+        stop = xp.zeros(work.Sn.shape, dtype=bool)
+
+        # Terminate before first iteration if integration limits are equal
+        if work.nit == 0:
+            i = xp_ravel(work.a == work.b)  # ravel singleton dimension
+            zero = xp.asarray(-xp.inf if log else 0.)
+            zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
+            zero[xp.isnan(Sn)] = xp.nan
+            work.Sn[i] = zero[i]
+            work.aerr[i] = zero[i]
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+        else:
+            # Terminate if convergence criterion is met
+            rerr, aerr = _estimate_error(work, xp)
+            i = (rerr < rtol) | (aerr < atol)
+            work.aerr =  xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+
+        # Terminate if integral estimate becomes invalid
+        if log:
+            Sn_real = xp_real(work.Sn)
+            Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
+            i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
+        else:
+            i = ~xp.isfinite(work.Sn) & ~stop
+        work.status[i] = eim._EVALUEERR
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        work.n += 1
+        work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
+        return
+
+    def customize_result(res, shape):
+        # If the integration limits were such that b < a, we reversed them
+        # to perform the calculation, and the final result needs to be negated.
+        if log and xp.any(negative):
+            dtype = res['integral'].dtype
+            pi = xp.asarray(xp.pi, dtype=dtype)[()]
+            j = xp.asarray(1j, dtype=xp.complex64)[()]  # minimum complex type
+            res['integral'] = res['integral'] + negative*pi*j
+        else:
+            res['integral'][negative] *= -1
+
+        # For this algorithm, it seems more appropriate to report the maximum
+        # level rather than the number of iterations in which it was performed.
+        res['maxlevel'] = minlevel + res['nit'] - 1
+        res['maxlevel'][res['nit'] == 0] = -1
+        del res['nit']
+        return shape
+
+    # Suppress all warnings initially, since there are many places in the code
+    # for which this is expected behavior.
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
+                        post_func_eval, check_termination, post_termination_check,
+                        customize_result, res_work_pairs, xp, preserve_shape)
+    return res
+
+
+def _get_base_step(dtype, xp):
+    # Compute the base step length for the provided dtype. Theoretically, the
+    # Euler-Maclaurin sum is infinite, but it gets cut off when either the
+    # weights underflow or the abscissae cannot be distinguished from the
+    # limits of integration. The latter happens to occur first for float32 and
+    # float64, and it occurs when `xjc` (the abscissa complement)
+    # in `_compute_pair` underflows. We can solve for the argument `tmax` at
+    # which it will underflow using [2] Eq. 13.
+    fmin = 4*xp.finfo(dtype).smallest_normal  # stay a little away from the limit
+    tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
+
+    # Based on this, we can choose a base step size `h` for level 0.
+    # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
+    # the level and `m` is an integer we get to choose. I choose
+    # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
+    # power of 2 makes floating point arithmetic more predictable. It also
+    # results in a base step size close to `1`, which is what [1] uses (and I
+    # used here until I found [2] and these ideas settled).
+    h0 = tmax / _N_BASE_STEPS
+    return xp.asarray(h0, dtype=dtype)[()]
+
+
+_N_BASE_STEPS = 8
+
+
+def _compute_pair(k, h0, xp):
+    # Compute the abscissa-weight pairs for each level k. See [1] page 9.
+
+    # For now, we compute and store in 64-bit precision. If higher-precision
+    # data types become better supported, it would be good to compute these
+    # using the highest precision available. Or, once there is an Array API-
+    # compatible arbitrary precision array, we can compute at the required
+    # precision.
+
+    # "....each level k of abscissa-weight pairs uses h = 2 **-k"
+    # We adapt to floating point arithmetic using ideas of [2].
+    h = h0 / 2**k
+    max = _N_BASE_STEPS * 2**k
+
+    # For iterations after the first, "....the integrand function needs to be
+    # evaluated only at the odd-indexed abscissas at each level."
+    j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
+    jh = j * h
+
+    # "In this case... the weights wj = u1/cosh(u2)^2, where..."
+    pi_2 = xp.pi / 2
+    u1 = pi_2*xp.cosh(jh)
+    u2 = pi_2*xp.sinh(jh)
+    # Denominators get big here. Overflow then underflow doesn't need warning.
+    # with np.errstate(under='ignore', over='ignore'):
+    wj = u1 / xp.cosh(u2)**2
+    # "We actually store 1-xj = 1/(...)."
+    xjc = 1 / (xp.exp(u2) * xp.cosh(u2))  # complement of xj = xp.tanh(u2)
+
+    # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
+    # code, the function will be evaluated there twice; each gets half weight.
+    wj[0] = wj[0] / 2 if k == 0 else wj[0]
+
+    return xjc, wj  # store at full precision
+
+
+def _pair_cache(k, h0, xp, work):
+    # Cache the abscissa-weight pairs up to a specified level.
+    # Abscissae and weights of consecutive levels are concatenated.
+    # `index` records the indices that correspond with each level:
+    # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
+    if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
+        work.pair_cache.xjc = xp.empty(0)
+        work.pair_cache.wj = xp.empty(0)
+        work.pair_cache.indices = [0]
+
+    xjcs = [work.pair_cache.xjc]
+    wjs = [work.pair_cache.wj]
+
+    for i in range(len(work.pair_cache.indices)-1, k + 1):
+        xjc, wj = _compute_pair(i, h0, xp)
+        xjcs.append(xjc)
+        wjs.append(wj)
+        work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
+
+    work.pair_cache.xjc = xp.concat(xjcs)
+    work.pair_cache.wj = xp.concat(wjs)
+    work.pair_cache.h0 = h0
+
+
+def _get_pairs(k, h0, inclusive, dtype, xp, work):
+    # Retrieve the specified abscissa-weight pairs from the cache
+    # If `inclusive`, return all up to and including the specified level
+    if (len(work.pair_cache.indices) <= k+2
+        or not isinstance (h0, type(work.pair_cache.h0))
+        or h0 != work.pair_cache.h0):
+            _pair_cache(k, h0, xp, work)
+
+    xjc = work.pair_cache.xjc
+    wj = work.pair_cache.wj
+    indices = work.pair_cache.indices
+
+    start = 0 if inclusive else indices[k]
+    end = indices[k+1]
+
+    return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
+
+
+def _transform_to_limits(xjc, wj, a, b, xp):
+    # Transform integral according to user-specified limits. This is just
+    # math that follows from the fact that the standard limits are (-1, 1).
+    # Note: If we had stored xj instead of xjc, we would have
+    # xj = alpha * xj + beta, where beta = (a + b)/2
+    alpha = (b - a) / 2
+    xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
+    wj = wj*alpha  # arguments get broadcasted, so we can't use *=
+    wj = xp.concat((wj, wj), axis=-1)
+
+    # Points at the boundaries can be generated due to finite precision
+    # arithmetic, but these function values aren't supposed to be included in
+    # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
+    # these points; however, we can't easily filter out points since this
+    # function is vectorized. Instead, zero the weights.
+    # Note: values may have complex dtype, but have zero imaginary part
+    xj_real, a_real, b_real = xp_real(xj), xp_real(a), xp_real(b)
+    invalid = (xj_real <= a_real) | (xj_real >= b_real)
+    wj[invalid] = 0
+    return xj, wj
+
+
+def _euler_maclaurin_sum(fj, work, xp):
+    # Perform the Euler-Maclaurin Sum, [1] Section 4
+
+    # The error estimate needs to know the magnitude of the last term
+    # omitted from the Euler-Maclaurin sum. This is a bit involved because
+    # it may have been computed at a previous level. I sure hope it's worth
+    # all the trouble.
+    xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
+    xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
+
+    # It is much more convenient to work with the transposes of our work
+    # variables here.
+    xj, fj, wj = work.xj.T, fj.T, work.wj.T
+    n_x, n_active = xj.shape  # number of abscissae, number of active elements
+
+    # We'll work with the left and right sides separately
+    xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active)))  # this gets modified
+    fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
+    wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
+
+    invalid_r = ~xp.isfinite(fr) | (wr == 0)
+    invalid_l = ~xp.isfinite(fl) | (wl == 0)
+
+    # integer index of the maximum abscissa at this level
+    xr[invalid_r] = -xp.inf
+    ir = xp.argmax(xp_real(xr), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    ### Not Array API Compatible... yet ###
+    xr_max = xp_take_along_axis(xr, ir, axis=0)[0]
+    fr_max = xp_take_along_axis(fr, ir, axis=0)[0]
+    wr_max = xp_take_along_axis(wr, ir, axis=0)[0]
+    # boolean indices at which maximum abscissa at this level exceeds
+    # the incumbent maximum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp_real(xr_max) > xp_real(xr0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xr0[j] = xr_max[j]
+    fr0[j] = fr_max[j]
+    wr0[j] = wr_max[j]
+
+    # integer index of the minimum abscissa at this level
+    xl[invalid_l] = xp.inf
+    il = xp.argmin(xp_real(xl), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    xl_min = xp_take_along_axis(xl, il, axis=0)[0]
+    fl_min = xp_take_along_axis(fl, il, axis=0)[0]
+    wl_min = xp_take_along_axis(wl, il, axis=0)[0]
+    # boolean indices at which minimum abscissa at this level is less than
+    # the incumbent minimum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp_real(xl_min) < xp_real(xl0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xl0[j] = xl_min[j]
+    fl0[j] = fl_min[j]
+    wl0[j] = wl_min[j]
+    fj = fj.T
+
+    # Compute the error estimate `d4` - the magnitude of the leftmost or
+    # rightmost term, whichever is greater.
+    flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0  # leftmost term
+    frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0  # rightmost term
+    magnitude = xp_real if work.log else xp.abs
+    work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
+
+    # There are two approaches to dealing with function values that are
+    # numerically infinite due to approaching a singularity - zero them, or
+    # replace them with the function value at the nearest non-infinite point.
+    # [3] pg. 22 suggests the latter, so let's do that given that we have the
+    # information.
+    fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
+    fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
+    fr[invalid_r] = fr0b[invalid_r]
+    fl[invalid_l] = fl0b[invalid_l]
+
+    # When wj is zero, log emits a warning
+    # with np.errstate(divide='ignore'):
+    fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
+
+    # update integral estimate
+    Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
+          else xp.sum(fjwj, axis=-1) * work.h)
+
+    work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
+    work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
+
+    return fjwj, Sn
+
+
+def _estimate_error(work, xp):
+    # Estimate the error according to [1] Section 5
+
+    if work.n == 0 or work.nit == 0:
+        # The paper says to use "one" as the error before it can be calculated.
+        # NaN seems to be more appropriate.
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    indices = work.pair_cache.indices
+
+    n_active = work.Sn.shape[0]  # number of active elements
+    axis_kwargs = dict(axis=-1, keepdims=True)
+
+    # With a jump start (starting at level higher than 0), we haven't
+    # explicitly calculated the integral estimate at lower levels. But we have
+    # all the function value-weight products, so we can compute the
+    # lower-level estimates.
+    if work.Sk.shape[-1] == 0:
+        h = 2 * work.h  # step size at this level
+        n_x = indices[work.n]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
+        fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
+
+    if work.n == 1:
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    # The paper says not to calculate the error for n<=2, but it's not clear
+    # about whether it starts at level 0 or level 1. We start at level 0, so
+    # why not compute the error beginning in level 2?
+    if work.Sk.shape[-1] < 2:
+        h = 4 * work.h  # step size at this level
+        n_x = indices[work.n-1]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
+        fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
+
+    Snm2 = work.Sk[..., -2]
+    Snm1 = work.Sk[..., -1]
+
+    e1 = xp.asarray(work.eps)[()]
+
+    if work.log:
+        log_e1 = xp.log(e1)
+        # Currently, only real integrals are supported in log-scale. All
+        # complex values have imaginary part in increments of pi*j, which just
+        # carries sign information of the original integral, so use of
+        # `xp.real` here is equivalent to absolute value in real scale.
+        d1 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
+        d2 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
+        d3 = log_e1 + xp.max(xp_real(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = log_e1 + xp.real(work.Sn)
+        temp = xp.where(d1 > -xp.inf, d1 ** 2 / d2, -xp.inf)
+        ds = xp.stack([temp, 2 * d1, d3, d4, d5])
+        aerr = xp.max(ds, axis=0)
+        rerr = aerr - xp.real(work.Sn)
+    else:
+        # Note: explicit computation of log10 of each of these is unnecessary.
+        d1 = xp.abs(work.Sn - Snm1)
+        d2 = xp.abs(work.Sn - Snm2)
+        d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = e1 * xp.abs(work.Sn)
+        temp = xp.where(d1 > 0, d1**(xp.log(d1)/xp.log(d2)), 0)
+        ds = xp.stack([temp, d1**2, d3, d4, d5])
+        aerr = xp.max(ds, axis=0)
+        rerr = aerr/xp.abs(work.Sn)
+
+    return rerr, aerr
+
+
+def _transform_integrals(a, b, xp):
+    # Transform integrals to a form with finite a <= b
+    # For b == a (even infinite), we ensure that the limits remain equal
+    # For b < a, we reverse the limits and will multiply the final result by -1
+    # For infinite limit on the right, we use the substitution x = 1/t - 1 + a
+    # For infinite limit on the left, we substitute x = -x and treat as above
+    # For infinite limits, we substitute x = t / (1-t**2)
+    ab_same = (a == b)
+    a[ab_same], b[ab_same] = 1, 1
+
+    # `a, b` may have complex dtype but have zero imaginary part
+    negative = xp_real(b) < xp_real(a)
+    a[negative], b[negative] = b[negative], a[negative]
+
+    abinf = xp.isinf(a) & xp.isinf(b)
+    a[abinf], b[abinf] = -1, 1
+
+    ainf = xp.isinf(a)
+    a[ainf], b[ainf] = -b[ainf], -a[ainf]
+
+    binf = xp.isinf(b)
+    a0 = xp_copy(a)
+    a[binf], b[binf] = 0, 1
+
+    return a, b, a0, negative, abinf, ainf, binf
+
+
+def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
+                 atol, rtol, args, preserve_shape, callback):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a` and `b` must be real numbers.'
+    a, b = xp.asarray(a), xp.asarray(b)
+    a, b = xp.broadcast_arrays(a, b)
+    if (xp.isdtype(a.dtype, 'complex floating')
+            or xp.isdtype(b.dtype, 'complex floating')):
+        raise ValueError(message)
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+    log = bool(log)
+
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol` and `rtol` may not be positive infinity.'
+        if np.any(np.isposinf(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol` and `rtol` must be non-negative and finite.'
+        if np.any(params < 0) or np.any(np.isinf(params)):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    BIGINT = float(2**62)
+    if maxfun is None and maxlevel is None:
+        maxlevel = 10
+
+    maxfun = BIGINT if maxfun is None else maxfun
+    maxlevel = BIGINT if maxlevel is None else maxlevel
+
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
+    params = np.asarray([maxfun, maxlevel, minlevel])
+    if not (np.issubdtype(params.dtype, np.number)
+            and np.all(np.isreal(params))
+            and np.all(params.astype(np.int64) == params)):
+        raise ValueError(message)
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
+    if np.any(params < 0):
+        raise ValueError(message)
+    maxfun, maxlevel, minlevel = params.astype(np.int64)
+    minlevel = min(minlevel, maxlevel)
+
+    if not np.iterable(args):
+        args = (args,)
+    args = (xp.asarray(arg) for arg in args)
+
+    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, a, b, log, maxfun, maxlevel, minlevel,
+            atol, rtol, args, preserve_shape, callback, xp)
+
+
+def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a`, `b`, and `step` must be real numbers.'
+    a, b, step = xp.broadcast_arrays(xp.asarray(a), xp.asarray(b), xp.asarray(step))
+    dtype = xp.result_type(a.dtype, b.dtype, step.dtype)
+    if not xp.isdtype(dtype, 'numeric') or xp.isdtype(dtype, 'complex floating'):
+        raise ValueError(message)
+
+    valid_b = b >= a  # NaNs will be False
+    valid_step = xp.isfinite(step) & (step > 0)
+    valid_abstep = valid_b & valid_step
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+
+    tolerances = {} if tolerances is None else tolerances
+
+    atol = tolerances.get('atol', None)
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol = tolerances.get('rtol', None)
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol`, `rtol` may not be positive infinity or NaN.'
+        if np.any(np.isposinf(params) | np.isnan(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol`, and `rtol` must be non-negative and finite.'
+        if np.any((params < 0) | (~np.isfinite(params))):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    maxterms_int = int(maxterms)
+    if maxterms_int != maxterms or maxterms < 0:
+        message = "`maxterms` must be a non-negative integer."
+        raise ValueError(message)
+
+    if not np.iterable(args):
+        args = (args,)
+
+    return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol, xp
+
+
+def nsum(f, a, b, *, step=1, args=(), log=False, maxterms=int(2**20), tolerances=None):
+    r"""Evaluate a convergent finite or infinite series.
+
+    For finite `a` and `b`, this evaluates::
+
+        f(a + np.arange(n)*step).sum()
+
+    where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
+    unimodal. The number of terms in the sum may be very large or infinite,
+    in which case a partial sum is evaluated directly and the remainder is
+    approximated using integration.
+
+    Parameters
+    ----------
+    f : callable
+        The function that evaluates terms to be summed. The signature must be::
+
+            f(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``.
+
+        `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``, and it must return NaN where
+        the argument is NaN.
+
+        `f` must represent a smooth, positive, unimodal function of `x` defined at
+        *all reals* between `a` and `b`.
+    a, b : float array_like
+        Real lower and upper limits of summed terms. Must be broadcastable.
+        Each element of `a` must be less than the corresponding element in `b`.
+    step : float array_like
+        Finite, positive, real step between summed terms. Must be broadcastable
+        with `a` and `b`. Note that the number of terms included in the sum will
+        be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
+        that ``f(b)`` is included if intended.
+    args : tuple of array_like, optional
+        Additional positional arguments to be passed to `f`. Must be arrays
+        broadcastable with `a`, `b`, and `step`. If the callable to be summed
+        requires arguments that are not broadcastable with `a`, `b`, and `step`,
+        wrap that callable with `f` such that `f` accepts only `x` and
+        broadcastable ``*args``. See Examples.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the terms
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the sum and error. This is useful for summands for which
+        numerical underflow or overflow would lead to inaccuracies.
+    maxterms : int, default: 2**20
+        The maximum number of terms to evaluate for direct summation.
+        Additional function evaluations may be performed for input
+        validation and integral evaluation.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.5``, where ``eps`` is the precision of
+        the result dtype), respectively. Must be non-negative
+        and finite if `log` is False, and must be expressed as the log of a
+        non-negative and finite number if `log` is True.
+
+    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
+            ``True`` when 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`` : Element(s) of `a`, `b`, or `step` are invalid
+            - ``-2`` : Numerical integration reached its iteration limit;
+              the sum may be divergent.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : The magnitude of the last term of the partial sum exceeds
+              the tolerances, so the error estimate exceeds the tolerances.
+              Consider increasing `maxterms` or loosening `tolerances`.
+              Alternatively, the callable may not be unimodal, or the limits of
+              summation may be too far from the function maximum. Consider
+              increasing `maxterms` or breaking the sum into pieces.
+
+        sum : float array
+            An estimate of the sum.
+        error : float array
+            An estimate of the absolute error, assuming all terms are non-negative,
+            the function is computed exactly, and direct summation is accurate to
+            the precision of the result dtype.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    mpmath.nsum
+
+    Notes
+    -----
+    The method implemented for infinite summation is related to the integral
+    test for convergence of an infinite series: assuming `step` size 1 for
+    simplicity of exposition, the sum of a monotone decreasing function is bounded by
+
+    .. math::
+
+        \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
+
+    Let :math:`a` represent  `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
+    represent `atol`, and :math:`\epsilon_r` represent `rtol`.
+    The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
+    as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
+    that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
+    let :math:`c = a + n`. Then the infinite sum is approximated as
+
+    .. math::
+
+        \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
+
+    and the reported error is :math:`f(c)/2` plus the error estimate of
+    numerical integration. Note that the integral approximations may require
+    evaluation of the function at points besides those that appear in the sum,
+    so `f` must be a continuous and monotonically decreasing function defined
+    for all reals within the integration interval. However, due to the nature
+    of the integral approximation, the shape of the function between points
+    that appear in the sum has little effect. If there is not a natural
+    extension of the function to all reals, consider using linear interpolation,
+    which is easy to evaluate and preserves monotonicity.
+
+    The approach described above is generalized for non-unit
+    `step` and finite `b` that is too large for direct evaluation of the sum,
+    i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
+    functions by directly summing terms surrounding the maximum.
+    This strategy may fail:
+
+    - If the left limit is finite and the maximum is far from it.
+    - If the right limit is finite and the maximum is far from it.
+    - If both limits are finite and the maximum is far from the origin.
+
+    In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
+
+    Although the callable `f` must be non-negative and unimodal,
+    `nsum` can be used to evaluate more general forms of series. For instance, to
+    evaluate an alternating series, pass a callable that returns the difference
+    between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
+
+    References
+    ----------
+    .. [1] Wikipedia. "Integral test for convergence."
+           https://en.wikipedia.org/wiki/Integral_test_for_convergence
+
+    Examples
+    --------
+    Compute the infinite sum of the reciprocals of squared integers.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import nsum
+    >>> res = nsum(lambda k: 1/k**2, 1, np.inf)
+    >>> ref = np.pi**2/6  # true value
+    >>> res.error  # estimated error
+    np.float64(7.448762306416137e-09)
+    >>> (res.sum - ref)/ref  # true error
+    np.float64(-1.839871898894426e-13)
+    >>> res.nfev  # number of points at which callable was evaluated
+    np.int32(8561)
+
+    Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
+    where ``p`` is an array.
+
+    >>> from scipy import special
+    >>> p = np.arange(3, 10)
+    >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
+    >>> ref = special.zeta(p, 1)
+    >>> np.allclose(res.sum, ref)
+    True
+
+    Evaluate the alternating harmonic series.
+
+    >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
+    >>> res.sum, res.sum - np.log(2)  # result, difference vs analytical sum
+    (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
+
+    """ # noqa: E501
+    # Potential future work:
+    # - improve error estimate of `_direct` sum
+    # - add other methods for convergence acceleration (Richardson, epsilon)
+    # - support negative monotone increasing functions?
+    # - b < a / negative step?
+    # - complex-valued function?
+    # - check for violations of monotonicity?
+
+    # Function-specific input validation / standardization
+    tmp = _nsum_iv(f, a, b, step, args, log, maxterms, tolerances)
+    f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
+
+    # Additional elementwise algorithm input validation / standardization
+    tmp = eim._initialize(f, (a,), args, complex_ok=False, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = tmp
+
+    # Finish preparing `a`, `b`, and `step` arrays
+    a = xs[0]
+    b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
+    step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
+    valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
+    nterms = xp.floor((b - a) / step)
+    finite_terms = xp.isfinite(nterms)
+    b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
+
+    # Define constants
+    eps = xp.finfo(dtype).eps
+    zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
+    if rtol is None:
+        rtol = 0.5*math.log(eps) if log else eps**0.5
+    constants = (dtype, log, eps, zero, rtol, atol, maxterms)
+
+    # Prepare result arrays
+    S = xp.empty_like(a)
+    E = xp.empty_like(a)
+    status = xp.zeros(len(a), dtype=xp.int32)
+    nfev = xp.ones(len(a), dtype=xp.int32)  # one function evaluation above
+
+    # Branch for direct sum evaluation / integral approximation / invalid input
+    i0 = ~valid_abstep                     # invalid
+    i1 = (nterms + 1 <= maxterms) & ~i0    # direct sum evaluation
+    i2 = xp.isfinite(a) & ~i1 & ~i0        # infinite sum to the right
+    i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0  # infinite sum to the left
+    i4 = ~i3 & ~i2 & ~i1 & ~i0             # infinite sum on both sides
+
+    if xp.any(i0):
+        S[i0], E[i0] = xp.nan, xp.nan
+        status[i0] = -1
+
+    if xp.any(i1):
+        args_direct = [arg[i1] for arg in args]
+        tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
+        S[i1], E[i1] = tmp[:-1]
+        nfev[i1] += tmp[-1]
+        status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
+
+    if xp.any(i2):
+        args_indirect = [arg[i2] for arg in args]
+        tmp = _integral_bound(f, a[i2], b[i2], step[i2],
+                              args_indirect, constants, xp)
+        S[i2], E[i2], status[i2] = tmp[:-1]
+        nfev[i2] += tmp[-1]
+
+    if xp.any(i3):
+        args_indirect = [arg[i3] for arg in args]
+        def _f(x, *args): return f(-x, *args)
+        tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
+                              args_indirect, constants, xp)
+        S[i3], E[i3], status[i3] = tmp[:-1]
+        nfev[i3] += tmp[-1]
+
+    if xp.any(i4):
+        args_indirect = [arg[i4] for arg in args]
+
+        # There are two obvious high-level strategies:
+        # - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
+        # - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
+        # I thought the latter would have about half the overhead, so I went that way.
+        # Then there are two ways of ensuring that f(0) doesn't get counted twice.
+        # - Evaluate the sum from 1 to inf and add f(0)
+        # - Evaluate the sum from 0 to inf and subtract f(0)
+        # - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
+        # The last option has more overhead, but is simpler to implement correctly
+        # (especially getting the status message right)
+        if log:
+            def _f(x, *args):
+                log_factor = xp.where(x==0, math.log(0.5), 0)
+                out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
+                return special.logsumexp(out, axis=0) + log_factor
+
+        else:
+            def _f(x, *args):
+                factor = xp.where(x==0, 0.5, 1)
+                return (f(x, *args) + f(-x, *args)) * factor
+
+        zero = xp.zeros_like(a[i4])
+        tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
+        S[i4], E[i4], status[i4] = tmp[:-1]
+        nfev[i4] += 2*tmp[-1]
+
+    # Return results
+    S, E = S.reshape(shape)[()], E.reshape(shape)[()]
+    status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
+    return _RichResult(sum=S, error=E, status=status, success=status == 0,
+                       nfev=nfev)
+
+
+def _direct(f, a, b, step, args, constants, xp, inclusive=True):
+    # Directly evaluate the sum.
+
+    # When used in the context of distributions, `args` would contain the
+    # distribution parameters. We have broadcasted for simplicity, but we could
+    # reduce function evaluations when distribution parameters are the same but
+    # sum limits differ. Roughly:
+    # - compute the function at all points between min(a) and max(b),
+    # - compute the cumulative sum,
+    # - take the difference between elements of the cumulative sum
+    #   corresponding with b and a.
+    # This is left to future enhancement
+
+    dtype, log, eps, zero, _, _, _ = constants
+
+    # To allow computation in a single vectorized call, find the maximum number
+    # of points (over all slices) at which the function needs to be evaluated.
+    # Note: if `inclusive` is `True`, then we want `1` more term in the sum.
+    # I didn't think it was great style to use `True` as `1` in Python, so I
+    # explicitly converted it to an `int` before using it.
+    inclusive_adjustment = int(inclusive)
+    steps = xp.round((b - a) / step) + inclusive_adjustment
+    # Equivalently, steps = xp.round((b - a) / step) + inclusive
+    max_steps = int(xp.max(steps))
+
+    # In each slice, the function will be evaluated at the same number of points,
+    # but excessive points (those beyond the right sum limit `b`) are replaced
+    # with NaN to (potentially) reduce the time of these unnecessary calculations.
+    # Use a new last axis for these calculations for consistency with other
+    # elementwise algorithms.
+    a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
+    args2 = [arg[:, xp.newaxis] for arg in args]
+    ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
+    i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
+    ks[i_nan] = xp.nan
+    fs = f(ks, *args2)
+
+    # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
+    # In some cases it may be faster to loop over slices than to vectorize
+    # like this. This is an optimization that can be added later.
+    fs[i_nan] = zero
+    nfev = max_steps - i_nan.sum(axis=-1)
+    S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
+    # Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
+    E = xp_real(S) + math.log(eps) if log else eps * abs(S)
+    return S, E, nfev
+
+
+def _integral_bound(f, a, b, step, args, constants, xp):
+    # Estimate the sum with integral approximation
+    dtype, log, _, _, rtol, atol, maxterms = constants
+    log2 = xp.asarray(math.log(2), dtype=dtype)
+
+    # Get a lower bound on the sum and compute effective absolute tolerance
+    lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
+    tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
+    if log:
+        tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
+    else:
+        tol = tol + rtol*lb.integral
+    i_skip = lb.status < 0  # avoid unnecessary f_evals if integral is divergent
+    tol[i_skip] = xp.nan
+    status = lb.status
+
+    # As in `_direct`, we'll need a temporary new axis for points
+    # at which to evaluate the function. Append axis at the end for
+    # consistency with other elementwise algorithms.
+    a2 = a[..., xp.newaxis]
+    step2 = step[..., xp.newaxis]
+    args2 = [arg[..., xp.newaxis] for arg in args]
+
+    # Find the location of a term that is less than the tolerance (if possible)
+    log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
+    n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
+    n_steps = xp.astype(n_steps, dtype)
+    nfev = len(n_steps) * 2
+    ks = a2 + n_steps * step2
+    fks = f(ks, *args2)
+    fksp1 = f(ks + step2, *args2)  # check that the function is decreasing
+    fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
+    n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
+    nt = xp.minimum(n_fk_insufficient, xp.asarray(n_steps.shape[-1]-1))
+    n_steps = n_steps[nt]
+
+    # If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
+    # partial sum exceeds the tolerance or the function is not decreasing), finish the
+    # calculation, but report nonzero status. (Improvement: separate the status codes
+    # for these two cases.)
+    i_fk_insufficient = (n_fk_insufficient == nfev//2)
+
+    # Directly evaluate the sum up to this term
+    k = a + n_steps * step
+    left, left_error, left_nfev = _direct(f, a, k, step, args,
+                                          constants, xp, inclusive=False)
+    left_is_pos_inf = xp.isinf(left) & (left > 0)
+    i_skip |= left_is_pos_inf  # if sum is infinite, no sense in continuing
+    status[left_is_pos_inf] = -3
+    k[i_skip] = xp.nan
+
+    # Use integration to estimate the remaining sum
+    # Possible optimization for future work: if there were no terms less than
+    # the tolerance, there is no need to compute the integral to better accuracy.
+    # Something like:
+    # atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
+    # rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
+    # where `fk`/`fb` are currently calculated below.
+    right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
+
+    # Calculate the full estimate and error from the pieces
+    fk = fks[xp.arange(len(fks)), nt]
+
+    # fb = f(b, *args), but some functions return NaN at infinity.
+    # instead of 0 like they must (for the sum to be convergent).
+    fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
+    i = xp.isfinite(b)
+    if xp.any(i):  # better not call `f` with empty arrays
+        fb[i] = f(b[i], *[arg[i] for arg in args])
+    nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
+
+    if log:
+        log_step = xp.log(step)
+        S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
+        S = special.logsumexp(xp.stack(S_terms), axis=0)
+        E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
+        E = xp_real(special.logsumexp(xp.stack(E_terms), axis=0))
+    else:
+        S = left + right.integral/step + fk/2 + fb/2
+        E = left_error + right.error/step + fk/2 - fb/2
+    status[~i_skip] = right.status[~i_skip]
+
+    status[(status == 0) & i_fk_insufficient] = -4
+    return S, E, status, left_nfev + right.nfev + nfev + lb.nfev
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_test_multivariate.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_test_multivariate.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c287e8b56aa04426bfaa77e359325f72bf2b0e1d
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_test_multivariate.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_test_odeint_banded.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_test_odeint_banded.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..d62b604add5d053e4be825a0a29b3d4e6d2d8dfc
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_test_odeint_banded.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_vode.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/integrate/_vode.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c7902e393c4416d657d42990a4933dfd7cfa462b
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/integrate/_vode.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/dop.py b/python_embeded/Lib/site-packages/scipy/integrate/dop.py
new file mode 100644
index 0000000000000000000000000000000000000000..11d101799ac31f9d5b4c4c79aeb42283422d038f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/dop.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="integrate", module="dop",
+                                   private_modules=["_dop"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/lsoda.py b/python_embeded/Lib/site-packages/scipy/integrate/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5034aadb31dd9b52ffd59abf108309b5fadeac5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/lsoda.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__ = ['lsoda']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="lsoda",
+                                   private_modules=["_lsoda"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/odepack.py b/python_embeded/Lib/site-packages/scipy/integrate/odepack.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c7e619f2408c72e2b3eb5e639312630c128914f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/odepack.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.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['odeint', 'ODEintWarning']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="odepack",
+                                   private_modules=["_odepack_py"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/quadpack.py b/python_embeded/Lib/site-packages/scipy/integrate/quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..711981a5996dac2f04b1162e888f9d03f4c87aa0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/quadpack.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.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    "quad",
+    "dblquad",
+    "tplquad",
+    "nquad",
+    "IntegrationWarning",
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="quadpack",
+                                   private_modules=["_quadpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/vode.py b/python_embeded/Lib/site-packages/scipy/integrate/vode.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ad87d9bf6c6eac0abe87c44067071a6c0f3aae8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/vode.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="integrate", module="vode",
+                                   private_modules=["_vode"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/__init__.py b/python_embeded/Lib/site-packages/scipy/interpolate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8be860b682a9166425cea79091c07a40d5782d6c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/__init__.py
@@ -0,0 +1,216 @@
+"""
+========================================
+Interpolation (:mod:`scipy.interpolate`)
+========================================
+
+.. currentmodule:: scipy.interpolate
+
+Sub-package for objects used in interpolation.
+
+As listed below, this sub-package contains spline functions and classes,
+1-D and multidimensional (univariate and multivariate)
+interpolation classes, Lagrange and Taylor polynomial interpolators, and
+wrappers for `FITPACK `__
+and DFITPACK functions.
+
+Univariate interpolation
+========================
+
+.. autosummary::
+   :toctree: generated/
+
+   interp1d
+   BarycentricInterpolator
+   KroghInterpolator
+   barycentric_interpolate
+   krogh_interpolate
+   pchip_interpolate
+   CubicHermiteSpline
+   PchipInterpolator
+   Akima1DInterpolator
+   CubicSpline
+   PPoly
+   BPoly
+   FloaterHormannInterpolator
+
+
+Multivariate interpolation
+==========================
+
+Unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   griddata
+   LinearNDInterpolator
+   NearestNDInterpolator
+   CloughTocher2DInterpolator
+   RBFInterpolator
+   Rbf
+   interp2d
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   interpn
+   RegularGridInterpolator
+   RectBivariateSpline
+
+.. seealso::
+
+    `scipy.ndimage.map_coordinates`
+
+Tensor product polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   NdPPoly
+   NdBSpline
+
+1-D Splines
+===========
+
+.. autosummary::
+   :toctree: generated/
+
+   BSpline
+   make_interp_spline
+   make_lsq_spline
+   make_smoothing_spline
+   generate_knots
+   make_splrep
+   make_splprep
+
+Functional interface to FITPACK routines:
+
+.. autosummary::
+   :toctree: generated/
+
+   splrep
+   splprep
+   splev
+   splint
+   sproot
+   spalde
+   splder
+   splantider
+   insert
+
+Object-oriented FITPACK interface:
+
+.. autosummary::
+   :toctree: generated/
+
+   UnivariateSpline
+   InterpolatedUnivariateSpline
+   LSQUnivariateSpline
+
+
+
+2-D Splines
+===========
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   RectBivariateSpline
+   RectSphereBivariateSpline
+
+For unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   BivariateSpline
+   SmoothBivariateSpline
+   SmoothSphereBivariateSpline
+   LSQBivariateSpline
+   LSQSphereBivariateSpline
+
+Low-level interface to FITPACK functions:
+
+.. autosummary::
+   :toctree: generated/
+
+   bisplrep
+   bisplev
+
+Rational Approximation
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   pade
+   AAA
+
+Additional tools
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   lagrange
+   approximate_taylor_polynomial
+
+.. seealso::
+
+   `scipy.ndimage.map_coordinates`,
+   `scipy.ndimage.spline_filter`,
+   `scipy.signal.resample`,
+   `scipy.signal.bspline`,
+   `scipy.signal.gauss_spline`,
+   `scipy.signal.qspline1d`,
+   `scipy.signal.cspline1d`,
+   `scipy.signal.qspline1d_eval`,
+   `scipy.signal.cspline1d_eval`,
+   `scipy.signal.qspline2d`,
+   `scipy.signal.cspline2d`.
+
+``pchip`` is an alias of `PchipInterpolator` for backward compatibility
+(should not be used in new code).
+"""
+from ._interpolate import *
+from ._fitpack_py import *
+
+# New interface to fitpack library:
+from ._fitpack2 import *
+
+from ._rbf import Rbf
+
+from ._rbfinterp import *
+
+from ._polyint import *
+
+from ._cubic import *
+
+from ._ndgriddata import *
+
+from ._bsplines import *
+from ._fitpack_repro import generate_knots, make_splrep, make_splprep
+
+from ._pade import *
+
+from ._rgi import *
+
+from ._ndbspline import NdBSpline
+
+from ._bary_rational import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import fitpack, fitpack2, interpolate, ndgriddata, polyint, rbf, interpnd
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+# Backward compatibility
+pchip = PchipInterpolator
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_bary_rational.py b/python_embeded/Lib/site-packages/scipy/interpolate/_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ccbe9d180ec3e054ef9fb05423b5ede6aeb4fe3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_bary_rational.py
@@ -0,0 +1,715 @@
+# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University
+# of Oxford, and the Chebfun Developers. 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 University of Oxford 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.
+
+import warnings
+import operator
+
+import numpy as np
+import scipy
+
+
+__all__ = ["AAA", "FloaterHormannInterpolator"]
+
+
+class _BarycentricRational:
+    """Base class for Barycentric representation of a rational function."""
+    def __init__(self, x, y, **kwargs):
+        # input validation
+        z = np.asarray(x)
+        f = np.asarray(y)
+
+        self._input_validation(z, f, **kwargs)
+
+        # Remove infinite or NaN function values and repeated entries
+        to_keep = np.logical_and.reduce(
+            ((np.isfinite(f)) & (~np.isnan(f))).reshape(f.shape[0], -1),
+            axis=-1
+        )
+        f = f[to_keep, ...]
+        z = z[to_keep]
+        z, uni = np.unique(z, return_index=True)
+        f = f[uni, ...]
+
+        self._shape = f.shape[1:]
+        self._support_points, self._support_values, self.weights = (
+            self._compute_weights(z, f, **kwargs)
+        )
+
+        # only compute once
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+    def _input_validation(self, x, y, **kwargs):
+        if x.ndim != 1:
+            raise ValueError("`x` must be 1-D.")
+
+        if not y.ndim >= 1:
+            raise ValueError("`y` must be at least 1-D.")
+
+        if x.size != y.shape[0]:
+            raise ValueError("`x` be the same size as the first dimension of `y`.")
+
+        if not np.all(np.isfinite(x)):
+            raise ValueError("`x` must be finite.")
+
+    def _compute_weights(z, f, **kwargs):
+        raise NotImplementedError
+
+    def __call__(self, z):
+        """Evaluate the rational approximation at given values.
+
+        Parameters
+        ----------
+        z : array_like
+            Input values.
+        """
+        # evaluate rational function in barycentric form.
+        z = np.asarray(z)
+        zv = np.ravel(z)
+
+        support_values = self._support_values.reshape(
+            (self._support_values.shape[0], -1)
+        )
+        weights = self.weights[..., np.newaxis]
+
+        # Cauchy matrix
+        # Ignore errors due to inf/inf at support points, these will be fixed later
+        with np.errstate(invalid="ignore", divide="ignore"):
+            CC = 1 / np.subtract.outer(zv, self._support_points)
+            # Vector of values
+            r = CC @ (weights * support_values) / (CC @ weights)
+
+        # Deal with input inf: `r(inf) = lim r(z) = sum(w*f) / sum(w)`
+        if np.any(np.isinf(zv)):
+            r[np.isinf(zv)] = (np.sum(weights * support_values)
+                               / np.sum(weights))
+
+        # Deal with NaN
+        ii = np.nonzero(np.isnan(r))[0]
+        for jj in ii:
+            if np.isnan(zv[jj]) or not np.any(zv[jj] == self._support_points):
+                # r(NaN) = NaN is fine.
+                # The second case may happen if `r(zv[ii]) = 0/0` at some point.
+                pass
+            else:
+                # Clean up values `NaN = inf/inf` at support points.
+                # Find the corresponding node and set entry to correct value:
+                r[jj] = support_values[zv[jj] == self._support_points].squeeze()
+
+        return np.reshape(r, z.shape + self._shape)
+
+    def poles(self):
+        """Compute the poles of the rational approximation.
+
+        Returns
+        -------
+        poles : array
+            Poles of the AAA approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._poles is None:
+            # Compute poles via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_points))
+            E[0, 1:] = self.weights
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            pol = scipy.linalg.eigvals(E, B)
+            self._poles = pol[np.isfinite(pol)]
+        return self._poles
+
+    def residues(self):
+        """Compute the residues of the poles of the approximation.
+
+        Returns
+        -------
+        residues : array
+            Residues associated with the `poles` of the approximation
+        """
+        if self._residues is None:
+            # Compute residues via formula for res of quotient of analytic functions
+            with np.errstate(divide="ignore", invalid="ignore"):
+                N = (1/(np.subtract.outer(self.poles(), self._support_points))) @ (
+                    self._support_values * self.weights
+                )
+                Ddiff = (
+                    -((1/np.subtract.outer(self.poles(), self._support_points))**2)
+                    @ self.weights
+                )
+                self._residues = N / Ddiff
+        return self._residues
+
+    def roots(self):
+        """Compute the zeros of the rational approximation.
+
+        Returns
+        -------
+        zeros : array
+            Zeros of the AAA approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._roots is None:
+            # Compute zeros via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_values,
+                                                      self._support_points))
+            E[0, 1:] = self.weights * self._support_values
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            zer = scipy.linalg.eigvals(E, B)
+            self._roots = zer[np.isfinite(zer)]
+        return self._roots
+
+
+class AAA(_BarycentricRational):
+    r"""
+    AAA real or complex rational approximation.
+
+    As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by
+    rational functions on a real or complex set of points. The rational approximation is
+    represented in a barycentric form from which the roots (zeros), poles, and residues
+    can be computed.
+
+    Parameters
+    ----------
+    x : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    y : 1D array_like, shape (n,)
+        Function values ``f(x)``. Infinite and NaN values of `values` and
+        corresponding values of `points` will be discarded.
+    rtol : float, optional
+        Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries
+        in `values` are much larger than the rest the default tolerance may be too
+        loose. If the tolerance is too tight then the approximation may contain
+        Froissart doublets or the algorithm may fail to converge entirely.
+    max_terms : int, optional
+        Maximum number of terms in the barycentric representation, defaults to ``100``.
+        Must be greater than or equal to one.
+    clean_up : bool, optional
+        Automatic removal of Froissart doublets, defaults to ``True``. See notes for
+        more details.
+    clean_up_tol : float, optional
+        Poles with residues less than this number times the geometric mean
+        of `values` times the minimum distance to `points` are deemed spurious by the
+        cleanup procedure, defaults to 1e-13. See notes for more details.
+
+    Attributes
+    ----------
+    support_points : array
+        Support points of the approximation. These are a subset of the provided `x` at
+        which the approximation strictly interpolates `y`.
+        See notes for more details.
+    support_values : array
+        Value of the approximation at the `support_points`.
+    weights : array
+        Weights of the barycentric approximation.
+    errors : array
+        Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations
+        of AAA.
+
+    Warns
+    -----
+    RuntimeWarning
+        If `rtol` is not achieved in `max_terms` iterations.
+
+    See Also
+    --------
+    FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    At iteration :math:`m` (at which point there are :math:`m` terms in the both the
+    numerator and denominator of the approximation), the
+    rational approximation in the AAA algorithm takes the barycentric form
+
+    .. math::
+
+        r(z) = n(z)/d(z) =
+        \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)},
+
+    where :math:`z_1,\dots,z_m` are real or complex support points selected from
+    `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values
+    from `y`, and :math:`w_1,\dots,w_m` are real or complex weights.
+
+    Each iteration of the algorithm has two parts: the greedy selection the next support
+    point and the computation of the weights. The first part of each iteration is to
+    select the next support point to be added :math:`z_{m+1}` from the remaining
+    unselected `x`, such that the nonlinear residual
+    :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates
+    when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means
+    the interpolation property is only satisfied up to a tolerance, except at the
+    support points where approximation exactly interpolates the supplied data.
+
+    In the second part of each iteration, the weights :math:`w_j` are selected to solve
+    the least-squares problem
+
+    .. math::
+
+        \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad
+        \sum_{j=1}^{m+1} w_j = 1,
+
+    over the unselected elements of `x`.
+
+    One of the challenges with working with rational approximations is the presence of
+    Froissart doublets, which are either poles with vanishingly small residues or
+    pole-zero pairs that are close enough together to nearly cancel, see [2]_. The
+    greedy nature of the AAA algorithm means Froissart doublets are rare. However, if
+    `rtol` is set too tight then the approximation will stagnate and many Froissart
+    doublets will appear. Froissart doublets can usually be removed by removing support
+    points and then resolving the least squares problem. The support point :math:`z_j`,
+    which is the closest support point to the pole :math:`a` with residue
+    :math:`\alpha`, is removed if the following is satisfied
+
+    .. math::
+
+        |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f},
+
+    where :math:`\tilde{f}` is the geometric mean of `support_values`.
+
+
+    References
+    ----------
+    .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for
+            rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522.
+            :doi:`10.1137/16M1106122`
+    .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions,
+           J. Comp. Appl. Math. 105 (1999), pp. 285-297.
+           :doi:`10.1016/S0377-0427(02)00674-X`
+
+    Examples
+    --------
+
+    Here we reproduce a number of the numerical examples from [1]_ as a demonstration
+    of the functionality offered by this method.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import AAA
+    >>> import warnings
+
+    For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by
+    extrapolating from 100 samples in ``[-1.5, 1.5]``.
+
+    >>> from scipy.special import gamma
+    >>> sample_points = np.linspace(-1.5, 1.5, num=100)
+    >>> r = AAA(sample_points, gamma(sample_points))
+    >>> z = np.linspace(-3.5, 4.5, num=1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z, gamma(z), label="Gamma")
+    >>> ax.plot(sample_points, gamma(sample_points), label="Sample points")
+    >>> ax.plot(z, r(z).real, '--', label="AAA approximation")
+    >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5])
+    >>> ax.legend()
+    >>> plt.show()
+
+    We can also view the poles of the rational approximation and their residues:
+
+    >>> order = np.argsort(r.poles())
+    >>> r.poles()[order]
+    array([-3.81591039e+00+0.j        , -3.00269049e+00+0.j        ,
+           -1.99999988e+00+0.j        , -1.00000000e+00+0.j        ,
+            5.85842812e-17+0.j        ,  4.77485458e+00-3.06919376j,
+            4.77485458e+00+3.06919376j,  5.29095868e+00-0.97373072j,
+            5.29095868e+00+0.97373072j])
+    >>> r.residues()[order]
+    array([ 0.03658074 +0.j        , -0.16915426 -0.j        ,
+            0.49999915 +0.j        , -1.         +0.j        ,
+            1.         +0.j        , -0.81132013 -2.30193429j,
+           -0.81132013 +2.30193429j,  0.87326839+10.70148546j,
+            0.87326839-10.70148546j])
+
+    For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5
+    times around the origin in the complex plane.
+
+    >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000))
+    >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13)
+
+    We see that AAA takes 12 steps to converge with the following errors:
+
+    >>> r.errors.size
+    12
+    >>> r.errors
+    array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02,
+           1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06,
+           3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13])
+
+    We can also plot the computed poles:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points")
+    >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5,
+    ...         label="Computed poles")
+    >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal")
+    >>> ax.legend()
+    >>> plt.show()
+
+    We now demonstrate the removal of Froissart doublets using the `clean_up` method
+    using an example from [1]_. Here we approximate the function
+    :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The
+    algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause
+    Froissart doublets to appear.
+
+    >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000))
+    >>> def f(z):
+    ...     return np.log(2 + z**4)/(1 - 16*z**4)
+    >>> with warnings.catch_warnings():  # filter convergence warning due to rtol=0
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False)
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> fig, axs = plt.subplots(ncols=2)
+    >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+
+    Now we call the `clean_up` method to remove Froissart doublets.
+
+    >>> with warnings.catch_warnings():
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r.clean_up()
+    4
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+    >>> plt.show()
+
+    The left image shows the poles prior of the approximation ``clean_up=False`` with
+    poles with residue less than ``10^-13`` in absolute value shown in red. The right
+    image then shows the poles after the `clean_up` method has been called.
+    """
+    def __init__(self, x, y, *, rtol=None, max_terms=100, clean_up=True,
+                 clean_up_tol=1e-13):
+        super().__init__(x, y, rtol=rtol, max_terms=max_terms)
+
+        if clean_up:
+            self.clean_up(clean_up_tol)
+
+    def _input_validation(self, x, y, rtol=None, max_terms=100, clean_up=True,
+                          clean_up_tol=1e-13):
+        max_terms = operator.index(max_terms)
+        if max_terms < 1:
+            raise ValueError("`max_terms` must be an integer value greater than or "
+                             "equal to one.")
+
+        if y.ndim != 1:
+            raise ValueError("`y` must be 1-D.")
+
+        super()._input_validation(x, y)
+
+    @property
+    def support_points(self):
+        return self._support_points
+
+    @property
+    def support_values(self):
+        return self._support_values
+
+    def _compute_weights(self, z, f, rtol, max_terms):
+        # Initialization for AAA iteration
+        M = np.size(z)
+        mask = np.ones(M, dtype=np.bool_)
+        dtype = np.result_type(z, f, 1.0)
+        rtol = np.finfo(dtype).eps**0.75 if rtol is None else rtol
+        atol = rtol * np.linalg.norm(f, ord=np.inf)
+        zj = np.empty(max_terms, dtype=dtype)
+        fj = np.empty(max_terms, dtype=dtype)
+        # Cauchy matrix
+        C = np.empty((M, max_terms), dtype=dtype)
+        # Loewner matrix
+        A = np.empty((M, max_terms), dtype=dtype)
+        errors = np.empty(max_terms, dtype=A.real.dtype)
+        R = np.repeat(np.mean(f), M)
+
+        # AAA iteration
+        for m in range(max_terms):
+            # Introduce next support point
+            # Select next support point
+            jj = np.argmax(np.abs(f[mask] - R[mask]))
+            # Update support points
+            zj[m] = z[mask][jj]
+            # Update data values
+            fj[m] = f[mask][jj]
+            # Next column of Cauchy matrix
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(divide="ignore", invalid="ignore"):
+                C[:, m] = 1 / (z - z[mask][jj])
+            # Update mask
+            mask[np.nonzero(mask)[0][jj]] = False
+            # Update Loewner matrix
+            # Ignore errors as inf values will be masked out in SVD call
+            with np.errstate(invalid="ignore"):
+                A[:, m] = (f - fj[m]) * C[:, m]
+
+            # Compute weights
+            rows = mask.sum()
+            if rows >= m + 1:
+                # The usual tall-skinny case
+                _, s, V = scipy.linalg.svd(
+                    A[mask, : m + 1], full_matrices=False, check_finite=False,
+                )
+                # Treat case of multiple min singular values
+                mm = s == np.min(s)
+                # Aim for non-sparse weight vector
+                wj = (V.conj()[mm, :].sum(axis=0) / np.sqrt(mm.sum())).astype(dtype)
+            else:
+                # Fewer rows than columns
+                V = scipy.linalg.null_space(A[mask, : m + 1], check_finite=False)
+                nm = V.shape[-1]
+                # Aim for non-sparse wt vector
+                wj = V.sum(axis=-1) / np.sqrt(nm)
+
+            # Compute rational approximant
+            # Omit columns with `wj == 0`
+            i0 = wj != 0
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(invalid="ignore"):
+                # Numerator
+                N = C[:, : m + 1][:, i0] @ (wj[i0] * fj[: m + 1][i0])
+                # Denominator
+                D = C[:, : m + 1][:, i0] @ wj[i0]
+            # Interpolate at support points with `wj !=0`
+            D_inf = np.isinf(D) | np.isnan(D)
+            D[D_inf] = 1
+            N[D_inf] = f[D_inf]
+            R = N / D
+
+            # Check if converged
+            max_error = np.linalg.norm(f - R, ord=np.inf)
+            errors[m] = max_error
+            if max_error <= atol:
+                break
+
+        if m == max_terms - 1:
+            warnings.warn(f"AAA failed to converge within {max_terms} iterations.",
+                          RuntimeWarning, stacklevel=2)
+
+        # Trim off unused array allocation
+        zj = zj[: m + 1]
+        fj = fj[: m + 1]
+
+        # Remove support points with zero weight
+        i_non_zero = wj != 0
+        self.errors = errors[: m + 1]
+        self._points = z
+        self._values = f
+        return zj[i_non_zero], fj[i_non_zero], wj[i_non_zero]
+
+    def clean_up(self, cleanup_tol=1e-13):
+        """Automatic removal of Froissart doublets.
+
+        Parameters
+        ----------
+        cleanup_tol : float, optional
+            Poles with residues less than this number times the geometric mean
+            of `values` times the minimum distance to `points` are deemed spurious by
+            the cleanup procedure, defaults to 1e-13.
+
+        Returns
+        -------
+        int
+            Number of Froissart doublets detected
+        """
+        # Find negligible residues
+        geom_mean_abs_f = scipy.stats.gmean(np.abs(self._values))
+
+        Z_distances = np.min(
+            np.abs(np.subtract.outer(self.poles(), self._points)), axis=1
+        )
+
+        with np.errstate(divide="ignore", invalid="ignore"):
+            ii = np.nonzero(
+                np.abs(self.residues()) / Z_distances < cleanup_tol * geom_mean_abs_f
+            )
+
+        ni = ii[0].size
+        if ni == 0:
+            return ni
+
+        warnings.warn(f"{ni} Froissart doublets detected.", RuntimeWarning,
+                        stacklevel=2)
+
+        # For each spurious pole find and remove closest support point
+        closest_spt_point = np.argmin(
+            np.abs(np.subtract.outer(self._support_points, self.poles()[ii])), axis=0
+        )
+        self._support_points = np.delete(self._support_points, closest_spt_point)
+        self._support_values = np.delete(self._support_values, closest_spt_point)
+
+        # Remove support points z from sample set
+        mask = np.logical_and.reduce(
+            np.not_equal.outer(self._points, self._support_points), axis=1
+        )
+        f = self._values[mask]
+        z = self._points[mask]
+
+        # recompute weights, we resolve the least squares problem for the remaining
+        # support points
+
+        m = self._support_points.size
+
+        # Cauchy matrix
+        C = 1 / np.subtract.outer(z, self._support_points)
+        # Loewner matrix
+        A = f[:, np.newaxis] * C - C * self._support_values
+
+        # Solve least-squares problem to obtain weights
+        _, _, V = scipy.linalg.svd(A, check_finite=False)
+        self.weights = np.conj(V[m - 1,:])
+
+        # reset roots, poles, residues as cached values will be wrong with new weights
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+        return ni
+
+
+class FloaterHormannInterpolator(_BarycentricRational):
+    r"""
+    Floater-Hormann barycentric rational interpolation.
+
+    As described in [1]_, the method of Floater and Hormann computes weights for a
+    Barycentric rational interpolant with no poles on the real axis.
+
+    Parameters
+    ----------
+    x : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    y : array_like, shape (n, ...)
+        Array containing values of the dependent variable. Infinite and NaN values
+        of `values` and corresponding values of `x` will be discarded.
+    d : int, optional
+        Blends ``n - d`` degree `d` polynomials together. For ``d = n - 1`` it is
+        equivalent to polynomial interpolation. Must satisfy ``0 <= d < n``,
+        defaults to 3.
+
+    Attributes
+    ----------
+    weights : array
+        Weights of the barycentric approximation.
+
+    See Also
+    --------
+    AAA : Barycentric rational approximation of real and complex functions.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    The Floater-Hormann interpolant is a rational function that interpolates the data
+    with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d``
+    polynomials of degree `d` together to produce a rational interpolant that contains
+    no poles on the real axis, unlike `AAA`. The interpolant is given
+    by
+
+    .. math::
+
+        r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)}
+        {\sum_{i=0}^{n-d} \lambda_i(x)},
+
+    where :math:`p_i(x)` is an interpolating polynomials of at most degree `d` through
+    the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d}), and :math:`\lambda_i(z)` are
+    blending functions defined by
+
+    .. math::
+
+        \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}.
+
+    When ``d = n - 1`` this reduces to polynomial interpolation.
+
+    Due to its stability following barycentric representation of the above equation
+    is used instead for computation
+
+    .. math::
+
+        r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)},
+
+    where the weights :math:`w_j` are computed as
+
+    .. math::
+
+        w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d}
+        1/|x_k - x_j|, \\
+        J_k &= \{ i \in I: k - d \leq i \leq k\},\\
+        I &= \{0, 1, \dots, n - d\}.
+
+    References
+    ----------
+    .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no
+           poles and high rates of approximation", Numer. Math. 107, 315 (2007).
+           :doi:`10.1007/s00211-007-0093-y`
+
+    Examples
+    --------
+
+    Here we compare the method against polynomial interpolation for an example where
+    the polynomial interpolation fails due to Runge's phenomenon.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import (FloaterHormannInterpolator,
+    ...                                BarycentricInterpolator)
+    >>> def f(z):
+    ...     return 1/(1 + z**2)
+    >>> z = np.linspace(-5, 5, num=15)
+    >>> r = FloaterHormannInterpolator(z, f(z))
+    >>> p = BarycentricInterpolator(z, f(z))
+    >>> zz = np.linspace(-5, 5, num=1000)
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(zz, r(zz), label="Floater=Hormann")
+    >>> ax.plot(zz, p(zz), label="Polynomial")
+    >>> ax.legend()
+    >>> plt.show()
+    """
+    def __init__(self, points, values, *, d=3):
+        super().__init__(points, values, d=d)
+
+    def _input_validation(self, x, y, d):
+        d = operator.index(d)
+        if not (0 <= d < len(x)):
+            raise ValueError("`d` must satisfy 0 <= d < n")
+
+        super()._input_validation(x, y)
+
+    def _compute_weights(self, z, f, d):
+        # Floater and Hormann 2007 Eqn. (18) 3 equations later
+        w = np.zeros_like(z, dtype=np.result_type(z, 1.0))
+        n = w.size
+        for k in range(n):
+            for i in range(max(k-d, 0), min(k+1, n-d)):
+                w[k] += 1/np.prod(np.abs(np.delete(z[k] - z[i : i + d + 1], k - i)))
+        w *= (-1.)**(np.arange(n) - d)
+
+        return z, f, w
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_bspl.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_bspl.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..1b3e3247944815c721a77f7ed8f0908a34f126b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_bspl.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_bsplines.py b/python_embeded/Lib/site-packages/scipy/interpolate/_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..e949ca9a1a1c8d3aaf7ce9cc4cb56489b461150b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_bsplines.py
@@ -0,0 +1,2416 @@
+import operator
+from math import prod
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from scipy.linalg import (get_lapack_funcs, LinAlgError,
+                          cholesky_banded, cho_solve_banded,
+                          solve, solve_banded)
+from scipy.optimize import minimize_scalar
+from . import _dierckx
+from . import _fitpack_impl
+from scipy.sparse import csr_array
+from scipy.special import poch
+from itertools import combinations
+
+
+__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline",
+           "make_smoothing_spline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+def _as_float_array(x, check_finite=False):
+    """Convert the input into a C contiguous float array.
+
+    NB: Upcasts half- and single-precision floats to double precision.
+    """
+    x = np.ascontiguousarray(x)
+    dtyp = _get_dtype(x.dtype)
+    x = x.astype(dtyp, copy=False)
+    if check_finite and not np.isfinite(x).all():
+        raise ValueError("Array must not contain infs or nans.")
+    return x
+
+
+def _dual_poly(j, k, t, y):
+    """
+    Dual polynomial of the B-spline B_{j,k,t} -
+    polynomial which is associated with B_{j,k,t}:
+    $p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$
+    """
+    if k == 0:
+        return 1
+    return np.prod([(y - t[j + i]) for i in range(1, k + 1)])
+
+
+def _diff_dual_poly(j, k, y, d, t):
+    """
+    d-th derivative of the dual polynomial $p_{j,k}(y)$
+    """
+    if d == 0:
+        return _dual_poly(j, k, t, y)
+    if d == k:
+        return poch(1, k)
+    comb = list(combinations(range(j + 1, j + k + 1), d))
+    res = 0
+    for i in range(len(comb) * len(comb[0])):
+        res += np.prod([(y - t[j + p]) for p in range(1, k + 1)
+                        if (j + p) not in comb[i//d]])
+    return res
+
+
+class BSpline:
+    r"""Univariate spline in the B-spline basis.
+
+    .. math::
+
+        S(x) = \sum_{j=0}^{n-1} c_j  B_{j, k; t}(x)
+
+    where :math:`B_{j, k; t}` are B-spline basis functions of degree `k`
+    and knots `t`.
+
+    Parameters
+    ----------
+    t : ndarray, shape (n+k+1,)
+        knots
+    c : ndarray, shape (>=n, ...)
+        spline coefficients
+    k : int
+        B-spline degree
+    extrapolate : bool or 'periodic', optional
+        whether to extrapolate beyond the base interval, ``t[k] .. t[n]``,
+        or to return nans.
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+        If 'periodic', periodic extrapolation is used.
+        Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    t : ndarray
+        knot vector
+    c : ndarray
+        spline coefficients
+    k : int
+        spline degree
+    extrapolate : bool
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+    axis : int
+        Interpolation axis.
+    tck : tuple
+        A read-only equivalent of ``(self.t, self.c, self.k)``
+
+    Methods
+    -------
+    __call__
+    basis_element
+    derivative
+    antiderivative
+    integrate
+    insert_knot
+    construct_fast
+    design_matrix
+    from_power_basis
+
+    Notes
+    -----
+    B-spline basis elements are defined via
+
+    .. math::
+
+        B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,}
+
+        B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
+                 + \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
+
+    **Implementation details**
+
+    - At least ``k+1`` coefficients are required for a spline of degree `k`,
+      so that ``n >= k+1``. Additional coefficients, ``c[j]`` with
+      ``j > n``, are ignored.
+
+    - B-spline basis elements of degree `k` form a partition of unity on the
+      *base interval*, ``t[k] <= x <= t[n]``.
+
+
+    Examples
+    --------
+
+    Translating the recursive definition of B-splines into Python code, we have:
+
+    >>> def B(x, k, i, t):
+    ...    if k == 0:
+    ...       return 1.0 if t[i] <= x < t[i+1] else 0.0
+    ...    if t[i+k] == t[i]:
+    ...       c1 = 0.0
+    ...    else:
+    ...       c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
+    ...    if t[i+k+1] == t[i+1]:
+    ...       c2 = 0.0
+    ...    else:
+    ...       c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
+    ...    return c1 + c2
+
+    >>> def bspline(x, t, c, k):
+    ...    n = len(t) - k - 1
+    ...    assert (n >= k+1) and (len(c) >= n)
+    ...    return sum(c[i] * B(x, k, i, t) for i in range(n))
+
+    Note that this is an inefficient (if straightforward) way to
+    evaluate B-splines --- this spline class does it in an equivalent,
+    but much more efficient way.
+
+    Here we construct a quadratic spline function on the base interval
+    ``2 <= x <= 4`` and compare with the naive way of evaluating the spline:
+
+    >>> from scipy.interpolate import BSpline
+    >>> k = 2
+    >>> t = [0, 1, 2, 3, 4, 5, 6]
+    >>> c = [-1, 2, 0, -1]
+    >>> spl = BSpline(t, c, k)
+    >>> spl(2.5)
+    array(1.375)
+    >>> bspline(2.5, t, c, k)
+    1.375
+
+    Note that outside of the base interval results differ. This is because
+    `BSpline` extrapolates the first and last polynomial pieces of B-spline
+    functions active on the base interval.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> fig, ax = plt.subplots()
+    >>> xx = np.linspace(1.5, 4.5, 50)
+    >>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive')
+    >>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
+    >>> ax.grid(True)
+    >>> ax.legend(loc='best')
+    >>> plt.show()
+
+
+    References
+    ----------
+    .. [1] Tom Lyche and Knut Morken, Spline methods,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+    .. [2] Carl de Boor, A practical guide to splines, Springer, 2001.
+
+    """
+
+    def __init__(self, t, c, k, extrapolate=True, axis=0):
+        super().__init__()
+
+        self.k = operator.index(k)
+        self.c = np.asarray(c)
+        self.t = np.ascontiguousarray(t, dtype=np.float64)
+
+        if extrapolate == 'periodic':
+            self.extrapolate = extrapolate
+        else:
+            self.extrapolate = bool(extrapolate)
+
+        n = self.t.shape[0] - self.k - 1
+
+        axis = normalize_axis_index(axis, self.c.ndim)
+
+        # Note that the normalized axis is stored in the object.
+        self.axis = axis
+        if axis != 0:
+            # roll the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (n, ...),
+            # and axis !=0 means that we have c.shape (..., n, ...)
+            #                                               ^
+            #                                              axis
+            self.c = np.moveaxis(self.c, axis, 0)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if self.t.ndim != 1:
+            raise ValueError("Knot vector must be one-dimensional.")
+        if n < self.k + 1:
+            raise ValueError("Need at least %d knots for degree %d" %
+                             (2*k + 2, k))
+        if (np.diff(self.t) < 0).any():
+            raise ValueError("Knots must be in a non-decreasing order.")
+        if len(np.unique(self.t[k:n+1])) < 2:
+            raise ValueError("Need at least two internal knots.")
+        if not np.isfinite(self.t).all():
+            raise ValueError("Knots should not have nans or infs.")
+        if self.c.ndim < 1:
+            raise ValueError("Coefficients must be at least 1-dimensional.")
+        if self.c.shape[0] < n:
+            raise ValueError("Knots, coefficients and degree are inconsistent.")
+
+        dt = _get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dt)
+
+    @classmethod
+    def construct_fast(cls, t, c, k, extrapolate=True, axis=0):
+        """Construct a spline without making checks.
+
+        Accepts same parameters as the regular constructor. Input arrays
+        `t` and `c` must of correct shape and dtype.
+        """
+        self = object.__new__(cls)
+        self.t, self.c, self.k = t, c, k
+        self.extrapolate = extrapolate
+        self.axis = axis
+        return self
+
+    @property
+    def tck(self):
+        """Equivalent to ``(self.t, self.c, self.k)`` (read-only).
+        """
+        return self.t, self.c, self.k
+
+    @classmethod
+    def basis_element(cls, t, extrapolate=True):
+        """Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``.
+
+        Parameters
+        ----------
+        t : ndarray, shape (k+2,)
+            internal knots
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``,
+            or to return nans.
+            If 'periodic', periodic extrapolation is used.
+            Default is True.
+
+        Returns
+        -------
+        basis_element : callable
+            A callable representing a B-spline basis element for the knot
+            vector `t`.
+
+        Notes
+        -----
+        The degree of the B-spline, `k`, is inferred from the length of `t` as
+        ``len(t)-2``. The knot vector is constructed by appending and prepending
+        ``k+1`` elements to internal knots `t`.
+
+        Examples
+        --------
+
+        Construct a cubic B-spline:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2, 3, 4])
+        >>> k = b.k
+        >>> b.t[k:-k]
+        array([ 0.,  1.,  2.,  3.,  4.])
+        >>> k
+        3
+
+        Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare
+        to its explicit form:
+
+        >>> t = [0, 1, 1, 2]
+        >>> b = BSpline.basis_element(t)
+        >>> def f(x):
+        ...     return np.where(x < 1, x*x, (2. - x)**2)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> x = np.linspace(0, 2, 51)
+        >>> ax.plot(x, b(x), 'g', lw=3)
+        >>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4)
+        >>> ax.grid(True)
+        >>> plt.show()
+
+        """
+        k = len(t) - 2
+        t = _as_float_array(t)
+        t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k]
+        c = np.zeros_like(t)
+        c[k] = 1.
+        return cls.construct_fast(t, c, k, extrapolate)
+
+    @classmethod
+    def design_matrix(cls, x, t, k, extrapolate=False):
+        """
+        Returns a design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Points to evaluate the spline at.
+        t : array_like, shape (nt,)
+            Sorted 1D array of knots.
+        k : int
+            B-spline degree.
+        extrapolate : bool or 'periodic', optional
+            Whether to extrapolate based on the first and last intervals
+            or raise an error. If 'periodic', periodic extrapolation is used.
+            Default is False.
+
+            .. versionadded:: 1.10.0
+
+        Returns
+        -------
+        design_matrix : `csr_array` object
+            Sparse matrix in CSR format where each row contains all the basis
+            elements of the input row (first row = basis elements of x[0],
+            ..., last row = basis elements x[-1]).
+
+        Examples
+        --------
+        Construct a design matrix for a B-spline
+
+        >>> from scipy.interpolate import make_interp_spline, BSpline
+        >>> import numpy as np
+        >>> x = np.linspace(0, np.pi * 2, 4)
+        >>> y = np.sin(x)
+        >>> k = 3
+        >>> bspl = make_interp_spline(x, y, k=k)
+        >>> design_matrix = bspl.design_matrix(x, bspl.t, k)
+        >>> design_matrix.toarray()
+        [[1.        , 0.        , 0.        , 0.        ],
+        [0.2962963 , 0.44444444, 0.22222222, 0.03703704],
+        [0.03703704, 0.22222222, 0.44444444, 0.2962963 ],
+        [0.        , 0.        , 0.        , 1.        ]]
+
+        Construct a design matrix for some vector of knots
+
+        >>> k = 2
+        >>> t = [-1, 0, 1, 2, 3, 4, 5, 6]
+        >>> x = [1, 2, 3, 4]
+        >>> design_matrix = BSpline.design_matrix(x, t, k).toarray()
+        >>> design_matrix
+        [[0.5, 0.5, 0. , 0. , 0. ],
+        [0. , 0.5, 0.5, 0. , 0. ],
+        [0. , 0. , 0.5, 0.5, 0. ],
+        [0. , 0. , 0. , 0.5, 0.5]]
+
+        This result is equivalent to the one created in the sparse format
+
+        >>> c = np.eye(len(t) - k - 1)
+        >>> design_matrix_gh = BSpline(t, c, k)(x)
+        >>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14)
+        True
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        In each row of the design matrix all the basis elements are evaluated
+        at the certain point (first row - x[0], ..., last row - x[-1]).
+
+        `nt` is a length of the vector of knots: as far as there are
+        `nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2`
+        to have at least `k + 1` basis element.
+
+        Out of bounds `x` raises a ValueError.
+        """
+        x = _as_float_array(x, True)
+        t = _as_float_array(t, True)
+
+        if extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+            raise ValueError(f"Expect t to be a 1-D sorted array_like, but "
+                             f"got t={t}.")
+        # There are `nt - k - 1` basis elements in a BSpline built on the
+        # vector of knots with length `nt`, so to have at least `k + 1` basis
+        # elements we need to have at least `2 * k + 2` elements in the vector
+        # of knots.
+        if len(t) < 2 * k + 2:
+            raise ValueError(f"Length t is not enough for k={k}.")
+
+        if extrapolate == 'periodic':
+            # With periodic extrapolation we map x to the segment
+            # [t[k], t[n]].
+            n = t.size - k - 1
+            x = t[k] + (x - t[k]) % (t[n] - t[k])
+            extrapolate = False
+        elif not extrapolate and (
+            (min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1])
+        ):
+            # Checks from `find_interval` function
+            raise ValueError(f'Out of bounds w/ x = {x}.')
+
+        # Compute number of non-zeros of final CSR array in order to determine
+        # the dtype of indices and indptr of the CSR array.
+        n = x.shape[0]
+        nnz = n * (k + 1)
+        if nnz < np.iinfo(np.int32).max:
+            int_dtype = np.int32
+        else:
+            int_dtype = np.int64
+
+        # Get the non-zero elements of the design matrix and per-row `offsets`:
+        # In row `i`, k+1 nonzero elements are consecutive, and start from `offset[i]`
+        data, offsets, _ = _dierckx.data_matrix(x, t, k, np.ones_like(x), extrapolate)
+        data = data.ravel()
+
+        if offsets.dtype != int_dtype:
+            offsets = offsets.astype(int_dtype)
+
+        # Convert from per-row offsets to the CSR indices/indptr format
+        indices = np.repeat(offsets, k+1).reshape(-1, k+1)
+        indices = indices + np.arange(k+1, dtype=int_dtype)
+        indices = indices.ravel()
+
+        indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype)
+
+        return csr_array(
+            (data, indices, indptr),
+            shape=(x.shape[0], t.shape[0] - k - 1)
+        )
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate a spline function.
+
+        Parameters
+        ----------
+        x : array_like
+            points to evaluate the spline at.
+        nu : int, optional
+            derivative to evaluate (default is 0).
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate based on the first and last intervals
+            or return nans. If 'periodic', periodic extrapolation is used.
+            Default is `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Shape is determined by replacing the interpolation axis
+            in the coefficient array with the shape of `x`.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.t[k], self.t[n]].
+        if extrapolate == 'periodic':
+            n = self.t.size - self.k - 1
+            x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] -
+                                                         self.t[self.k])
+            extrapolate = False
+
+        out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # if self.c is complex, so is `out`; cython code in _bspl.pyx expectes
+        # floats though, so make a view---this expands the last axis, and
+        # the view is C contiguous if the original is.
+        # if c.dtype is complex of shape (n,), c.view(float).shape == (2*n,)
+        # if c.dtype is complex of shape (n, m), c.view(float).shape == (n, 2*m)
+
+        cc = self.c.view(float)
+        if self.c.ndim == 1 and self.c.dtype.kind == 'c':
+            cc = cc.reshape(self.c.shape[0], 2)
+
+        _dierckx.evaluate_spline(self.t, cc.reshape(cc.shape[0], -1),
+                              self.k, x, nu, extrapolate, out.view(float))
+
+        out = out.reshape(x_shape + self.c.shape[1:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+    def _ensure_c_contiguous(self):
+        """
+        c and t may be modified by the user. The Cython code expects
+        that they are C contiguous.
+
+        """
+        if not self.t.flags.c_contiguous:
+            self.t = self.t.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def derivative(self, nu=1):
+        """Return a B-spline representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Derivative order.
+            Default is 1.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the derivative.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splder((self.t, c, self.k), nu)
+        return self.construct_fast(*tck, extrapolate=self.extrapolate,
+                                   axis=self.axis)
+
+    def antiderivative(self, nu=1):
+        """Return a B-spline representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Antiderivative order. Default is 1.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the antiderivative.
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splantider((self.t, c, self.k), nu)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(*tck, extrapolate=extrapolate,
+                                   axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """Compute a definite integral of the spline.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval,
+            ``t[k] .. t[-k-1]``, or take the spline to be zero outside of the
+            base interval. If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        I : array_like
+            Definite integral of the spline over the interval ``[a, b]``.
+
+        Examples
+        --------
+        Construct the linear spline ``x if x < 1 else 2 - x`` on the base
+        interval :math:`[0, 2]`, and integrate it
+
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2])
+        >>> b.integrate(0, 1)
+        array(0.5)
+
+        If the integration limits are outside of the base interval, the result
+        is controlled by the `extrapolate` parameter
+
+        >>> b.integrate(-1, 1)
+        array(0.0)
+        >>> b.integrate(-1, 1, extrapolate=False)
+        array(0.5)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> ax.grid(True)
+        >>> ax.axvline(0, c='r', lw=5, alpha=0.5)  # base interval
+        >>> ax.axvline(2, c='r', lw=5, alpha=0.5)
+        >>> xx = [-1, 1, 2]
+        >>> ax.plot(xx, b(xx))
+        >>> plt.show()
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Prepare self.t and self.c.
+        self._ensure_c_contiguous()
+
+        # Swap integration bounds if needed.
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+        n = self.t.size - self.k - 1
+
+        if extrapolate != "periodic" and not extrapolate:
+            # Shrink the integration interval, if needed.
+            a = max(a, self.t[self.k])
+            b = min(b, self.t[n])
+
+            if self.c.ndim == 1:
+                # Fast path: use FITPACK's routine
+                # (cf _fitpack_impl.splint).
+                integral = _fitpack_impl.splint(a, b, self.tck)
+                return np.asarray(integral * sign)
+
+        out = np.empty((2, prod(self.c.shape[1:])), dtype=self.c.dtype)
+
+        # Compute the antiderivative.
+        c = self.c
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        ta, ca, ka = _fitpack_impl.splantider((self.t, c, self.k), 1)
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            ts, te = self.t[self.k], self.t[n]
+            period = te - ts
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                # Evaluate the difference of antiderivatives.
+                x = np.asarray([ts, te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral = out[1] - out[0]
+                integral *= n_periods
+            else:
+                integral = np.zeros((1, prod(self.c.shape[1:])),
+                                    dtype=self.c.dtype)
+
+            # Map a to [ts, te], b is always a + left.
+            a = ts + (a - ts) % period
+            b = a + left
+
+            # If b <= te then we need to integrate over [a, b], otherwise
+            # over [a, te] and from xs to what is remained.
+            if b <= te:
+                x = np.asarray([a, b], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+            else:
+                x = np.asarray([a, te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+
+                x = np.asarray([ts, ts + b - te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+        else:
+            # Evaluate the difference of antiderivatives.
+            x = np.asarray([a, b], dtype=np.float64)
+            _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                  ka, x, 0, extrapolate, out)
+            integral = out[1] - out[0]
+
+        integral *= sign
+        return integral.reshape(ca.shape[1:])
+
+    @classmethod
+    def from_power_basis(cls, pp, bc_type='not-a-knot'):
+        r"""
+        Construct a polynomial in the B-spline basis
+        from a piecewise polynomial in the power basis.
+
+        For now, accepts ``CubicSpline`` instances only.
+
+        Parameters
+        ----------
+        pp : CubicSpline
+            A piecewise polynomial in the power basis, as created
+            by ``CubicSpline``
+        bc_type : string, optional
+            Boundary condition type as in ``CubicSpline``: one of the
+            ``not-a-knot``, ``natural``, ``clamped``, or ``periodic``.
+            Necessary for construction an instance of ``BSpline`` class.
+            Default is ``not-a-knot``.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the initial polynomial
+            in the B-spline basis.
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        Accepts only ``CubicSpline`` instances for now.
+
+        The algorithm follows from differentiation
+        the Marsden's identity [1]: each of coefficients of spline
+        interpolation function in the B-spline basis is computed as follows:
+
+        .. math::
+
+            c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!}
+                       c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i)
+
+        :math:`c_{m, i}` - a coefficient of CubicSpline,
+        :math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial
+        in :math:`x_i`.
+
+        ``k`` always equals 3 for now.
+
+        First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g.
+
+        .. math::
+
+            c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1)
+
+        Last ``nod + 2`` coefficients are computed in ``x[-2]``,
+        ``nod`` - number of derivatives at the ends.
+
+        For example, consider :math:`x = [0, 1, 2, 3, 4]`,
+        :math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural``
+
+        The coefficients of CubicSpline in the power basis:
+
+        :math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]`
+
+        The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]`
+
+        In this case
+
+        .. math::
+
+            c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6
+
+        References
+        ----------
+        .. [1] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2
+
+        """
+        from ._cubic import CubicSpline
+        if not isinstance(pp, CubicSpline):
+            raise NotImplementedError(f"Only CubicSpline objects are accepted "
+                                      f"for now. Got {type(pp)} instead.")
+        x = pp.x
+        coef = pp.c
+        k = pp.c.shape[0] - 1
+        n = x.shape[0]
+
+        if bc_type == 'not-a-knot':
+            t = _not_a_knot(x, k)
+        elif bc_type == 'natural' or bc_type == 'clamped':
+            t = _augknt(x, k)
+        elif bc_type == 'periodic':
+            t = _periodic_knots(x, k)
+        else:
+            raise TypeError(f'Unknown boundary condition: {bc_type}')
+
+        nod = t.shape[0] - (n + k + 1)  # number of derivatives at the ends
+        c = np.zeros(n + nod, dtype=pp.c.dtype)
+        for m in range(k + 1):
+            for i in range(n - 2):
+                c[i] += poch(k + 1, -m) * coef[m, i]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(i, k, x[i], m, t)
+            for j in range(n - 2, n + nod):
+                c[j] += poch(k + 1, -m) * coef[m, n - 2]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(j, k, x[n - 2], m, t)
+        return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis)
+
+    def insert_knot(self, x, m=1):
+        """Insert a new knot at `x` of multiplicity `m`.
+
+        Given the knots and coefficients of a B-spline representation, create a
+        new B-spline with a knot inserted `m` times at point `x`.
+
+        Parameters
+        ----------
+        x : float
+            The position of the new knot
+        m : int, optional
+            The number of times to insert the given knot (its multiplicity).
+            Default is 1.
+
+        Returns
+        -------
+        spl : BSpline object
+            A new BSpline object with the new knot inserted.
+
+        Notes
+        -----
+        Based on algorithms from [1]_ and [2]_.
+
+        In case of a periodic spline (``self.extrapolate == "periodic"``)
+        there must be either at least k interior knots t(j) satisfying
+        ``t(k+1)>> import numpy as np
+        >>> from scipy.interpolate import BSpline, make_interp_spline
+        >>> x = np.linspace(0, 10, 5)
+        >>> y = np.sin(x)
+        >>> spl = make_interp_spline(x, y, k=3)
+        >>> spl.t
+        array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+        Insert a single knot
+
+        >>> spl_1 = spl.insert_knot(3)
+        >>> spl_1.t
+        array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+        Insert a multiple knot
+
+        >>> spl_2 = spl.insert_knot(8, m=3)
+        >>> spl_2.t
+        array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+        """
+        if x < self.t[self.k] or x > self.t[-self.k-1]:
+            raise ValueError(f"Cannot insert a knot at {x}.")
+        if m <= 0:
+            raise ValueError(f"`m` must be positive, got {m = }.")
+
+        tt = self.t.copy()
+        cc = self.c.copy()
+
+        for _ in range(m):
+            tt, cc = _insert(x, tt, cc, self.k, self.extrapolate == "periodic")
+        return self.construct_fast(tt, cc, self.k, self.extrapolate, self.axis)
+
+
+def _insert(xval, t, c, k, periodic=False):
+    """Insert a single knot at `xval`."""
+    #
+    # This is a port of the FORTRAN `insert` routine by P. Dierckx,
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/insert.f
+    # which carries the following comment:
+    #
+    # subroutine insert inserts a new knot x into a spline function s(x)
+    # of degree k and calculates the b-spline representation of s(x) with
+    # respect to the new set of knots. in addition, if iopt.ne.0, s(x)
+    # will be considered as a periodic spline with period per=t(n-k)-t(k+1)
+    # satisfying the boundary constraints
+    #      t(i+n-2*k-1) = t(i)+per  ,i=1,2,...,2*k+1
+    #      c(i+n-2*k-1) = c(i)      ,i=1,2,...,k
+    # in that case, the knots and b-spline coefficients returned will also
+    # satisfy these boundary constraints, i.e.
+    #      tt(i+nn-2*k-1) = tt(i)+per  ,i=1,2,...,2*k+1
+    #      cc(i+nn-2*k-1) = cc(i)      ,i=1,2,...,k
+    interval = _dierckx.find_interval(t, k, float(xval), k, False)
+    if interval < 0:
+        # extrapolated values are guarded for in BSpline.insert_knot
+        raise ValueError(f"Cannot insert the knot at {xval}.")
+
+    # super edge case: a knot with multiplicity > k+1
+    # see https://github.com/scipy/scipy/commit/037204c3e91
+    if t[interval] == t[interval + k + 1]:
+        interval -= 1
+
+    if periodic:
+        if (interval + 1 <= 2*k) and (interval + 1 >= t.shape[0] - 2*k):
+            # in case of a periodic spline (iopt.ne.0) there must be
+            # either at least k interior knots t(j) satisfying t(k+1)= nk - k:
+            # adjust the left-hand boundary knots & coefs
+            tt[:k] = tt[nk - k:nk] - T
+            cc[:k, ...] = cc[n2k:n2k + k, ...]
+
+        if interval <= 2*k-1:
+            # adjust the right-hand boundary knots & coefs
+            tt[n-k:] = tt[k+1:k+1+k] + T
+            cc[n2k:n2k + k, ...] = cc[:k, ...]
+
+    return tt, cc
+
+
+#################################
+#  Interpolating spline helpers #
+#################################
+
+def _not_a_knot(x, k):
+    """Given data x, construct the knot vector w/ not-a-knot BC.
+    cf de Boor, XIII(12).
+
+    For even k, it's a bit ad hoc: Greville sites + omit 2nd and 2nd-to-last
+    data points, a la not-a-knot.
+    This seems to match what Dierckx does, too:
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L63-L80
+    """
+    x = np.asarray(x)
+    if k % 2 == 1:
+        k2 = (k + 1) // 2
+        t = x.copy()
+    else:
+        k2 = k // 2
+        t = (x[1:] + x[:-1]) / 2
+
+    t = t[k2:-k2]
+    t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)]
+    return t
+
+
+def _augknt(x, k):
+    """Construct a knot vector appropriate for the order-k interpolation."""
+    return np.r_[(x[0],)*k, x, (x[-1],)*k]
+
+
+def _convert_string_aliases(deriv, target_shape):
+    if isinstance(deriv, str):
+        if deriv == "clamped":
+            deriv = [(1, np.zeros(target_shape))]
+        elif deriv == "natural":
+            deriv = [(2, np.zeros(target_shape))]
+        else:
+            raise ValueError(f"Unknown boundary condition : {deriv}")
+    return deriv
+
+
+def _process_deriv_spec(deriv):
+    if deriv is not None:
+        try:
+            ords, vals = zip(*deriv)
+        except TypeError as e:
+            msg = ("Derivatives, `bc_type`, should be specified as a pair of "
+                   "iterables of pairs of (order, value).")
+            raise ValueError(msg) from e
+    else:
+        ords, vals = [], []
+    return np.atleast_1d(ords, vals)
+
+
+def _woodbury_algorithm(A, ur, ll, b, k):
+    '''
+    Solve a cyclic banded linear system with upper right
+    and lower blocks of size ``(k-1) / 2`` using
+    the Woodbury formula
+
+    Parameters
+    ----------
+    A : 2-D array, shape(k, n)
+        Matrix of diagonals of original matrix (see
+        ``solve_banded`` documentation).
+    ur : 2-D array, shape(bs, bs)
+        Upper right block matrix.
+    ll : 2-D array, shape(bs, bs)
+        Lower left block matrix.
+    b : 1-D array, shape(n,)
+        Vector of constant terms of the system of linear equations.
+    k : int
+        B-spline degree.
+
+    Returns
+    -------
+    c : 1-D array, shape(n,)
+        Solution of the original system of linear equations.
+
+    Notes
+    -----
+    This algorithm works only for systems with banded matrix A plus
+    a correction term U @ V.T, where the matrix U @ V.T gives upper right
+    and lower left block of A
+    The system is solved with the following steps:
+        1.  New systems of linear equations are constructed:
+            A @ z_i = u_i,
+            u_i - column vector of U,
+            i = 1, ..., k - 1
+        2.  Matrix Z is formed from vectors z_i:
+            Z = [ z_1 | z_2 | ... | z_{k - 1} ]
+        3.  Matrix H = (1 + V.T @ Z)^{-1}
+        4.  The system A' @ y = b is solved
+        5.  x = y - Z @ (H @ V.T @ y)
+    Also, ``n`` should be greater than ``k``, otherwise corner block
+    elements will intersect with diagonals.
+
+    Examples
+    --------
+    Consider the case of n = 8, k = 5 (size of blocks - 2 x 2).
+    The matrix of a system:       U:          V:
+      x  x  x  *  *  a  b         a b 0 0     0 0 1 0
+      x  x  x  x  *  *  c         0 c 0 0     0 0 0 1
+      x  x  x  x  x  *  *         0 0 0 0     0 0 0 0
+      *  x  x  x  x  x  *         0 0 0 0     0 0 0 0
+      *  *  x  x  x  x  x         0 0 0 0     0 0 0 0
+      d  *  *  x  x  x  x         0 0 d 0     1 0 0 0
+      e  f  *  *  x  x  x         0 0 e f     0 1 0 0
+
+    References
+    ----------
+    .. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling
+           and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3
+
+    '''
+    k_mod = k - k % 2
+    bs = int((k - 1) / 2) + (k + 1) % 2
+
+    n = A.shape[1] + 1
+    U = np.zeros((n - 1, k_mod))
+    VT = np.zeros((k_mod, n - 1))  # V transpose
+
+    # upper right block
+    U[:bs, :bs] = ur
+    VT[np.arange(bs), np.arange(bs) - bs] = 1
+
+    # lower left block
+    U[-bs:, -bs:] = ll
+    VT[np.arange(bs) - bs, np.arange(bs)] = 1
+
+    Z = solve_banded((bs, bs), A, U)
+
+    H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod))
+
+    y = solve_banded((bs, bs), A, b)
+    c = y - Z @ (H @ (VT @ y))
+
+    return c
+
+
+def _periodic_knots(x, k):
+    '''
+    returns vector of nodes on circle
+    '''
+    xc = np.copy(x)
+    n = len(xc)
+    if k % 2 == 0:
+        dx = np.diff(xc)
+        xc[1: -1] -= dx[:-1] / 2
+    dx = np.diff(xc)
+    t = np.zeros(n + 2 * k)
+    t[k: -k] = xc
+    for i in range(0, k):
+        # filling first `k` elements in descending order
+        t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1]
+        # filling last `k` elements in ascending order
+        t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)]
+    return t
+
+
+def _make_interp_per_full_matr(x, y, t, k):
+    '''
+    Returns a solution of a system for B-spline interpolation with periodic
+    boundary conditions. First ``k - 1`` rows of matrix are conditions of
+    periodicity (continuity of ``k - 1`` derivatives at the boundary points).
+    Last ``n`` rows are interpolation conditions.
+    RHS is ``k - 1`` zeros and ``n`` ordinates in this case.
+
+    Parameters
+    ----------
+    x : 1-D array, shape (n,)
+        Values of x - coordinate of a given set of points.
+    y : 1-D array, shape (n,)
+        Values of y - coordinate of a given set of points.
+    t : 1-D array, shape(n+2*k,)
+        Vector of knots.
+    k : int
+        The maximum degree of spline
+
+    Returns
+    -------
+    c : 1-D array, shape (n+k-1,)
+        B-spline coefficients
+
+    Notes
+    -----
+    ``t`` is supposed to be taken on circle.
+
+    '''
+
+    x, y, t = map(np.asarray, (x, y, t))
+
+    n = x.size
+    # LHS: the colocation matrix + derivatives at edges
+    matr = np.zeros((n + k - 1, n + k - 1))
+
+    # derivatives at x[0] and x[-1]:
+    for i in range(k - 1):
+        bb = _dierckx.evaluate_all_bspl(t, k, x[0], k, i + 1)
+        matr[i, : k + 1] += bb
+        bb = _dierckx.evaluate_all_bspl(t, k, x[-1], n + k - 1, i + 1)[:-1]
+        matr[i, -k:] -= bb
+
+    # colocation matrix
+    for i in range(n):
+        xval = x[i]
+        # find interval
+        if xval == t[k]:
+            left = k
+        else:
+            left = np.searchsorted(t, xval) - 1
+
+        # fill a row
+        bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
+        matr[i + k - 1, left-k:left+1] = bb
+
+    # RHS
+    b = np.r_[[0] * (k - 1), y]
+
+    c = solve(matr, b)
+    return c
+
+
+def _handle_lhs_derivatives(t, k, xval, ab, kl, ku, deriv_ords, offset=0):
+    """ Fill in the entries of the colocation matrix corresponding to known
+    derivatives at `xval`.
+
+    The colocation matrix is in the banded storage, as prepared by _coloc.
+    No error checking.
+
+    Parameters
+    ----------
+    t : ndarray, shape (nt + k + 1,)
+        knots
+    k : integer
+        B-spline order
+    xval : float
+        The value at which to evaluate the derivatives at.
+    ab : ndarray, shape(2*kl + ku + 1, nt), Fortran order
+        B-spline colocation matrix.
+        This argument is modified *in-place*.
+    kl : integer
+        Number of lower diagonals of ab.
+    ku : integer
+        Number of upper diagonals of ab.
+    deriv_ords : 1D ndarray
+        Orders of derivatives known at xval
+    offset : integer, optional
+        Skip this many rows of the matrix ab.
+
+    """
+    # find where `xval` is in the knot vector, `t`
+    left = _dierckx.find_interval(t, k, float(xval), k, False)
+
+    # compute and fill in the derivatives @ xval
+    for row in range(deriv_ords.shape[0]):
+        nu = deriv_ords[row]
+        wrk = _dierckx.evaluate_all_bspl(t, k, xval, left, nu)
+
+        # if A were a full matrix, it would be just
+        # ``A[row + offset, left-k:left+1] = bb``.
+        for a in range(k+1):
+            clmn = left - k + a
+            ab[kl + ku + offset + row - clmn, clmn] = wrk[a]
+
+
+def _make_periodic_spline(x, y, t, k, axis):
+    '''
+    Compute the (coefficients of) interpolating B-spline with periodic
+    boundary conditions.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n,)
+        Ordinates.
+    k : int
+        B-spline degree.
+    t : array_like, shape (n + 2 * k,).
+        Knots taken on a circle, ``k`` on the left and ``k`` on the right
+        of the vector ``x``.
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` and with knots ``t``.
+
+    Notes
+    -----
+    The original system is formed by ``n + k - 1`` equations where the first
+    ``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the
+    edges while the other equations correspond to an interpolating case
+    (matching all the input points). Due to a special form of knot vector, it
+    can be proved that in the original system the first and last ``k``
+    coefficients of a spline function are the same, respectively. It follows
+    from the fact that all ``k - 1`` derivatives are equal term by term at ends
+    and that the matrix of the original system of linear equations is
+    non-degenerate. So, we can reduce the number of equations to ``n - 1``
+    (first ``k - 1`` equations could be reduced). Another trick of this
+    implementation is cyclic shift of values of B-splines due to equality of
+    ``k`` unknown coefficients. With this we can receive matrix of the system
+    with upper right and lower left blocks, and ``k`` diagonals.  It allows
+    to use Woodbury formula to optimize the computations.
+
+    '''
+    n = y.shape[0]
+
+    extradim = prod(y.shape[1:])
+    y_new = y.reshape(n, extradim)
+    c = np.zeros((n + k - 1, extradim))
+
+    # n <= k case is solved with full matrix
+    if n <= k:
+        for i in range(extradim):
+            c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k)
+        c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+        return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+    nt = len(t) - k - 1
+
+    # size of block elements
+    kul = int(k / 2)
+
+    # kl = ku = k
+    ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F')
+
+    # upper right and lower left blocks
+    ur = np.zeros((kul, kul))
+    ll = np.zeros_like(ur)
+
+    # `offset` is made to shift all the non-zero elements to the end of the
+    # matrix
+    # NB: 1. drop the last element of `x` because `x[0] = x[-1] + T` & `y[0] == y[-1]`
+    #     2. pass ab.T to _coloc to make it C-ordered; below it'll be fed to banded
+    #        LAPACK, which needs F-ordered arrays
+    _dierckx._coloc(x[:-1], t, k, ab.T, k)
+
+    # remove zeros before the matrix
+    ab = ab[-k - (k + 1) % 2:, :]
+
+    # The least elements in rows (except repetitions) are diagonals
+    # of block matrices. Upper right matrix is an upper triangular
+    # matrix while lower left is a lower triangular one.
+    for i in range(kul):
+        ur += np.diag(ab[-i - 1, i: kul], k=i)
+        ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i)
+
+    # remove elements that occur in the last point
+    # (first and last points are equivalent)
+    A = ab[:, kul: -k + kul]
+
+    for i in range(extradim):
+        cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k)
+        c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2]))
+    c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+    return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+
+def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0,
+                       check_finite=True):
+    """Compute the (coefficients of) interpolating B-spline.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n, ...)
+        Ordinates.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    t : array_like, shape (nt + k + 1,), optional.
+        Knots.
+        The number of knots needs to agree with the number of data points and
+        the number of derivatives at the edges. Specifically, ``nt - n`` must
+        equal ``len(deriv_l) + len(deriv_r)``.
+    bc_type : 2-tuple or None
+        Boundary conditions.
+        Default is None, which means choosing the boundary conditions
+        automatically. Otherwise, it must be a length-two tuple where the first
+        element (``deriv_l``) sets the boundary conditions at ``x[0]`` and
+        the second element (``deriv_r``) sets the boundary conditions at
+        ``x[-1]``. Each of these must be an iterable of pairs
+        ``(order, value)`` which gives the values of derivatives of specified
+        orders at the given edge of the interpolation interval.
+        Alternatively, the following string aliases are recognized:
+
+        * ``"clamped"``: The first derivatives at the ends are zero. This is
+           equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``.
+        * ``"natural"``: The second derivatives at ends are zero. This is
+          equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``.
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    axis : int, optional
+        Interpolation axis. Default is 0.
+    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.
+        Default is True.
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` and with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    CubicSpline : a cubic spline in the polynomial basis
+    make_lsq_spline : a similar factory function for spline fitting
+    UnivariateSpline : a wrapper over FITPACK spline fitting routines
+    splrep : a wrapper over FITPACK spline fitting routines
+
+    Examples
+    --------
+
+    Use cubic interpolation on Chebyshev nodes:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> def cheb_nodes(N):
+    ...     jj = 2.*np.arange(N) + 1
+    ...     x = np.cos(np.pi * jj / 2 / N)[::-1]
+    ...     return x
+
+    >>> x = cheb_nodes(20)
+    >>> y = np.sqrt(1 - x**2)
+
+    >>> from scipy.interpolate import BSpline, make_interp_spline
+    >>> b = make_interp_spline(x, y)
+    >>> np.allclose(b(x), y)
+    True
+
+    Note that the default is a cubic spline with a not-a-knot boundary condition
+
+    >>> b.k
+    3
+
+    Here we use a 'natural' spline, with zero 2nd derivatives at edges:
+
+    >>> l, r = [(2, 0.0)], [(2, 0.0)]
+    >>> b_n = make_interp_spline(x, y, bc_type=(l, r))  # or, bc_type="natural"
+    >>> np.allclose(b_n(x), y)
+    True
+    >>> x0, x1 = x[0], x[-1]
+    >>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0])
+    True
+
+    Interpolation of parametric curves is also supported. As an example, we
+    compute a discretization of a snail curve in polar coordinates
+
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.3 + np.cos(phi)
+    >>> x, y = r*np.cos(phi), r*np.sin(phi)  # convert to Cartesian coordinates
+
+    Build an interpolating curve, parameterizing it by the angle
+
+    >>> spl = make_interp_spline(phi, np.c_[x, y])
+
+    Evaluate the interpolant on a finer grid (note that we transpose the result
+    to unpack it into a pair of x- and y-arrays)
+
+    >>> phi_new = np.linspace(0, 2.*np.pi, 100)
+    >>> x_new, y_new = spl(phi_new).T
+
+    Plot the result
+
+    >>> plt.plot(x, y, 'o')
+    >>> plt.plot(x_new, y_new, '-')
+    >>> plt.show()
+
+    Build a B-spline curve with 2 dimensional y
+
+    >>> x = np.linspace(0, 2*np.pi, 10)
+    >>> y = np.array([np.sin(x), np.cos(x)])
+
+    Periodic condition is satisfied because y coordinates of points on the ends
+    are equivalent
+
+    >>> ax = plt.axes(projection='3d')
+    >>> xx = np.linspace(0, 2*np.pi, 100)
+    >>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
+    >>> ax.plot3D(xx, *bspl(xx))
+    >>> ax.scatter3D(x, *y, color='red')
+    >>> plt.show()
+
+    """
+    # convert string aliases for the boundary conditions
+    if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic':
+        deriv_l, deriv_r = None, None
+    elif isinstance(bc_type, str):
+        deriv_l, deriv_r = bc_type, bc_type
+    else:
+        try:
+            deriv_l, deriv_r = bc_type
+        except TypeError as e:
+            raise ValueError(f"Unknown boundary condition: {bc_type}") from e
+
+    y = np.asarray(y)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+
+    # sanity check the input
+    if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15):
+        raise ValueError("First and last points does not match while "
+                         "periodic case expected")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if np.any(x[1:] == x[:-1]):
+        raise ValueError("Expect x to not have duplicates")
+    if x.ndim != 1 or np.any(x[1:] < x[:-1]):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+
+    # special-case k=0 right away
+    if k == 0:
+        if any(_ is not None for _ in (t, deriv_l, deriv_r)):
+            raise ValueError("Too much info for k=0: t and bc_type can only "
+                             "be None.")
+        t = np.r_[x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # special-case k=1 (e.g., Lyche and Morken, Eq.(2.16))
+    if k == 1 and t is None:
+        if not (deriv_l is None and deriv_r is None):
+            raise ValueError("Too much info for k=1: bc_type can only be None.")
+        t = np.r_[x[0], x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    k = operator.index(k)
+
+    if bc_type == 'periodic' and t is not None:
+        raise NotImplementedError("For periodic case t is constructed "
+                                  "automatically and can not be passed "
+                                  "manually")
+
+    # come up with a sensible knot vector, if needed
+    if t is None:
+        if deriv_l is None and deriv_r is None:
+            if bc_type == 'periodic':
+                t = _periodic_knots(x, k)
+            else:
+                t = _not_a_knot(x, k)
+        else:
+            t = _augknt(x, k)
+
+    t = _as_float_array(t, check_finite)
+
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+        raise ValueError("Expect t to be a 1-D sorted array_like.")
+    if t.size < x.size + k + 1:
+        raise ValueError('Got %d knots, need at least %d.' %
+                         (t.size, x.size + k + 1))
+    if (x[0] < t[k]) or (x[-1] > t[-k]):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+
+    if bc_type == 'periodic':
+        return _make_periodic_spline(x, y, t, k, axis)
+
+    # Here : deriv_l, r = [(nu, value), ...]
+    deriv_l = _convert_string_aliases(deriv_l, y.shape[1:])
+    deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l)
+    nleft = deriv_l_ords.shape[0]
+
+    deriv_r = _convert_string_aliases(deriv_r, y.shape[1:])
+    deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r)
+    nright = deriv_r_ords.shape[0]
+
+    if not all(0 <= i <= k for i in deriv_l_ords):
+        raise ValueError(f"Bad boundary conditions at {x[0]}.")
+
+    if not all(0 <= i <= k for i in deriv_r_ords):
+        raise ValueError(f"Bad boundary conditions at {x[-1]}.")
+
+    # have `n` conditions for `nt` coefficients; need nt-n derivatives
+    n = x.size
+    nt = t.size - k - 1
+
+    if nt - n != nleft + nright:
+        raise ValueError("The number of derivatives at boundaries does not "
+                         f"match: expected {nt-n}, got {nleft}+{nright}")
+
+    # bail out if the `y` array is zero-sized
+    if y.size == 0:
+        c = np.zeros((nt,) + y.shape[1:], dtype=float)
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # set up the LHS: the colocation matrix + derivatives at boundaries
+    # NB: ab is in F order for banded LAPACK; _coloc needs C-ordered arrays,
+    #     this pass ab.T into _coloc
+    kl = ku = k
+    ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F')
+    _dierckx._coloc(x, t, k, ab.T, nleft)
+    if nleft > 0:
+        _handle_lhs_derivatives(t, k, x[0], ab, kl, ku, deriv_l_ords)
+    if nright > 0:
+        _handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, deriv_r_ords,
+                                offset=nt-nright)
+
+    # set up the RHS: values to interpolate (+ derivative values, if any)
+    extradim = prod(y.shape[1:])
+    rhs = np.empty((nt, extradim), dtype=y.dtype)
+    if nleft > 0:
+        rhs[:nleft] = deriv_l_vals.reshape(-1, extradim)
+    rhs[nleft:nt - nright] = y.reshape(-1, extradim)
+    if nright > 0:
+        rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim)
+
+    # solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded
+    if check_finite:
+        ab, rhs = map(np.asarray_chkfinite, (ab, rhs))
+    gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs))
+    lu, piv, c, info = gbsv(kl, ku, ab, rhs,
+                            overwrite_ab=True, overwrite_b=True)
+
+    if info > 0:
+        raise LinAlgError("Colocation matrix is singular.")
+    elif info < 0:
+        raise ValueError('illegal value in %d-th argument of internal gbsv' % -info)
+
+    c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:]))
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"):
+    r"""Compute the (coefficients of) an LSQ (Least SQuared) based
+    fitting B-spline.
+
+    The result is a linear combination
+
+    .. math::
+
+            S(x) = \sum_j c_j B_j(x; t)
+
+    of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes
+
+    .. math::
+
+        \sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2
+
+    Parameters
+    ----------
+    x : array_like, shape (m,)
+        Abscissas.
+    y : array_like, shape (m, ...)
+        Ordinates.
+    t : array_like, shape (n + k + 1,).
+        Knots.
+        Knots and data points must satisfy Schoenberg-Whitney conditions.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    w : array_like, shape (m,), optional
+        Weights for spline fitting. Must be positive. If ``None``,
+        then weights are all equal.
+        Default is ``None``.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+    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.
+        Default is True.
+    method : str, optional
+        Method for solving the linear LSQ problem. Allowed values are "norm-eq"
+        (Explicitly construct and solve the normal system of equations), and
+        "qr" (Use the QR factorization of the design matrix).
+        Default is "qr".
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    make_interp_spline : a similar factory function for interpolating splines
+    LSQUnivariateSpline : a FITPACK-based spline fitting routine
+    splrep : a FITPACK-based fitting routine
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree ``k``.
+
+    Knots ``t`` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    Generate some noisy data:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Now fit a smoothing cubic spline with a pre-defined internal knots.
+    Here we make the knot vector (k+1)-regular by adding boundary knots:
+
+    >>> from scipy.interpolate import make_lsq_spline, BSpline
+    >>> t = [-1, 0, 1]
+    >>> k = 3
+    >>> t = np.r_[(x[0],)*(k+1),
+    ...           t,
+    ...           (x[-1],)*(k+1)]
+    >>> spl = make_lsq_spline(x, y, t, k)
+
+    For comparison, we also construct an interpolating spline for the same
+    set of data:
+
+    >>> from scipy.interpolate import make_interp_spline
+    >>> spl_i = make_interp_spline(x, y)
+
+    Plot both:
+
+    >>> xs = np.linspace(-3, 3, 100)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline')
+    >>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    **NaN handling**: If the input arrays contain ``nan`` values, the result is
+    not useful since the underlying spline fitting routines cannot deal with
+    ``nan``. A workaround is to use zero weights for not-a-number data points:
+
+    >>> y[8] = np.nan
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> tck = make_lsq_spline(x, y, t, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    """
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+    t = _as_float_array(t, check_finite)
+    if w is not None:
+        w = _as_float_array(w, check_finite)
+    else:
+        w = np.ones_like(x)
+    k = operator.index(k)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+
+    if x.ndim != 1:
+        raise ValueError("Expect x to be a 1-D sequence.")
+    if x.shape[0] < k+1:
+        raise ValueError("Need more x points.")
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0):
+        raise ValueError("Expect t to be a 1D strictly increasing sequence.")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if k > 0 and np.any((x < t[k]) | (x > t[-k])):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+    if x.size != w.size:
+        raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible')
+    if method == "norm-eq" and np.any(x[1:] - x[:-1] <= 0):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+    if method == "qr" and any(x[1:] - x[:-1] < 0):
+        raise ValueError("Expect x to be a 1D non-decreasing sequence.")
+
+    # number of coefficients
+    n = t.size - k - 1
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    if method == "norm-eq":
+        # construct A.T @ A and rhs with A the colocation matrix, and
+        # rhs = A.T @ y for solving the LSQ problem  ``A.T @ A @ c = A.T @ y``
+        lower = True
+        ab = np.zeros((k+1, n), dtype=np.float64, order='F')
+        rhs = np.zeros((n, extradim), dtype=np.float64)
+        _dierckx._norm_eq_lsq(x, t, k,
+                              yy,
+                              w,
+                              ab.T, rhs)
+
+        # undo complex -> float and flattening the trailing dims
+        if was_complex:
+            rhs = rhs.view(complex)
+
+        rhs = rhs.reshape((n,) + y.shape[1:])
+
+        # have observation matrix & rhs, can solve the LSQ problem
+        cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower,
+                                     check_finite=check_finite)
+        c = cho_solve_banded((cho_decomp, lower), rhs, overwrite_b=True,
+                             check_finite=check_finite)
+    elif method == "qr":
+        _, _, c = _lsq_solve_qr(x, yy, t, k, w)
+
+        if was_complex:
+            c = c.view(complex)
+
+    else:
+        raise ValueError(f"Unknown {method =}.")
+
+
+    # restore the shape of `c` for both single and multiple r.h.s.
+    c = c.reshape((n,) + y.shape[1:])
+    c = np.ascontiguousarray(c)
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+######################
+# LSQ spline helpers #
+######################
+
+def _lsq_solve_qr(x, y, t, k, w):
+    """Solve for the LSQ spline coeffs given x, y and knots.
+
+    `y` is always 2D: for 1D data, the shape is ``(m, 1)``.
+    `w` is always 1D: one weight value per `x` value.
+
+    """
+    assert y.ndim == 2
+
+    y_w = y * w[:, None]
+    A, offset, nc = _dierckx.data_matrix(x, t, k, w)
+    _dierckx.qr_reduce(A, offset, nc, y_w)         # modifies arguments in-place
+    c = _dierckx.fpback(A, nc, y_w)
+
+    return A, y_w, c
+
+
+#############################
+#  Smoothing spline helpers #
+#############################
+
+def _compute_optimal_gcv_parameter(X, wE, y, w):
+    """
+    Returns an optimal regularization parameter from the GCV criteria [1].
+
+    Parameters
+    ----------
+    X : array, shape (5, n)
+        5 bands of the design matrix ``X`` stored in LAPACK banded storage.
+    wE : array, shape (5, n)
+        5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded
+        storage.
+    y : array, shape (n,)
+        Ordinates.
+    w : array, shape (n,)
+        Vector of weights.
+
+    Returns
+    -------
+    lam : float
+        An optimal from the GCV criteria point of view regularization
+        parameter.
+
+    Notes
+    -----
+    No checks are performed.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+        for observational data, Philadelphia, Pennsylvania: Society for
+        Industrial and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+
+    """
+
+    def compute_banded_symmetric_XT_W_Y(X, w, Y):
+        """
+        Assuming that the product :math:`X^T W Y` is symmetric and both ``X``
+        and ``Y`` are 5-banded, compute the unique bands of the product.
+
+        Parameters
+        ----------
+        X : array, shape (5, n)
+            5 bands of the matrix ``X`` stored in LAPACK banded storage.
+        w : array, shape (n,)
+            Array of weights
+        Y : array, shape (5, n)
+            5 bands of the matrix ``Y`` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : array, shape (4, n)
+            The result of the product :math:`X^T Y` stored in the banded way.
+
+        Notes
+        -----
+        As far as the matrices ``X`` and ``Y`` are 5-banded, their product
+        :math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only
+        unique diagonals.
+
+        """
+        # compute W Y
+        W_Y = np.copy(Y)
+
+        W_Y[2] *= w
+        for i in range(2):
+            W_Y[i, 2 - i:] *= w[:-2 + i]
+            W_Y[3 + i, :-1 - i] *= w[1 + i:]
+
+        n = X.shape[1]
+        res = np.zeros((4, n))
+        for i in range(n):
+            for j in range(min(n-i, 4)):
+                res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j])
+        return res
+
+    def compute_b_inv(A):
+        """
+        Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that
+        ``U`` is a unit upper triangular banded matrix using an algorithm
+        proposed in [1].
+
+        Parameters
+        ----------
+        A : array, shape (4, n)
+            Matrix to inverse, stored in LAPACK banded storage.
+
+        Returns
+        -------
+        B : array, shape (4, n)
+            3 unique bands of the symmetric matrix that is an inverse to ``A``.
+            The first row is filled with zeros.
+
+        Notes
+        -----
+        The algorithm is based on the cholesky decomposition and, therefore,
+        in case matrix ``A`` is close to not positive defined, the function
+        raises LinalgError.
+
+        Both matrices ``A`` and ``B`` are stored in LAPACK banded storage.
+
+        References
+        ----------
+        .. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+
+        """
+
+        def find_b_inv_elem(i, j, U, D, B):
+            rng = min(3, n - i - 1)
+            rng_sum = 0.
+            if j == 0:
+                # use 2-nd formula from [1]
+                for k in range(1, rng + 1):
+                    rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k]
+                rng_sum += D[i]
+                B[-1, i] = rng_sum
+            else:
+                # use 1-st formula from [1]
+                for k in range(1, rng + 1):
+                    diag = abs(k - j)
+                    ind = i + min(k, j)
+                    rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag]
+                B[-j - 1, i + j] = rng_sum
+
+        U = cholesky_banded(A)
+        for i in range(2, 5):
+            U[-i, i-1:] /= U[-1, :-i+1]
+        D = 1. / (U[-1])**2
+        U[-1] /= U[-1]
+
+        n = U.shape[1]
+
+        B = np.zeros(shape=(4, n))
+        for i in range(n - 1, -1, -1):
+            for j in range(min(3, n - i - 1), -1, -1):
+                find_b_inv_elem(i, j, U, D, B)
+        # the first row contains garbage and should be removed
+        B[0] = [0.] * n
+        return B
+
+    def _gcv(lam, X, XtWX, wE, XtE):
+        r"""
+        Computes the generalized cross-validation criteria [1].
+
+        Parameters
+        ----------
+        lam : float, (:math:`\lambda \geq 0`)
+            Regularization parameter.
+        X : array, shape (5, n)
+            Matrix is stored in LAPACK banded storage.
+        XtWX : array, shape (4, n)
+            Product :math:`X^T W X` stored in LAPACK banded storage.
+        wE : array, shape (5, n)
+            Matrix :math:`W^{-1} E` stored in LAPACK banded storage.
+        XtE : array, shape (4, n)
+            Product :math:`X^T E` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : float
+            Value of the GCV criteria with the regularization parameter
+            :math:`\lambda`.
+
+        Notes
+        -----
+        Criteria is computed from the formula (1.3.2) [3]:
+
+        .. math:
+
+        GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left(
+        y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}$.
+        The criteria is discussed in section 1.3 [3].
+
+        The numerator is computed using (2.2.4) [3] and the denominator is
+        computed using an algorithm from [2] (see in the ``compute_b_inv``
+        function).
+
+        References
+        ----------
+        .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+            for observational data, Philadelphia, Pennsylvania: Society for
+            Industrial and Applied Mathematics, 1990, pp. 45-65.
+            :doi:`10.1137/1.9781611970128`
+        .. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+        .. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+            BSc thesis, 2022. Might be available (in Russian)
+            `here `_
+
+        """
+        # Compute the numerator from (2.2.4) [3]
+        n = X.shape[1]
+        c = solve_banded((2, 2), X + lam * wE, y)
+        res = np.zeros(n)
+        # compute ``W^{-1} E c`` with respect to banded-storage of ``E``
+        tmp = wE * c
+        for i in range(n):
+            for j in range(max(0, i - n + 3), min(5, i + 3)):
+                res[i] += tmp[j, i + 2 - j]
+        numer = np.linalg.norm(lam * res)**2 / n
+
+        # compute the denominator
+        lhs = XtWX + lam * XtE
+        try:
+            b_banded = compute_b_inv(lhs)
+            # compute the trace of the product b_banded @ XtX
+            tr = b_banded * XtWX
+            tr[:-1] *= 2
+            # find the denominator
+            denom = (1 - sum(sum(tr)) / n)**2
+        except LinAlgError:
+            # cholesky decomposition cannot be performed
+            raise ValueError('Seems like the problem is ill-posed')
+
+        res = numer / denom
+
+        return res
+
+    n = X.shape[1]
+
+    XtWX = compute_banded_symmetric_XT_W_Y(X, w, X)
+    XtE = compute_banded_symmetric_XT_W_Y(X, w, wE)
+
+    def fun(lam):
+        return _gcv(lam, X, XtWX, wE, XtE)
+
+    gcv_est = minimize_scalar(fun, bounds=(0, n), method='Bounded')
+    if gcv_est.success:
+        return gcv_est.x
+    raise ValueError(f"Unable to find minimum of the GCV "
+                     f"function: {gcv_est.message}")
+
+
+def _coeff_of_divided_diff(x):
+    """
+    Returns the coefficients of the divided difference.
+
+    Parameters
+    ----------
+    x : array, shape (n,)
+        Array which is used for the computation of divided difference.
+
+    Returns
+    -------
+    res : array_like, shape (n,)
+        Coefficients of the divided difference.
+
+    Notes
+    -----
+    Vector ``x`` should have unique elements, otherwise an error division by
+    zero might be raised.
+
+    No checks are performed.
+
+    """
+    n = x.shape[0]
+    res = np.zeros(n)
+    for i in range(n):
+        pp = 1.
+        for k in range(n):
+            if k != i:
+                pp *= (x[i] - x[k])
+        res[i] = 1. / pp
+    return res
+
+
+def make_smoothing_spline(x, y, w=None, lam=None):
+    r"""
+    Compute the (coefficients of) smoothing cubic spline function using
+    ``lam`` to control the tradeoff between the amount of smoothness of the
+    curve and its proximity to the data. In case ``lam`` is None, using the
+    GCV criteria [1] to find it.
+
+    A smoothing spline is found as a solution to the regularized weighted
+    linear regression problem:
+
+    .. math::
+
+        \sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 +
+        \lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u
+
+    where :math:`f` is a spline function, :math:`w` is a vector of weights and
+    :math:`\lambda` is a regularization parameter.
+
+    If ``lam`` is None, we use the GCV criteria to find an optimal
+    regularization parameter, otherwise we solve the regularized weighted
+    linear regression problem with given parameter. The parameter controls
+    the tradeoff in the following way: the larger the parameter becomes, the
+    smoother the function gets.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas. `n` must be at least 5.
+    y : array_like, shape (n,)
+        Ordinates. `n` must be at least 5.
+    w : array_like, shape (n,), optional
+        Vector of weights. Default is ``np.ones_like(x)``.
+    lam : float, (:math:`\lambda \geq 0`), optional
+        Regularization parameter. If ``lam`` is None, then it is found from
+        the GCV criteria. Default is None.
+
+    Returns
+    -------
+    func : a BSpline object.
+        A callable representing a spline in the B-spline basis
+        as a solution of the problem of smoothing splines using
+        the GCV criteria [1] in case ``lam`` is None, otherwise using the
+        given parameter ``lam``.
+
+    Notes
+    -----
+    This algorithm is a clean room reimplementation of the algorithm
+    introduced by Woltring in FORTRAN [2]. The original version cannot be used
+    in SciPy source code because of the license issues. The details of the
+    reimplementation are discussed here (available only in Russian) [4].
+
+    If the vector of weights ``w`` is None, we assume that all the points are
+    equal in terms of weights, and vector of weights is vector of ones.
+
+    Note that in weighted residual sum of squares, weights are not squared:
+    :math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in
+    ``splrep`` the sum is built from the squared weights.
+
+    In cases when the initial problem is ill-posed (for example, the product
+    :math:`X^T W X` where :math:`X` is a design matrix is not a positive
+    defined matrix) a ValueError is raised.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for
+        observational data, Philadelphia, Pennsylvania: Society for Industrial
+        and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+    .. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory
+        spline smoothing and differentiation, Advances in Engineering
+        Software, vol. 8, no. 2, pp. 104-113, 1986.
+        :doi:`10.1016/0141-1195(86)90098-7`
+    .. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in
+        The elements of Statistical Learning: Data Mining, Inference, and
+        prediction, New York: Springer, 2017, pp. 241-249.
+        :doi:`10.1007/978-0-387-84858-7`
+    .. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+        BSc thesis, 2022.
+        ``_ (in
+        Russian)
+
+    Examples
+    --------
+    Generate some noisy data
+
+    >>> import numpy as np
+    >>> np.random.seed(1234)
+    >>> n = 200
+    >>> def func(x):
+    ...    return x**3 + x**2 * np.sin(4 * x)
+    >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
+    >>> y = func(x) + np.random.normal(scale=1.5, size=n)
+
+    Make a smoothing spline function
+
+    >>> from scipy.interpolate import make_smoothing_spline
+    >>> spl = make_smoothing_spline(x, y)
+
+    Plot both
+
+    >>> import matplotlib.pyplot as plt
+    >>> grid = np.linspace(x[0], x[-1], 400)
+    >>> plt.plot(grid, spl(grid), label='Spline')
+    >>> plt.plot(grid, func(grid), label='Original function')
+    >>> plt.scatter(x, y, marker='.')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+
+    x = np.ascontiguousarray(x, dtype=float)
+    y = np.ascontiguousarray(y, dtype=float)
+
+    if any(x[1:] - x[:-1] <= 0):
+        raise ValueError('``x`` should be an ascending array')
+
+    if x.ndim != 1 or y.ndim != 1 or x.shape[0] != y.shape[0]:
+        raise ValueError('``x`` and ``y`` should be one dimensional and the'
+                         ' same size')
+
+    if w is None:
+        w = np.ones(len(x))
+    else:
+        w = np.ascontiguousarray(w)
+        if any(w <= 0):
+            raise ValueError('Invalid vector of weights')
+
+    t = np.r_[[x[0]] * 3, x, [x[-1]] * 3]
+    n = x.shape[0]
+
+    if n <= 4:
+        raise ValueError('``x`` and ``y`` length must be at least 5')
+
+    # It is known that the solution to the stated minimization problem exists
+    # and is a natural cubic spline with vector of knots equal to the unique
+    # elements of ``x`` [3], so we will solve the problem in the basis of
+    # natural splines.
+
+    # create design matrix in the B-spline basis
+    X_bspl = BSpline.design_matrix(x, t, 3)
+    # move from B-spline basis to the basis of natural splines using equations
+    # (2.1.7) [4]
+    # central elements
+    X = np.zeros((5, n))
+    for i in range(1, 4):
+        X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)]
+
+    # first elements
+    X[1, 1] = X_bspl[0, 0]
+    X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0],
+                X_bspl[1, 1] + X_bspl[1, 2])
+    X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2])
+
+    # last elements
+    X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2])
+    X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2],
+                 (2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1])
+    X[3, -2] = X_bspl[-1, -1]
+
+    # create penalty matrix and divide it by vector of weights: W^{-1} E
+    wE = np.zeros((5, n))
+    wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3]
+    wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4]
+    for j in range(2, n - 2):
+        wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\
+                   / w[j-2: j+3]
+
+    wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:]
+    wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:]
+    wE *= 6
+
+    if lam is None:
+        lam = _compute_optimal_gcv_parameter(X, wE, y, w)
+    elif lam < 0.:
+        raise ValueError('Regularization parameter should be non-negative')
+
+    # solve the initial problem in the basis of natural splines
+    c = solve_banded((2, 2), X + lam * wE, y)
+    # move back to B-spline basis using equations (2.2.10) [4]
+    c_ = np.r_[c[0] * (t[5] + t[4] - 2 * t[3]) + c[1],
+               c[0] * (t[5] - t[3]) + c[1],
+               c[1: -1],
+               c[-1] * (t[-4] - t[-6]) + c[-2],
+               c[-1] * (2 * t[-4] - t[-5] - t[-6]) + c[-2]]
+
+    return BSpline.construct_fast(t, c_, 3)
+
+
+########################
+#  FITPACK look-alikes #
+########################
+
+def fpcheck(x, t, k):
+    """ Check consistency of the data vector `x` and the knot vector `t`.
+
+    Return None if inputs are consistent, raises a ValueError otherwise.
+    """
+    # This routine is a clone of the `fpchec` Fortran routine,
+    # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
+    # which carries the following comment:
+    #
+    # subroutine fpchec verifies the number and the position of the knots
+    #  t(j),j=1,2,...,n of a spline of degree k, in relation to the number
+    #  and the position of the data points x(i),i=1,2,...,m. if all of the
+    #  following conditions are fulfilled, the error parameter ier is set
+    #  to zero. if one of the conditions is violated ier is set to ten.
+    #      1) k+1 <= n-k-1 <= m
+    #      2) t(1) <= t(2) <= ... <= t(k+1)
+    #         t(n-k) <= t(n-k+1) <= ... <= t(n)
+    #      3) t(k+1) < t(k+2) < ... < t(n-k)
+    #      4) t(k+1) <= x(i) <= t(n-k)
+    #      5) the conditions specified by schoenberg and whitney must hold
+    #         for at least one subset of data points, i.e. there must be a
+    #         subset of data points y(j) such that
+    #             t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+    x = np.asarray(x)
+    t = np.asarray(t)
+
+    if x.ndim != 1 or t.ndim != 1:
+        raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }")
+
+    m = x.shape[0]
+    n = t.shape[0]
+    nk1 = n - k - 1
+
+    # check condition no 1
+    # c      1) k+1 <= n-k-1 <= m
+    if not (k + 1 <= nk1 <= m):
+        raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.")
+
+    # check condition no 2
+    # c      2) t(1) <= t(2) <= ... <= t(k+1)
+    # c         t(n-k) <= t(n-k+1) <= ... <= t(n)
+    if (t[:k+1] > t[1:k+2]).any():
+        raise ValueError(f"First k knots must be ordered; got {t = }.")
+
+    if (t[nk1:] < t[nk1-1:-1]).any():
+        raise ValueError(f"Last k knots must be ordered; got {t = }.")
+
+    # c  check condition no 3
+    # c      3) t(k+1) < t(k+2) < ... < t(n-k)
+    if (t[k+1:n-k] <= t[k:n-k-1]).any():
+        raise ValueError(f"Internal knots must be distinct. Got {t = }.")
+
+    # c  check condition no 4
+    # c      4) t(k+1) <= x(i) <= t(n-k)
+    # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
+    if (x[0] < t[k]) or (x[-1] > t[n-k-1]):
+        raise ValueError(f"Out of bounds: {x = } and {t = }.")
+
+    # c  check condition no 5
+    # c      5) the conditions specified by schoenberg and whitney must hold
+    # c         for at least one subset of data points, i.e. there must be a
+    # c         subset of data points y(j) such that
+    # c             t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+    mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}."
+
+    if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]):
+        raise ValueError(mesg)
+
+    m = x.shape[0]
+    l = k+1
+    nk3 = n - k - 3
+    if nk3 < 2:
+        return
+    for j in range(1, nk3+1):
+        tj = t[j]
+        l += 1
+        tl = t[l]
+        i = np.argmax(x > tj)
+        if i >= m-1:
+            raise ValueError(mesg)
+        if x[i] >= tl:
+            raise ValueError(mesg)
+    return
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_cubic.py b/python_embeded/Lib/site-packages/scipy/interpolate/_cubic.py
new file mode 100644
index 0000000000000000000000000000000000000000..f10d0f00d8790205f64f50e919a69241c0033373
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_cubic.py
@@ -0,0 +1,958 @@
+"""Interpolation algorithms using piecewise cubic polynomials."""
+
+from typing import Literal
+
+import numpy as np
+
+from scipy.linalg import solve, solve_banded
+
+from . import PPoly
+from ._polyint import _isscalar
+
+__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate",
+           "Akima1DInterpolator", "CubicSpline"]
+
+
+def prepare_input(x, y, axis, dydx=None):
+    """Prepare input for cubic spline interpolators.
+
+    All data are converted to numpy arrays and checked for correctness.
+    Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th
+    axis. The value of `axis` is converted to lie in
+    [0, number of dimensions of `y`).
+    """
+
+    x, y = map(np.asarray, (x, y))
+    if np.issubdtype(x.dtype, np.complexfloating):
+        raise ValueError("`x` must contain real values.")
+    x = x.astype(float)
+
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+
+    if dydx is not None:
+        dydx = np.asarray(dydx)
+        if y.shape != dydx.shape:
+            raise ValueError("The shapes of `y` and `dydx` must be identical.")
+        if np.issubdtype(dydx.dtype, np.complexfloating):
+            dtype = complex
+        dydx = dydx.astype(dtype, copy=False)
+
+    y = y.astype(dtype, copy=False)
+    axis = axis % y.ndim
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1-dimensional.")
+    if x.shape[0] < 2:
+        raise ValueError("`x` must contain at least 2 elements.")
+    if x.shape[0] != y.shape[axis]:
+        raise ValueError(f"The length of `y` along `axis`={axis} doesn't "
+                         "match the length of `x`")
+
+    if not np.all(np.isfinite(x)):
+        raise ValueError("`x` must contain only finite values.")
+    if not np.all(np.isfinite(y)):
+        raise ValueError("`y` must contain only finite values.")
+
+    if dydx is not None and not np.all(np.isfinite(dydx)):
+        raise ValueError("`dydx` must contain only finite values.")
+
+    dx = np.diff(x)
+    if np.any(dx <= 0):
+        raise ValueError("`x` must be strictly increasing sequence.")
+
+    y = np.moveaxis(y, axis, 0)
+    if dydx is not None:
+        dydx = np.moveaxis(dydx, axis, 0)
+
+    return x, dx, y, axis, dydx
+
+
+class CubicHermiteSpline(PPoly):
+    """Piecewise-cubic interpolator matching values and first derivatives.
+
+    The result is represented as a `PPoly` instance.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    dydx : array_like
+        Array containing derivatives of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    If you want to create a higher-order spline matching higher-order
+    derivatives, use `BPoly.from_derivatives`.
+
+    References
+    ----------
+    .. [1] `Cubic Hermite spline
+            `_
+            on Wikipedia.
+    """
+
+    def __init__(self, x, y, dydx, axis=0, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = True
+
+        x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx)
+
+        dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+        slope = np.diff(y, axis=0) / dxr
+        t = (dydx[:-1] + dydx[1:] - 2 * slope) / dxr
+
+        c = np.empty((4, len(x) - 1) + y.shape[1:], dtype=t.dtype)
+        c[0] = t / dxr
+        c[1] = (slope - dydx[:-1]) / dxr - t
+        c[2] = dydx[:-1]
+        c[3] = y[:-1]
+
+        super().__init__(c, x, extrapolate=extrapolate)
+        self.axis = axis
+
+
+class PchipInterpolator(CubicHermiteSpline):
+    r"""PCHIP 1-D monotonic cubic interpolation.
+
+    ``x`` and ``y`` are arrays of values used to approximate some function f,
+    with ``y = f(x)``. The interpolant uses monotonic cubic splines
+    to find the value of new points. (PCHIP stands for Piecewise Cubic
+    Hermite Interpolating Polynomial).
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        A 1-D array of monotonically increasing real values. ``x`` cannot
+        include duplicate values (otherwise f is overspecified)
+    y : ndarray, shape (..., npoints, ...)
+        A N-D array of real values. ``y``'s length along the interpolation
+        axis must be equal to the length of ``x``. Use the ``axis``
+        parameter to select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    extrapolate : bool, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    roots
+
+    See Also
+    --------
+    CubicHermiteSpline : Piecewise-cubic interpolator.
+    Akima1DInterpolator : Akima 1D interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    The interpolator preserves monotonicity in the interpolation data and does
+    not overshoot if the data is not smooth.
+
+    The first derivatives are guaranteed to be continuous, but the second
+    derivatives may jump at :math:`x_k`.
+
+    Determines the derivatives at the points :math:`x_k`, :math:`f'_k`,
+    by using PCHIP algorithm [1]_.
+
+    Let :math:`h_k = x_{k+1} - x_k`, and  :math:`d_k = (y_{k+1} - y_k) / h_k`
+    are the slopes at internal points :math:`x_k`.
+    If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of
+    them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the
+    weighted harmonic mean
+
+    .. math::
+
+        \frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k}
+
+    where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`.
+
+    The end slopes are set using a one-sided scheme [2]_.
+
+
+    References
+    ----------
+    .. [1] F. N. Fritsch and J. Butland,
+           A method for constructing local
+           monotone piecewise cubic interpolants,
+           SIAM J. Sci. Comput., 5(2), 300-304 (1984).
+           :doi:`10.1137/0905021`.
+    .. [2] see, e.g., C. Moler, Numerical Computing with Matlab, 2004.
+           :doi:`10.1137/1.9780898717952`
+
+    """
+
+    def __init__(self, x, y, axis=0, extrapolate=None):
+        x, _, y, axis, _ = prepare_input(x, y, axis)
+        if np.iscomplexobj(y):
+            msg = ("`PchipInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to `PchipInterpolator`.")
+            raise ValueError(msg)
+        xp = x.reshape((x.shape[0],) + (1,)*(y.ndim-1))
+        dk = self._find_derivatives(xp, y)
+        super().__init__(x, y, dk, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _edge_case(h0, h1, m0, m1):
+        # one-sided three-point estimate for the derivative
+        d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
+
+        # try to preserve shape
+        mask = np.sign(d) != np.sign(m0)
+        mask2 = (np.sign(m0) != np.sign(m1)) & (np.abs(d) > 3.*np.abs(m0))
+        mmm = (~mask) & mask2
+
+        d[mask] = 0.
+        d[mmm] = 3.*m0[mmm]
+
+        return d
+
+    @staticmethod
+    def _find_derivatives(x, y):
+        # Determine the derivatives at the points y_k, d_k, by using
+        #  PCHIP algorithm is:
+        # We choose the derivatives at the point x_k by
+        # Let m_k be the slope of the kth segment (between k and k+1)
+        # If m_k=0 or m_{k-1}=0 or sgn(m_k) != sgn(m_{k-1}) then d_k == 0
+        # else use weighted harmonic mean:
+        #   w_1 = 2h_k + h_{k-1}, w_2 = h_k + 2h_{k-1}
+        #   1/d_k = 1/(w_1 + w_2)*(w_1 / m_k + w_2 / m_{k-1})
+        #   where h_k is the spacing between x_k and x_{k+1}
+        y_shape = y.shape
+        if y.ndim == 1:
+            # So that _edge_case doesn't end up assigning to scalars
+            x = x[:, None]
+            y = y[:, None]
+
+        hk = x[1:] - x[:-1]
+        mk = (y[1:] - y[:-1]) / hk
+
+        if y.shape[0] == 2:
+            # edge case: only have two points, use linear interpolation
+            dk = np.zeros_like(y)
+            dk[0] = mk
+            dk[1] = mk
+            return dk.reshape(y_shape)
+
+        smk = np.sign(mk)
+        condition = (smk[1:] != smk[:-1]) | (mk[1:] == 0) | (mk[:-1] == 0)
+
+        w1 = 2*hk[1:] + hk[:-1]
+        w2 = hk[1:] + 2*hk[:-1]
+
+        # values where division by zero occurs will be excluded
+        # by 'condition' afterwards
+        with np.errstate(divide='ignore', invalid='ignore'):
+            whmean = (w1/mk[:-1] + w2/mk[1:]) / (w1 + w2)
+
+        dk = np.zeros_like(y)
+        dk[1:-1][condition] = 0.0
+        dk[1:-1][~condition] = 1.0 / whmean[~condition]
+
+        # special case endpoints, as suggested in
+        # Cleve Moler, Numerical Computing with MATLAB, Chap 3.6 (pchiptx.m)
+        dk[0] = PchipInterpolator._edge_case(hk[0], hk[1], mk[0], mk[1])
+        dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2])
+
+        return dk.reshape(y_shape)
+
+
+def pchip_interpolate(xi, yi, x, der=0, axis=0):
+    """
+    Convenience function for pchip interpolation.
+
+    xi and yi are arrays of values used to approximate some function f,
+    with ``yi = f(xi)``. The interpolant uses monotonic cubic splines
+    to find the value of new points x and the derivatives there.
+
+    See `scipy.interpolate.PchipInterpolator` for details.
+
+    Parameters
+    ----------
+    xi : array_like
+        A sorted list of x-coordinates, of length N.
+    yi : array_like
+        A 1-D array of real values. `yi`'s length along the interpolation
+        axis must be equal to the length of `xi`. If N-D array, use axis
+        parameter to select correct axis.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated and will raise an error in
+            SciPy 1.15.0. If you are trying to use the real components of
+            the passed array, use ``np.real`` on `yi`.
+
+    x : scalar or array_like
+        Of length M.
+    der : int or list, optional
+        Derivatives to extract. The 0th derivative can be included to
+        return the function value.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    y : scalar or array_like
+        The result, of length R or length M or M by R.
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using pchip interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import pchip_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = pchip_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="pchip interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = PchipInterpolator(xi, yi, axis=axis)
+
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(der)(x)
+    else:
+        return [P.derivative(nu)(x) for nu in der]
+
+
+class Akima1DInterpolator(CubicHermiteSpline):
+    r"""
+    Akima interpolator
+
+    Fit piecewise cubic polynomials, given vectors x and y. The interpolation
+    method by Akima uses a continuously differentiable sub-spline built from
+    piecewise cubic polynomials. The resultant curve passes through the given
+    data points and will appear smooth and natural.
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        1-D array of monotonically increasing real values.
+    y : ndarray, shape (..., npoints, ...)
+        N-D array of real values. The length of ``y`` along the interpolation axis
+        must be equal to the length of ``x``. Use the ``axis`` parameter to
+        select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    method : {'akima', 'makima'}, optional
+        If ``"makima"``, use the modified Akima interpolation [2]_.
+        Defaults to ``"akima"``, use the Akima interpolation [1]_.
+
+        .. versionadded:: 1.13.0
+
+    extrapolate : {bool, None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points 
+        based on first and last intervals, or to return NaNs. If None, 
+        ``extrapolate`` is set to False.
+        
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    roots
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    .. versionadded:: 0.14
+
+    Use only for precise data, as the fitted curve passes through the given
+    points exactly. This routine is useful for plotting a pleasingly smooth
+    curve through a few given points for purposes of plotting.
+
+    Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of
+    the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at
+    :math:`x_i` is defined as:
+
+    .. math::
+
+        d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i
+
+    In the Akima interpolation [1]_ (``method="akima"``), the weights are:
+
+    .. math::
+
+        \begin{aligned}
+        w_1 &= |\delta_{i+1} - \delta_i| \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}|
+        \end{aligned}
+
+    In the modified Akima interpolation [2]_ (``method="makima"``),
+    to eliminate overshoot and avoid edge cases of both numerator and
+    denominator being equal to 0, the weights are modified as follows:
+
+    .. math::
+
+        \begin{align*}
+        w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2
+        \end{align*}
+
+    Examples
+    --------
+    Comparison of ``method="akima"`` and ``method="makima"``:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import Akima1DInterpolator
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(1, 7, 7)
+    >>> y = np.array([-1, -1, -1, 0, 1, 1, 1])
+    >>> xs = np.linspace(min(x), max(x), num=100)
+    >>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
+    >>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, "o", label="data")
+    >>> ax.plot(xs, y_akima, label="akima")
+    >>> ax.plot(xs, y_makima, label="makima")
+    >>> ax.legend()
+    >>> fig.show()
+
+    The overshoot that occurred in ``"akima"`` has been avoided in ``"makima"``.
+
+    References
+    ----------
+    .. [1] A new method of interpolation and smooth curve fitting based
+           on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4),
+           589-602. :doi:`10.1145/321607.321609`
+    .. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019.
+           https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/
+
+    """
+
+    def __init__(self, x, y, axis=0, *, method: Literal["akima", "makima"]="akima", 
+                 extrapolate:bool | None = None):
+        if method not in {"akima", "makima"}:
+            raise NotImplementedError(f"`method`={method} is unsupported.")
+        # Original implementation in MATLAB by N. Shamsundar (BSD licensed), see
+        # https://www.mathworks.com/matlabcentral/fileexchange/1814-akima-interpolation
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+
+        if np.iscomplexobj(y):
+            msg = ("`Akima1DInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to "
+                   "`Akima1DInterpolator`.")
+            raise ValueError(msg)
+
+        # Akima extrapolation historically False; parent class defaults to True.
+        extrapolate = False if extrapolate is None else extrapolate
+
+        # determine slopes between breakpoints
+        m = np.empty((x.size + 3, ) + y.shape[1:])
+        dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)]
+        m[2:-2] = np.diff(y, axis=0) / dx
+
+        # add two additional points on the left ...
+        m[1] = 2. * m[2] - m[3]
+        m[0] = 2. * m[1] - m[2]
+        # ... and on the right
+        m[-2] = 2. * m[-3] - m[-4]
+        m[-1] = 2. * m[-2] - m[-3]
+
+        # if m1 == m2 != m3 == m4, the slope at the breakpoint is not
+        # defined. This is the fill value:
+        t = .5 * (m[3:] + m[:-3])
+        # get the denominator of the slope t
+        dm = np.abs(np.diff(m, axis=0))
+        if method == "makima":
+            pm = np.abs(m[1:] + m[:-1])
+            f1 = dm[2:] + 0.5 * pm[2:]
+            f2 = dm[:-2] + 0.5 * pm[:-2]
+        else:
+            f1 = dm[2:]
+            f2 = dm[:-2]
+        f12 = f1 + f2
+        # These are the mask of where the slope at breakpoint is defined:
+        ind = np.nonzero(f12 > 1e-9 * np.max(f12, initial=-np.inf))
+        x_ind, y_ind = ind[0], ind[1:]
+        # Set the slope at breakpoint
+        t[ind] = (f1[ind] * m[(x_ind + 1,) + y_ind] +
+                  f2[ind] * m[(x_ind + 2,) + y_ind]) / f12[ind]
+
+        super().__init__(x, y, t, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    def extend(self, c, x, right=True):
+        raise NotImplementedError("Extending a 1-D Akima interpolator is not "
+                                  "yet implemented")
+
+    # These are inherited from PPoly, but they do not produce an Akima
+    # interpolator. Hence stub them out.
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+
+class CubicSpline(CubicHermiteSpline):
+    """Cubic spline data interpolator.
+
+    Interpolate data with a piecewise cubic polynomial which is twice
+    continuously differentiable [1]_. The result is represented as a `PPoly`
+    instance with breakpoints matching the given data.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    bc_type : string or 2-tuple, optional
+        Boundary condition type. Two additional equations, given by the
+        boundary conditions, are required to determine all coefficients of
+        polynomials on each segment [2]_.
+
+        If `bc_type` is a string, then the specified condition will be applied
+        at both ends of a spline. Available conditions are:
+
+        * 'not-a-knot' (default): The first and second segment at a curve end
+          are the same polynomial. It is a good default when there is no
+          information on boundary conditions.
+        * 'periodic': The interpolated functions is assumed to be periodic
+          of period ``x[-1] - x[0]``. The first and last value of `y` must be
+          identical: ``y[0] == y[-1]``. This boundary condition will result in
+          ``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``.
+        * 'clamped': The first derivative at curves ends are zero. Assuming
+          a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition.
+        * 'natural': The second derivative at curve ends are zero. Assuming
+          a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition.
+
+        If `bc_type` is a 2-tuple, the first and the second value will be
+        applied at the curve start and end respectively. The tuple values can
+        be one of the previously mentioned strings (except 'periodic') or a
+        tuple ``(order, deriv_values)`` allowing to specify arbitrary
+        derivatives at curve ends:
+
+        * `order`: the derivative order, 1 or 2.
+        * `deriv_value`: array_like containing derivative values, shape must
+          be the same as `y`, excluding ``axis`` dimension. For example, if
+          `y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with
+          the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D
+          and have the shape (n0, n1).
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), ``extrapolate`` is
+        set to 'periodic' for ``bc_type='periodic'`` and to True otherwise.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    Parameters `bc_type` and ``extrapolate`` work independently, i.e. the
+    former controls only construction of a spline, and the latter only
+    evaluation.
+
+    When a boundary condition is 'not-a-knot' and n = 2, it is replaced by
+    a condition that the first derivative is equal to the linear interpolant
+    slope. When both boundary conditions are 'not-a-knot' and n = 3, the
+    solution is sought as a parabola passing through given points.
+
+    When 'not-a-knot' boundary conditions is applied to both ends, the
+    resulting spline will be the same as returned by `splrep` (with ``s=0``)
+    and `InterpolatedUnivariateSpline`, but these two methods use a
+    representation in B-spline basis.
+
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    In this example the cubic spline is used to interpolate a sampled sinusoid.
+    You can see that the spline continuity property holds for the first and
+    second derivatives and violates only for the third derivative.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import CubicSpline
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(10)
+    >>> y = np.sin(x)
+    >>> cs = CubicSpline(x, y)
+    >>> xs = np.arange(-0.5, 9.6, 0.1)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(x, y, 'o', label='data')
+    >>> ax.plot(xs, np.sin(xs), label='true')
+    >>> ax.plot(xs, cs(xs), label="S")
+    >>> ax.plot(xs, cs(xs, 1), label="S'")
+    >>> ax.plot(xs, cs(xs, 2), label="S''")
+    >>> ax.plot(xs, cs(xs, 3), label="S'''")
+    >>> ax.set_xlim(-0.5, 9.5)
+    >>> ax.legend(loc='lower left', ncol=2)
+    >>> plt.show()
+
+    In the second example, the unit circle is interpolated with a spline. A
+    periodic boundary condition is used. You can see that the first derivative
+    values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly
+    computed. Note that a circle cannot be exactly represented by a cubic
+    spline. To increase precision, more breakpoints would be required.
+
+    >>> theta = 2 * np.pi * np.linspace(0, 1, 5)
+    >>> y = np.c_[np.cos(theta), np.sin(theta)]
+    >>> cs = CubicSpline(theta, y, bc_type='periodic')
+    >>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1]))
+    ds/dx=0.0 ds/dy=1.0
+    >>> xs = 2 * np.pi * np.linspace(0, 1, 100)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(y[:, 0], y[:, 1], 'o', label='data')
+    >>> ax.plot(np.cos(xs), np.sin(xs), label='true')
+    >>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline')
+    >>> ax.axes.set_aspect('equal')
+    >>> ax.legend(loc='center')
+    >>> plt.show()
+
+    The third example is the interpolation of a polynomial y = x**3 on the
+    interval 0 <= x<= 1. A cubic spline can represent this function exactly.
+    To achieve that we need to specify values and first derivatives at
+    endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and
+    y'(1) = 3.
+
+    >>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3)))
+    >>> x = np.linspace(0, 1)
+    >>> np.allclose(x**3, cs(x))
+    True
+
+    References
+    ----------
+    .. [1] `Cubic Spline Interpolation
+            `_
+            on Wikiversity.
+    .. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978.
+    """
+
+    def __init__(self, x, y, axis=0, bc_type='not-a-knot', extrapolate=None):
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+        n = len(x)
+
+        bc, y = self._validate_bc(bc_type, y, y.shape[1:], axis)
+
+        if extrapolate is None:
+            if bc[0] == 'periodic':
+                extrapolate = 'periodic'
+            else:
+                extrapolate = True
+
+        if y.size == 0:
+            # bail out early for zero-sized arrays
+            s = np.zeros_like(y)
+        else:
+            dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+            slope = np.diff(y, axis=0) / dxr
+
+            # If bc is 'not-a-knot' this change is just a convention.
+            # If bc is 'periodic' then we already checked that y[0] == y[-1],
+            # and the spline is just a constant, we handle this case in the
+            # same way by setting the first derivatives to slope, which is 0.
+            if n == 2:
+                if bc[0] in ['not-a-knot', 'periodic']:
+                    bc[0] = (1, slope[0])
+                if bc[1] in ['not-a-knot', 'periodic']:
+                    bc[1] = (1, slope[0])
+
+            # This is a special case, when both conditions are 'not-a-knot'
+            # and n == 3. In this case 'not-a-knot' can't be handled regularly
+            # as the both conditions are identical. We handle this case by
+            # constructing a parabola passing through given points.
+            if n == 3 and bc[0] == 'not-a-knot' and bc[1] == 'not-a-knot':
+                A = np.zeros((3, 3))  # This is a standard matrix.
+                b = np.empty((3,) + y.shape[1:], dtype=y.dtype)
+
+                A[0, 0] = 1
+                A[0, 1] = 1
+                A[1, 0] = dx[1]
+                A[1, 1] = 2 * (dx[0] + dx[1])
+                A[1, 2] = dx[0]
+                A[2, 1] = 1
+                A[2, 2] = 1
+
+                b[0] = 2 * slope[0]
+                b[1] = 3 * (dxr[0] * slope[1] + dxr[1] * slope[0])
+                b[2] = 2 * slope[1]
+
+                s = solve(A, b, overwrite_a=True, overwrite_b=True,
+                          check_finite=False)
+            elif n == 3 and bc[0] == 'periodic':
+                # In case when number of points is 3 we compute the derivatives
+                # manually
+                t = (slope / dxr).sum(0) / (1. / dxr).sum(0)
+                s = np.broadcast_to(t, (n,) + y.shape[1:])
+            else:
+                # Find derivative values at each x[i] by solving a tridiagonal
+                # system.
+                A = np.zeros((3, n))  # This is a banded matrix representation.
+                b = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+
+                # Filling the system for i=1..n-2
+                #                         (x[i-1] - x[i]) * s[i-1] +\
+                # 2 * ((x[i] - x[i-1]) + (x[i+1] - x[i])) * s[i]   +\
+                #                         (x[i] - x[i-1]) * s[i+1] =\
+                #       3 * ((x[i+1] - x[i])*(y[i] - y[i-1])/(x[i] - x[i-1]) +\
+                #           (x[i] - x[i-1])*(y[i+1] - y[i])/(x[i+1] - x[i]))
+
+                A[1, 1:-1] = 2 * (dx[:-1] + dx[1:])  # The diagonal
+                A[0, 2:] = dx[:-1]                   # The upper diagonal
+                A[-1, :-2] = dx[1:]                  # The lower diagonal
+
+                b[1:-1] = 3 * (dxr[1:] * slope[:-1] + dxr[:-1] * slope[1:])
+
+                bc_start, bc_end = bc
+
+                if bc_start == 'periodic':
+                    # Due to the periodicity, and because y[-1] = y[0], the
+                    # linear system has (n-1) unknowns/equations instead of n:
+                    A = A[:, 0:-1]
+                    A[1, 0] = 2 * (dx[-1] + dx[0])
+                    A[0, 1] = dx[-1]
+
+                    b = b[:-1]
+
+                    # Also, due to the periodicity, the system is not tri-diagonal.
+                    # We need to compute a "condensed" matrix of shape (n-2, n-2).
+                    # See https://web.archive.org/web/20151220180652/http://www.cfm.brown.edu/people/gk/chap6/node14.html
+                    # for more explanations.
+                    # The condensed matrix is obtained by removing the last column
+                    # and last row of the (n-1, n-1) system matrix. The removed
+                    # values are saved in scalar variables with the (n-1, n-1)
+                    # system matrix indices forming their names:
+                    a_m1_0 = dx[-2]  # lower left corner value: A[-1, 0]
+                    a_m1_m2 = dx[-1]
+                    a_m1_m1 = 2 * (dx[-1] + dx[-2])
+                    a_m2_m1 = dx[-3]
+                    a_0_m1 = dx[0]
+
+                    b[0] = 3 * (dxr[0] * slope[-1] + dxr[-1] * slope[0])
+                    b[-1] = 3 * (dxr[-1] * slope[-2] + dxr[-2] * slope[-1])
+
+                    Ac = A[:, :-1]
+                    b1 = b[:-1]
+                    b2 = np.zeros_like(b1)
+                    b2[0] = -a_0_m1
+                    b2[-1] = -a_m2_m1
+
+                    # s1 and s2 are the solutions of (n-2, n-2) system
+                    s1 = solve_banded((1, 1), Ac, b1, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    s2 = solve_banded((1, 1), Ac, b2, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    # computing the s[n-2] solution:
+                    s_m1 = ((b[-1] - a_m1_0 * s1[0] - a_m1_m2 * s1[-1]) /
+                            (a_m1_m1 + a_m1_0 * s2[0] + a_m1_m2 * s2[-1]))
+
+                    # s is the solution of the (n, n) system:
+                    s = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+                    s[:-2] = s1 + s_m1 * s2
+                    s[-2] = s_m1
+                    s[-1] = s[0]
+                else:
+                    if bc_start == 'not-a-knot':
+                        A[1, 0] = dx[1]
+                        A[0, 1] = x[2] - x[0]
+                        d = x[2] - x[0]
+                        b[0] = ((dxr[0] + 2*d) * dxr[1] * slope[0] +
+                                dxr[0]**2 * slope[1]) / d
+                    elif bc_start[0] == 1:
+                        A[1, 0] = 1
+                        A[0, 1] = 0
+                        b[0] = bc_start[1]
+                    elif bc_start[0] == 2:
+                        A[1, 0] = 2 * dx[0]
+                        A[0, 1] = dx[0]
+                        b[0] = -0.5 * bc_start[1] * dx[0]**2 + 3 * (y[1] - y[0])
+
+                    if bc_end == 'not-a-knot':
+                        A[1, -1] = dx[-2]
+                        A[-1, -2] = x[-1] - x[-3]
+                        d = x[-1] - x[-3]
+                        b[-1] = ((dxr[-1]**2*slope[-2] +
+                                 (2*d + dxr[-1])*dxr[-2]*slope[-1]) / d)
+                    elif bc_end[0] == 1:
+                        A[1, -1] = 1
+                        A[-1, -2] = 0
+                        b[-1] = bc_end[1]
+                    elif bc_end[0] == 2:
+                        A[1, -1] = 2 * dx[-1]
+                        A[-1, -2] = dx[-1]
+                        b[-1] = 0.5 * bc_end[1] * dx[-1]**2 + 3 * (y[-1] - y[-2])
+
+                    s = solve_banded((1, 1), A, b, overwrite_ab=True,
+                                     overwrite_b=True, check_finite=False)
+
+        super().__init__(x, y, s, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _validate_bc(bc_type, y, expected_deriv_shape, axis):
+        """Validate and prepare boundary conditions.
+
+        Returns
+        -------
+        validated_bc : 2-tuple
+            Boundary conditions for a curve start and end.
+        y : ndarray
+            y casted to complex dtype if one of the boundary conditions has
+            complex dtype.
+        """
+        if isinstance(bc_type, str):
+            if bc_type == 'periodic':
+                if not np.allclose(y[0], y[-1], rtol=1e-15, atol=1e-15):
+                    raise ValueError(
+                        f"The first and last `y` point along axis {axis} must "
+                        "be identical (within machine precision) when "
+                        "bc_type='periodic'.")
+
+            bc_type = (bc_type, bc_type)
+
+        else:
+            if len(bc_type) != 2:
+                raise ValueError("`bc_type` must contain 2 elements to "
+                                 "specify start and end conditions.")
+
+            if 'periodic' in bc_type:
+                raise ValueError("'periodic' `bc_type` is defined for both "
+                                 "curve ends and cannot be used with other "
+                                 "boundary conditions.")
+
+        validated_bc = []
+        for bc in bc_type:
+            if isinstance(bc, str):
+                if bc == 'clamped':
+                    validated_bc.append((1, np.zeros(expected_deriv_shape)))
+                elif bc == 'natural':
+                    validated_bc.append((2, np.zeros(expected_deriv_shape)))
+                elif bc in ['not-a-knot', 'periodic']:
+                    validated_bc.append(bc)
+                else:
+                    raise ValueError(f"bc_type={bc} is not allowed.")
+            else:
+                try:
+                    deriv_order, deriv_value = bc
+                except Exception as e:
+                    raise ValueError(
+                        "A specified derivative value must be "
+                        "given in the form (order, value)."
+                    ) from e
+
+                if deriv_order not in [1, 2]:
+                    raise ValueError("The specified derivative order must "
+                                     "be 1 or 2.")
+
+                deriv_value = np.asarray(deriv_value)
+                if deriv_value.shape != expected_deriv_shape:
+                    raise ValueError(
+                        f"`deriv_value` shape {deriv_value.shape} is not "
+                        f"the expected one {expected_deriv_shape}."
+                    )
+
+                if np.issubdtype(deriv_value.dtype, np.complexfloating):
+                    y = y.astype(complex, copy=False)
+
+                validated_bc.append((deriv_order, deriv_value))
+
+        return validated_bc, y
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_dfitpack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_dfitpack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dda7b072e2e23bc332194e9359e195470e2a1a7c
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_dfitpack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_dierckx.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_dierckx.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dac5ebbf51dbd86a6b306a22c1cd5aebec1dbad4
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_dierckx.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9f6224630192e78cc1f0b977fa671bbf8c6f7a09
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack2.py b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..53ddf7955feee008c3787b03bf73cb1c4604456f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack2.py
@@ -0,0 +1,2394 @@
+"""
+fitpack --- curve and surface fitting with splines
+
+fitpack is based on a collection of Fortran routines DIERCKX
+by P. Dierckx (see http://www.netlib.org/dierckx/) transformed
+to double routines by Pearu Peterson.
+"""
+# Created by Pearu Peterson, June,August 2003
+__all__ = [
+    'UnivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQUnivariateSpline',
+    'BivariateSpline',
+    'LSQBivariateSpline',
+    'SmoothBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline']
+
+
+import warnings
+from threading import Lock
+
+from numpy import zeros, concatenate, ravel, diff, array
+import numpy as np
+
+from . import _fitpack_impl
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+FITPACK_LOCK = Lock()
+
+
+# ############### Univariate spline ####################
+
+_curfit_messages = {1: """
+The required storage space exceeds the available storage space, as
+specified by the parameter nest: nest too small. If nest is already
+large (say nest > m/2), it may also indicate that s is too small.
+The approximation returned is the weighted least-squares spline
+according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp
+gives the corresponding weighted sum of squared residuals (fp>s).
+""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    3: """
+The maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached: s
+too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[0]0, i=0..m-1
+if iopt=-1:
+  xb>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4])
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> spl = UnivariateSpline(x, y, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> plt.plot(x, y, 'ro', ms=5)
+
+    Use the default value for the smoothing parameter:
+
+    >>> spl = UnivariateSpline(x, y)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3)
+
+    Manually change the amount of smoothing:
+
+    >>> spl.set_smoothing_factor(0.5)
+    >>> plt.plot(xs, spl(xs), 'b', lw=3)
+    >>> plt.show()
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext,
+                                                      check_finite)
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                    xe=bbox[1], s=s)
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    @staticmethod
+    def validate_input(x, y, w, bbox, k, s, ext, check_finite):
+        x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox)
+        if w is not None:
+            w = np.asarray(w)
+        if check_finite:
+            w_finite = np.isfinite(w).all() if w is not None else True
+            if (not np.isfinite(x).all() or not np.isfinite(y).all() or
+                    not w_finite):
+                raise ValueError("x and y array must not contain "
+                                 "NaNs or infs.")
+        if s is None or s > 0:
+            if not np.all(diff(x) >= 0.0):
+                raise ValueError("x must be increasing if s > 0")
+        else:
+            if not np.all(diff(x) > 0.0):
+                raise ValueError("x must be strictly increasing if s = 0")
+        if x.size != y.size:
+            raise ValueError("x and y should have a same length")
+        elif w is not None and not x.size == y.size == w.size:
+            raise ValueError("x, y, and w should have a same length")
+        elif bbox.shape != (2,):
+            raise ValueError("bbox shape should be (2,)")
+        elif not (1 <= k <= 5):
+            raise ValueError("k should be 1 <= k <= 5")
+        elif s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        try:
+            ext = _extrap_modes[ext]
+        except KeyError as e:
+            raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+
+        return x, y, w, bbox, ext
+
+    @classmethod
+    def _from_tck(cls, tck, ext=0):
+        """Construct a spline object from given tck"""
+        self = cls.__new__(cls)
+        t, c, k = tck
+        self._eval_args = tck
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        self._data = (None, None, None, None, None, k, None, len(t), t,
+                      c, None, None, None, None)
+        self.ext = ext
+        return self
+
+    def _reset_class(self):
+        data = self._data
+        n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1]
+        self._eval_args = t[:n], c[:n], k
+        if ier == 0:
+            # the spline returned has a residual sum of squares fp
+            # such that abs(fp-s)/s <= tol with tol a relative
+            # tolerance set to 0.001 by the program
+            pass
+        elif ier == -1:
+            # the spline returned is an interpolating spline
+            self._set_class(InterpolatedUnivariateSpline)
+        elif ier == -2:
+            # the spline returned is the weighted least-squares
+            # polynomial of degree k. In this extreme case fp gives
+            # the upper bound fp0 for the smoothing factor s.
+            self._set_class(LSQUnivariateSpline)
+        else:
+            # error
+            if ier == 1:
+                self._set_class(LSQUnivariateSpline)
+            message = _curfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=3)
+
+    def _set_class(self, cls):
+        self._spline_class = cls
+        if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline,
+                              LSQUnivariateSpline):
+            self.__class__ = cls
+        else:
+            # It's an unknown subclass -- don't change class. cf. #731
+            pass
+
+    def _reset_nest(self, data, nest=None):
+        n = data[10]
+        if nest is None:
+            k, m = data[5], len(data[0])
+            nest = m+k+1  # this is the maximum bound for nest
+        else:
+            if not n <= nest:
+                raise ValueError("`nest` can only be increased")
+        t, c, fpint, nrdata = (np.resize(data[j], nest) for j in
+                               [8, 9, 11, 12])
+
+        args = data[:8] + (t, c, n, fpint, nrdata, data[13])
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        return data
+
+    def set_smoothing_factor(self, s):
+        """ Continue spline computation with the given smoothing
+        factor s and with the knots found at the last call.
+
+        This routine modifies the spline in place.
+
+        """
+        data = self._data
+        if data[6] == -1:
+            warnings.warn('smoothing factor unchanged for'
+                          'LSQ spline with fixed knots',
+                          stacklevel=2)
+            return
+        args = data[:6] + (s,) + data[7:]
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    def __call__(self, x, nu=0, ext=None):
+        """
+        Evaluate spline (or its nu-th derivative) at positions x.
+
+        Parameters
+        ----------
+        x : array_like
+            A 1-D array of points at which to return the value of the smoothed
+            spline or its derivatives. Note: `x` can be unordered but the
+            evaluation is more efficient if `x` is (partially) ordered.
+        nu  : int
+            The order of derivative of the spline to compute.
+        ext : int
+            Controls the value returned for elements of `x` not in the
+            interval defined by the knot sequence.
+
+            * if ext=0 or 'extrapolate', return the extrapolated value.
+            * if ext=1 or 'zeros', return 0
+            * if ext=2 or 'raise', raise a ValueError
+            * if ext=3 or 'const', return the boundary value.
+
+            The default value is 0, passed from the initialization of
+            UnivariateSpline.
+
+        """
+        x = np.asarray(x)
+        # empty input yields empty output
+        if x.size == 0:
+            return array([])
+        if ext is None:
+            ext = self.ext
+        else:
+            try:
+                ext = _extrap_modes[ext]
+            except KeyError as e:
+                raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+        with FITPACK_LOCK:
+            return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext)
+
+    def get_knots(self):
+        """ Return positions of interior knots of the spline.
+
+        Internally, the knot vector contains ``2*k`` additional boundary knots.
+        """
+        data = self._data
+        k, n = data[5], data[7]
+        return data[8][k:n-k]
+
+    def get_coeffs(self):
+        """Return spline coefficients."""
+        data = self._data
+        k, n = data[5], data[7]
+        return data[9][:n-k-1]
+
+    def get_residual(self):
+        """Return weighted sum of squared residuals of the spline approximation.
+
+           This is equivalent to::
+
+                sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)
+
+        """
+        return self._data[10]
+
+    def integral(self, a, b):
+        """ Return definite integral of the spline between two given points.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+
+        Returns
+        -------
+        integral : float
+            The value of the definite integral of the spline between limits.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.integral(0, 3)
+        9.0
+
+        which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits
+        of 0 and 3.
+
+        A caveat is that this routine assumes the spline to be zero outside of
+        the data limits:
+
+        >>> spl.integral(-1, 4)
+        9.0
+        >>> spl.integral(-1, 0)
+        0.0
+
+        """
+        with FITPACK_LOCK:
+            return _fitpack_impl.splint(a, b, self._eval_args)
+
+    def derivatives(self, x):
+        """ Return all derivatives of the spline at the point x.
+
+        Parameters
+        ----------
+        x : float
+            The point to evaluate the derivatives at.
+
+        Returns
+        -------
+        der : ndarray, shape(k+1,)
+            Derivatives of the orders 0 to k.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.derivatives(1.5)
+        array([2.25, 3.0, 2.0, 0])
+
+        """
+        with FITPACK_LOCK:
+            return _fitpack_impl.spalde(x, self._eval_args)
+
+    def roots(self):
+        """ Return the zeros of the spline.
+
+        Notes
+        -----
+        Restriction: only cubic splines are supported by FITPACK. For non-cubic
+        splines, use `PPoly.root` (see below for an example).
+
+        Examples
+        --------
+
+        For some data, this method may miss a root. This happens when one of
+        the spline knots (which FITPACK places automatically) happens to
+        coincide with the true root. A workaround is to convert to `PPoly`,
+        which uses a different root-finding algorithm.
+
+        For example,
+
+        >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+        >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+        ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+        ...      6.520430e-03,  8.170770e-03]
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> spl = UnivariateSpline(x, y, s=0)
+        >>> spl.roots()
+        array([], dtype=float64)
+
+        Converting to a PPoly object does find the roots at `x=2`:
+
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> tck = splrep(x, y, s=0)
+        >>> ppoly = PPoly.from_spline(tck)
+        >>> ppoly.roots(extrapolate=False)
+        array([2.])
+
+        See Also
+        --------
+        sproot
+        PPoly.roots
+
+        """
+        k = self._data[5]
+        if k == 3:
+            t = self._eval_args[0]
+            mest = 3 * (len(t) - 7)
+            with FITPACK_LOCK:
+                return _fitpack_impl.sproot(self._eval_args, mest=mest)
+        raise NotImplementedError('finding roots unsupported for '
+                                  'non-cubic splines')
+
+    def derivative(self, n=1):
+        """
+        Construct a new spline representing the derivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of derivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k-n representing the derivative of this
+            spline.
+
+        See Also
+        --------
+        splder, antiderivative
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        Examples
+        --------
+        This can be used for finding maxima of a curve:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 10, 70)
+        >>> y = np.sin(x)
+        >>> spl = UnivariateSpline(x, y, k=4, s=0)
+
+        Now, differentiate the spline and find the zeros of the
+        derivative. (NB: `sproot` only works for order 3 splines, so we
+        fit an order 4 spline):
+
+        >>> spl.derivative().roots() / np.pi
+        array([ 0.50000001,  1.5       ,  2.49999998])
+
+        This agrees well with roots :math:`\\pi/2 + n\\pi` of
+        :math:`\\cos(x) = \\sin'(x)`.
+
+        """
+        with FITPACK_LOCK:
+            tck = _fitpack_impl.splder(self._eval_args, n)
+        # if self.ext is 'const', derivative.ext will be 'zeros'
+        ext = 1 if self.ext == 3 else self.ext
+        return UnivariateSpline._from_tck(tck, ext=ext)
+
+    def antiderivative(self, n=1):
+        """
+        Construct a new spline representing the antiderivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of antiderivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k+n representing the antiderivative of this
+            spline.
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        See Also
+        --------
+        splantider, derivative
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, np.pi/2, 70)
+        >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+        >>> spl = UnivariateSpline(x, y, s=0)
+
+        The derivative is the inverse operation of the antiderivative,
+        although some floating point error accumulates:
+
+        >>> spl(1.7), spl.antiderivative().derivative()(1.7)
+        (array(2.1565429877197317), array(2.1565429877201865))
+
+        Antiderivative can be used to evaluate definite integrals:
+
+        >>> ispl = spl.antiderivative()
+        >>> ispl(np.pi/2) - ispl(0)
+        2.2572053588768486
+
+        This is indeed an approximation to the complete elliptic integral
+        :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+        >>> from scipy.special import ellipk
+        >>> ellipk(0.8)
+        2.2572053268208538
+
+        """
+        with FITPACK_LOCK:
+            tck = _fitpack_impl.splantider(self._eval_args, n)
+        return UnivariateSpline._from_tck(tck, self.ext)
+
+
+class InterpolatedUnivariateSpline(UnivariateSpline):
+    """
+    1-D interpolating spline for a given set of data points.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_interp_spline` instead.
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.
+    Spline function passes through all provided points. Equivalent to
+    `UnivariateSpline` with  `s` = 0.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be strictly increasing
+    y : (N,) array_like
+        input dimension of data points
+    w : (N,) array_like, optional
+        Weights for spline fitting.  Must be positive.  If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox=[x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be ``1 <= k <= 5``. Default is
+        ``k = 3``, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    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 or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQUnivariateSpline :
+        a spline for which knots are user-selected
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import InterpolatedUnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> spl = InterpolatedUnivariateSpline(x, y)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7)
+    >>> plt.show()
+
+    Notice that the ``spl(x)`` interpolates `y`:
+
+    >>> spl.get_residual()
+    0.0
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                            ext, check_finite)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        with FITPACK_LOCK:
+            self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                          xe=bbox[1], s=0)
+        self._reset_class()
+
+
+_fpchec_error_string = """The input parameters have been rejected by fpchec. \
+This means that at least one of the following conditions is violated:
+
+1) k+1 <= n-k-1 <= m
+2) t(1) <= t(2) <= ... <= t(k+1)
+   t(n-k) <= t(n-k+1) <= ... <= t(n)
+3) t(k+1) < t(k+2) < ... < t(n-k)
+4) t(k+1) <= x(i) <= t(n-k)
+5) The conditions specified by Schoenberg and Whitney must hold
+   for at least one subset of data points, i.e., there must be a
+   subset of data points y(j) such that
+       t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+"""
+
+
+class LSQUnivariateSpline(UnivariateSpline):
+    """
+    1-D spline with explicit internal knots.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_lsq_spline` instead.
+
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.  `t`
+    specifies the internal knots of the spline
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be increasing
+    y : (N,) array_like
+        Input dimension of data points
+    t : (M,) array_like
+        interior knots of the spline.  Must be in ascending order and::
+
+            bbox[0] < t[0] < ... < t[-1] < bbox[-1]
+
+    w : (N,) array_like, optional
+        weights for spline fitting. Must be positive. If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox = [x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be 1 <= `k` <= 5.
+        Default is `k` = 3, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    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 or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    Raises
+    ------
+    ValueError
+        If the interior knots do not satisfy the Schoenberg-Whitney conditions
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    InterpolatedUnivariateSpline :
+        a interpolating univariate spline for a given set of data points.
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Fit a smoothing spline with a pre-defined internal knots:
+
+    >>> t = [-1, 0, 1]
+    >>> spl = LSQUnivariateSpline(x, y, t)
+
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3)
+    >>> plt.show()
+
+    Check the knot vector:
+
+    >>> spl.get_knots()
+    array([-3., -1., 0., 1., 3.])
+
+    Constructing lsq spline using the knots from another spline:
+
+    >>> x = np.arange(10)
+    >>> s = UnivariateSpline(x, x, s=0)
+    >>> s.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+    >>> knt = s.get_knots()
+    >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1])    # Chop 1st and last knot
+    >>> s1.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+
+    """
+
+    def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                                      ext, check_finite)
+        if not np.all(diff(x) >= 0.0):
+            raise ValueError('x must be increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        xb = bbox[0]
+        xe = bbox[1]
+        if xb is None:
+            xb = x[0]
+        if xe is None:
+            xe = x[-1]
+        t = concatenate(([xb]*(k+1), t, [xe]*(k+1)))
+        n = len(t)
+        if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0):
+            raise ValueError('Interior knots t must satisfy '
+                             'Schoenberg-Whitney conditions')
+        with FITPACK_LOCK:
+            if not dfitpack.fpchec(x, t, k) == 0:
+                raise ValueError(_fpchec_error_string)
+            data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe)
+        self._data = data[:-3] + (None, None, data[-1])
+        self._reset_class()
+
+
+# ############### Bivariate spline ####################
+
+class _BivariateSplineBase:
+    """ Base class for Bivariate spline s(x,y) interpolation on the rectangle
+    [xb,xe] x [yb, ye] calculated from a given set of data points
+    (x,y,z).
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    BivariateSpline :
+        a base class for bivariate splines.
+    SphereBivariateSpline :
+        a bivariate spline on a spherical grid
+    """
+
+    @classmethod
+    def _from_tck(cls, tck):
+        """Construct a spline object from given tck and degree"""
+        self = cls.__new__(cls)
+        if len(tck) != 5:
+            raise ValueError("tck should be a 5 element tuple of tx,"
+                             " ty, c, kx, ky")
+        self.tck = tck[:3]
+        self.degrees = tck[3:]
+        return self
+
+    def get_residual(self):
+        """ Return weighted sum of squared residuals of the spline
+        approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
+        """
+        return self.fp
+
+    def get_knots(self):
+        """ Return a tuple (tx,ty) where tx,ty contain knots positions
+        of the spline with respect to x-, y-variable, respectively.
+        The position of interior and additional knots are given as
+        t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively.
+        """
+        return self.tck[:2]
+
+    def get_coeffs(self):
+        """ Return spline coefficients."""
+        return self.tck[2]
+
+    def __call__(self, x, y, dx=0, dy=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        x, y : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points ``(x[i],
+            y[i]), i=0, ..., len(x)-1``.  Standard Numpy broadcasting
+            is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays x, y. The arrays must be
+            sorted to increasing order.
+
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dx : int
+            Order of x-derivative
+
+            .. versionadded:: 0.14.0
+        dy : int
+            Order of y-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+        Suppose that we want to bilinearly interpolate an exponentially decaying
+        function in 2 dimensions.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+
+        We sample the function on a coarse grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 100)
+        >>> yarr = np.linspace(-3, 3, 100)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+
+        The function to interpolate decays faster along one axis than the other.
+
+        >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2))
+
+        Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear).
+
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+        >>> xarr_fine = np.linspace(-3, 3, 200)
+        >>> yarr_fine = np.linspace(-3, 3, 200)
+        >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij")
+        >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False)
+
+        And check that the result agrees with the input by plotting both.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal")
+        >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal")
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_interp)
+        >>> plt.show()
+        """
+        x = np.asarray(x)
+        y = np.asarray(y)
+
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        if grid:
+            if x.size == 0 or y.size == 0:
+                return np.zeros((x.size, y.size), dtype=self.tck[2].dtype)
+
+            if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)):
+                raise ValueError("x must be strictly increasing when `grid` is True")
+            if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)):
+                raise ValueError("y must be strictly increasing when `grid` is True")
+
+            if dx or dy:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by parder: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispev: {ier}")
+        else:
+            # standard Numpy broadcasting
+            if x.shape != y.shape:
+                x, y = np.broadcast_arrays(x, y)
+
+            shape = x.shape
+            x = x.ravel()
+            y = y.ravel()
+
+            if x.size == 0 or y.size == 0:
+                return np.zeros(shape, dtype=self.tck[2].dtype)
+
+            if dx or dy:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by pardeu: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.bispeu(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispeu: {ier}")
+
+            z = z.reshape(shape)
+        return z
+
+    def partial_derivative(self, dx, dy):
+        """Construct a new spline representing a partial derivative of this
+        spline.
+
+        Parameters
+        ----------
+        dx, dy : int
+            Orders of the derivative in x and y respectively. They must be
+            non-negative integers and less than the respective degree of the
+            original spline (self) in that direction (``kx``, ``ky``).
+
+        Returns
+        -------
+        spline :
+            A new spline of degrees (``kx - dx``, ``ky - dy``) representing the
+            derivative of this spline.
+
+        Notes
+        -----
+
+        .. versionadded:: 1.9.0
+
+        """
+        if dx == 0 and dy == 0:
+            return self
+        else:
+            kx, ky = self.degrees
+            if not (dx >= 0 and dy >= 0):
+                raise ValueError("order of derivative must be positive or"
+                                 " zero")
+            if not (dx < kx and dy < ky):
+                raise ValueError("order of derivative must be less than"
+                                 " degree of spline")
+            tx, ty, c = self.tck[:3]
+            with FITPACK_LOCK:
+                newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy)
+            if ier != 0:
+                # This should not happen under normal conditions.
+                raise ValueError("Unexpected error code returned by"
+                                 " pardtc: %d" % ier)
+            nx = len(tx)
+            ny = len(ty)
+            newtx = tx[dx:nx - dx]
+            newty = ty[dy:ny - dy]
+            newkx, newky = kx - dx, ky - dy
+            newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1)
+            return _DerivedBivariateSpline._from_tck((newtx, newty,
+                                                      newc[:newclen],
+                                                      newkx, newky))
+
+
+_surfit_messages = {1: """
+The required storage space exceeds the available storage space: nxest
+or nyest too small, or s too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small or
+badly chosen eps.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
+                    3: """
+the maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached:
+s too small.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
+                    4: """
+No more knots can be added because the number of b-spline coefficients
+(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m:
+either s or m too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    5: """
+No more knots can be added because the additional knot would (quasi)
+coincide with an old one: s too small or too large a weight to an
+inaccurate data point.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1
+If iopt==-1, then
+  xb>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+        >>> def f(x, y):
+        ...     return np.exp(-np.sqrt((x / 2) ** 2 + y**2))
+
+        We sample the function on a coarse grid and set up the interpolator. Note that
+        the default ``indexing="xy"`` of meshgrid would result in an unexpected
+        (transposed) result after interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 21)
+        >>> yarr = np.linspace(-3, 3, 21)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+        >>> zdata = f(xgrid, ygrid)
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+
+        Next we sample the function along a diagonal slice through the coordinate space
+        on a finer grid using interpolation.
+
+        >>> xinterp = np.linspace(-3, 3, 201)
+        >>> yinterp = np.linspace(3, -3, 201)
+        >>> zinterp = rbs.ev(xinterp, yinterp)
+
+        And check that the interpolation passes through the function evaluations as a
+        function of the distance from the origin along the slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or")
+        >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(xi, yi, dx=dx, dy=dy, grid=False)
+
+    def integral(self, xa, xb, ya, yb):
+        """
+        Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
+
+        Parameters
+        ----------
+        xa, xb : float
+            The end-points of the x integration interval.
+        ya, yb : float
+            The end-points of the y integration interval.
+
+        Returns
+        -------
+        integ : float
+            The value of the resulting integral.
+
+        """
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        with FITPACK_LOCK:
+            return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+    @staticmethod
+    def _validate_input(x, y, z, w, kx, ky, eps):
+        x, y, z = np.asarray(x), np.asarray(y), np.asarray(z)
+        if not x.size == y.size == z.size:
+            raise ValueError('x, y, and z should have a same length')
+
+        if w is not None:
+            w = np.asarray(w)
+            if x.size != w.size:
+                raise ValueError('x, y, z, and w should have a same length')
+            elif not np.all(w >= 0.0):
+                raise ValueError('w should be positive')
+        if (eps is not None) and (not 0.0 < eps < 1.0):
+            raise ValueError('eps should be between (0, 1)')
+        if not x.size >= (kx + 1) * (ky + 1):
+            raise ValueError('The length of x, y and z should be at least'
+                             ' (kx+1) * (ky+1)')
+        return x, y, z, w
+
+
+class _DerivedBivariateSpline(_BivariateSplineBase):
+    """Bivariate spline constructed from the coefficients and knots of another
+    spline.
+
+    Notes
+    -----
+    The class is not meant to be instantiated directly from the data to be
+    interpolated or smoothed. As a result, its ``fp`` attribute and
+    ``get_residual`` method are inherited but overridden; ``AttributeError`` is
+    raised when they are accessed.
+
+    The other inherited attributes can be used as usual.
+    """
+    _invalid_why = ("is unavailable, because _DerivedBivariateSpline"
+                    " instance is not constructed from data that are to be"
+                    " interpolated or smoothed, but derived from the"
+                    " underlying knots and coefficients of another spline"
+                    " object")
+
+    @property
+    def fp(self):
+        raise AttributeError(f"attribute \"fp\" {self._invalid_why}")
+
+    def get_residual(self):
+        raise AttributeError(f"method \"get_residual\" {self._invalid_why}")
+
+
+class SmoothBivariateSpline(BivariateSpline):
+    """
+    Smooth bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    w : array_like, optional
+        Positive 1-D sequence of weights, of same length as `x`, `y` and `z`.
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``z[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    This routine constructs spline knot vectors automatically via the FITPACK
+    algorithm. The spline knots may be placed away from the data points. For
+    some data sets, this routine may fail to construct an interpolating spline,
+    even if one is requested via ``s=0`` parameter. In such situations, it is
+    recommended to use `bisplrep` / `bisplev` directly instead of this routine
+    and, if needed, increase the values of ``nxest`` and ``nyest`` parameters
+    of `bisplrep`.
+
+    For linear interpolation, prefer `LinearNDInterpolator`.
+    See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff``
+    for discussion.
+
+    """
+
+    def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None,
+                 eps=1e-16):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1)
+            if ier > 10:          # lwrk2 was to small, re-run
+                nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                    x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps,
+                    lwrk2=ier)
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)]
+        self.degrees = kx, ky
+
+
+class LSQBivariateSpline(BivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    tx, ty : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+    w : array_like, optional
+        Positive 1-D array of weights, of the same length as `x`, `y` and `z`.
+    bbox : (4,) array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3,
+                 eps=None):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+
+        nx = 2*kx+2+len(tx)
+        ny = 2*ky+2+len(ty)
+        # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq)
+        # requires that the knot arrays passed as input should be "real
+        # array(s) of dimension nmax" where "nmax" refers to the greater of nx
+        # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and
+        # slice them to the desired sizes upon return.
+        nmax = max(nx, ny)
+        tx1 = zeros((nmax,), float)
+        ty1 = zeros((nmax,), float)
+        tx1[kx+1:nx-kx-1] = tx
+        ty1[ky+1:ny-ky-1] = ty
+
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1,
+                                                    w, xb, xe, yb, ye,
+                                                    kx, ky, eps, lwrk2=1)
+            if ier > 10:
+                tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z,
+                                                        nx, tx1, ny, ty1, w,
+                                                        xb, xe, yb, ye,
+                                                        kx, ky, eps, lwrk2=ier)
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            if ier < -2:
+                deficiency = (nx-kx-1)*(ny-ky-1)+ier
+                message = _surfit_messages.get(-3) % (deficiency)
+            else:
+                message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+        self.fp = fp
+        self.tck = tx1[:nx], ty1[:ny], c
+        self.degrees = kx, ky
+
+
+class RectBivariateSpline(BivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh.
+
+    Can be used for both smoothing and interpolating data.
+
+    Parameters
+    ----------
+    x,y : array_like
+        1-D arrays of coordinates in strictly ascending order.
+        Evaluated points outside the data range will be extrapolated.
+    z : array_like
+        2-D array of data with shape (x.size,y.size).
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain, which means the start and end spline knots of
+        each dimension are set by these values. By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline
+        function. Default is ``s=0``, which is for interpolation.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0):
+        x, y, bbox = ravel(x), ravel(y), ravel(bbox)
+        z = np.asarray(z)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+        if not np.all(diff(y) > 0.0):
+            raise ValueError('y must be strictly increasing')
+        if not x.size == z.shape[0]:
+            raise ValueError('x dimension of z must have same number of '
+                             'elements as x')
+        if not y.size == z.shape[1]:
+            raise ValueError('y dimension of z must have same number of '
+                             'elements as y')
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        z = ravel(z)
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb,
+                                                            ye, kx, ky, s)
+
+        if ier not in [0, -1, -2]:
+            msg = _surfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)]
+        self.degrees = kx, ky
+
+
+_spherefit_messages = _surfit_messages.copy()
+_spherefit_messages[10] = """
+ERROR. On entry, the input data are controlled on validity. The following
+       restrictions must be satisfied:
+            -1<=iopt<=1,  m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m
+            lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
+            kwrk >= m+(ntest-7)*(npest-7)
+            if iopt=-1: 8<=nt<=ntest , 9<=np<=npest
+                        0=0: s>=0
+            if one of these conditions is found to be violated,control
+            is immediately repassed to the calling program. in that
+            case there is no approximation returned."""
+_spherefit_messages[-3] = """
+WARNING. The coefficients of the spline returned have been computed as the
+         minimal norm least-squares solution of a (numerically) rank
+         deficient system (deficiency=%i, rank=%i). Especially if the rank
+         deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large,
+         the results may be inaccurate. They could also seriously depend on
+         the value of eps."""
+
+
+class SphereBivariateSpline(_BivariateSplineBase):
+    """
+    Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a
+    given set of data points (theta,phi,r).
+
+    .. versionadded:: 0.11.0
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQUnivariateSpline :
+        a univariate spline using weighted least-squares fitting
+    """
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points
+            ``(theta[i], phi[i]), i=0, ..., len(x)-1``.  Standard
+            Numpy broadcasting is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays theta, phi. The arrays
+            must be sorted to increasing order.
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        on a finer grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetaarr_fine = np.linspace(0, np.pi, 200)
+        >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200)
+        >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine)
+
+        Finally we plot the coarsly-sampled input data alongside the
+        finely-sampled interpolated data to check that they agree.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1)
+        >>> ax2 = fig.add_subplot(1, 2, 2)
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_fine)
+        >>> plt.show()
+        """
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi):
+            raise ValueError("requested theta out of bounds.")
+
+        return _BivariateSplineBase.__call__(self, theta, phi,
+                                             dx=dtheta, dy=dphi, grid=grid)
+
+    def ev(self, theta, phi, dtheta=0, dphi=0):
+        """
+        Evaluate the spline at points
+
+        Returns the interpolated value at ``(theta[i], phi[i]),
+        i=0,...,len(theta)-1``.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates. Standard Numpy broadcasting is obeyed.
+            The ordering of axes is consistent with
+            np.meshgrid(..., indexing="ij") and inconsistent with the
+            default ordering np.meshgrid(..., indexing="xy").
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int, optional
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        at points not on the original grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200)
+        >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200)
+        >>> zinterp = rsbs.ev(thetainterp, phiinterp)
+
+        Finally we plot the original data for a diagonal slice through the
+        initial grid, and the spline approximation along the same slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or")
+        >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False)
+
+
+class SmoothSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Smooth bivariate spline approximation in spherical coordinates.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    w : array_like, optional
+        Positive 1-D sequence of weights.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``r[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> import numpy as np
+    >>> theta = np.linspace(0., np.pi, 7)
+    >>> phi = np.linspace(0., 2*np.pi, 9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> from scipy.interpolate import SmoothSphereBivariateSpline
+    >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                   data.T.ravel(), s=3.5)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2 * np.pi, 90)
+
+    >>> data_smth = lut(fine_lats, fine_lons)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_smth, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+
+        # input validation
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        with FITPACK_LOCK:
+            nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi,
+                                                                    r, w=w, s=s,
+                                                                    eps=eps)
+        if ier not in [0, -1, -2]:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)]
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+class LSQSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation in spherical
+    coordinates.
+
+    Determines a smoothing bicubic spline according to a given
+    set of knots in the `theta` and `phi` directions.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    tt, tp : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+        Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.
+    w : array_like, optional
+        Positive 1-D sequence of weights, of the same length as `theta`, `phi`
+        and `r`.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the
+        open interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> from scipy.interpolate import LSQSphereBivariateSpline
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> theta = np.linspace(0, np.pi, num=7)
+    >>> phi = np.linspace(0, 2*np.pi, num=9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object. Here, we must also specify the
+    coordinates of the knots to use.
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> knotst, knotsp = theta.copy(), phi.copy()
+    >>> knotst[0] += .0001
+    >>> knotst[-1] -= .0001
+    >>> knotsp[0] += .0001
+    >>> knotsp[-1] -= .0001
+    >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                data.T.ravel(), knotst, knotsp)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2*np.pi, 90)
+    >>> data_lsq = lut(fine_lats, fine_lons)
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_lsq, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+        tt, tp = np.asarray(tt), np.asarray(tp)
+
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if not ((0.0 < tt).all() and (tt < np.pi).all()):
+            raise ValueError('tt should be between (0, pi)')
+        if not ((0.0 < tp).all() and (tp < 2*np.pi).all()):
+            raise ValueError('tp should be between (0, 2pi)')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        nt_, np_ = 8 + len(tt), 8 + len(tp)
+        tt_, tp_ = zeros((nt_,), float), zeros((np_,), float)
+        tt_[4:-4], tp_[4:-4] = tt, tp
+        tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi
+        with FITPACK_LOCK:
+            tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_,
+                                                        w=w, eps=eps)
+        if ier > 0:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_, tp_, c
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+_spfit_messages = _surfit_messages.copy()
+_spfit_messages[10] = """
+ERROR: on entry, the input data are controlled on validity
+       the following restrictions must be satisfied.
+          -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1,
+          -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0.
+          -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0.
+          mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8,
+          kwrk>=5+mu+mv+nuest+nvest,
+          lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest)
+          0< u(i-1)=0: s>=0
+          if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7
+       if one of these conditions is found to be violated,control is
+       immediately repassed to the calling program. in that case there is no
+       approximation returned."""
+
+
+class RectSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh on a sphere.
+
+    Can be used for smoothing data.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    u : array_like
+        1-D array of colatitude coordinates in strictly ascending order.
+        Coordinates must be given in radians and lie within the open interval
+        ``(0, pi)``.
+    v : array_like
+        1-D array of longitude coordinates in strictly ascending order.
+        Coordinates must be given in radians. First element (``v[0]``) must lie
+        within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy
+        ``v[-1] <= v[0] + 2*pi``.
+    r : array_like
+        2-D array of data with shape ``(u.size, v.size)``.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition
+        (``s=0`` is for interpolation).
+    pole_continuity : bool or (bool, bool), optional
+        Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and
+        ``u=pi`` (``pole_continuity[1]``).  The order of continuity at the pole
+        will be 1 or 0 when this is True or False, respectively.
+        Defaults to False.
+    pole_values : float or (float, float), optional
+        Data values at the poles ``u=0`` and ``u=pi``.  Either the whole
+        parameter or each individual element can be None.  Defaults to None.
+    pole_exact : bool or (bool, bool), optional
+        Data value exactness at the poles ``u=0`` and ``u=pi``.  If True, the
+        value is considered to be the right function value, and it will be
+        fitted exactly. If False, the value will be considered to be a data
+        value just like the other data values.  Defaults to False.
+    pole_flat : bool or (bool, bool), optional
+        For the poles at ``u=0`` and ``u=pi``, specify whether or not the
+        approximation has vanishing derivatives.  Defaults to False.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    Currently, only the smoothing spline approximation (``iopt[0] = 0`` and
+    ``iopt[0] = 1`` in the FITPACK routine) is supported.  The exact
+    least-squares spline approximation is not implemented yet.
+
+    When actually performing the interpolation, the requested `v` values must
+    lie within the same length 2pi interval that the original `v` values were
+    chosen from.
+
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid
+
+    >>> import numpy as np
+    >>> lats = np.linspace(10, 170, 9) * np.pi / 180.
+    >>> lons = np.linspace(0, 350, 18) * np.pi / 180.
+    >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
+    ...               np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
+
+    We want to interpolate it to a global one-degree grid
+
+    >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180
+    >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180
+    >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons)
+
+    We need to set up the interpolator object
+
+    >>> from scipy.interpolate import RectSphereBivariateSpline
+    >>> lut = RectSphereBivariateSpline(lats, lons, data)
+
+    Finally we interpolate the data.  The `RectSphereBivariateSpline` object
+    only takes 1-D arrays as input, therefore we need to do some reshaping.
+
+    >>> data_interp = lut.ev(new_lats.ravel(),
+    ...                      new_lons.ravel()).reshape((360, 180)).T
+
+    Looking at the original and the interpolated data, one can see that the
+    interpolant reproduces the original data very well:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(212)
+    >>> ax2.imshow(data_interp, interpolation='nearest')
+    >>> plt.show()
+
+    Choosing the optimal value of ``s`` can be a delicate task. Recommended
+    values for ``s`` depend on the accuracy of the data values.  If the user
+    has an idea of the statistical errors on the data, she can also find a
+    proper estimate for ``s``. By assuming that, if she specifies the
+    right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly
+    reproduces the function underlying the data, she can evaluate
+    ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``.
+    For example, if she knows that the statistical errors on her
+    ``r(i,j)``-values are not greater than 0.1, she may expect that a good
+    ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``.
+
+    If nothing is known about the statistical error in ``r(i,j)``, ``s`` must
+    be determined by trial and error.  The best is then to start with a very
+    large value of ``s`` (to determine the least-squares polynomial and the
+    corresponding upper bound ``fp0`` for ``s``) and then to progressively
+    decrease the value of ``s`` (say by a factor 10 in the beginning, i.e.
+    ``s = fp0 / 10, fp0 / 100, ...``  and more carefully as the approximation
+    shows more detail) to obtain closer fits.
+
+    The interpolation results for different values of ``s`` give some insight
+    into this process:
+
+    >>> fig2 = plt.figure()
+    >>> s = [3e9, 2e9, 1e9, 1e8]
+    >>> for idx, sval in enumerate(s, 1):
+    ...     lut = RectSphereBivariateSpline(lats, lons, data, s=sval)
+    ...     data_interp = lut.ev(new_lats.ravel(),
+    ...                          new_lons.ravel()).reshape((360, 180)).T
+    ...     ax = fig2.add_subplot(2, 2, idx)
+    ...     ax.imshow(data_interp, interpolation='nearest')
+    ...     ax.set_title(f"s = {sval:g}")
+    >>> plt.show()
+
+    """
+
+    def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None,
+                 pole_exact=False, pole_flat=False):
+        iopt = np.array([0, 0, 0], dtype=dfitpack_int)
+        ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int)
+        if pole_values is None:
+            pole_values = (None, None)
+        elif isinstance(pole_values, (float, np.float32, np.float64)):
+            pole_values = (pole_values, pole_values)
+        if isinstance(pole_continuity, bool):
+            pole_continuity = (pole_continuity, pole_continuity)
+        if isinstance(pole_exact, bool):
+            pole_exact = (pole_exact, pole_exact)
+        if isinstance(pole_flat, bool):
+            pole_flat = (pole_flat, pole_flat)
+
+        r0, r1 = pole_values
+        iopt[1:] = pole_continuity
+        if r0 is None:
+            ider[0] = -1
+        else:
+            ider[0] = pole_exact[0]
+
+        if r1 is None:
+            ider[2] = -1
+        else:
+            ider[2] = pole_exact[1]
+
+        ider[1], ider[3] = pole_flat
+
+        u, v = np.ravel(u), np.ravel(v)
+        r = np.asarray(r)
+
+        if not (0.0 < u[0] and u[-1] < np.pi):
+            raise ValueError('u should be between (0, pi)')
+        if not -np.pi <= v[0] < np.pi:
+            raise ValueError('v[0] should be between [-pi, pi)')
+        if not v[-1] <= v[0] + 2*np.pi:
+            raise ValueError('v[-1] should be v[0] + 2pi or less ')
+
+        if not np.all(np.diff(u) > 0.0):
+            raise ValueError('u must be strictly increasing')
+        if not np.all(np.diff(v) > 0.0):
+            raise ValueError('v must be strictly increasing')
+
+        if not u.size == r.shape[0]:
+            raise ValueError('u dimension of r must have same number of '
+                             'elements as u')
+        if not v.size == r.shape[1]:
+            raise ValueError('v dimension of r must have same number of '
+                             'elements as v')
+
+        if pole_continuity[1] is False and pole_flat[1] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+        if pole_continuity[0] is False and pole_flat[0] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+
+        r = np.ravel(r)
+        with FITPACK_LOCK:
+            nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider,
+                                                                    u.copy(),
+                                                                    v.copy(),
+                                                                    r.copy(),
+                                                                    r0, r1, s)
+
+        if ier not in [0, -1, -2]:
+            msg = _spfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)]
+        self.degrees = (3, 3)
+        self.v0 = v[0]
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_impl.py b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a1bcbaeaa5a5bd572de94f98aef096c6d6a97b8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_impl.py
@@ -0,0 +1,805 @@
+"""
+fitpack (dierckx in netlib) --- A Python-C wrapper to FITPACK (by P. Dierckx).
+        FITPACK is a collection of FORTRAN programs for curve and surface
+        fitting with splines and tensor product splines.
+
+See
+ https://web.archive.org/web/20010524124604/http://www.cs.kuleuven.ac.be:80/cwis/research/nalag/research/topics/fitpack.html
+or
+ http://www.netlib.org/dierckx/
+
+Copyright 2002 Pearu Peterson all rights reserved,
+Pearu Peterson 
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
+
+TODO: Make interfaces to the following fitpack functions:
+    For univariate splines: cocosp, concon, fourco, insert
+    For bivariate splines: profil, regrid, parsur, surev
+"""
+
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+import warnings
+import numpy as np
+from . import _fitpack
+from numpy import (atleast_1d, array, ones, zeros, sqrt, ravel, transpose,
+                   empty, iinfo, asarray)
+
+# Try to replace _fitpack interface with
+#  f2py-generated version
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+
+
+def _int_overflow(x, exception, msg=None):
+    """Cast the value to an dfitpack_int and raise an OverflowError if the value
+    cannot fit.
+    """
+    if x > iinfo(dfitpack_int).max:
+        if msg is None:
+            msg = f'{x!r} cannot fit into an {dfitpack_int!r}'
+        raise exception(msg)
+    return dfitpack_int.type(x)
+
+
+_iermess = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree k.\n"
+         "fp gives the upper bound fp0 for the smoothing factor s", None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: data (x,y) size is too small or smoothing parameter"
+        "\ns is too small (fp>s).", ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable cause: s too small. (abs(fp-s)/s>0.001)",
+        ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    10: ["Error on input data", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_iermess2 = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree kx and ky."
+         "\nfp gives the upper bound fp0 for the smoothing factor s", None],
+    -3: ["Warning. The coefficients of the spline have been computed as the\n"
+         "minimal norm least-squares solution of a rank deficient system.",
+         None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: nxest or nyest too small or s is too small. (fp>s)",
+        ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable causes: s too small or badly chosen eps.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    4: ["No more knots can be added because the number of B-spline\n"
+        "coefficients already exceeds the number of data points m.\n"
+        "Probable causes: either s or m too small. (fp>s)", ValueError],
+    5: ["No more knots can be added because the additional knot would\n"
+        "coincide with an old one. Probable cause: s too small or too large\n"
+        "a weight to an inaccurate data point. (fp>s)", ValueError],
+    10: ["Error on input data", ValueError],
+    11: ["rwrk2 too small, i.e., there is not enough workspace for computing\n"
+         "the minimal least-squares solution of a rank deficient system of\n"
+         "linear equations.", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], dfitpack_int), 'u': array([], float),
+                 'ub': 0, 'ue': 1}
+
+
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splprep`
+    if task <= 0:
+        _parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                         'iwrk': array([], dfitpack_int), 'u': array([], float),
+                         'ub': 0, 'ue': 1}
+    x = atleast_1d(x)
+    idim, m = x.shape
+    if per:
+        for i in range(idim):
+            if x[i][0] != x[i][-1]:
+                if not quiet:
+                    warnings.warn(RuntimeWarning('Setting x[%d][%d]=x[%d][0]' %
+                                                 (i, m, i)),
+                                  stacklevel=2)
+                x[i][-1] = x[i][0]
+    if not 0 < idim < 11:
+        raise TypeError('0 < idim < 11 must hold')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    ipar = (u is not None)
+    if ipar:
+        _parcur_cache['u'] = u
+        if ub is None:
+            _parcur_cache['ub'] = u[0]
+        else:
+            _parcur_cache['ub'] = ub
+        if ue is None:
+            _parcur_cache['ue'] = u[-1]
+        else:
+            _parcur_cache['ue'] = ue
+    else:
+        _parcur_cache['u'] = zeros(m, float)
+    if not (1 <= k <= 5):
+        raise TypeError('1 <= k= %d <=5 must hold' % k)
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if (not len(w) == m) or (ipar == 1 and (not len(u) == m)):
+        raise TypeError('Mismatch of input dimensions')
+    if s is None:
+        s = m - sqrt(2*m)
+    if t is None and task == -1:
+        raise TypeError('Knots must be given for task=-1')
+    if t is not None:
+        _parcur_cache['t'] = atleast_1d(t)
+    n = len(_parcur_cache['t'])
+    if task == -1 and n < 2*k + 2:
+        raise TypeError('There must be at least 2*k+2 knots for task=-1')
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if nest is None:
+        nest = m + 2*k
+
+    if (task >= 0 and s == 0) or (nest < 0):
+        if per:
+            nest = m + 2*k
+        else:
+            nest = m + k + 1
+    nest = max(nest, 2*k + 3)
+    u = _parcur_cache['u']
+    ub = _parcur_cache['ub']
+    ue = _parcur_cache['ue']
+    t = _parcur_cache['t']
+    wrk = _parcur_cache['wrk']
+    iwrk = _parcur_cache['iwrk']
+    t, c, o = _fitpack._parcur(ravel(transpose(x)), w, u, ub, ue, k,
+                               task, ipar, s, t, nest, wrk, iwrk, per)
+    _parcur_cache['u'] = o['u']
+    _parcur_cache['ub'] = o['ub']
+    _parcur_cache['ue'] = o['ue']
+    _parcur_cache['t'] = t
+    _parcur_cache['wrk'] = o['wrk']
+    _parcur_cache['iwrk'] = o['iwrk']
+    ier = o['ier']
+    fp = o['fp']
+    n = len(t)
+    u = o['u']
+    c.shape = idim, n - k - 1
+    tcku = [t, list(c), k], u
+    if ier <= 0 and not quiet:
+        warnings.warn(RuntimeWarning(_iermess[ier][0] +
+                                     "\tk=%d n=%d m=%d fp=%f s=%f" %
+                                     (k, len(t), m, fp, s)),
+                      stacklevel=2)
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tcku, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tcku, fp, ier, _iermess['unknown'][0]
+    else:
+        return tcku
+
+
+_curfit_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], dfitpack_int)}
+
+
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splrep`
+    if task <= 0:
+        _curfit_cache = {}
+    x, y = map(atleast_1d, [x, y])
+    m = len(x)
+    if w is None:
+        w = ones(m, float)
+        if s is None:
+            s = 0.0
+    else:
+        w = atleast_1d(w)
+        if s is None:
+            s = m - sqrt(2*m)
+    if not len(w) == m:
+        raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m))
+    if (m != len(y)) or (m != len(w)):
+        raise TypeError('Lengths of the first three arguments (x,y,w) must '
+                        'be equal')
+    if not (1 <= k <= 5):
+        raise TypeError('Given degree of the spline (k=%d) is not supported. '
+                        '(1<=k<=5)' % k)
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if xb is None:
+        xb = x[0]
+    if xe is None:
+        xe = x[-1]
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if t is not None:
+        task = -1
+    if task == -1:
+        if t is None:
+            raise TypeError('Knots must be given for task=-1')
+        numknots = len(t)
+        _curfit_cache['t'] = empty((numknots + 2*k + 2,), float)
+        _curfit_cache['t'][k+1:-k-1] = t
+        nest = len(_curfit_cache['t'])
+    elif task == 0:
+        if per:
+            nest = max(m + 2*k, 2*k + 3)
+        else:
+            nest = max(m + k + 1, 2*k + 3)
+        t = empty((nest,), float)
+        _curfit_cache['t'] = t
+    if task <= 0:
+        if per:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(8 + 5*k),), float)
+        else:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(7 + 3*k),), float)
+        _curfit_cache['iwrk'] = empty((nest,), dfitpack_int)
+    try:
+        t = _curfit_cache['t']
+        wrk = _curfit_cache['wrk']
+        iwrk = _curfit_cache['iwrk']
+    except KeyError as e:
+        raise TypeError("must call with task=1 only after"
+                        " call with task=0,-1") from e
+    if not per:
+        n, c, fp, ier = dfitpack.curfit(task, x, y, w, t, wrk, iwrk,
+                                        xb, xe, k, s)
+    else:
+        n, c, fp, ier = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s)
+    tck = (t[:n], c[:n], k)
+    if ier <= 0 and not quiet:
+        _mess = (_iermess[ier][0] + "\tk=%d n=%d m=%d fp=%f s=%f" %
+                 (k, len(t), m, fp, s))
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tck, fp, ier, _iermess['unknown'][0]
+    else:
+        return tck
+
+
+def splev(x, tck, der=0, ext=0):
+    # see the docstring of `_fitpack_py/splev`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, x=x, t=t, k=k, der=der:
+                        splev(x, [t, c, k], der, ext), c))
+    else:
+        if not (0 <= der <= k):
+            raise ValueError("0<=der=%d<=k=%d must hold" % (der, k))
+        if ext not in (0, 1, 2, 3):
+            raise ValueError(f"ext = {ext} not in (0, 1, 2, 3) ")
+
+        x = asarray(x)
+        shape = x.shape
+        x = atleast_1d(x).ravel()
+        if der == 0:
+            y, ier = dfitpack.splev(t, c, k, x, ext)
+        else:
+            y, ier = dfitpack.splder(t, c, k, x, der, ext)
+
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier == 1:
+            raise ValueError("Found x value not in the domain")
+        if ier:
+            raise TypeError("An error occurred")
+
+        return y.reshape(shape)
+
+
+def splint(a, b, tck, full_output=0):
+    # see the docstring of `_fitpack_py/splint`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, a=a, b=b, t=t, k=k:
+                        splint(a, b, [t, c, k]), c))
+    else:
+        aint, wrk = dfitpack.splint(t, c, k, a, b)
+        if full_output:
+            return aint, wrk
+        else:
+            return aint
+
+
+def sproot(tck, mest=10):
+    # see the docstring of `_fitpack_py/sproot`
+    t, c, k = tck
+    if k != 3:
+        raise ValueError("sproot works only for cubic (k=3) splines")
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, t=t, k=k, mest=mest:
+                        sproot([t, c, k], mest), c))
+    else:
+        if len(t) < 8:
+            raise TypeError(f"The number of knots {len(t)}>=8")
+        z, m, ier = dfitpack.sproot(t, c, mest)
+        if ier == 10:
+            raise TypeError("Invalid input data. "
+                            "t1<=..<=t4 1:
+            return list(map(lambda x, tck=tck: spalde(x, tck), x))
+        d, ier = dfitpack.spalde(t, c, k+1, x[0])
+        if ier == 0:
+            return d
+        if ier == 10:
+            raise TypeError("Invalid input data. t(k)<=x<=t(n-k+1) must hold.")
+        raise TypeError("Unknown error")
+
+# def _curfit(x,y,w=None,xb=None,xe=None,k=3,task=0,s=None,t=None,
+#           full_output=0,nest=None,per=0,quiet=1):
+
+
+_surfit_cache = {'tx': array([], float), 'ty': array([], float),
+                 'wrk': array([], float), 'iwrk': array([], dfitpack_int)}
+
+
+def bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
+             kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
+             full_output=0, nxest=None, nyest=None, quiet=1):
+    """
+    Find a bivariate B-spline representation of a surface.
+
+    Given a set of data points (x[i], y[i], z[i]) representing a surface
+    z=f(x,y), compute a B-spline representation of the surface. Based on
+    the routine SURFIT from FITPACK.
+
+    Parameters
+    ----------
+    x, y, z : ndarray
+        Rank-1 arrays of data points.
+    w : ndarray, optional
+        Rank-1 array of weights. By default ``w=np.ones(len(x))``.
+    xb, xe : float, optional
+        End points of approximation interval in `x`.
+        By default ``xb = x.min(), xe=x.max()``.
+    yb, ye : float, optional
+        End points of approximation interval in `y`.
+        By default ``yb=y.min(), ye = y.max()``.
+    kx, ky : int, optional
+        The degrees of the spline (1 <= kx, ky <= 5).
+        Third order (kx=ky=3) is recommended.
+    task : int, optional
+        If task=0, find knots in x and y and coefficients for a given
+        smoothing factor, s.
+        If task=1, find knots and coefficients for another value of the
+        smoothing factor, s.  bisplrep must have been previously called
+        with task=0 or task=1.
+        If task=-1, find coefficients for a given set of knots tx, ty.
+    s : float, optional
+        A non-negative smoothing factor. If weights correspond
+        to the inverse of the standard-deviation of the errors in z,
+        then a good s-value should be found in the range
+        ``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x).
+    eps : float, optional
+        A threshold for determining the effective rank of an
+        over-determined linear system of equations (0 < eps < 1).
+        `eps` is not likely to need changing.
+    tx, ty : ndarray, optional
+        Rank-1 arrays of the knots of the spline for task=-1
+    full_output : int, optional
+        Non-zero to return optional outputs.
+    nxest, nyest : int, optional
+        Over-estimates of the total number of knots. If None then
+        ``nxest = max(kx+sqrt(m/2),2*kx+3)``,
+        ``nyest = max(ky+sqrt(m/2),2*ky+3)``.
+    quiet : int, optional
+        Non-zero to suppress printing of messages.
+
+    Returns
+    -------
+    tck : array_like
+        A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and
+        coefficients (c) of the bivariate B-spline representation of the
+        surface along with the degree of the spline.
+    fp : ndarray
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success. Success is indicated if
+        ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+    See `bisplev` to evaluate the value of the B-spline given its tck
+    representation.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    References
+    ----------
+    .. [1] Dierckx P.:An algorithm for surface fitting with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P.:An algorithm for surface fitting with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    x, y, z = map(ravel, [x, y, z])  # ensure 1-d arrays.
+    m = len(x)
+    if not (m == len(y) == len(z)):
+        raise TypeError('len(x)==len(y)==len(z) must hold.')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    if not len(w) == m:
+        raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m))
+    if xb is None:
+        xb = x.min()
+    if xe is None:
+        xe = x.max()
+    if yb is None:
+        yb = y.min()
+    if ye is None:
+        ye = y.max()
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if s is None:
+        s = m - sqrt(2*m)
+    if tx is None and task == -1:
+        raise TypeError('Knots_x must be given for task=-1')
+    if tx is not None:
+        _surfit_cache['tx'] = atleast_1d(tx)
+    nx = len(_surfit_cache['tx'])
+    if ty is None and task == -1:
+        raise TypeError('Knots_y must be given for task=-1')
+    if ty is not None:
+        _surfit_cache['ty'] = atleast_1d(ty)
+    ny = len(_surfit_cache['ty'])
+    if task == -1 and nx < 2*kx+2:
+        raise TypeError('There must be at least 2*kx+2 knots_x for task=-1')
+    if task == -1 and ny < 2*ky+2:
+        raise TypeError('There must be at least 2*ky+2 knots_x for task=-1')
+    if not ((1 <= kx <= 5) and (1 <= ky <= 5)):
+        raise TypeError('Given degree of the spline (kx,ky=%d,%d) is not '
+                        'supported. (1<=k<=5)' % (kx, ky))
+    if m < (kx + 1)*(ky + 1):
+        raise TypeError('m >= (kx+1)(ky+1) must hold')
+    if nxest is None:
+        nxest = int(kx + sqrt(m/2))
+    if nyest is None:
+        nyest = int(ky + sqrt(m/2))
+    nxest, nyest = max(nxest, 2*kx + 3), max(nyest, 2*ky + 3)
+    if task >= 0 and s == 0:
+        nxest = int(kx + sqrt(3*m))
+        nyest = int(ky + sqrt(3*m))
+    if task == -1:
+        _surfit_cache['tx'] = atleast_1d(tx)
+        _surfit_cache['ty'] = atleast_1d(ty)
+    tx, ty = _surfit_cache['tx'], _surfit_cache['ty']
+    wrk = _surfit_cache['wrk']
+    u = nxest - kx - 1
+    v = nyest - ky - 1
+    km = max(kx, ky) + 1
+    ne = max(nxest, nyest)
+    bx, by = kx*v + ky + 1, ky*u + kx + 1
+    b1, b2 = bx, bx + v - ky
+    if bx > by:
+        b1, b2 = by, by + u - kx
+    msg = "Too many data points to interpolate"
+    lwrk1 = _int_overflow(u*v*(2 + b1 + b2) +
+                          2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1,
+                          OverflowError,
+                          msg=msg)
+    lwrk2 = _int_overflow(u*v*(b2 + 1) + b2, OverflowError, msg=msg)
+    tx, ty, c, o = _fitpack._surfit(x, y, z, w, xb, xe, yb, ye, kx, ky,
+                                    task, s, eps, tx, ty, nxest, nyest,
+                                    wrk, lwrk1, lwrk2)
+    _curfit_cache['tx'] = tx
+    _curfit_cache['ty'] = ty
+    _curfit_cache['wrk'] = o['wrk']
+    ier, fp = o['ier'], o['fp']
+    tck = [tx, ty, c, kx, ky]
+
+    ierm = min(11, max(-3, ier))
+    if ierm <= 0 and not quiet:
+        _mess = (_iermess2[ierm][0] +
+                 "\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                 (kx, ky, len(tx), len(ty), m, fp, s))
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ierm > 0 and not full_output:
+        if ier in [1, 2, 3, 4, 5]:
+            _mess = ("\n\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                     (kx, ky, len(tx), len(ty), m, fp, s))
+            warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess), stacklevel=2)
+        else:
+            try:
+                raise _iermess2[ierm][1](_iermess2[ierm][0])
+            except KeyError as e:
+                raise _iermess2['unknown'][1](_iermess2['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess2[ierm][0]
+        except KeyError:
+            return tck, fp, ier, _iermess2['unknown'][0]
+    else:
+        return tck
+
+
+def bisplev(x, y, tck, dx=0, dy=0):
+    """
+    Evaluate a bivariate B-spline and its derivatives.
+
+    Return a rank-2 array of spline function values (or spline derivative
+    values) at points given by the cross-product of the rank-1 arrays `x` and
+    `y`.  In special cases, return an array or just a float if either `x` or
+    `y` or both are floats.  Based on BISPEV and PARDER from FITPACK.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        Rank-1 arrays specifying the domain over which to evaluate the
+        spline or its derivative.
+    tck : tuple
+        A sequence of length 5 returned by `bisplrep` containing the knot
+        locations, the coefficients, and the degree of the spline:
+        [tx, ty, c, kx, ky].
+    dx, dy : int, optional
+        The orders of the partial derivatives in `x` and `y` respectively.
+
+    Returns
+    -------
+    vals : ndarray
+        The B-spline or its derivative evaluated over the set formed by
+        the cross-product of `x` and `y`.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+        See `bisplrep` to generate the `tck` representation.
+
+    References
+    ----------
+    .. [1] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P. : Curve and surface fitting with splines,
+       Monographs on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    tx, ty, c, kx, ky = tck
+    if not (0 <= dx < kx):
+        raise ValueError("0 <= dx = %d < kx = %d must hold" % (dx, kx))
+    if not (0 <= dy < ky):
+        raise ValueError("0 <= dy = %d < ky = %d must hold" % (dy, ky))
+    x, y = map(atleast_1d, [x, y])
+    if (len(x.shape) != 1) or (len(y.shape) != 1):
+        raise ValueError("First two entries should be rank-1 arrays.")
+
+    msg = "Too many data points to interpolate."
+
+    _int_overflow(x.size * y.size, MemoryError, msg=msg)
+
+    if dx != 0 or dy != 0:
+        _int_overflow((tx.size - kx - 1)*(ty.size - ky - 1),
+                      MemoryError, msg=msg)
+        z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+    else:
+        z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
+
+    if ier == 10:
+        raise ValueError("Invalid input data")
+    if ier:
+        raise TypeError("An error occurred")
+    z.shape = len(x), len(y)
+    if len(z) > 1:
+        return z
+    if len(z[0]) > 1:
+        return z[0]
+    return z[0][0]
+
+
+def dblint(xa, xb, ya, yb, tck):
+    """Evaluate the integral of a spline over area [xa,xb] x [ya,yb].
+
+    Parameters
+    ----------
+    xa, xb : float
+        The end-points of the x integration interval.
+    ya, yb : float
+        The end-points of the y integration interval.
+    tck : list [tx, ty, c, kx, ky]
+        A sequence of length 5 returned by bisplrep containing the knot
+        locations tx, ty, the coefficients c, and the degrees kx, ky
+        of the spline.
+
+    Returns
+    -------
+    integ : float
+        The value of the resulting integral.
+    """
+    tx, ty, c, kx, ky = tck
+    return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+
+def insert(x, tck, m=1, per=0):
+    # see the docstring of `_fitpack_py/insert`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        cc = []
+        for c_vals in c:
+            tt, cc_val, kk = insert(x, [t, c_vals, k], m)
+            cc.append(cc_val)
+        return (tt, cc, kk)
+    else:
+        tt, cc, ier = _fitpack._insert(per, t, c, k, x, m)
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier:
+            raise TypeError("An error occurred")
+        return (tt, cc, k)
+
+
+def splder(tck, n=1):
+    # see the docstring of `_fitpack_py/splder`
+    if n < 0:
+        return splantider(tck, -n)
+
+    t, c, k = tck
+
+    if n > k:
+        raise ValueError(f"Order of derivative (n = {n!r}) must be <= "
+                         f"order of spline (k = {tck[2]!r})")
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + ((None,)*len(c.shape[1:]))
+
+    with np.errstate(invalid='raise', divide='raise'):
+        try:
+            for j in range(n):
+                # See e.g. Schumaker, Spline Functions: Basic Theory, Chapter 5
+
+                # Compute the denominator in the differentiation formula.
+                # (and append trailing dims, if necessary)
+                dt = t[k+1:-1] - t[1:-k-1]
+                dt = dt[sh]
+                # Compute the new coefficients
+                c = (c[1:-1-k] - c[:-2-k]) * k / dt
+                # Pad coefficient array to same size as knots (FITPACK
+                # convention)
+                c = np.r_[c, np.zeros((k,) + c.shape[1:])]
+                # Adjust knots
+                t = t[1:-1]
+                k -= 1
+        except FloatingPointError as e:
+            raise ValueError(("The spline has internal repeated knots "
+                              "and is not differentiable %d times") % n) from e
+
+    return t, c, k
+
+
+def splantider(tck, n=1):
+    # see the docstring of `_fitpack_py/splantider`
+    if n < 0:
+        return splder(tck, -n)
+
+    t, c, k = tck
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + (None,)*len(c.shape[1:])
+
+    for j in range(n):
+        # This is the inverse set of operations to splder.
+
+        # Compute the multiplier in the antiderivative formula.
+        dt = t[k+1:] - t[:-k-1]
+        dt = dt[sh]
+        # Compute the new coefficients
+        c = np.cumsum(c[:-k-1] * dt, axis=0) / (k + 1)
+        c = np.r_[np.zeros((1,) + c.shape[1:]),
+                  c,
+                  [c[-1]] * (k+2)]
+        # New knots
+        t = np.r_[t[0], t, t[-1]]
+        k += 1
+
+    return t, c, k
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_py.py b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..140fdd60b6a69da4cc4543ed0ee7b359706190f3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_py.py
@@ -0,0 +1,898 @@
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+
+import numpy as np
+
+# These are in the API for fitpack even if not used in fitpack.py itself.
+from ._fitpack_impl import bisplrep, bisplev, dblint  # noqa: F401
+from . import _fitpack_impl as _impl
+from ._bsplines import BSpline
+
+
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    """
+    Find the B-spline representation of an N-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splprep` in new code.
+
+    Given a list of N rank-1 arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        A list of sample vector arrays representing the curve.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x[0]`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard-deviation given by
+        the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
+    u : array_like, optional
+        An array of parameter values. If not given, these values are
+        calculated automatically as ``M = len(x[0])``, where
+
+            v[0] = 0
+
+            v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)
+
+            u[i] = v[i] / v[M-1]
+
+    ub, ue : int, optional
+        The end-points of the parameters interval.  Defaults to
+        u[0] and u[-1].
+    k : int, optional
+        Degree of the spline. Cubic splines are recommended.
+        Even values of `k` should be avoided especially with a small s-value.
+        ``1 <= k <= 5``, default is 3.
+    task : int, optional
+        If task==0 (default), find t and c for a given smoothing factor, s.
+        If task==1, find t and c for another value of the smoothing factor, s.
+        There must have been a previous call with task=0 or task=1
+        for the same set of data.
+        If task=-1 find the weighted least square spline for a given set of
+        knots, t.
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
+        where g(x) is the smoothed interpolation of (x,y).  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger `s` means more smoothing while smaller values of `s`
+        indicate less smoothing. Recommended values of `s` depend on the
+        weights, w.  If the weights represent the inverse of the
+        standard-deviation of y, then a good `s` value should be found in
+        the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
+        data points in x, y, and w.
+    t : array, optional
+        The knots needed for ``task=-1``.
+        There must be at least ``2*k+2`` knots.
+    full_output : int, optional
+        If non-zero, then return optional outputs.
+    nest : int, optional
+        An over-estimate of the total number of knots of the spline to
+        help in determining the storage space.  By default nest=m/2.
+        Always large enough is nest=m+k+1.
+    per : int, optional
+       If non-zero, data points are considered periodic with period
+       ``x[m-1] - x[0]`` and a smooth periodic spline approximation is
+       returned.  Values of ``y[m-1]`` and ``w[m-1]`` are not used.
+    quiet : int, optional
+         Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple, ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    u : array
+        An array of the values of the parameter.
+    fp : float
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success.  Success is indicated
+        if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splrep, splev, sproot, spalde, splint,
+    bisplrep, bisplev
+    UnivariateSpline, BivariateSpline
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives.
+    The number of dimensions N must be smaller than 11.
+
+    The number of coefficients in the `c` array is ``k+1`` less than the number
+    of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
+    the array of coefficients to have the same length as the array of knots.
+    These additional coefficients are ignored by evaluation routines, `splev`
+    and `BSpline`.
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines", report tw55, Dept. Computer Science,
+        K.U.Leuven, 1981.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Generate a discretization of a limacon curve in the polar coordinates:
+
+    >>> import numpy as np
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.5 + np.cos(phi)         # polar coords
+    >>> x, y = r * np.cos(phi), r * np.sin(phi)    # convert to cartesian
+
+    And interpolate:
+
+    >>> from scipy.interpolate import splprep, splev
+    >>> tck, u = splprep([x, y], s=0)
+    >>> new_points = splev(u, tck)
+
+    Notice that (i) we force interpolation by using ``s=0``,
+    (ii) the parameterization, ``u``, is generated automatically.
+    Now plot the result:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, 'ro')
+    >>> ax.plot(new_points[0], new_points[1], 'r-')
+    >>> plt.show()
+
+    """
+
+    res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
+                        quiet)
+    return res
+
+
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    """
+    Find the B-spline representation of a 1-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splrep` in new code.
+
+
+    Given the set of data points ``(x[i], y[i])`` determine a smooth spline
+    approximation of degree k on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `y` values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``. Default is ``ones(len(x))``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines.
+        Even values of `k` should be avoided especially with small `s` values.
+        ``1 <= k <= 5``.
+    task : {1, 0, -1}, optional
+        If ``task==0``, find ``t`` and ``c`` for a given smoothing factor, `s`.
+
+        If ``task==1`` find ``t`` and ``c`` for another value of the smoothing factor,
+        `s`. There must have been a previous call with ``task=0`` or ``task=1`` for
+        the same set of data (``t`` will be stored an used internally)
+
+        If ``task=-1`` find the weighted least square spline for a given set of
+        knots, ``t``. These should be interior knots as knots on the ends will be
+        added automatically.
+    s : float, optional
+        A smoothing condition. The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s`` where ``g(x)``
+        is the smoothed interpolation of ``(x,y)``. The user can use `s` to control
+        the tradeoff between closeness and smoothness of fit. Larger `s` means
+        more smoothing while smaller values of `s` indicate less smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard-deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m),m+sqrt(2*m))`` where ``m`` is
+        the number of datapoints in `x`, `y`, and `w`. default : ``s=m-sqrt(2*m)`` if
+        weights are supplied. ``s = 0.0`` (interpolating) if no weights are
+        supplied.
+    t : array_like, optional
+        The knots needed for ``task=-1``. If given then task is automatically set
+        to ``-1``.
+    full_output : bool, optional
+        If non-zero, then return optional outputs.
+    per : bool, optional
+        If non-zero, data points are considered periodic with period ``x[m-1]`` -
+        ``x[0]`` and a smooth periodic spline approximation is returned. Values of
+        ``y[m-1]`` and ``w[m-1]`` are not used.
+        The default is zero, corresponding to boundary condition 'not-a-knot'.
+    quiet : bool, optional
+        Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    fp : array, optional
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int, optional
+        An integer flag about splrep success. Success is indicated if ``ier<=0``.
+        If ``ier in [1,2,3]``, an error occurred but was not raised. Otherwise an
+        error is raised.
+    msg : str, optional
+        A message corresponding to the integer flag, `ier`.
+
+    See Also
+    --------
+    UnivariateSpline, BivariateSpline
+    splprep, splev, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives. Uses the
+    FORTRAN routine ``curfit`` from FITPACK.
+
+    The user is responsible for assuring that the values of `x` are unique.
+    Otherwise, `splrep` will not return sensible results.
+
+    If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    This routine zero-pads the coefficients array ``c`` to have the same length
+    as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
+    by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
+    `splprep`, which does not zero-pad the coefficients.
+
+    The default boundary condition is 'not-a-knot', i.e. the first and second
+    segment at a curve end are the same polynomial. More boundary conditions are
+    available in `CubicSpline`.
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    You can interpolate 1-D points with a B-spline curve.
+    Further examples are given in
+    :ref:`in the tutorial `.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import splev, splrep
+    >>> x = np.linspace(0, 10, 10)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y)
+    >>> x2 = np.linspace(0, 10, 200)
+    >>> y2 = splev(x2, spl)
+    >>> plt.plot(x, y, 'o', x2, y2)
+    >>> plt.show()
+
+    """
+    res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
+    return res
+
+
+def splev(x, tck, der=0, ext=0):
+    """
+    Evaluate a B-spline or its derivatives.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``__call__`` method.
+
+    Given the knots and coefficients of a B-spline representation, evaluate
+    the value of the smoothing polynomial and its derivatives. This is a
+    wrapper around the FORTRAN routines splev and splder of FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        An array of points at which to return the value of the smoothed
+        spline or its derivatives. If `tck` was returned from `splprep`,
+        then the parameter values, u should be given.
+    tck : BSpline instance or tuple
+        If a tuple, then it should be a sequence of length 3 returned by
+        `splrep` or `splprep` containing the knots, coefficients, and degree
+        of the spline. (Also see Notes.)
+    der : int, optional
+        The order of derivative of the spline to compute (must be less than
+        or equal to k, the degree of the spline).
+    ext : int, optional
+        Controls the value returned for elements of ``x`` not in the
+        interval defined by the knot sequence.
+
+        * if ext=0, return the extrapolated value.
+        * if ext=1, return 0
+        * if ext=2, raise a ValueError
+        * if ext=3, return the boundary value.
+
+        The default value is 0.
+
+    Returns
+    -------
+    y : ndarray or list of ndarrays
+        An array of values representing the spline function evaluated at
+        the points in `x`.  If `tck` was returned from `splprep`, then this
+        is a list of arrays representing the curve in an N-D space.
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.__call__(x) instead.")
+            raise ValueError(mesg)
+
+        # remap the out-of-bounds behavior
+        try:
+            extrapolate = {0: True, }[ext]
+        except KeyError as e:
+            raise ValueError(f"Extrapolation mode {ext} is not supported "
+                             "by BSpline.") from e
+
+        return tck(x, der, extrapolate=extrapolate)
+    else:
+        return _impl.splev(x, tck, der, ext)
+
+
+def splint(a, b, tck, full_output=0):
+    """
+    Evaluate the definite integral of a B-spline between two given points.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``integrate`` method.
+
+    Parameters
+    ----------
+    a, b : float
+        The end-points of the integration interval.
+    tck : tuple or a BSpline instance
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline (see `splev`).
+    full_output : int, optional
+        Non-zero to return optional output.
+
+    Returns
+    -------
+    integral : float
+        The resulting integral.
+    wrk : ndarray
+        An array containing the integrals of the normalized B-splines
+        defined on the set of knots.
+        (Only returned if `full_output` is non-zero)
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    `splint` silently assumes that the spline function is zero outside the data
+    interval (`a`, `b`).
+
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
+        J. Inst. Maths Applics, 17, p.37-41, 1976.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.integrate() instead.")
+            raise ValueError(mesg)
+
+        if full_output != 0:
+            mesg = (f"full_output = {full_output} is not supported. Proceeding as if "
+                    "full_output = 0")
+
+        return tck.integrate(a, b, extrapolate=False)
+    else:
+        return _impl.splint(a, b, tck, full_output)
+
+
+def sproot(tck, mest=10):
+    """
+    Find the roots of a cubic B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using the
+        following pattern: `PPoly.from_spline(spl).roots()`.
+
+    Given the knots (>=8) and coefficients of a cubic B-spline return the
+    roots of the spline.
+
+    Parameters
+    ----------
+    tck : tuple or a BSpline object
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline.
+        The number of knots must be >= 8, and the degree must be 3.
+        The knots must be a montonically increasing sequence.
+    mest : int, optional
+        An estimate of the number of zeros (Default is 10).
+
+    Returns
+    -------
+    zeros : ndarray
+        An array giving the roots of the spline.
+
+    See Also
+    --------
+    splprep, splrep, splint, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+
+    For some data, this method may miss a root. This happens when one of
+    the spline knots (which FITPACK places automatically) happens to
+    coincide with the true root. A workaround is to convert to `PPoly`,
+    which uses a different root-finding algorithm.
+
+    For example,
+
+    >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+    >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+    ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+    ...      6.520430e-03,  8.170770e-03]
+    >>> from scipy.interpolate import splrep, sproot, PPoly
+    >>> tck = splrep(x, y, s=0)
+    >>> sproot(tck)
+    array([], dtype=float64)
+
+    Converting to a PPoly object does find the roots at ``x=2``:
+
+    >>> ppoly = PPoly.from_spline(tck)
+    >>> ppoly.roots(extrapolate=False)
+    array([2.])
+
+
+    Further examples are given :ref:`in the tutorial
+    `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
+                    "not allowed.")
+            raise ValueError(mesg)
+
+        t, c, k = tck.tck
+
+        # _impl.sproot expects the interpolation axis to be last, so roll it.
+        # NB: This transpose is a no-op if c is 1D.
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        return _impl.sproot((t, c, k), mest)
+    else:
+        return _impl.sproot(tck, mest)
+
+
+def spalde(x, tck):
+    """
+    Evaluate a B-spline and all its derivatives at one point (or set of points) up
+    to order k (the degree of the spline), being 0 the spline itself.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and evaluate
+        its derivative in a loop or a list comprehension.
+
+    Parameters
+    ----------
+    x : array_like
+        A point or a set of points at which to evaluate the derivatives.
+        Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
+    tck : tuple
+        A tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivatives to compute.
+
+    Returns
+    -------
+    results : {ndarray, list of ndarrays}
+        An array (or a list of arrays) containing all derivatives
+        up to order k inclusive for each point `x`, being the first element the 
+        spline itself.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
+    UnivariateSpline, BivariateSpline
+
+    References
+    ----------
+    .. [1] de Boor C : On calculating with b-splines, J. Approximation Theory
+       6 (1972) 50-62.
+    .. [2] Cox M.G. : The numerical evaluation of b-splines, J. Inst. Maths
+       applics 10 (1972) 134-149.
+    .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    To calculate the derivatives of a B-spline there are several aproaches. 
+    In this example, we will demonstrate that `spalde` is equivalent to
+    calling `splev` and `splder`.
+    
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BSpline, spalde, splder, splev
+    
+    >>> # Store characteristic parameters of a B-spline
+    >>> tck = ((-2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2),  # knots
+    ...        (0, 0, 0, 6, 0, 0, 0),  # coefficients
+    ...        3)  # degree (cubic)
+    >>> # Instance a B-spline object
+    >>> # `BSpline` objects are preferred, except for spalde()
+    >>> bspl = BSpline(tck[0], tck[1], tck[2])
+    >>> # Generate extra points to get a smooth curve
+    >>> x = np.linspace(min(tck[0]), max(tck[0]), 100)
+    
+    Evaluate the curve and all derivatives
+    
+    >>> # The order of derivative must be less or equal to k, the degree of the spline
+    >>> # Method 1: spalde()
+    >>> f1_y_bsplin = [spalde(i, tck)[0] for i in x ]  # The B-spline itself
+    >>> f1_y_deriv1 = [spalde(i, tck)[1] for i in x ]  # 1st derivative
+    >>> f1_y_deriv2 = [spalde(i, tck)[2] for i in x ]  # 2nd derivative
+    >>> f1_y_deriv3 = [spalde(i, tck)[3] for i in x ]  # 3rd derivative
+    >>> # You can reach the same result by using `splev`and `splder`
+    >>> f2_y_deriv3 = splev(x, bspl, der=3)
+    >>> f3_y_deriv3 = splder(bspl, n=3)(x)
+    
+    >>> # Generate a figure with three axes for graphic comparison
+    >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16, 5))
+    >>> suptitle = fig.suptitle(f'Evaluate a B-spline and all derivatives')
+    >>> # Plot B-spline and all derivatives using the three methods
+    >>> orders = range(4)
+    >>> linetypes = ['-', '--', '-.', ':']
+    >>> labels = ['B-Spline', '1st deriv.', '2nd deriv.', '3rd deriv.']
+    >>> functions = ['splev()', 'splder()', 'spalde()']
+    >>> for order, linetype, label in zip(orders, linetypes, labels):
+    ...     ax1.plot(x, splev(x, bspl, der=order), linetype, label=label)
+    ...     ax2.plot(x, splder(bspl, n=order)(x), linetype, label=label)
+    ...     ax3.plot(x, [spalde(i, tck)[order] for i in x], linetype, label=label)
+    >>> for ax, function in zip((ax1, ax2, ax3), functions):
+    ...     ax.set_title(function)
+    ...     ax.legend()
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if isinstance(tck, BSpline):
+        raise TypeError("spalde does not accept BSpline instances.")
+    else:
+        return _impl.spalde(x, tck)
+
+
+def insert(x, tck, m=1, per=0):
+    """
+    Insert knots into a B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``insert_knot`` method.
+
+    Given the knots and coefficients of a B-spline representation, create a
+    new B-spline with a knot inserted `m` times at point `x`.
+    This is a wrapper around the FORTRAN routine insert of FITPACK.
+
+    Parameters
+    ----------
+    x (u) : float
+        A knot value at which to insert a new knot.  If `tck` was returned
+        from ``splprep``, then the parameter values, u should be given.
+    tck : a `BSpline` instance or a tuple
+        If tuple, then it is expected to be a tuple (t,c,k) containing
+        the vector of knots, the B-spline coefficients, and the degree of
+        the spline.
+    m : int, optional
+        The number of times to insert the given knot (its multiplicity).
+        Default is 1.
+    per : int, optional
+        If non-zero, the input spline is considered periodic.
+
+    Returns
+    -------
+    BSpline instance or a tuple
+        A new B-spline with knots t, coefficients c, and degree k.
+        ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
+        In case of a periodic spline (``per != 0``) there must be
+        either at least k interior knots t(j) satisfying ``t(k+1)>> from scipy.interpolate import splrep, insert
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 5)
+    >>> y = np.sin(x)
+    >>> tck = splrep(x, y)
+    >>> tck[0]
+    array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+    A knot is inserted:
+
+    >>> tck_inserted = insert(3, tck)
+    >>> tck_inserted[0]
+    array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+    Some knots are inserted:
+
+    >>> tck_inserted2 = insert(8, tck, m=3)
+    >>> tck_inserted2[0]
+    array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+    """
+    if isinstance(tck, BSpline):
+
+        t, c, k = tck.tck
+
+        # FITPACK expects the interpolation axis to be last, so roll it over
+        # NB: if c array is 1D, transposes are no-ops
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
+
+        # and roll the last axis back
+        c_ = np.asarray(c_)
+        c_ = c_.transpose((sh[-1],) + sh[:-1])
+        return BSpline(t_, c_, k_)
+    else:
+        return _impl.insert(x, tck, m, per)
+
+
+def splder(tck, n=1):
+    """
+    Compute the spline representation of the derivative of a given spline
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``derivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or tuple
+        BSpline instance or a tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivative to compute
+    n : int, optional
+        Order of derivative to evaluate. Default: 1
+
+    Returns
+    -------
+    `BSpline` instance or tuple
+        Spline of order k2=k-n representing the derivative
+        of the input spline.
+        A tuple is returned if the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splantider, splev, spalde
+    BSpline
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This can be used for finding maxima of a curve:
+
+    >>> from scipy.interpolate import splrep, splder, sproot
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 70)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y, k=4)
+
+    Now, differentiate the spline and find the zeros of the
+    derivative. (NB: `sproot` only works for order 3 splines, so we
+    fit an order 4 spline):
+
+    >>> dspl = splder(spl)
+    >>> sproot(dspl) / np.pi
+    array([ 0.50000001,  1.5       ,  2.49999998])
+
+    This agrees well with roots :math:`\\pi/2 + n\\pi` of
+    :math:`\\cos(x) = \\sin'(x)`.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.derivative(n)
+    else:
+        return _impl.splder(tck, n)
+
+
+def splantider(tck, n=1):
+    """
+    Compute the spline for the antiderivative (integral) of a given spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``antiderivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or a tuple of (t, c, k)
+        Spline whose antiderivative to compute
+    n : int, optional
+        Order of antiderivative to evaluate. Default: 1
+
+    Returns
+    -------
+    BSpline instance or a tuple of (t2, c2, k2)
+        Spline of order k2=k+n representing the antiderivative of the input
+        spline.
+        A tuple is returned iff the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splder, splev, spalde
+    BSpline
+
+    Notes
+    -----
+    The `splder` function is the inverse operation of this function.
+    Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
+    rounding error.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    >>> from scipy.interpolate import splrep, splder, splantider, splev
+    >>> import numpy as np
+    >>> x = np.linspace(0, np.pi/2, 70)
+    >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+    >>> spl = splrep(x, y)
+
+    The derivative is the inverse operation of the antiderivative,
+    although some floating point error accumulates:
+
+    >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
+    (array(2.1565429877197317), array(2.1565429877201865))
+
+    Antiderivative can be used to evaluate definite integrals:
+
+    >>> ispl = splantider(spl)
+    >>> splev(np.pi/2, ispl) - splev(0, ispl)
+    2.2572053588768486
+
+    This is indeed an approximation to the complete elliptic integral
+    :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+    >>> from scipy.special import ellipk
+    >>> ellipk(0.8)
+    2.2572053268208538
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.antiderivative(n)
+    else:
+        return _impl.splantider(tck, n)
+
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_repro.py b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_repro.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0e5e852492ecc01ce8ccec8a681a4ae424757e2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_fitpack_repro.py
@@ -0,0 +1,992 @@
+""" Replicate FITPACK's logic for constructing smoothing spline functions and curves.
+
+    Currently provides analogs of splrep and splprep python routines, i.e.
+    curfit.f and parcur.f routines (the drivers are fpcurf.f and fppara.f, respectively)
+
+    The Fortran sources are from
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/
+
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+        :doi:`10.1016/0146-664X(82)90043-0`.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+         Numerical Analysis, Oxford University Press, 1993.
+    .. [3] P. Dierckx, "An algorithm for smoothing, differentiation and integration
+         of experimental data using spline functions",
+         Journal of Computational and Applied Mathematics, vol. I, no 3, p. 165 (1975).
+         https://doi.org/10.1016/0771-050X(75)90034-0
+"""
+import warnings
+import operator
+import numpy as np
+
+from ._bsplines import (
+    _not_a_knot, make_interp_spline, BSpline, fpcheck, _lsq_solve_qr
+)
+from . import _dierckx      # type: ignore[attr-defined]
+
+
+#    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#    c  part 1: determination of the number of knots and their position     c
+#    c  **************************************************************      c
+#
+# https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L31
+
+
+# Hardcoded in curfit.f
+TOL = 0.001
+MAXIT = 20
+
+
+def _get_residuals(x, y, t, k, w):
+    # FITPACK has (w*(spl(x)-y))**2; make_lsq_spline has w*(spl(x)-y)**2
+    w2 = w**2
+
+    # inline the relevant part of
+    # >>> spl = make_lsq_spline(x, y, w=w2, t=t, k=k)
+    # NB:
+    #     1. y is assumed to be 2D here. For 1D case (parametric=False),
+    #        the call must have been preceded by y = y[:, None] (cf _validate_inputs)
+    #     2. We always sum the squares across axis=1:
+    #         * For 1D (parametric=False), the last dimension has size one,
+    #           so the summation is a no-op.
+    #         * For 2D (parametric=True), the summation is actually how the
+    #           'residuals' are defined, see Eq. (42) in Dierckx1982
+    #           (the reference is in the docstring of `class F`) below.
+    _, _, c = _lsq_solve_qr(x, y, t, k, w)
+    c = np.ascontiguousarray(c)
+    spl = BSpline(t, c, k)
+    return _compute_residuals(w2, spl(x), y)
+
+
+def _compute_residuals(w2, splx, y):
+    delta = ((splx - y)**2).sum(axis=1)
+    return w2 * delta
+
+
+def add_knot(x, t, k, residuals):
+    """Add a new knot.
+
+    (Approximately) replicate FITPACK's logic:
+      1. split the `x` array into knot intervals, ``t(j+k) <= x(i) <= t(j+k+1)``
+      2. find the interval with the maximum sum of residuals
+      3. insert a new knot into the middle of that interval.
+
+    NB: a new knot is in fact an `x` value at the middle of the interval.
+    So *the knots are a subset of `x`*.
+
+    This routine is an analog of
+    https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpcurf.f#L190-L215
+    (cf _split function)
+
+    and https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpknot.f
+    """
+    new_knot = _dierckx.fpknot(x, t, k, residuals)
+
+    idx_t = np.searchsorted(t, new_knot)
+    t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]]
+    return t_new
+
+
+def _validate_inputs(x, y, w, k, s, xb, xe, parametric):
+    """Common input validations for generate_knots and make_splrep.
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if w is None:
+        w = np.ones_like(x, dtype=float)
+    else:
+        w = np.asarray(w, dtype=float)
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } not implemented yet.")
+        if (w < 0).any():
+            raise ValueError("Weights must be non-negative")
+
+    if y.ndim == 0 or y.ndim > 2:
+        raise ValueError(f"{y.ndim = } not supported (must be 1 or 2.)")
+
+    parametric = bool(parametric)
+    if parametric:
+        if y.ndim != 2:
+            raise ValueError(f"{y.ndim = } != 2 not supported with {parametric =}.")
+    else:
+        if y.ndim != 1:
+            raise ValueError(f"{y.ndim = } != 1 not supported with {parametric =}.")
+        # all _impl functions expect y.ndim = 2
+        y = y[:, None]
+
+    if w.shape[0] != x.shape[0]:
+        raise ValueError(f"Weights is incompatible: {w.shape =} != {x.shape}.")
+
+    if x.shape[0] != y.shape[0]:
+        raise ValueError(f"Data is incompatible: {x.shape = } and {y.shape = }.")
+    if x.ndim != 1 or (x[1:] < x[:-1]).any():
+        raise ValueError("Expect `x` to be an ordered 1D sequence.")
+
+    k = operator.index(k)
+
+    if s < 0:
+        raise ValueError(f"`s` must be non-negative. Got {s = }")
+
+    if xb is None:
+        xb = min(x)
+    if xe is None:
+        xe = max(x)
+
+    return x, y, w, k, s, xb, xe
+
+
+def generate_knots(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+    """Replicate FITPACK's constructing the knot vector.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining the curve ``y = f(x)``.
+    w : array_like, optional
+        Weights.
+    xb : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[0]``.
+    xe : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[-1]``.
+    k : int, optional
+        The spline degree. Default is cubic, ``k = 3``.
+    s : float, optional
+        The smoothing factor. Default is ``s = 0``.
+    nest : int, optional
+        Stop when at least this many knots are placed.
+
+    Yields
+    ------
+    t : ndarray
+        Knot vectors with an increasing number of knots.
+        The generator is finite: it stops when the smoothing critetion is
+        satisfied, or when then number of knots exceeds the maximum value:
+        the user-provided `nest` or `x.size + k + 1` --- which is the knot vector
+        for the interpolating spline.
+
+    Examples
+    --------
+    Generate some noisy data and fit a sequence of LSQ splines:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import make_lsq_spline, generate_knots
+    >>> rng = np.random.default_rng(12345)
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(size=50)
+
+    >>> knots = list(generate_knots(x, y, s=1e-10))
+    >>> for t in knots[::3]:
+    ...     spl = make_lsq_spline(x, y, t)
+    ...     xs = xs = np.linspace(-3, 3, 201)
+    ...     plt.plot(xs, spl(xs), '-', label=f'n = {len(t)}', lw=3, alpha=0.7)
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> plt.plot(xs, np.exp(-xs**2), '--')
+    >>> plt.legend()
+
+    Note that increasing the number of knots make the result follow the data
+    more and more closely.
+
+    Also note that a step of the generator may add multiple knots:
+
+    >>> [len(t) for t in knots]
+    [8, 9, 10, 12, 16, 24, 40, 48, 52, 54]
+
+    Notes
+    -----
+    The routine generates successive knots vectors of increasing length, starting
+    from ``2*(k+1)`` to ``len(x) + k + 1``, trying to make knots more dense
+    in the regions where the deviation of the LSQ spline from data is large.
+
+    When the maximum number of knots, ``len(x) + k + 1`` is reached
+    (this happens when ``s`` is small and ``nest`` is large), the generator
+    stops, and the last output is the knots for the interpolation with the
+    not-a-knot boundary condition.
+
+    Knots are located at data sites, unless ``k`` is even and the number of knots
+    is ``len(x) + k + 1``. In that case, the last output of the generator
+    has internal knots at Greville sites, ``(x[1:] + x[:-1]) / 2``.
+
+    .. versionadded:: 1.15.0
+
+    """
+    if s == 0:
+        if nest is not None or w is not None:
+            raise ValueError("s == 0 is interpolation only")
+        t = _not_a_knot(x, k)
+        yield t
+        return
+
+    x, y, w, k, s, xb, xe = _validate_inputs(
+        x, y, w, k, s, xb, xe, parametric=np.ndim(y) == 2
+    )
+
+    yield from _generate_knots_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, nest=nest)
+
+
+def _generate_knots_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")
+
+    nmin = 2*(k + 1)    # the number of knots for an LSQ polynomial approximation
+    nmax = m + k + 1  # the number of knots for the spline interpolation
+
+    # start from no internal knots
+    t = np.asarray([xb]*(k+1) + [xe]*(k+1), dtype=float)
+    n = t.shape[0]
+    fp = 0.0
+    fpold = 0.0
+
+    # c  main loop for the different sets of knots. m is a safe upper bound
+    # c  for the number of trials.
+    for _ in range(m):
+        yield t
+
+        # construct the LSQ spline with this set of knots
+        fpold = fp
+        residuals = _get_residuals(x, y, t, k, w=w)
+        fp = residuals.sum()
+        fpms = fp - s
+
+        # c  test whether the approximation sinf(x) is an acceptable solution.
+        # c  if f(p=inf) < s accept the choice of knots.
+        if (abs(fpms) < acc) or (fpms < 0):
+            return
+
+        # ### c  increase the number of knots. ###
+
+        # c  determine the number of knots nplus we are going to add.
+        if n == nmin:
+            # the first iteration
+            nplus = 1
+        else:
+            delta = fpold - fp
+            npl1 = int(nplus * fpms / delta) if delta > acc else nplus*2
+            nplus = min(nplus*2, max(npl1, nplus//2, 1))
+
+        # actually add knots
+        for j in range(nplus):
+            t = add_knot(x, t, k, residuals)
+
+            # check if we have enough knots already
+
+            n = t.shape[0]
+            # c  if n = nmax, sinf(x) is an interpolating spline.
+            # c  if n=nmax we locate the knots as for interpolation.
+            if n >= nmax:
+                t = _not_a_knot(x, k)
+                yield t
+                return
+
+            # c  if n=nest we cannot increase the number of knots because of
+            # c  the storage capacity limitation.
+            if n >= nest:
+                yield t
+                return
+
+            # recompute if needed
+            if j < nplus - 1:
+                residuals = _get_residuals(x, y, t, k, w=w)
+
+    # this should never be reached
+    return
+
+
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#   c  part 2: determination of the smoothing spline sp(x).                c
+#   c  ***************************************************                 c
+#   c  we have determined the number of knots and their position.          c
+#   c  we now compute the b-spline coefficients of the smoothing spline    c
+#   c  sp(x). the observation matrix a is extended by the rows of matrix   c
+#   c  b expressing that the kth derivative discontinuities of sp(x) at    c
+#   c  the interior knots t(k+2),...t(n-k-1) must be zero. the corres-     c
+#   c  ponding weights of these additional rows are set to 1/p.            c
+#   c  iteratively we then have to determine the value of p such that      c
+#   c  f(p)=sum((w(i)*(y(i)-sp(x(i))))**2) be = s. we already know that    c
+#   c  the least-squares kth degree polynomial corresponds to p=0, and     c
+#   c  that the least-squares spline corresponds to p=infinity. the        c
+#   c  iteration process which is proposed here, makes use of rational     c
+#   c  interpolation. since f(p) is a convex and strictly decreasing       c
+#   c  function of p, it can be approximated by a rational function        c
+#   c  r(p) = (u*p+v)/(p+w). three values of p(p1,p2,p3) with correspond-  c
+#   c  ing values of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s) are used      c
+#   c  to calculate the new value of p such that r(p)=s. convergence is    c
+#   c  guaranteed by taking f1>0 and f3<0.                                 c
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+
+
+def prodd(t, i, j, k):
+    res = 1.0
+    for s in range(k+2):
+        if i + s != j:
+            res *= (t[j] - t[i+s])
+    return res
+
+
+def disc(t, k):
+    """Discontinuity matrix: jumps of k-th derivatives of b-splines at internal knots.
+
+    See Eqs. (9)-(10) of Ref. [1], or, equivalently, Eq. (3.43) of Ref. [2].
+
+    This routine assumes internal knots are all simple (have multiplicity =1).
+
+    Parameters
+    ----------
+    t : ndarray, 1D, shape(n,)
+        Knots.
+    k : int
+        The spline degree
+
+    Returns
+    -------
+    disc : ndarray, shape(n-2*k-1, k+2)
+        The jumps of the k-th derivatives of b-splines at internal knots,
+        ``t[k+1], ...., t[n-k-1]``.
+    offset : ndarray, shape(2-2*k-1,)
+        Offsets
+    nc : int
+
+    Notes
+    -----
+
+    The normalization here follows FITPACK:
+    (https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpdisc.f#L36)
+
+    The k-th derivative jumps are multiplied by a factor::
+
+        (delta / nrint)**k / k!
+
+    where ``delta`` is the length of the interval spanned by internal knots, and
+    ``nrint`` is one less the number of internal knots (i.e., the number of
+    subintervals between them).
+
+    References
+    ----------
+    .. [1] Paul Dierckx, Algorithms for smoothing data with periodic and parametric
+           splines, Computer Graphics and Image Processing, vol. 20, p. 171 (1982).
+           :doi:`10.1016/0146-664X(82)90043-0`
+
+    .. [2] Tom Lyche and Knut Morken, Spline methods,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+
+    """
+    n = t.shape[0]
+
+    # the length of the base interval spanned by internal knots & the number
+    # of subintervas between these internal knots
+    delta = t[n - k - 1] - t[k]
+    nrint = n - 2*k - 1
+
+    matr = np.empty((nrint - 1, k + 2), dtype=float)
+    for jj in range(nrint - 1):
+        j = jj + k + 1
+        for ii in range(k + 2):
+            i = jj + ii
+            matr[jj, ii] = (t[i + k + 1] - t[i]) / prodd(t, i, j, k)
+        # NB: equivalent to
+        # row = [(t[i + k + 1] - t[i]) / prodd(t, i, j, k) for i in range(j-k-1, j+1)]
+        # assert (matr[j-k-1, :] == row).all()
+
+    # follow FITPACK
+    matr *= (delta/ nrint)**k
+
+    # make it packed
+    offset = np.array([i for i in range(nrint-1)], dtype=np.int64)
+    nc = n - k - 1
+    return matr, offset, nc
+
+
+class F:
+    """ The r.h.s. of ``f(p) = s``.
+
+    Given scalar `p`, we solve the system of equations in the LSQ sense:
+
+        | A     |  @ | c | = | y |
+        | B / p |    | 0 |   | 0 |
+
+    where `A` is the matrix of b-splines and `b` is the discontinuity matrix
+    (the jumps of the k-th derivatives of b-spline basis elements at knots).
+
+    Since we do that repeatedly while minimizing over `p`, we QR-factorize
+    `A` only once and update the QR factorization only of the `B` rows of the
+    augmented matrix |A, B/p|.
+
+    The system of equations is Eq. (15) Ref. [1]_, the strategy and implementation
+    follows that of FITPACK, see specific links below.
+
+    References
+    ----------
+    [1] P. Dierckx, Algorithms for Smoothing Data with Periodic and Parametric Splines,
+        COMPUTER GRAPHICS AND IMAGE PROCESSING vol. 20, pp 171-184 (1982.)
+        https://doi.org/10.1016/0146-664X(82)90043-0
+
+    """
+    def __init__(self, x, y, t, k, s, w=None, *, R=None, Y=None):
+        self.x = x
+        self.y = y
+        self.t = t
+        self.k = k
+        w = np.ones_like(x, dtype=float) if w is None else w
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } != 1.")
+        self.w = w
+        self.s = s
+
+        if y.ndim != 2:
+            raise ValueError(f"F: expected y.ndim == 2, got {y.ndim = } instead.")
+
+        # ### precompute what we can ###
+
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L250
+        # c  evaluate the discontinuity jump of the kth derivative of the
+        # c  b-splines at the knots t(l),l=k+2,...n-k-1 and store in b.
+        b, b_offset, b_nc = disc(t, k)
+
+        # the QR factorization of the data matrix, if not provided
+        # NB: otherwise, must be consistent with x,y & s, but this is not checked
+        if R is None and Y is None:
+            R, Y, _ = _lsq_solve_qr(x, y, t, k, w)
+
+        # prepare to combine R and the discontinuity matrix (AB); also r.h.s. (YY)
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L269
+        # c  the rows of matrix b with weight 1/p are rotated into the
+        # c  triangularised observation matrix a which is stored in g.
+        nc = t.shape[0] - k - 1
+        nz = k + 1
+        if R.shape[1] != nz:
+            raise ValueError(f"Internal error: {R.shape[1] =} != {k+1 =}.")
+
+        # r.h.s. of the augmented system
+        z = np.zeros((b.shape[0], Y.shape[1]), dtype=float)
+        self.YY = np.r_[Y[:nc], z]
+
+        # l.h.s. of the augmented system
+        AA = np.zeros((nc + b.shape[0], self.k+2), dtype=float)
+        AA[:nc, :nz] = R[:nc, :]
+        # AA[nc:, :] = b.a / p  # done in __call__(self, p)
+        self.AA  = AA
+        self.offset = np.r_[np.arange(nc, dtype=np.int64), b_offset]
+
+        self.nc = nc
+        self.b = b
+
+    def __call__(self, p):
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L279
+        # c  the row of matrix b is rotated into triangle by givens transformation
+
+        # copy the precomputed matrices over for in-place work
+        # R = PackedMatrix(self.AB.a.copy(), self.AB.offset.copy(), nc)
+        AB = self.AA.copy()
+        offset = self.offset.copy()
+        nc = self.nc
+
+        AB[nc:, :] = self.b / p
+        QY = self.YY.copy()
+
+        # heavy lifting happens here, in-place
+        _dierckx.qr_reduce(AB, offset, nc, QY, startrow=nc)
+
+        # solve for the coefficients
+        c = _dierckx.fpback(AB, nc, QY)
+
+        spl = BSpline(self.t, c, self.k)
+        residuals = _compute_residuals(self.w**2, spl(self.x), self.y)
+        fp = residuals.sum()
+
+        self.spl = spl   # store it
+
+        return fp - self.s
+
+
+def fprati(p1, f1, p2, f2, p3, f3):
+    """The root of r(p) = (u*p + v) / (p + w) given three points and values,
+    (p1, f2), (p2, f2) and (p3, f3).
+
+    The FITPACK analog adjusts the bounds, and we do not
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fprati.f
+
+    NB: FITPACK uses p < 0 to encode p=infinity. We just use the infinity itself.
+    Since the bracket is ``p1 <= p2 <= p3``, ``p3`` can be infinite (in fact,
+    this is what the minimizer starts with, ``p3=inf``).
+    """
+    h1 = f1 * (f2 - f3)
+    h2 = f2 * (f3 - f1)
+    h3 = f3 * (f1 - f2)
+    if p3 == np.inf:
+        return -(p2*h1 + p1*h2) / h3
+    return -(p1*p2*h3 + p2*p3*h1 + p1*p3*h2) / (p1*h1 + p2*h2 + p3*h3)
+
+
+class Bunch:
+    def __init__(self, **kwargs):
+        self.__dict__.update(**kwargs)
+
+
+_iermesg = {
+2: """error. a theoretically impossible result was found during
+the iteration process for finding a smoothing spline with
+fp = s. probably causes : s too small.
+there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+""",
+3: """error. the maximal number of iterations maxit (set to 20
+by the program) allowed for finding a smoothing spline
+with fp=s has been reached. probably causes : s too small
+there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+"""
+}
+
+
+def root_rati(f, p0, bracket, acc):
+    """Solve `f(p) = 0` using a rational function approximation.
+
+    In a nutshell, since the function f(p) is known to be monotonically decreasing, we
+       - maintain the bracket (p1, f1), (p2, f2) and (p3, f3)
+       - at each iteration step, approximate f(p) by a rational function
+         r(p) = (u*p + v) / (p + w)
+         and make a step to p_new to the root of f(p): r(p_new) = 0.
+         The coefficients u, v and w are found from the bracket values p1..3 and f1...3
+
+    The algorithm and implementation follows
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L229
+    and
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L290
+
+    Note that the latter is for parametric splines and the former is for 1D spline
+    functions. The minimization is indentical though [modulo a summation over the
+    dimensions in the computation of f(p)], so we reuse the minimizer for both
+    d=1 and d>1.
+    """
+    # Magic values from
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L27
+    con1 = 0.1
+    con9 = 0.9
+    con4 = 0.04
+
+    # bracketing flags (follow FITPACK)
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L365
+    ich1, ich3 = 0, 0
+
+    (p1, f1), (p3, f3)  = bracket
+    p = p0
+
+    for it in range(MAXIT):
+        p2, f2 = p, f(p)
+
+        # c  test whether the approximation sp(x) is an acceptable solution.
+        if abs(f2) < acc:
+            ier, converged = 0, True
+            break
+
+        # c  carry out one more step of the iteration process.
+        if ich3 == 0:
+            if f2 - f3 <= acc:
+                # c  our initial choice of p is too large.
+                p3 = p2
+                f3 = f2
+                p = p*con4
+                if p <= p1:
+                     p = p1*con9 + p2*con1
+                continue
+            else:
+                if f2 < 0:
+                    ich3 = 1
+
+        if ich1 == 0:
+            if f1 - f2 <= acc:
+                # c  our initial choice of p is too small
+                p1 = p2
+                f1 = f2
+                p = p/con4
+                if p3 != np.inf and p <= p3:
+                     p = p2*con1 + p3*con9
+                continue
+            else:
+                if f2 > 0:
+                    ich1 = 1
+
+        # c  test whether the iteration process proceeds as theoretically expected.
+        # [f(p) should be monotonically decreasing]
+        if f1 <= f2 or f2 <= f3:
+            ier, converged = 2, False
+            break
+
+        # actually make the iteration step
+        p = fprati(p1, f1, p2, f2, p3, f3)
+
+        # c  adjust the value of p1,f1,p3 and f3 such that f1 > 0 and f3 < 0.
+        if f2 < 0:
+            p3, f3 = p2, f2
+        else:
+            p1, f1 = p2, f2
+
+    else:
+        # not converged in MAXIT iterations
+        ier, converged = 3, False
+
+    if ier != 0:
+        warnings.warn(RuntimeWarning(_iermesg[ier]), stacklevel=2)
+
+    return Bunch(converged=converged, root=p, iterations=it, ier=ier)
+
+
+def _make_splrep_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    """Shared infra for make_splrep and make_splprep.
+    """
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")    
+        if t is not None:
+            raise ValueError("Either supply `t` or `nest`.")
+
+    if t is None:
+        gen = _generate_knots_impl(x, y, w=w, k=k, s=s, xb=xb, xe=xe, nest=nest)
+        t = list(gen)[-1]
+    else:
+        fpcheck(x, t, k)
+
+    if t.shape[0] == 2 * (k + 1):
+        # nothing to optimize
+        _, _, c = _lsq_solve_qr(x, y, t, k, w)
+        return BSpline(t, c, k)
+
+    ### solve ###
+
+    # c  initial value for p.
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L253
+    R, Y, _ = _lsq_solve_qr(x, y, t, k, w)
+    nc = t.shape[0] -k -1
+    p = nc / R[:, 0].sum()
+
+    # ### bespoke solver ####
+    # initial conditions
+    # f(p=inf) : LSQ spline with knots t   (XXX: reuse R, c)
+    residuals = _get_residuals(x, y, t, k, w=w)
+    fp = residuals.sum()
+    fpinf = fp - s
+
+    # f(p=0): LSQ spline without internal knots
+    residuals = _get_residuals(x, y, np.array([xb]*(k+1) + [xe]*(k+1)), k, w)
+    fp0 = residuals.sum()
+    fp0 = fp0 - s
+
+    # solve
+    bracket = (0, fp0), (np.inf, fpinf)
+    f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+    _ = root_rati(f, p, bracket, acc)
+
+    # solve ALTERNATIVE: is roughly equivalent, gives slightly different results
+    # starting from scratch, that would have probably been tolerable;
+    # backwards compatibility dictates that we replicate the FITPACK minimizer though.
+ #   f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+ #   from scipy.optimize import root_scalar
+ #   res_ = root_scalar(f, x0=p, rtol=acc)
+ #   assert res_.converged
+
+    # f.spl is the spline corresponding to the found `p` value
+    return f.spl
+
+
+def make_splrep(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    r"""Find the B-spline representation of a 1D function.
+
+    Given the set of data points ``(x[i], y[i])``, determine a smooth spline
+    approximation of degree ``k`` on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like, shape (m,)
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, shape (m,), optional
+        Strictly positive 1D array of weights, of the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the y values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``.
+        Default is ``np.ones(m)``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``,
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines,
+        ``k=3``, which is the default. Even values of `k` should be avoided,
+        especially with small `s` values.
+    s : float, optional
+        The smoothing condition. The amount of smoothness is determined by
+        satisfying the conditions::
+
+            sum((w * (g(x)  - y))**2 ) <= s
+
+        where ``g(x)`` is the smoothed fit to ``(x, y)``. The user can use `s`
+        to control the tradeoff between closeness to data and smoothness of fit.
+        Larger `s` means more smoothing while smaller values of `s` indicate less
+        smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m), m+sqrt(2*m))`` where
+        ``m`` is the number of datapoints in `x`, `y`, and `w`.
+        Default is ``s = 0.0``, i.e. interpolation.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(x) == y``.
+        For non-zero values of `s` the `spl` represents the smoothed approximation
+        to `(x, y)`, generally with fewer knots.
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splprep : the analog of this routine for parametric curves
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splrep : a FITPACK analog of this routine
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Notes
+    -----
+    This routine constructs the smoothing spline function, :math:`g(x)`, to
+    minimize the sum of jumps, :math:`D_j`, of the ``k``-th derivative at the
+    internal knots (:math:`x_b < t_i < x_e`), where
+
+    .. math::
+
+        D_i = g^{(k)}(t_i + 0) - g^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(x)` which
+    minimizes
+
+    .. math::
+
+            \sum_i | D_i |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+           \sum_{j=1}^m (w_j \times (g(x_j) - y_j))^2 \leqslant s ,
+
+    where :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(x_j)`
+    from the data :math:`y_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``xb < t[i] < xe``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    Also note the difference of this routine to `make_lsq_spline`: the latter
+    routine does not consider smoothness and simply solves a least-squares
+    problem
+
+    .. math::
+
+        \sum w_j \times (g(x_j) - y_j)^2 \to \mathrm{min}
+
+    for a spline function :math:`g(x)` with a _fixed_ knot vector ``t``.
+
+    .. versionadded:: 1.15.0
+    """
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(x, y, k=k)
+
+    x, y, w, k, s, xb, xe = _validate_inputs(x, y, w, k, s, xb, xe, parametric=False)
+
+    spl = _make_splrep_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, t=t, nest=nest)
+
+    # postprocess: squeeze out the last dimension: was added to simplify the internals.
+    spl.c = spl.c[:, 0]
+    return spl
+
+
+def make_splprep(x, *, w=None, u=None, ub=None, ue=None, k=3, s=0, t=None, nest=None):
+    r"""
+    Find a smoothed B-spline representation of a parametric N-D curve.
+
+    Given a list of N 1D arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve ``g(u)``.
+
+    Parameters
+    ----------
+    x : array_like, shape (m, ndim)
+        Sampled data points representing the curve in ``ndim`` dimensions.
+        The typical use is a list of 1D arrays, each of length ``m``.
+    w : array_like, shape(m,), optional
+        Strictly positive 1D array of weights.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard deviation given by
+        the vector d, then `w` should be 1/d. Default is ``np.ones(m)``.
+    u : array_like, optional
+        An array of parameter values for the curve in the parametric form.
+        If not given, these values are calculated automatically, according to::
+
+            v[0] = 0
+            v[i] = v[i-1] + distance(x[i], x[i-1])
+            u[i] = v[i] / v[-1]
+
+    ub, ue : float, optional
+        The end-points of the parameters interval. Default to ``u[0]`` and ``u[-1]``.
+    k : int, optional
+        Degree of the spline. Cubic splines, ``k=3``, are recommended.
+        Even values of `k` should be avoided especially with a small ``s`` value.
+        Default is ``k=3``
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions::
+
+            sum((w * (g(u) - x))**2) <= s,
+
+        where ``g(u)`` is the smoothed approximation to ``x``.  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger ``s`` means more smoothing while smaller values of ``s``
+        indicate less smoothing.
+        Recommended values of ``s`` depend on the weights, ``w``.  If the weights
+        represent the inverse of the standard deviation of ``x``, then a good
+        ``s`` value should be found in the range ``(m - sqrt(2*m), m + sqrt(2*m))``,
+        where ``m`` is the number of data points in ``x`` and ``w``.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(u) == x``.
+        For non-zero values of ``s``, `spl` represents the smoothed approximation
+        to ``x``, generally with fewer knots.
+    u : ndarray
+        The values of the parameters
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splrep : the analog of this routine 1D functions
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splprep : a FITPACK analog of this routine
+
+    Notes
+    -----
+    Given a set of :math:`m` data points in :math:`D` dimensions, :math:`\vec{x}_j`,
+    with :math:`j=1, ..., m` and :math:`\vec{x}_j = (x_{j; 1}, ..., x_{j; D})`,
+    this routine constructs the parametric spline curve :math:`g_a(u)` with
+    :math:`a=1, ..., D`, to minimize the sum of jumps, :math:`D_{i; a}`, of the
+    ``k``-th derivative at the internal knots (:math:`u_b < t_i < u_e`), where
+
+    .. math::
+
+        D_{i; a} = g_a^{(k)}(t_i + 0) - g_a^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(u)` which
+    minimizes
+
+    .. math::
+
+            \sum_i \sum_{a=1}^D | D_{i; a} |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+        \sum_{j=1}^m \sum_{a=1}^D (w_j \times (g_a(u_j) - x_{j; a}))^2 \leqslant s
+
+    where :math:`u_j` is the value of the parameter corresponding to the data point
+    :math:`(x_{j; 1}, ..., x_{j; D})`, and :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(u_j)`
+    from the data :math:`x_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``ub < t[i] < ue``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    .. versionadded:: 1.15.0
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+    """
+    x = np.stack(x, axis=1)
+
+    # construct the default parametrization of the curve
+    if u is None:
+        dp = (x[1:, :] - x[:-1, :])**2
+        u = np.sqrt((dp).sum(axis=1)).cumsum()
+        u = np.r_[0, u / u[-1]]
+
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(u, x.T, k=k, axis=1), u
+
+    u, x, w, k, s, ub, ue = _validate_inputs(u, x, w, k, s, ub, ue, parametric=True)
+
+    spl = _make_splrep_impl(u, x, w=w, xb=ub, xe=ue, k=k, s=s, t=t, nest=nest)
+
+    # posprocess: `axis=1` so that spl(u).shape == np.shape(x)
+    # when `x` is a list of 1D arrays (cf original splPrep)
+    cc = spl.c.T
+    spl1 = BSpline(spl.t, cc, spl.k, axis=1)
+
+    return spl1, u
+
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_interpnd.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_interpnd.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..18887465e8d94bdd8f050c4380f3a527bccbb5ee
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_interpnd.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_interpolate.py b/python_embeded/Lib/site-packages/scipy/interpolate/_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..7539597a89574d1a08f365c2ab095b132881382b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_interpolate.py
@@ -0,0 +1,2248 @@
+__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly']
+
+from math import prod
+
+import numpy as np
+from numpy import array, asarray, intp, poly1d, searchsorted
+
+import scipy.special as spec
+from scipy._lib._util import copy_if_needed
+from scipy.special import comb
+
+from . import _fitpack_py
+from ._polyint import _Interpolator1D
+from . import _ppoly
+from ._interpnd import _ndim_coords_from_arrays
+from ._bsplines import make_interp_spline, BSpline
+
+
+def lagrange(x, w):
+    r"""
+    Return a Lagrange interpolating polynomial.
+
+    Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating
+    polynomial through the points ``(x, w)``.
+
+    Warning: This implementation is numerically unstable. Do not expect to
+    be able to use more than about 20 points even if they are chosen optimally.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` represents the x-coordinates of a set of datapoints.
+    w : array_like
+        `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`).
+
+    Returns
+    -------
+    lagrange : `numpy.poly1d` instance
+        The Lagrange interpolating polynomial.
+
+    Examples
+    --------
+    Interpolate :math:`f(x) = x^3` by 3 points.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import lagrange
+    >>> x = np.array([0, 1, 2])
+    >>> y = x**3
+    >>> poly = lagrange(x, y)
+
+    Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly,
+    it is given by
+
+    .. math::
+
+        \begin{aligned}
+            L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\
+                 &= x (-2 + 3x)
+        \end{aligned}
+
+    >>> from numpy.polynomial.polynomial import Polynomial
+    >>> Polynomial(poly.coef[::-1]).coef
+    array([ 0., -2.,  3.])
+
+    >>> import matplotlib.pyplot as plt
+    >>> x_new = np.arange(0, 2.1, 0.1)
+    >>> plt.scatter(x, y, label='data')
+    >>> plt.plot(x_new, Polynomial(poly.coef[::-1])(x_new), label='Polynomial')
+    >>> plt.plot(x_new, 3*x_new**2 - 2*x_new + 0*x_new,
+    ...          label=r"$3 x^2 - 2 x$", linestyle='-.')
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+
+    M = len(x)
+    p = poly1d(0.0)
+    for j in range(M):
+        pt = poly1d(w[j])
+        for k in range(M):
+            if k == j:
+                continue
+            fac = x[j]-x[k]
+            pt *= poly1d([1.0, -x[k]])/fac
+        p += pt
+    return p
+
+
+# !! Need to find argument for keeping initialize. If it isn't
+# !! found, get rid of it!
+
+
+err_mesg = """\
+`interp2d` has been removed in SciPy 1.14.0.
+
+For legacy code, nearly bug-for-bug compatible replacements are
+`RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+scattered 2D data.
+
+In new code, for regular grids use `RegularGridInterpolator` instead.
+For scattered data, prefer `LinearNDInterpolator` or
+`CloughTocher2DInterpolator`.
+
+For more details see
+https://scipy.github.io/devdocs/tutorial/interpolate/interp_transition_guide.html
+"""
+
+class interp2d:
+    """
+    interp2d(x, y, z, kind='linear', copy=True, bounds_error=False,
+             fill_value=None)
+
+    .. versionremoved:: 1.14.0
+
+        `interp2d` has been removed in SciPy 1.14.0.
+
+        For legacy code, nearly bug-for-bug compatible replacements are
+        `RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+        scattered 2D data.
+
+        In new code, for regular grids use `RegularGridInterpolator` instead.
+        For scattered data, prefer `LinearNDInterpolator` or
+        `CloughTocher2DInterpolator`.
+
+        For more details see :ref:`interp-transition-guide`.
+    """
+    def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False,
+                 fill_value=None):
+        raise NotImplementedError(err_mesg)
+
+
+def _check_broadcast_up_to(arr_from, shape_to, name):
+    """Helper to check that arr_from broadcasts up to shape_to"""
+    shape_from = arr_from.shape
+    if len(shape_to) >= len(shape_from):
+        for t, f in zip(shape_to[::-1], shape_from[::-1]):
+            if f != 1 and f != t:
+                break
+        else:  # all checks pass, do the upcasting that we need later
+            if arr_from.size != 1 and arr_from.shape != shape_to:
+                arr_from = np.ones(shape_to, arr_from.dtype) * arr_from
+            return arr_from.ravel()
+    # at least one check failed
+    raise ValueError(f'{name} argument must be able to broadcast up '
+                     f'to shape {shape_to} but had shape {shape_from}')
+
+
+def _do_extrapolate(fill_value):
+    """Helper to check if fill_value == "extrapolate" without warnings"""
+    return (isinstance(fill_value, str) and
+            fill_value == 'extrapolate')
+
+
+class interp1d(_Interpolator1D):
+    """
+    Interpolate a 1-D function.
+
+    .. legacy:: class
+
+        For a guide to the intended replacements for `interp1d` see
+        :ref:`tutorial-interpolate_1Dsection`.
+
+    `x` and `y` are arrays of values used to approximate some function f:
+    ``y = f(x)``. This class returns a function whose call method uses
+    interpolation to find the value of new points.
+
+    Parameters
+    ----------
+    x : (npoints, ) array_like
+        A 1-D array of real values.
+    y : (..., npoints, ...) array_like
+        A N-D array of real values. The length of `y` along the interpolation
+        axis must be equal to the length of `x`. Use the ``axis`` parameter
+        to select correct axis. Unlike other interpolators, the default
+        interpolation axis is the last axis of `y`.
+    kind : str or int, optional
+        Specifies the kind of interpolation as a string or as an integer
+        specifying the order of the spline interpolator to use.
+        The string has to be one of 'linear', 'nearest', 'nearest-up', 'zero',
+        'slinear', 'quadratic', 'cubic', 'previous', or 'next'. 'zero',
+        'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of
+        zeroth, first, second or third order; 'previous' and 'next' simply
+        return the previous or next value of the point; 'nearest-up' and
+        'nearest' differ when interpolating half-integers (e.g. 0.5, 1.5)
+        in that 'nearest-up' rounds up and 'nearest' rounds down. Default
+        is 'linear'.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Unlike
+        other interpolators, defaults to ``axis=-1``.
+    copy : bool, optional
+        If ``True``, the class makes internal copies of x and y. If ``False``,
+        references to ``x`` and ``y`` are used if possible. The default is to copy.
+    bounds_error : bool, optional
+        If True, a ValueError is raised any time interpolation is attempted on
+        a value outside of the range of x (where extrapolation is
+        necessary). If False, out of bounds values are assigned `fill_value`.
+        By default, an error is raised unless ``fill_value="extrapolate"``.
+    fill_value : array-like or (array-like, array_like) or "extrapolate", optional
+        - if a ndarray (or float), this value will be used to fill in for
+          requested points outside of the data range. If not provided, then
+          the default is NaN. The array-like must broadcast properly to the
+          dimensions of the non-interpolation axes.
+        - If a two-element tuple, then the first element is used as a
+          fill value for ``x_new < x[0]`` and the second element is used for
+          ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g.,
+          list or ndarray, regardless of shape) is taken to be a single
+          array-like argument meant to be used for both bounds as
+          ``below, above = fill_value, fill_value``. Using a two-element tuple
+          or ndarray requires ``bounds_error=False``.
+
+          .. versionadded:: 0.17.0
+        - If "extrapolate", then points outside the data range will be
+          extrapolated.
+
+          .. versionadded:: 0.17.0
+    assume_sorted : bool, optional
+        If False, values of `x` can be in any order and they are sorted first.
+        If True, `x` has to be an array of monotonically increasing values.
+
+    Attributes
+    ----------
+    fill_value
+
+    Methods
+    -------
+    __call__
+
+    See Also
+    --------
+    splrep, splev
+        Spline interpolation/smoothing based on FITPACK.
+    UnivariateSpline : An object-oriented wrapper of the FITPACK routines.
+    interp2d : 2-D interpolation
+
+    Notes
+    -----
+    Calling `interp1d` with NaNs present in input values results in
+    undefined behaviour.
+
+    Input values `x` and `y` must be convertible to `float` values like
+    `int` or `float`.
+
+    If the values in `x` are not unique, the resulting behavior is
+    undefined and specific to the choice of `kind`, i.e., changing
+    `kind` will change the behavior for duplicates.
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import interpolate
+    >>> x = np.arange(0, 10)
+    >>> y = np.exp(-x/3.0)
+    >>> f = interpolate.interp1d(x, y)
+
+    >>> xnew = np.arange(0, 9, 0.1)
+    >>> ynew = f(xnew)   # use interpolation function returned by `interp1d`
+    >>> plt.plot(x, y, 'o', xnew, ynew, '-')
+    >>> plt.show()
+    """
+
+    def __init__(self, x, y, kind='linear', axis=-1,
+                 copy=True, bounds_error=None, fill_value=np.nan,
+                 assume_sorted=False):
+        """ Initialize a 1-D linear interpolation class."""
+        _Interpolator1D.__init__(self, x, y, axis=axis)
+
+        self.bounds_error = bounds_error  # used by fill_value setter
+
+        # `copy` keyword semantics changed in NumPy 2.0, once that is
+        # the minimum version this can use `copy=None`.
+        self.copy = copy
+        if not copy:
+            self.copy = copy_if_needed
+
+        if kind in ['zero', 'slinear', 'quadratic', 'cubic']:
+            order = {'zero': 0, 'slinear': 1,
+                     'quadratic': 2, 'cubic': 3}[kind]
+            kind = 'spline'
+        elif isinstance(kind, int):
+            order = kind
+            kind = 'spline'
+        elif kind not in ('linear', 'nearest', 'nearest-up', 'previous',
+                          'next'):
+            raise NotImplementedError(f"{kind} is unsupported: Use fitpack "
+                                      "routines for other types.")
+        x = array(x, copy=self.copy)
+        y = array(y, copy=self.copy)
+
+        if not assume_sorted:
+            ind = np.argsort(x, kind="mergesort")
+            x = x[ind]
+            y = np.take(y, ind, axis=axis)
+
+        if x.ndim != 1:
+            raise ValueError("the x array must have exactly one dimension.")
+        if y.ndim == 0:
+            raise ValueError("the y array must have at least one dimension.")
+
+        # Force-cast y to a floating-point type, if it's not yet one
+        if not issubclass(y.dtype.type, np.inexact):
+            y = y.astype(np.float64)
+
+        # Backward compatibility
+        self.axis = axis % y.ndim
+
+        # Interpolation goes internally along the first axis
+        self.y = y
+        self._y = self._reshape_yi(self.y)
+        self.x = x
+        del y, x  # clean up namespace to prevent misuse; use attributes
+        self._kind = kind
+
+        # Adjust to interpolation kind; store reference to *unbound*
+        # interpolation methods, in order to avoid circular references to self
+        # stored in the bound instance methods, and therefore delayed garbage
+        # collection.  See: https://docs.python.org/reference/datamodel.html
+        if kind in ('linear', 'nearest', 'nearest-up', 'previous', 'next'):
+            # Make a "view" of the y array that is rotated to the interpolation
+            # axis.
+            minval = 1
+            if kind == 'nearest':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'left'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'nearest-up':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'right'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'previous':
+                # Side for np.searchsorted and index for clipping
+                self._side = 'left'
+                self._ind = 0
+                # Move x by one floating point value to the left
+                self._x_shift = np.nextafter(self.x, -np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.nan, np.take(self.y, -1, axis))
+            elif kind == 'next':
+                self._side = 'right'
+                self._ind = 1
+                # Move x by one floating point value to the right
+                self._x_shift = np.nextafter(self.x, np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.take(self.y, 0, axis), np.nan)
+            else:
+                # Check if we can delegate to numpy.interp (2x-10x faster).
+                np_dtypes = (np.dtype(np.float64), np.dtype(int))
+                cond = self.x.dtype in np_dtypes and self.y.dtype in np_dtypes
+                cond = cond and self.y.ndim == 1
+                cond = cond and not _do_extrapolate(fill_value)
+
+                if cond:
+                    self._call = self.__class__._call_linear_np
+                else:
+                    self._call = self.__class__._call_linear
+        else:
+            minval = order + 1
+
+            rewrite_nan = False
+            xx, yy = self.x, self._y
+            if order > 1:
+                # Quadratic or cubic spline. If input contains even a single
+                # nan, then the output is all nans. We cannot just feed data
+                # with nans to make_interp_spline because it calls LAPACK.
+                # So, we make up a bogus x and y with no nans and use it
+                # to get the correct shape of the output, which we then fill
+                # with nans.
+                # For slinear or zero order spline, we just pass nans through.
+                mask = np.isnan(self.x)
+                if mask.any():
+                    sx = self.x[~mask]
+                    if sx.size == 0:
+                        raise ValueError("`x` array is all-nan")
+                    xx = np.linspace(np.nanmin(self.x),
+                                     np.nanmax(self.x),
+                                     len(self.x))
+                    rewrite_nan = True
+                if np.isnan(self._y).any():
+                    yy = np.ones_like(self._y)
+                    rewrite_nan = True
+
+            self._spline = make_interp_spline(xx, yy, k=order,
+                                              check_finite=False)
+            if rewrite_nan:
+                self._call = self.__class__._call_nan_spline
+            else:
+                self._call = self.__class__._call_spline
+
+        if len(self.x) < minval:
+            raise ValueError("x and y arrays must have at "
+                             "least %d entries" % minval)
+
+        self.fill_value = fill_value  # calls the setter, can modify bounds_err
+
+    @property
+    def fill_value(self):
+        """The fill value."""
+        # backwards compat: mimic a public attribute
+        return self._fill_value_orig
+
+    @fill_value.setter
+    def fill_value(self, fill_value):
+        # extrapolation only works for nearest neighbor and linear methods
+        if _do_extrapolate(fill_value):
+            self._check_and_update_bounds_error_for_extrapolation()
+            self._extrapolate = True
+        else:
+            broadcast_shape = (self.y.shape[:self.axis] +
+                               self.y.shape[self.axis + 1:])
+            if len(broadcast_shape) == 0:
+                broadcast_shape = (1,)
+            # it's either a pair (_below_range, _above_range) or a single value
+            # for both above and below range
+            if isinstance(fill_value, tuple) and len(fill_value) == 2:
+                below_above = [np.asarray(fill_value[0]),
+                               np.asarray(fill_value[1])]
+                names = ('fill_value (below)', 'fill_value (above)')
+                for ii in range(2):
+                    below_above[ii] = _check_broadcast_up_to(
+                        below_above[ii], broadcast_shape, names[ii])
+            else:
+                fill_value = np.asarray(fill_value)
+                below_above = [_check_broadcast_up_to(
+                    fill_value, broadcast_shape, 'fill_value')] * 2
+            self._fill_value_below, self._fill_value_above = below_above
+            self._extrapolate = False
+            if self.bounds_error is None:
+                self.bounds_error = True
+        # backwards compat: fill_value was a public attr; make it writeable
+        self._fill_value_orig = fill_value
+
+    def _check_and_update_bounds_error_for_extrapolation(self):
+        if self.bounds_error:
+            raise ValueError("Cannot extrapolate and raise "
+                             "at the same time.")
+        self.bounds_error = False
+
+    def _call_linear_np(self, x_new):
+        # Note that out-of-bounds values are taken care of in self._evaluate
+        return np.interp(x_new, self.x, self.y)
+
+    def _call_linear(self, x_new):
+        # 2. Find where in the original data, the values to interpolate
+        #    would be inserted.
+        #    Note: If x_new[n] == x[m], then m is returned by searchsorted.
+        x_new_indices = searchsorted(self.x, x_new)
+
+        # 3. Clip x_new_indices so that they are within the range of
+        #    self.x indices and at least 1. Removes mis-interpolation
+        #    of x_new[n] = x[0]
+        x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int)
+
+        # 4. Calculate the slope of regions that each x_new value falls in.
+        lo = x_new_indices - 1
+        hi = x_new_indices
+
+        x_lo = self.x[lo]
+        x_hi = self.x[hi]
+        y_lo = self._y[lo]
+        y_hi = self._y[hi]
+
+        # Note that the following two expressions rely on the specifics of the
+        # broadcasting semantics.
+        slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
+
+        # 5. Calculate the actual value for each entry in x_new.
+        y_new = slope*(x_new - x_lo)[:, None] + y_lo
+
+        return y_new
+
+    def _call_nearest(self, x_new):
+        """ Find nearest neighbor interpolated y_new = f(x_new)."""
+
+        # 2. Find where in the averaged data the values to interpolate
+        #    would be inserted.
+        #    Note: use side='left' (right) to searchsorted() to define the
+        #    halfway point to be nearest to the left (right) neighbor
+        x_new_indices = searchsorted(self.x_bds, x_new, side=self._side)
+
+        # 3. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp)
+
+        # 4. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices]
+
+        return y_new
+
+    def _call_previousnext(self, x_new):
+        """Use previous/next neighbor of x_new, y_new = f(x_new)."""
+
+        # 1. Get index of left/right value
+        x_new_indices = searchsorted(self._x_shift, x_new, side=self._side)
+
+        # 2. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(1-self._ind,
+                                           len(self.x)-self._ind).astype(intp)
+
+        # 3. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices+self._ind-1]
+
+        return y_new
+
+    def _call_spline(self, x_new):
+        return self._spline(x_new)
+
+    def _call_nan_spline(self, x_new):
+        out = self._spline(x_new)
+        out[...] = np.nan
+        return out
+
+    def _evaluate(self, x_new):
+        # 1. Handle values in x_new that are outside of x. Throw error,
+        #    or return a list of mask array indicating the outofbounds values.
+        #    The behavior is set by the bounds_error variable.
+        x_new = asarray(x_new)
+        y_new = self._call(self, x_new)
+        if not self._extrapolate:
+            below_bounds, above_bounds = self._check_bounds(x_new)
+            if len(y_new) > 0:
+                # Note fill_value must be broadcast up to the proper size
+                # and flattened to work here
+                y_new[below_bounds] = self._fill_value_below
+                y_new[above_bounds] = self._fill_value_above
+        return y_new
+
+    def _check_bounds(self, x_new):
+        """Check the inputs for being in the bounds of the interpolated data.
+
+        Parameters
+        ----------
+        x_new : array
+
+        Returns
+        -------
+        out_of_bounds : bool array
+            The mask on x_new of values that are out of the bounds.
+        """
+
+        # If self.bounds_error is True, we raise an error if any x_new values
+        # fall outside the range of x. Otherwise, we return an array indicating
+        # which values are outside the boundary region.
+        below_bounds = x_new < self.x[0]
+        above_bounds = x_new > self.x[-1]
+
+        if self.bounds_error and below_bounds.any():
+            below_bounds_value = x_new[np.argmax(below_bounds)]
+            raise ValueError(f"A value ({below_bounds_value}) in x_new is below "
+                             f"the interpolation range's minimum value ({self.x[0]}).")
+        if self.bounds_error and above_bounds.any():
+            above_bounds_value = x_new[np.argmax(above_bounds)]
+            raise ValueError(f"A value ({above_bounds_value}) in x_new is above "
+                             f"the interpolation range's maximum value ({self.x[-1]}).")
+
+        # !! Should we emit a warning if some values are out of bounds?
+        # !! matlab does not.
+        return below_bounds, above_bounds
+
+
+class _PPolyBase:
+    """Base class for piecewise polynomials."""
+    __slots__ = ('c', 'x', 'extrapolate', 'axis')
+
+    def __init__(self, c, x, extrapolate=None, axis=0):
+        self.c = np.asarray(c)
+        self.x = np.ascontiguousarray(x, dtype=np.float64)
+
+        if extrapolate is None:
+            extrapolate = True
+        elif extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+        self.extrapolate = extrapolate
+
+        if self.c.ndim < 2:
+            raise ValueError("Coefficients array must be at least "
+                             "2-dimensional.")
+
+        if not (0 <= axis < self.c.ndim - 1):
+            raise ValueError(f"axis={axis} must be between 0 and {self.c.ndim-1}")
+
+        self.axis = axis
+        if axis != 0:
+            # move the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (k, m, ...),
+            # and axis !=0 means that we have c.shape (..., k, m, ...)
+            #                                               ^
+            #                                              axis
+            # So we roll two of them.
+            self.c = np.moveaxis(self.c, axis+1, 0)
+            self.c = np.moveaxis(self.c, axis+1, 0)
+
+        if self.x.ndim != 1:
+            raise ValueError("x must be 1-dimensional")
+        if self.x.size < 2:
+            raise ValueError("at least 2 breakpoints are needed")
+        if self.c.ndim < 2:
+            raise ValueError("c must have at least 2 dimensions")
+        if self.c.shape[0] == 0:
+            raise ValueError("polynomial must be at least of order 0")
+        if self.c.shape[1] != self.x.size-1:
+            raise ValueError("number of coefficients != len(x)-1")
+        dx = np.diff(self.x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` must be strictly increasing or decreasing.")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None, axis=0):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type. The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+        """
+        self = object.__new__(cls)
+        self.c = c
+        self.x = x
+        self.axis = axis
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _ensure_c_contiguous(self):
+        """
+        c and x may be modified by the user. The Cython code expects
+        that they are C contiguous.
+        """
+        if not self.x.flags.c_contiguous:
+            self.x = self.x.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def extend(self, c, x):
+        """
+        Add additional breakpoints and coefficients to the polynomial.
+
+        Parameters
+        ----------
+        c : ndarray, size (k, m, ...)
+            Additional coefficients for polynomials in intervals. Note that
+            the first additional interval will be formed using one of the
+            ``self.x`` end points.
+        x : ndarray, size (m,)
+            Additional breakpoints. Must be sorted in the same order as
+            ``self.x`` and either to the right or to the left of the current
+            breakpoints.
+
+        Notes
+        -----
+        This method is not thread safe and must not be executed concurrently
+        with other methods available in this class. Doing so may cause
+        unexpected errors or numerical output mismatches.
+        """
+
+        c = np.asarray(c)
+        x = np.asarray(x)
+
+        if c.ndim < 2:
+            raise ValueError("invalid dimensions for c")
+        if x.ndim != 1:
+            raise ValueError("invalid dimensions for x")
+        if x.shape[0] != c.shape[1]:
+            raise ValueError(f"Shapes of x {x.shape} and c {c.shape} are incompatible")
+        if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim:
+            raise ValueError(
+                f"Shapes of c {c.shape} and self.c {self.c.shape} are incompatible"
+            )
+
+        if c.size == 0:
+            return
+
+        dx = np.diff(x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` is not sorted.")
+
+        if self.x[-1] >= self.x[0]:
+            if not x[-1] >= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] >= self.x[-1]:
+                action = 'append'
+            elif x[-1] <= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+        else:
+            if not x[-1] <= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] <= self.x[-1]:
+                action = 'append'
+            elif x[-1] >= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+
+        dtype = self._get_dtype(c.dtype)
+
+        k2 = max(c.shape[0], self.c.shape[0])
+        c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:],
+                    dtype=dtype)
+
+        if action == 'append':
+            c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c
+            c2[k2-c.shape[0]:, self.c.shape[1]:] = c
+            self.x = np.r_[self.x, x]
+        elif action == 'prepend':
+            c2[k2-self.c.shape[0]:, :c.shape[1]] = c
+            c2[k2-c.shape[0]:, c.shape[1]:] = self.c
+            self.x = np.r_[x, self.x]
+
+        self.c = c2
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative.
+
+        Parameters
+        ----------
+        x : array_like
+            Points to evaluate the interpolant at.
+        nu : int, optional
+            Order of derivative to evaluate. Must be non-negative.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.x[0], self.x[-1]].
+        if extrapolate == 'periodic':
+            x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0])
+            extrapolate = False
+
+        out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+        self._evaluate(x, nu, extrapolate, out)
+        out = out.reshape(x_shape + self.c.shape[2:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+
+class PPoly(_PPolyBase):
+    """
+    Piecewise polynomial in terms of coefficients and breakpoints
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    local power basis::
+
+        S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1))
+
+    where ``k`` is the degree of the polynomial.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k, m, ...)
+        Polynomial coefficients, order `k` and `m` intervals.
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : bool or 'periodic', optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+    extend
+    from_spline
+    from_bernstein_basis
+    construct_fast
+
+    See also
+    --------
+    BPoly : piecewise polynomials in the Bernstein basis
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable. Precision problems can start to appear for orders
+    larger than 20-30.
+    """
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                        self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k - n representing the derivative
+            of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            c2 = self.c[:-nu, :].copy()
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu)
+        c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)]
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:],
+                     dtype=self.c.dtype)
+        c[:-nu] = self.c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu)
+        c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        self._ensure_c_contiguous()
+        _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1),
+                              self.x, nu - 1)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        # construct a compatible polynomial
+        return self.construct_fast(c, self.x, extrapolate, self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over [a, b]
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Swap integration bounds if needed
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+
+        range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # Compute the integral.
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xe, False, out=range_int)
+                range_int *= n_periods
+            else:
+                range_int.fill(0)
+
+            # Map a to [xs, xe], b is always a + left.
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            remainder_int = np.empty_like(range_int)
+            if b <= xe:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, b, False, out=remainder_int)
+                range_int += remainder_int
+            else:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, xe, False, out=remainder_int)
+                range_int += remainder_int
+
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xs + left + a - xe, False, out=remainder_int)
+                range_int += remainder_int
+        else:
+            _ppoly.integrate(
+                self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                self.x, a, b, bool(extrapolate), out=range_int)
+
+        # Return
+        range_int *= sign
+        return range_int.reshape(self.c.shape[2:])
+
+    def solve(self, y=0., discontinuity=True, extrapolate=None):
+        """
+        Find real solutions of the equation ``pp(x) == y``.
+
+        Parameters
+        ----------
+        y : float, optional
+            Right-hand side. Default is zero.
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        Notes
+        -----
+        This routine works only on real-valued polynomials.
+
+        If the piecewise polynomial contains sections that are
+        identically zero, the root list will contain the start point
+        of the corresponding interval, followed by a ``nan`` value.
+
+        If the polynomial is discontinuous across a breakpoint, and
+        there is a sign change across the breakpoint, this is reported
+        if the `discont` parameter is True.
+
+        Examples
+        --------
+
+        Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals
+        ``[-2, 1], [1, 2]``:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import PPoly
+        >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2])
+        >>> pp.solve()
+        array([-1.,  1.])
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        self._ensure_c_contiguous()
+
+        if np.issubdtype(self.c.dtype, np.complexfloating):
+            raise ValueError("Root finding is only for "
+                             "real-valued polynomials")
+
+        y = float(y)
+        r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                              self.x, y, bool(discontinuity),
+                              bool(extrapolate))
+        if self.c.ndim == 2:
+            return r[0]
+        else:
+            r2 = np.empty(prod(self.c.shape[2:]), dtype=object)
+            # this for-loop is equivalent to ``r2[...] = r``, but that's broken
+            # in NumPy 1.6.0
+            for ii, root in enumerate(r):
+                r2[ii] = root
+
+            return r2.reshape(self.c.shape[2:])
+
+    def roots(self, discontinuity=True, extrapolate=None):
+        """
+        Find real roots of the piecewise polynomial.
+
+        Parameters
+        ----------
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        See Also
+        --------
+        PPoly.solve
+        """
+        return self.solve(0, discontinuity, extrapolate)
+
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        """
+        Construct a piecewise polynomial from a spline
+
+        Parameters
+        ----------
+        tck
+            A spline, as returned by `splrep` or a BSpline object.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Examples
+        --------
+        Construct an interpolating spline and convert it to a `PPoly` instance
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> x = np.linspace(0, 1, 11)
+        >>> y = np.sin(2*np.pi*x)
+        >>> tck = splrep(x, y, s=0)
+        >>> p = PPoly.from_spline(tck)
+        >>> isinstance(p, PPoly)
+        True
+
+        Note that this function only supports 1D splines out of the box.
+
+        If the ``tck`` object represents a parametric spline (e.g. constructed
+        by `splprep` or a `BSpline` with ``c.ndim > 1``), you will need to loop
+        over the dimensions manually.
+
+        >>> from scipy.interpolate import splprep, splev
+        >>> t = np.linspace(0, 1, 11)
+        >>> x = np.sin(2*np.pi*t)
+        >>> y = np.cos(2*np.pi*t)
+        >>> (t, c, k), u = splprep([x, y], s=0)
+
+        Note that ``c`` is a list of two arrays of length 11.
+
+        >>> unew = np.arange(0, 1.01, 0.01)
+        >>> out = splev(unew, (t, c, k))
+
+        To convert this spline to the power basis, we convert each
+        component of the list of b-spline coefficients, ``c``, into the
+        corresponding cubic polynomial.
+
+        >>> polys = [PPoly.from_spline((t, cj, k)) for cj in c]
+        >>> polys[0].c.shape
+        (4, 14)
+
+        Note that the coefficients of the polynomials `polys` are in the
+        power basis and their dimensions reflect just that: here 4 is the order
+        (degree+1), and 14 is the number of intervals---which is nothing but
+        the length of the knot array of the original `tck` minus one.
+
+        Optionally, we can stack the components into a single `PPoly` along
+        the third dimension:
+
+        >>> cc = np.dstack([p.c for p in polys])    # has shape = (4, 14, 2)
+        >>> poly = PPoly(cc, polys[0].x)
+        >>> np.allclose(poly(unew).T,     # note the transpose to match `splev`
+        ...             out, atol=1e-15)
+        True
+
+        """
+        if isinstance(tck, BSpline):
+            t, c, k = tck.tck
+            if extrapolate is None:
+                extrapolate = tck.extrapolate
+        else:
+            t, c, k = tck
+
+        cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype)
+        for m in range(k, -1, -1):
+            y = _fitpack_py.splev(t[:-1], tck, der=m)
+            cvals[k - m, :] = y/spec.gamma(m+1)
+
+        return cls.construct_fast(cvals, t, extrapolate)
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in the power basis
+        from a polynomial in Bernstein basis.
+
+        Parameters
+        ----------
+        bp : BPoly
+            A Bernstein basis polynomial, as created by BPoly
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(bp, BPoly):
+            raise TypeError(f".from_bernstein_basis only accepts BPoly instances. "
+                            f"Got {type(bp)} instead.")
+
+        dx = np.diff(bp.x)
+        k = bp.c.shape[0] - 1  # polynomial order
+
+        rest = (None,)*(bp.c.ndim-2)
+
+        c = np.zeros_like(bp.c)
+        for a in range(k+1):
+            factor = (-1)**a * comb(k, a) * bp.c[a]
+            for s in range(a, k+1):
+                val = comb(k-a, s-a) * (-1)**s
+                c[k-s] += factor * val / dx[(slice(None),)+rest]**s
+
+        if extrapolate is None:
+            extrapolate = bp.extrapolate
+
+        return cls.construct_fast(c, bp.x, extrapolate, bp.axis)
+
+
+class BPoly(_PPolyBase):
+    """Piecewise polynomial in terms of coefficients and breakpoints.
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    Bernstein polynomial basis::
+
+        S = sum(c[a, i] * b(a, k; x) for a in range(k+1)),
+
+    where ``k`` is the degree of the polynomial, and::
+
+        b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a),
+
+    with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial
+    coefficient.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k, m, ...)
+        Polynomial coefficients, order `k` and `m` intervals
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : bool, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    extend
+    derivative
+    antiderivative
+    integrate
+    construct_fast
+    from_power_basis
+    from_derivatives
+
+    See also
+    --------
+    PPoly : piecewise polynomials in the power basis
+
+    Notes
+    -----
+    Properties of Bernstein polynomials are well documented in the literature,
+    see for example [1]_ [2]_ [3]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial
+
+    .. [2] Kenneth I. Joy, Bernstein polynomials,
+       http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf
+
+    .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems,
+           vol 2011, article ID 829546, :doi:`10.1155/2011/829543`.
+
+    Examples
+    --------
+    >>> from scipy.interpolate import BPoly
+    >>> x = [0, 1]
+    >>> c = [[1], [2], [3]]
+    >>> bp = BPoly(c, x)
+
+    This creates a 2nd order polynomial
+
+    .. math::
+
+        B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3
+               \\times b_{2, 2}(x) \\\\
+             = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2
+
+    """  # noqa: E501
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate_bernstein(
+            self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+            self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k - nu representing the derivative of
+            this polynomial.
+
+        """
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.derivative()
+            return bp
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            # For a polynomial
+            #    B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x),
+            # we use the fact that
+            #   b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ),
+            # which leads to
+            #   B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1}
+            #
+            # finally, for an interval [y, y + dy] with dy != 1,
+            # we need to correct for an extra power of dy
+
+            rest = (None,)*(self.c.ndim-2)
+
+            k = self.c.shape[0] - 1
+            dx = np.diff(self.x)[(None, slice(None))+rest]
+            c2 = k * np.diff(self.c, axis=0) / dx
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k + nu representing the
+            antiderivative of this polynomial.
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.antiderivative()
+            return bp
+
+        # Construct the indefinite integrals on individual intervals
+        c, x = self.c, self.x
+        k = c.shape[0]
+        c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype)
+
+        c2[1:, ...] = np.cumsum(c, axis=0) / k
+        delta = x[1:] - x[:-1]
+        c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)]
+
+        # Now fix continuity: on the very first interval, take the integration
+        # constant to be zero; on an interval [x_j, x_{j+1}) with j>0,
+        # the integration constant is then equal to the jump of the `bp` at x_j.
+        # The latter is given by the coefficient of B_{n+1, n+1}
+        # *on the previous interval* (other B. polynomials are zero at the
+        # breakpoint). Finally, use the fact that BPs form a partition of unity.
+        c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1]
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(c2, x, extrapolate, axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs. If 'periodic', periodic
+            extrapolation is used. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        array_like
+            Definite integral of the piecewise polynomial over [a, b]
+
+        """
+        # XXX: can probably use instead the fact that
+        # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1)
+        ib = self.antiderivative()
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # ib.extrapolate shouldn't be 'periodic', it is converted to
+        # False for 'periodic. in antiderivative() call.
+        if extrapolate != 'periodic':
+            ib.extrapolate = extrapolate
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            # For simplicity and clarity convert to a <= b case.
+            if a <= b:
+                sign = 1
+            else:
+                a, b = b, a
+                sign = -1
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+            res = n_periods * (ib(xe) - ib(xs))
+
+            # Map a and b to [xs, xe].
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            if b <= xe:
+                res += ib(b) - ib(a)
+            else:
+                res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs)
+
+            return sign * res
+        else:
+            return ib(b) - ib(a)
+
+    def extend(self, c, x):
+        k = max(self.c.shape[0], c.shape[0])
+        self.c = self._raise_degree(self.c, k - self.c.shape[0])
+        c = self._raise_degree(c, k - c.shape[0])
+        return _PPolyBase.extend(self, c, x)
+    extend.__doc__ = _PPolyBase.extend.__doc__
+
+    @classmethod
+    def from_power_basis(cls, pp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in Bernstein basis
+        from a power basis polynomial.
+
+        Parameters
+        ----------
+        pp : PPoly
+            A piecewise polynomial in the power basis
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(pp, PPoly):
+            raise TypeError(f".from_power_basis only accepts PPoly instances. "
+                            f"Got {type(pp)} instead.")
+
+        dx = np.diff(pp.x)
+        k = pp.c.shape[0] - 1   # polynomial order
+
+        rest = (None,)*(pp.c.ndim-2)
+
+        c = np.zeros_like(pp.c)
+        for a in range(k+1):
+            factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a)
+            for j in range(k-a, k+1):
+                c[j] += factor * comb(j, k-a)
+
+        if extrapolate is None:
+            extrapolate = pp.extrapolate
+
+        return cls.construct_fast(c, pp.x, extrapolate, pp.axis)
+
+    @classmethod
+    def from_derivatives(cls, xi, yi, orders=None, extrapolate=None):
+        """Construct a piecewise polynomial in the Bernstein basis,
+        compatible with the specified values and derivatives at breakpoints.
+
+        Parameters
+        ----------
+        xi : array_like
+            sorted 1-D array of x-coordinates
+        yi : array_like or list of array_likes
+            ``yi[i][j]`` is the ``j``\\ th derivative known at ``xi[i]``
+        orders : None or int or array_like of ints. Default: None.
+            Specifies the degree of local polynomials. If not None, some
+            derivatives are ignored.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Notes
+        -----
+        If ``k`` derivatives are specified at a breakpoint ``x``, the
+        constructed polynomial is exactly ``k`` times continuously
+        differentiable at ``x``, unless the ``order`` is provided explicitly.
+        In the latter case, the smoothness of the polynomial at
+        the breakpoint is controlled by the ``order``.
+
+        Deduces the number of derivatives to match at each end
+        from ``order`` and the number of derivatives available. If
+        possible it uses the same number of derivatives from
+        each end; if the number is odd it tries to take the
+        extra one from y2. In any case if not enough derivatives
+        are available at one end or another it draws enough to
+        make up the total from the other end.
+
+        If the order is too high and not enough derivatives are available,
+        an exception is raised.
+
+        Examples
+        --------
+
+        >>> from scipy.interpolate import BPoly
+        >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]])
+
+        Creates a polynomial `f(x)` of degree 3, defined on ``[0, 1]``
+        such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4`
+
+        >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]])
+
+        Creates a piecewise polynomial `f(x)`, such that
+        `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`.
+        Based on the number of derivatives provided, the order of the
+        local polynomials is 2 on ``[0, 1]`` and 1 on ``[1, 2]``.
+        Notice that no restriction is imposed on the derivatives at
+        ``x = 1`` and ``x = 2``.
+
+        Indeed, the explicit form of the polynomial is::
+
+            f(x) = | x * (1 - x),  0 <= x < 1
+                   | 2 * (x - 1),  1 <= x <= 2
+
+        So that f'(1-0) = -1 and f'(1+0) = 2
+
+        """
+        xi = np.asarray(xi)
+        if len(xi) != len(yi):
+            raise ValueError("xi and yi need to have the same length")
+        if np.any(xi[1:] - xi[:1] <= 0):
+            raise ValueError("x coordinates are not in increasing order")
+
+        # number of intervals
+        m = len(xi) - 1
+
+        # global poly order is k-1, local orders are <=k and can vary
+        try:
+            k = max(len(yi[i]) + len(yi[i+1]) for i in range(m))
+        except TypeError as e:
+            raise ValueError(
+                "Using a 1-D array for y? Please .reshape(-1, 1)."
+            ) from e
+
+        if orders is None:
+            orders = [None] * m
+        else:
+            if isinstance(orders, (int, np.integer)):
+                orders = [orders] * m
+            k = max(k, max(orders))
+
+            if any(o <= 0 for o in orders):
+                raise ValueError("Orders must be positive.")
+
+        c = []
+        for i in range(m):
+            y1, y2 = yi[i], yi[i+1]
+            if orders[i] is None:
+                n1, n2 = len(y1), len(y2)
+            else:
+                n = orders[i]+1
+                n1 = min(n//2, len(y1))
+                n2 = min(n - n1, len(y2))
+                n1 = min(n - n2, len(y2))
+                if n1+n2 != n:
+                    mesg = ("Point %g has %d derivatives, point %g"
+                            " has %d derivatives, but order %d requested" % (
+                               xi[i], len(y1), xi[i+1], len(y2), orders[i]))
+                    raise ValueError(mesg)
+
+                if not (n1 <= len(y1) and n2 <= len(y2)):
+                    raise ValueError("`order` input incompatible with"
+                                     " length y1 or y2.")
+
+            b = BPoly._construct_from_derivatives(xi[i], xi[i+1],
+                                                  y1[:n1], y2[:n2])
+            if len(b) < k:
+                b = BPoly._raise_degree(b, k - len(b))
+            c.append(b)
+
+        c = np.asarray(c)
+        return cls(c.swapaxes(0, 1), xi, extrapolate)
+
+    @staticmethod
+    def _construct_from_derivatives(xa, xb, ya, yb):
+        r"""Compute the coefficients of a polynomial in the Bernstein basis
+        given the values and derivatives at the edges.
+
+        Return the coefficients of a polynomial in the Bernstein basis
+        defined on ``[xa, xb]`` and having the values and derivatives at the
+        endpoints `xa` and `xb` as specified by `ya` and `yb`.
+        The polynomial constructed is of the minimal possible degree, i.e.,
+        if the lengths of `ya` and `yb` are `na` and `nb`, the degree
+        of the polynomial is ``na + nb - 1``.
+
+        Parameters
+        ----------
+        xa : float
+            Left-hand end point of the interval
+        xb : float
+            Right-hand end point of the interval
+        ya : array_like
+            Derivatives at `xa`. ``ya[0]`` is the value of the function, and
+            ``ya[i]`` for ``i > 0`` is the value of the ``i``\ th derivative.
+        yb : array_like
+            Derivatives at `xb`.
+
+        Returns
+        -------
+        array
+            coefficient array of a polynomial having specified derivatives
+
+        Notes
+        -----
+        This uses several facts from life of Bernstein basis functions.
+        First of all,
+
+            .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1})
+
+        If B(x) is a linear combination of the form
+
+            .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n},
+
+        then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}.
+        Iterating the latter one, one finds for the q-th derivative
+
+            .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q},
+
+        with
+
+          .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a}
+
+        This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and
+        `c_q` are found one by one by iterating `q = 0, ..., na`.
+
+        At ``x = xb`` it's the same with ``a = n - q``.
+
+        """
+        ya, yb = np.asarray(ya), np.asarray(yb)
+        if ya.shape[1:] != yb.shape[1:]:
+            raise ValueError(
+                f"Shapes of ya {ya.shape} and yb {yb.shape} are incompatible"
+            )
+
+        dta, dtb = ya.dtype, yb.dtype
+        if (np.issubdtype(dta, np.complexfloating) or
+               np.issubdtype(dtb, np.complexfloating)):
+            dt = np.complex128
+        else:
+            dt = np.float64
+
+        na, nb = len(ya), len(yb)
+        n = na + nb
+
+        c = np.empty((na+nb,) + ya.shape[1:], dtype=dt)
+
+        # compute coefficients of a polynomial degree na+nb-1
+        # walk left-to-right
+        for q in range(0, na):
+            c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q
+            for j in range(0, q):
+                c[q] -= (-1)**(j+q) * comb(q, j) * c[j]
+
+        # now walk right-to-left
+        for q in range(0, nb):
+            c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q
+            for j in range(0, q):
+                c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j]
+
+        return c
+
+    @staticmethod
+    def _raise_degree(c, d):
+        r"""Raise a degree of a polynomial in the Bernstein basis.
+
+        Given the coefficients of a polynomial degree `k`, return (the
+        coefficients of) the equivalent polynomial of degree `k+d`.
+
+        Parameters
+        ----------
+        c : array_like
+            coefficient array, 1-D
+        d : integer
+
+        Returns
+        -------
+        array
+            coefficient array, 1-D array of length `c.shape[0] + d`
+
+        Notes
+        -----
+        This uses the fact that a Bernstein polynomial `b_{a, k}` can be
+        identically represented as a linear combination of polynomials of
+        a higher degree `k+d`:
+
+            .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \
+                                 comb(d, j) / comb(k+d, a+j)
+
+        """
+        if d == 0:
+            return c
+
+        k = c.shape[0] - 1
+        out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype)
+
+        for a in range(c.shape[0]):
+            f = c[a] * comb(k, a)
+            for j in range(d+1):
+                out[a+j] += f * comb(d, j) / comb(k+d, a+j)
+        return out
+
+
+class NdPPoly:
+    """
+    Piecewise tensor product polynomial
+
+    The value at point ``xp = (x', y', z', ...)`` is evaluated by first
+    computing the interval indices `i` such that::
+
+        x[0][i[0]] <= x' < x[0][i[0]+1]
+        x[1][i[1]] <= y' < x[1][i[1]+1]
+        ...
+
+    and then computing::
+
+        S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]]
+                * (xp[0] - x[0][i[0]])**m0
+                * ...
+                * (xp[n] - x[n][i[n]])**mn
+                for m0 in range(k[0]+1)
+                ...
+                for mn in range(k[n]+1))
+
+    where ``k[j]`` is the degree of the polynomial in dimension j. This
+    representation is the piecewise multivariate power basis.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...)
+        Polynomial coefficients, with polynomial order `kj` and
+        `mj+1` intervals for each dimension `j`.
+    x : ndim-tuple of ndarrays, shapes (mj+1,)
+        Polynomial breakpoints for each dimension. These must be
+        sorted in increasing order.
+    extrapolate : bool, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs. Default: True.
+
+    Attributes
+    ----------
+    x : tuple of ndarrays
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    integrate_1d
+    construct_fast
+
+    See also
+    --------
+    PPoly : piecewise polynomials in 1D
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable.
+
+    """
+
+    def __init__(self, c, x, extrapolate=None):
+        self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x)
+        self.c = np.asarray(c)
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        if any(v.ndim != 1 for v in self.x):
+            raise ValueError("x arrays must all be 1-dimensional")
+        if any(v.size < 2 for v in self.x):
+            raise ValueError("x arrays must all contain at least 2 points")
+        if c.ndim < 2*ndim:
+            raise ValueError("c must have at least 2*len(x) dimensions")
+        if any(np.any(v[1:] - v[:-1] < 0) for v in self.x):
+            raise ValueError("x-coordinates are not in increasing order")
+        if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)):
+            raise ValueError("x and c do not agree on the number of intervals")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type.  The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+
+        """
+        self = object.__new__(cls)
+        self.c = c
+        self.x = x
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    def _ensure_c_contiguous(self):
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+        if not isinstance(self.x, tuple):
+            self.x = tuple(self.x)
+
+    def __call__(self, x, nu=None, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative
+
+        Parameters
+        ----------
+        x : array-like
+            Points to evaluate the interpolant at.
+        nu : tuple, optional
+            Orders of derivatives to evaluate. Each must be non-negative.
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        y : array-like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+
+        x = _ndim_coords_from_arrays(x)
+        x_shape = x.shape
+        x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float64)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError("invalid number of derivative orders nu")
+
+        dim1 = prod(self.c.shape[:ndim])
+        dim2 = prod(self.c.shape[ndim:2*ndim])
+        dim3 = prod(self.c.shape[2*ndim:])
+        ks = np.array(self.c.shape[:ndim], dtype=np.intc)
+
+        out = np.empty((x.shape[0], dim3), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3),
+                           self.x,
+                           ks,
+                           x,
+                           nu,
+                           bool(extrapolate),
+                           out)
+
+        return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:])
+
+    def _derivative_inplace(self, nu, axis):
+        """
+        Compute 1-D derivative along a selected dimension in-place
+        May result to non-contiguous c array.
+        """
+        if nu < 0:
+            return self._antiderivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        # reduce order
+        if nu == 0:
+            # noop
+            return
+        else:
+            sl = [slice(None)]*ndim
+            sl[axis] = slice(None, -nu, None)
+            c2 = self.c[tuple(sl)]
+
+        if c2.shape[axis] == 0:
+            # derivative of order 0 is zero
+            shp = list(c2.shape)
+            shp[axis] = 1
+            c2 = np.zeros(shp, dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu)
+        sl = [None]*c2.ndim
+        sl[axis] = slice(None)
+        c2 *= factor[tuple(sl)]
+
+        self.c = c2
+
+    def _antiderivative_inplace(self, nu, axis):
+        """
+        Compute 1-D antiderivative along a selected dimension
+        May result to non-contiguous c array.
+        """
+        if nu <= 0:
+            return self._derivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        perm = list(range(ndim))
+        perm[0], perm[axis] = perm[axis], perm[0]
+        perm = perm + list(range(ndim, self.c.ndim))
+
+        c = self.c.transpose(perm)
+
+        c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:],
+                     dtype=c.dtype)
+        c2[:-nu] = c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(c.shape[0], 0, -1), nu)
+        c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        perm2 = list(range(c2.ndim))
+        perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1]
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.copy()
+        _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1),
+                              self.x[axis], nu-1)
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.transpose(perm)
+
+        # Done
+        self.c = c2
+
+    def derivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : NdPPoly
+            Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n])
+            representing the derivative of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals in each dimension are
+        considered half-open, ``[a, b)``, except for the last interval
+        which is closed ``[a, b]``.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._derivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def antiderivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._antiderivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def integrate_1d(self, a, b, axis, extrapolate=None):
+        r"""
+        Compute NdPPoly representation for one dimensional definite integral
+
+        The result is a piecewise polynomial representing the integral:
+
+        .. math::
+
+           p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...)
+
+        where the dimension integrated over is specified with the
+        `axis` parameter.
+
+        Parameters
+        ----------
+        a, b : float
+            Lower and upper bound for integration.
+        axis : int
+            Dimension over which to compute the 1-D integrals
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : NdPPoly or array-like
+            Definite integral of the piecewise polynomial over [a, b].
+            If the polynomial was 1D, an array is returned,
+            otherwise, an NdPPoly object.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        axis = int(axis) % ndim
+
+        # reuse 1-D integration routines
+        c = self.c
+        swap = list(range(c.ndim))
+        swap.insert(0, swap[axis])
+        del swap[axis + 1]
+        swap.insert(1, swap[ndim + axis])
+        del swap[ndim + axis + 1]
+
+        c = c.transpose(swap)
+        p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1),
+                                 self.x[axis],
+                                 extrapolate=extrapolate)
+        out = p.integrate(a, b, extrapolate=extrapolate)
+
+        # Construct result
+        if ndim == 1:
+            return out.reshape(c.shape[2:])
+        else:
+            c = out.reshape(c.shape[2:])
+            x = self.x[:axis] + self.x[axis+1:]
+            return self.construct_fast(c, x, extrapolate=extrapolate)
+
+    def integrate(self, ranges, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        ranges : ndim-tuple of 2-tuples float
+            Sequence of lower and upper bounds for each dimension,
+            ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]``
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over
+            [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]]
+
+        """
+
+        ndim = len(self.x)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        if not hasattr(ranges, '__len__') or len(ranges) != ndim:
+            raise ValueError("Range not a sequence of correct length")
+
+        self._ensure_c_contiguous()
+
+        # Reuse 1D integration routine
+        c = self.c
+        for n, (a, b) in enumerate(ranges):
+            swap = list(range(c.ndim))
+            swap.insert(1, swap[ndim - n])
+            del swap[ndim - n + 1]
+
+            c = c.transpose(swap)
+
+            p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate)
+            out = p.integrate(a, b, extrapolate=extrapolate)
+            c = out.reshape(c.shape[2:])
+
+        return c
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_ndbspline.py b/python_embeded/Lib/site-packages/scipy/interpolate/_ndbspline.py
new file mode 100644
index 0000000000000000000000000000000000000000..50f9ab36a7ea41cab5305093ac29432d315737ce
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_ndbspline.py
@@ -0,0 +1,420 @@
+import itertools
+import functools
+import operator
+import numpy as np
+
+from math import prod
+
+from . import _bspl   # type: ignore[attr-defined]
+
+import scipy.sparse.linalg as ssl
+from scipy.sparse import csr_array
+
+from ._bsplines import _not_a_knot
+
+__all__ = ["NdBSpline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+class NdBSpline:
+    """Tensor product spline object.
+
+    The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear
+    combination of products of one-dimensional b-splines in each of the ``N``
+    dimensions::
+
+       c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN)
+
+
+    Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector
+    ``t`` evaluated at ``x``.
+
+    Parameters
+    ----------
+    t : tuple of 1D ndarrays
+        knot vectors in directions 1, 2, ... N,
+        ``len(t[i]) == n[i] + k + 1``
+    c : ndarray, shape (n1, n2, ..., nN, ...)
+        b-spline coefficients
+    k : int or length-d tuple of integers
+        spline degrees.
+        A single integer is interpreted as having this degree for
+        all dimensions.
+    extrapolate : bool, optional
+        Whether to extrapolate out-of-bounds inputs, or return `nan`.
+        Default is to extrapolate.
+
+    Attributes
+    ----------
+    t : tuple of ndarrays
+        Knots vectors.
+    c : ndarray
+        Coefficients of the tensor-product spline.
+    k : tuple of integers
+        Degrees for each dimension.
+    extrapolate : bool, optional
+        Whether to extrapolate or return nans for out-of-bounds inputs.
+        Defaults to true.
+
+    Methods
+    -------
+    __call__
+    design_matrix
+
+    See Also
+    --------
+    BSpline : a one-dimensional B-spline object
+    NdPPoly : an N-dimensional piecewise tensor product polynomial
+
+    """
+    def __init__(self, t, c, k, *, extrapolate=None):
+        self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t)
+
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        self.c = np.asarray(c)
+
+        ndim = self._t.shape[0]   # == len(self.t)
+        if self.c.ndim < ndim:
+            raise ValueError(f"Coefficients must be at least {ndim}-dimensional.")
+
+        for d in range(ndim):
+            td = self.t[d]
+            kd = self.k[d]
+            n = td.shape[0] - kd - 1
+
+            if self.c.shape[d] != n:
+                raise ValueError(f"Knots, coefficients and degree in dimension"
+                                 f" {d} are inconsistent:"
+                                 f" got {self.c.shape[d]} coefficients for"
+                                 f" {len(td)} knots, need at least {n} for"
+                                 f" k={k}.")
+
+        dt = _get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dt)
+
+    @property
+    def k(self):
+        return tuple(self._k)
+
+    @property
+    def t(self):
+        # repack the knots into a tuple
+        return tuple(self._t[d, :self._len_t[d]] for d in range(self._t.shape[0]))
+
+    def __call__(self, xi, *, nu=None, extrapolate=None):
+        """Evaluate the tensor product b-spline at ``xi``.
+
+        Parameters
+        ----------
+        xi : array_like, shape(..., ndim)
+            The coordinates to evaluate the interpolator at.
+            This can be a list or tuple of ndim-dimensional points
+            or an array with the shape (num_points, ndim).
+        nu : array_like, optional, shape (ndim,)
+            Orders of derivatives to evaluate. Each must be non-negative.
+            Defaults to the zeroth derivivative.
+        extrapolate : bool, optional
+            Whether to exrapolate based on first and last intervals in each
+            dimension, or return `nan`. Default is to ``self.extrapolate``.
+
+        Returns
+        -------
+        values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]``
+            Interpolated values at ``xi``
+        """
+        ndim = self._t.shape[0]  # == len(self.t)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        extrapolate = bool(extrapolate)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError(
+                    f"invalid number of derivative orders {nu = } for "
+                    f"ndim = {len(self.t)}.")
+            if any(nu < 0):
+                raise ValueError(f"derivatives must be positive, got {nu = }")
+
+        # prepare xi : shape (..., m1, ..., md) -> (1, m1, ..., md)
+        xi = np.asarray(xi, dtype=float)
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.ascontiguousarray(xi)
+
+        if xi_shape[-1] != ndim:
+            raise ValueError(f"Shapes: xi.shape={xi_shape} and ndim={ndim}")
+
+        # complex -> double
+        was_complex = self.c.dtype.kind == 'c'
+        cc = self.c
+        if was_complex and self.c.ndim == ndim:
+            # make sure that core dimensions are intact, and complex->float
+            # size doubling only adds a trailing dimension
+            cc = self.c[..., None]
+        cc = cc.view(float)
+
+        # prepare the coefficients: flatten the trailing dimensions
+        c1 = cc.reshape(cc.shape[:ndim] + (-1,))
+        c1r = c1.ravel()
+
+        # replacement for np.ravel_multi_index for indexing of `c1`:
+        _strides_c1 = np.asarray([s // c1.dtype.itemsize
+                                  for s in c1.strides], dtype=np.intp)
+
+        num_c_tr = c1.shape[-1]  # # of trailing coefficients
+        out = np.empty(xi.shape[:-1] + (num_c_tr,), dtype=c1.dtype)
+
+        _bspl.evaluate_ndbspline(xi,
+                                 self._t,
+                                 self._len_t,
+                                 self._k,
+                                 nu,
+                                 extrapolate,
+                                 c1r,
+                                 num_c_tr,
+                                 _strides_c1,
+                                 self._indices_k1d,
+                                 out,)
+        out = out.view(self.c.dtype)
+        return out.reshape(xi_shape[:-1] + self.c.shape[ndim:])
+
+    @classmethod
+    def design_matrix(cls, xvals, t, k, extrapolate=True):
+        """Construct the design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        xvals :  ndarray, shape(npts, ndim)
+            Data points. ``xvals[j, :]`` gives the ``j``-th data point as an
+            ``ndim``-dimensional array.
+        t : tuple of 1D ndarrays, length-ndim
+            Knot vectors in directions 1, 2, ... ndim,
+        k : int
+            B-spline degree.
+        extrapolate : bool, optional
+            Whether to extrapolate out-of-bounds values of raise a `ValueError`
+
+        Returns
+        -------
+        design_matrix : a CSR array
+            Each row of the design matrix corresponds to a value in `xvals` and
+            contains values of b-spline basis elements which are non-zero
+            at this value.
+
+        """
+        xvals = np.asarray(xvals, dtype=float)
+        ndim = xvals.shape[-1]
+        if len(t) != ndim:
+            raise ValueError(
+                f"Data and knots are inconsistent: len(t) = {len(t)} for "
+                f" {ndim = }."
+            )
+
+        # tabulate the flat indices for iterating over the (k+1)**ndim subarray
+        k, _indices_k1d, (_t, len_t) = _preprocess_inputs(k, t)
+
+        # Precompute the shape and strides of the 'coefficients array'.
+        # This would have been the NdBSpline coefficients; in the present context
+        # this is a helper to compute the indices into the colocation matrix.
+        c_shape = tuple(len_t[d] - k[d] - 1 for d in range(ndim))
+
+        # The strides of the coeffs array: the computation is equivalent to
+        # >>> cstrides = [s // 8 for s in np.empty(c_shape).strides]
+        cs = c_shape[1:] + (1,)
+        cstrides = np.cumprod(cs[::-1], dtype=np.intp)[::-1].copy()
+
+        # heavy lifting happens here
+        data, indices, indptr = _bspl._colloc_nd(xvals,
+                                                _t,
+                                                len_t,
+                                                k,
+                                                _indices_k1d,
+                                                cstrides)
+        return csr_array((data, indices, indptr))
+
+
+def _preprocess_inputs(k, t_tpl):
+    """Helpers: validate and preprocess NdBSpline inputs.
+
+       Parameters
+       ----------
+       k : int or tuple
+          Spline orders
+       t_tpl : tuple or array-likes
+          Knots.
+    """
+    # 1. Make sure t_tpl is a tuple
+    if not isinstance(t_tpl, tuple):
+        raise ValueError(f"Expect `t` to be a tuple of array-likes. "
+                         f"Got {t_tpl} instead."
+        )
+
+    # 2. Make ``k`` a tuple of integers
+    ndim = len(t_tpl)
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    k = np.asarray([operator.index(ki) for ki in k], dtype=np.int32)
+
+    if len(k) != ndim:
+        raise ValueError(f"len(t) = {len(t_tpl)} != {len(k) = }.")
+
+    # 3. Validate inputs
+    ndim = len(t_tpl)
+    for d in range(ndim):
+        td = np.asarray(t_tpl[d])
+        kd = k[d]
+        n = td.shape[0] - kd - 1
+        if kd < 0:
+            raise ValueError(f"Spline degree in dimension {d} cannot be"
+                             f" negative.")
+        if td.ndim != 1:
+            raise ValueError(f"Knot vector in dimension {d} must be"
+                             f" one-dimensional.")
+        if n < kd + 1:
+            raise ValueError(f"Need at least {2*kd + 2} knots for degree"
+                             f" {kd} in dimension {d}.")
+        if (np.diff(td) < 0).any():
+            raise ValueError(f"Knots in dimension {d} must be in a"
+                             f" non-decreasing order.")
+        if len(np.unique(td[kd:n + 1])) < 2:
+            raise ValueError(f"Need at least two internal knots in"
+                             f" dimension {d}.")
+        if not np.isfinite(td).all():
+            raise ValueError(f"Knots in dimension {d} should not have"
+                             f" nans or infs.")
+
+    # 4. tabulate the flat indices for iterating over the (k+1)**ndim subarray
+    # non-zero b-spline elements
+    shape = tuple(kd + 1 for kd in k)
+    indices = np.unravel_index(np.arange(prod(shape)), shape)
+    _indices_k1d = np.asarray(indices, dtype=np.intp).T.copy()
+
+    # 5. pack the knots into a single array:
+    #    ([1, 2, 3, 4], [5, 6], (7, 8, 9)) -->
+    #    array([[1, 2, 3, 4],
+    #           [5, 6, nan, nan],
+    #           [7, 8, 9, nan]])
+    ndim = len(t_tpl)
+    len_t = [len(ti) for ti in t_tpl]
+    _t = np.empty((ndim, max(len_t)), dtype=float)
+    _t.fill(np.nan)
+    for d in range(ndim):
+        _t[d, :len(t_tpl[d])] = t_tpl[d]
+    len_t = np.asarray(len_t, dtype=np.int32)
+
+    return k, _indices_k1d, (_t, len_t)
+
+
+def _iter_solve(a, b, solver=ssl.gcrotmk, **solver_args):
+    # work around iterative solvers not accepting multiple r.h.s.
+
+    # also work around a.dtype == float64 and b.dtype == complex128
+    # cf https://github.com/scipy/scipy/issues/19644
+    if np.issubdtype(b.dtype, np.complexfloating):
+        real = _iter_solve(a, b.real, solver, **solver_args)
+        imag = _iter_solve(a, b.imag, solver, **solver_args)
+        return real + 1j*imag
+
+    if b.ndim == 2 and b.shape[1] !=1:
+        res = np.empty_like(b)
+        for j in range(b.shape[1]):
+            res[:, j], info = solver(a, b[:, j], **solver_args)
+            if info != 0:
+                raise ValueError(f"{solver = } returns {info =} for column {j}.")
+        return res
+    else:
+        res, info = solver(a, b, **solver_args)
+        if info != 0:
+            raise ValueError(f"{solver = } returns {info = }.")
+        return res
+
+
+def make_ndbspl(points, values, k=3, *, solver=ssl.gcrotmk, **solver_args):
+    """Construct an interpolating NdBspline.
+
+    Parameters
+    ----------
+    points : tuple of ndarrays of float, with shapes (m1,), ... (mN,)
+        The points defining the regular grid in N dimensions. The points in
+        each dimension (i.e. every element of the `points` tuple) must be
+        strictly ascending or descending.      
+    values : ndarray of float, shape (m1, ..., mN, ...)
+        The data on the regular grid in n dimensions.
+    k : int, optional
+        The spline degree. Must be odd. Default is cubic, k=3
+    solver : a `scipy.sparse.linalg` solver (iterative or direct), optional.
+        An iterative solver from `scipy.sparse.linalg` or a direct one,
+        `sparse.sparse.linalg.spsolve`.
+        Used to solve the sparse linear system
+        ``design_matrix @ coefficients = rhs`` for the coefficients.
+        Default is `scipy.sparse.linalg.gcrotmk`
+    solver_args : dict, optional
+        Additional arguments for the solver. The call signature is
+        ``solver(csr_array, rhs_vector, **solver_args)``
+
+    Returns
+    -------
+    spl : NdBSpline object
+
+    Notes
+    -----
+    Boundary conditions are not-a-knot in all dimensions.
+    """
+    ndim = len(points)
+    xi_shape = tuple(len(x) for x in points)
+
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    for d, point in enumerate(points):
+        numpts = len(np.atleast_1d(point))
+        if numpts <= k[d]:
+            raise ValueError(f"There are {numpts} points in dimension {d},"
+                             f" but order {k[d]} requires at least "
+                             f" {k[d]+1} points per dimension.")
+
+    t = tuple(_not_a_knot(np.asarray(points[d], dtype=float), k[d])
+              for d in range(ndim))
+    xvals = np.asarray([xv for xv in itertools.product(*points)], dtype=float)
+
+    # construct the colocation matrix
+    matr = NdBSpline.design_matrix(xvals, t, k)
+
+    # Solve for the coefficients given `values`.
+    # Trailing dimensions: first ndim dimensions are data, the rest are batch
+    # dimensions, so stack `values` into a 2D array for `spsolve` to undestand.
+    v_shape = values.shape
+    vals_shape = (prod(v_shape[:ndim]), prod(v_shape[ndim:]))
+    vals = values.reshape(vals_shape)
+
+    if solver != ssl.spsolve:
+        solver = functools.partial(_iter_solve, solver=solver)
+        if "atol" not in solver_args:
+            # avoid a DeprecationWarning, grumble grumble
+            solver_args["atol"] = 1e-6
+
+    coef = solver(matr, vals, **solver_args)
+    coef = coef.reshape(xi_shape + v_shape[ndim:])
+    return NdBSpline(t, coef, k)
+
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_ndgriddata.py b/python_embeded/Lib/site-packages/scipy/interpolate/_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..78414808951a493fa6f53e9f71912fbb0bb49b3a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_ndgriddata.py
@@ -0,0 +1,332 @@
+"""
+Convenience interface to N-D interpolation
+
+.. versionadded:: 0.9
+
+"""
+import numpy as np
+from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase,
+     CloughTocher2DInterpolator, _ndim_coords_from_arrays)
+from scipy.spatial import cKDTree
+
+__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
+           'CloughTocher2DInterpolator']
+
+#------------------------------------------------------------------------------
+# Nearest-neighbor interpolation
+#------------------------------------------------------------------------------
+
+
+class NearestNDInterpolator(NDInterpolatorBase):
+    """NearestNDInterpolator(x, y).
+
+    Nearest-neighbor interpolator in N > 1 dimensions.
+
+    .. versionadded:: 0.9
+
+    Methods
+    -------
+    __call__
+
+    Parameters
+    ----------
+    x : (npoints, ndims) 2-D ndarray of floats
+        Data point coordinates.
+    y : (npoints, ) 1-D ndarray of float or complex
+        Data values.
+    rescale : boolean, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+    tree_options : dict, optional
+        Options passed to the underlying ``cKDTree``.
+
+        .. versionadded:: 0.17.0
+
+    See Also
+    --------
+    griddata :
+        Interpolate unstructured D-D data.
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+    Uses ``scipy.spatial.cKDTree``
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+    We can interpolate values on a 2D plane:
+
+    >>> from scipy.interpolate import NearestNDInterpolator
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(10) - 0.5
+    >>> y = rng.random(10) - 0.5
+    >>> z = np.hypot(x, y)
+    >>> X = np.linspace(min(x), max(x))
+    >>> Y = np.linspace(min(y), max(y))
+    >>> X, Y = np.meshgrid(X, Y)  # 2D grid for interpolation
+    >>> interp = NearestNDInterpolator(list(zip(x, y)), z)
+    >>> Z = interp(X, Y)
+    >>> plt.pcolormesh(X, Y, Z, shading='auto')
+    >>> plt.plot(x, y, "ok", label="input point")
+    >>> plt.legend()
+    >>> plt.colorbar()
+    >>> plt.axis("equal")
+    >>> plt.show()
+
+    """
+
+    def __init__(self, x, y, rescale=False, tree_options=None):
+        NDInterpolatorBase.__init__(self, x, y, rescale=rescale,
+                                    need_contiguous=False,
+                                    need_values=False)
+        if tree_options is None:
+            tree_options = dict()
+        self.tree = cKDTree(self.points, **tree_options)
+        self.values = np.asarray(y)
+
+    def __call__(self, *args, **query_options):
+        """
+        Evaluate interpolator at given points.
+
+        Parameters
+        ----------
+        x1, x2, ... xn : array-like of float
+            Points where to interpolate data at.
+            x1, x2, ... xn can be array-like of float with broadcastable shape.
+            or x1 can be array-like of float with shape ``(..., ndim)``
+        **query_options
+            This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers``
+            being passed to the cKDTree's query function to be explicitly set.
+            See `scipy.spatial.cKDTree.query` for an overview of the different options.
+
+            .. versionadded:: 1.12.0
+
+        """
+        # For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs
+        # some operations which are not required by NearestNDInterpolator.__call__, 
+        # hence here we operate on xi directly, without calling a parent class function.
+        xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1])
+        xi = self._check_call_shape(xi)
+        xi = self._scale_x(xi)
+
+        # We need to handle two important cases:
+        # (1) the case where xi has trailing dimensions (..., ndim), and
+        # (2) the case where y has trailing dimensions
+        # We will first flatten xi to deal with case (1),
+        # do the computation in flattened array while retaining y's dimensionality,
+        # and then reshape the interpolated values back to match xi's shape.
+
+        # Flatten xi for the query
+        xi_flat = xi.reshape(-1, xi.shape[-1])
+        original_shape = xi.shape
+        flattened_shape = xi_flat.shape
+
+        # if distance_upper_bound is set to not be infinite,
+        # then we need to consider the case where cKDtree
+        # does not find any points within distance_upper_bound to return.
+        # It marks those points as having infinte distance, which is what will be used
+        # below to mask the array and return only the points that were deemed
+        # to have a close enough neighbor to return something useful.
+        dist, i = self.tree.query(xi_flat, **query_options)
+        valid_mask = np.isfinite(dist)
+
+        # create a holder interp_values array and fill with nans.
+        if self.values.ndim > 1:
+            interp_shape = flattened_shape[:-1] + self.values.shape[1:]
+        else:
+            interp_shape = flattened_shape[:-1]
+
+        if np.issubdtype(self.values.dtype, np.complexfloating):
+            interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype)
+        else:
+            interp_values = np.full(interp_shape, np.nan)
+
+        interp_values[valid_mask] = self.values[i[valid_mask], ...]
+
+        if self.values.ndim > 1:
+            new_shape = original_shape[:-1] + self.values.shape[1:]
+        else:
+            new_shape = original_shape[:-1]
+        interp_values = interp_values.reshape(new_shape)
+
+        return interp_values
+
+
+#------------------------------------------------------------------------------
+# Convenience interface function
+#------------------------------------------------------------------------------
+
+
+def griddata(points, values, xi, method='linear', fill_value=np.nan,
+             rescale=False):
+    """
+    Interpolate unstructured D-D data.
+
+    Parameters
+    ----------
+    points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,).
+        Data point coordinates.
+    values : ndarray of float or complex, shape (n,)
+        Data values.
+    xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape.
+        Points at which to interpolate data.
+    method : {'linear', 'nearest', 'cubic'}, optional
+        Method of interpolation. One of
+
+        ``nearest``
+          return the value at the data point closest to
+          the point of interpolation. See `NearestNDInterpolator` for
+          more details.
+
+        ``linear``
+          tessellate the input point set to N-D
+          simplices, and interpolate linearly on each simplex. See
+          `LinearNDInterpolator` for more details.
+
+        ``cubic`` (1-D)
+          return the value determined from a cubic
+          spline.
+
+        ``cubic`` (2-D)
+          return the value determined from a
+          piecewise cubic, continuously differentiable (C1), and
+          approximately curvature-minimizing polynomial surface. See
+          `CloughTocher2DInterpolator` for more details.
+    fill_value : float, optional
+        Value used to fill in for requested points outside of the
+        convex hull of the input points. If not provided, then the
+        default is ``nan``. This option has no effect for the
+        'nearest' method.
+    rescale : bool, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+
+    Returns
+    -------
+    ndarray
+        Array of interpolated values.
+
+    See Also
+    --------
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    NearestNDInterpolator :
+        Nearest-neighbor interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+
+    .. versionadded:: 0.9
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+
+    Suppose we want to interpolate the 2-D function
+
+    >>> import numpy as np
+    >>> def func(x, y):
+    ...     return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
+
+    on a grid in [0, 1]x[0, 1]
+
+    >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
+
+    but we only know its values at 1000 data points:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((1000, 2))
+    >>> values = func(points[:,0], points[:,1])
+
+    This can be done with `griddata` -- below we try out all of the
+    interpolation methods:
+
+    >>> from scipy.interpolate import griddata
+    >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
+    >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
+    >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
+
+    One can see that the exact result is reproduced by all of the
+    methods to some degree, but for this smooth function the piecewise
+    cubic interpolant gives the best results:
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.subplot(221)
+    >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
+    >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
+    >>> plt.title('Original')
+    >>> plt.subplot(222)
+    >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Nearest')
+    >>> plt.subplot(223)
+    >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Linear')
+    >>> plt.subplot(224)
+    >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Cubic')
+    >>> plt.gcf().set_size_inches(6, 6)
+    >>> plt.show()
+
+    """ # numpy/numpydoc#87  # noqa: E501
+
+    points = _ndim_coords_from_arrays(points)
+
+    if points.ndim < 2:
+        ndim = points.ndim
+    else:
+        ndim = points.shape[-1]
+
+    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
+        from ._interpolate import interp1d
+        points = points.ravel()
+        if isinstance(xi, tuple):
+            if len(xi) != 1:
+                raise ValueError("invalid number of dimensions in xi")
+            xi, = xi
+        # Sort points/values together, necessary as input for interp1d
+        idx = np.argsort(points)
+        points = points[idx]
+        values = values[idx]
+        if method == 'nearest':
+            fill_value = 'extrapolate'
+        ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
+                      fill_value=fill_value)
+        return ip(xi)
+    elif method == 'nearest':
+        ip = NearestNDInterpolator(points, values, rescale=rescale)
+        return ip(xi)
+    elif method == 'linear':
+        ip = LinearNDInterpolator(points, values, fill_value=fill_value,
+                                  rescale=rescale)
+        return ip(xi)
+    elif method == 'cubic' and ndim == 2:
+        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
+                                        rescale=rescale)
+        return ip(xi)
+    else:
+        raise ValueError("Unknown interpolation method %r for "
+                         "%d dimensional data" % (method, ndim))
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_pade.py b/python_embeded/Lib/site-packages/scipy/interpolate/_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a27e4d440bd60473c64bf0054ad2364dea1bf6de
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_pade.py
@@ -0,0 +1,67 @@
+from numpy import zeros, asarray, eye, poly1d, hstack, r_
+from scipy import linalg
+
+__all__ = ["pade"]
+
+def pade(an, m, n=None):
+    """
+    Return Pade approximation to a polynomial as the ratio of two polynomials.
+
+    Parameters
+    ----------
+    an : (N,) array_like
+        Taylor series coefficients.
+    m : int
+        The order of the returned approximating polynomial `q`.
+    n : int, optional
+        The order of the returned approximating polynomial `p`. By default,
+        the order is ``len(an)-1-m``.
+
+    Returns
+    -------
+    p, q : Polynomial class
+        The Pade approximation of the polynomial defined by `an` is
+        ``p(x)/q(x)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import pade
+    >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
+    >>> p, q = pade(e_exp, 2)
+
+    >>> e_exp.reverse()
+    >>> e_poly = np.poly1d(e_exp)
+
+    Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
+
+    >>> e_poly(1)
+    2.7166666666666668
+
+    >>> p(1)/q(1)
+    2.7179487179487181
+
+    """
+    an = asarray(an)
+    if n is None:
+        n = len(an) - 1 - m
+        if n < 0:
+            raise ValueError("Order of q  must be smaller than len(an)-1.")
+    if n < 0:
+        raise ValueError("Order of p  must be greater than 0.")
+    N = m + n
+    if N > len(an)-1:
+        raise ValueError("Order of q+p  must be smaller than len(an).")
+    an = an[:N+1]
+    Akj = eye(N+1, n+1, dtype=an.dtype)
+    Bkj = zeros((N+1, m), dtype=an.dtype)
+    for row in range(1, m+1):
+        Bkj[row,:row] = -(an[:row])[::-1]
+    for row in range(m+1, N+1):
+        Bkj[row,:] = -(an[row-m:row])[::-1]
+    C = hstack((Akj, Bkj))
+    pq = linalg.solve(C, an)
+    p = pq[:n+1]
+    q = r_[1.0, pq[n+1:]]
+    return poly1d(p[::-1]), poly1d(q[::-1])
+
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_polyint.py b/python_embeded/Lib/site-packages/scipy/interpolate/_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b12712d7125a6a27b6a9a050a4abd601f09ac15
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_polyint.py
@@ -0,0 +1,961 @@
+import warnings
+
+import numpy as np
+from scipy.special import factorial
+from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state,
+                              _transition_to_rng)
+
+
+__all__ = ["KroghInterpolator", "krogh_interpolate",
+           "BarycentricInterpolator", "barycentric_interpolate",
+           "approximate_taylor_polynomial"]
+
+
+def _isscalar(x):
+    """Check whether x is if a scalar type, or 0-dim"""
+    return np.isscalar(x) or hasattr(x, 'shape') and x.shape == ()
+
+
+class _Interpolator1D:
+    """
+    Common features in univariate interpolation
+
+    Deal with input data type and interpolation axis rolling. The
+    actual interpolator can assume the y-data is of shape (n, r) where
+    `n` is the number of x-points, and `r` the number of variables,
+    and use self.dtype as the y-data type.
+
+    Attributes
+    ----------
+    _y_axis
+        Axis along which the interpolation goes in the original array
+    _y_extra_shape
+        Additional trailing shape of the input arrays, excluding
+        the interpolation axis.
+    dtype
+        Dtype of the y-data arrays. Can be set via _set_dtype, which
+        forces it to be float or complex.
+
+    Methods
+    -------
+    __call__
+    _prepare_x
+    _finish_y
+    _reshape_yi
+    _set_yi
+    _set_dtype
+    _evaluate
+
+    """
+
+    __slots__ = ('_y_axis', '_y_extra_shape', 'dtype')
+
+    def __init__(self, xi=None, yi=None, axis=None):
+        self._y_axis = axis
+        self._y_extra_shape = None
+        self.dtype = None
+        if yi is not None:
+            self._set_yi(yi, xi=xi, axis=axis)
+
+    def __call__(self, x):
+        """
+        Evaluate the interpolant
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Input values `x` must be convertible to `float` values like `int`
+        or `float`.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate(x)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate(self, x):
+        """
+        Actually evaluate the value of the interpolator.
+        """
+        raise NotImplementedError()
+
+    def _prepare_x(self, x):
+        """Reshape input x array to 1-D"""
+        x = _asarray_validated(x, check_finite=False, as_inexact=True)
+        x_shape = x.shape
+        return x.ravel(), x_shape
+
+    def _finish_y(self, y, x_shape):
+        """Reshape interpolated y back to an N-D array similar to initial y"""
+        y = y.reshape(x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = (list(range(nx, nx + self._y_axis))
+                 + list(range(nx)) + list(range(nx+self._y_axis, nx+ny)))
+            y = y.transpose(s)
+        return y
+
+    def _reshape_yi(self, yi, check=False):
+        yi = np.moveaxis(np.asarray(yi), self._y_axis, 0)
+        if check and yi.shape[1:] != self._y_extra_shape:
+            ok_shape = (f"{self._y_extra_shape[-self._y_axis:]!r} + (N,) + "
+                        f"{self._y_extra_shape[:-self._y_axis]!r}")
+            raise ValueError(f"Data must be of shape {ok_shape}")
+        return yi.reshape((yi.shape[0], -1))
+
+    def _set_yi(self, yi, xi=None, axis=None):
+        if axis is None:
+            axis = self._y_axis
+        if axis is None:
+            raise ValueError("no interpolation axis specified")
+
+        yi = np.asarray(yi)
+
+        shape = yi.shape
+        if shape == ():
+            shape = (1,)
+        if xi is not None and shape[axis] != len(xi):
+            raise ValueError("x and y arrays must be equal in length along "
+                             "interpolation axis.")
+
+        self._y_axis = (axis % yi.ndim)
+        self._y_extra_shape = yi.shape[:self._y_axis] + yi.shape[self._y_axis+1:]
+        self.dtype = None
+        self._set_dtype(yi.dtype)
+
+    def _set_dtype(self, dtype, union=False):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.dtype, np.complexfloating):
+            self.dtype = np.complex128
+        else:
+            if not union or self.dtype != np.complex128:
+                self.dtype = np.float64
+
+
+class _Interpolator1DWithDerivatives(_Interpolator1D):
+    def derivatives(self, x, der=None):
+        """
+        Evaluate several derivatives of the polynomial at the point `x`
+
+        Produce an array of derivatives evaluated at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : int or list or None, optional
+            How many derivatives to evaluate, or None for all potentially
+            nonzero derivatives (that is, a number equal to the number
+            of points), or a list of derivatives to evaluate. This number
+            includes the function value as the '0th' derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Array with derivatives; ``d[j]`` contains the jth derivative.
+            Shape of ``d[j]`` is determined by replacing the interpolation
+            axis in the original array with the shape of `x`.
+
+        Examples
+        --------
+        >>> from scipy.interpolate import KroghInterpolator
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0)
+        array([1.0,2.0,3.0])
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0])
+        array([[1.0,1.0],
+               [2.0,2.0],
+               [3.0,3.0]])
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der)
+
+        y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = ([0] + list(range(nx+1, nx + self._y_axis+1))
+                 + list(range(1, nx+1)) +
+                 list(range(nx+1+self._y_axis, nx+ny+1)))
+            y = y.transpose(s)
+        return y
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+
+        der : integer, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+
+        Notes
+        -----
+        This may be computed by evaluating all derivatives up to the desired
+        one (using self.derivatives()) and then discarding the rest.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1)
+        return self._finish_y(y[der], x_shape)
+
+    def _evaluate_derivatives(self, x, der=None):
+        """
+        Actually evaluate the derivatives.
+
+        Parameters
+        ----------
+        x : array_like
+            1D array of points at which to evaluate the derivatives
+        der : integer, optional
+            The number of derivatives to evaluate, from 'order 0' (der=1)
+            to order der-1.  If omitted, return all possibly-non-zero
+            derivatives, ie 0 to order n-1.
+
+        Returns
+        -------
+        d : ndarray
+            Array of shape ``(der, x.size, self.yi.shape[1])`` containing
+            the derivatives from 0 to der-1
+        """
+        raise NotImplementedError()
+
+
+class KroghInterpolator(_Interpolator1DWithDerivatives):
+    """
+    Interpolating polynomial for a set of points.
+
+    The polynomial passes through all the pairs ``(xi, yi)``. One may
+    additionally specify a number of derivatives at each point `xi`;
+    this is done by repeating the value `xi` and specifying the
+    derivatives as successive `yi` values.
+
+    Allows evaluation of the polynomial and all its derivatives.
+    For reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial, although they can be obtained
+    by evaluating all the derivatives.
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        Known x-coordinates. Must be sorted in increasing order.
+    yi : array_like, shape (..., npoints, ...)
+        Known y-coordinates. When an xi occurs two or more times in
+        a row, the corresponding yi's represent derivative values. The length of `yi`
+        along the interpolation axis must be equal to the length of `xi`. Use the
+        `axis` parameter to select the correct axis.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values. Defaults to
+        ``axis=0``.
+
+    Notes
+    -----
+    Be aware that the algorithms implemented here are not necessarily
+    the most numerically stable known. Moreover, even in a world of
+    exact computation, unless the x coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon. In general, even with well-chosen
+    x values, degrees higher than about thirty cause problems with
+    numerical instability in this code.
+
+    Based on [1]_.
+
+    References
+    ----------
+    .. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation
+        and Numerical Differentiation", 1970.
+
+    Examples
+    --------
+    To produce a polynomial that is zero at 0 and 1 and has
+    derivative 2 at 0, call
+
+    >>> from scipy.interpolate import KroghInterpolator
+    >>> KroghInterpolator([0,0,1],[0,2,0])
+
+    This constructs the quadratic :math:`2x^2-2x`. The derivative condition
+    is indicated by the repeated zero in the `xi` array; the corresponding
+    yi values are 0, the function value, and 2, the derivative value.
+
+    For another example, given `xi`, `yi`, and a derivative `ypi` for each
+    point, appropriate arrays can be constructed as:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> xi = np.linspace(0, 1, 5)
+    >>> yi, ypi = rng.random((2, 5))
+    >>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi)))
+    >>> KroghInterpolator(xi_k, yi_k)
+
+    To produce a vector-valued polynomial, supply a higher-dimensional
+    array for `yi`:
+
+    >>> KroghInterpolator([0,1],[[2,3],[4,5]])
+
+    This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1.
+
+    """
+
+    def __init__(self, xi, yi, axis=0):
+        super().__init__(xi, yi, axis)
+
+        self.xi = np.asarray(xi)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+
+        if (deg := self.xi.size) > 30:
+            warnings.warn(f"{deg} degrees provided, degrees higher than about"
+                          " thirty cause problems with numerical instability "
+                          "with 'KroghInterpolator'", stacklevel=2)
+
+        c = np.zeros((self.n+1, self.r), dtype=self.dtype)
+        c[0] = self.yi[0]
+        Vk = np.zeros((self.n, self.r), dtype=self.dtype)
+        for k in range(1, self.n):
+            s = 0
+            while s <= k and xi[k-s] == xi[k]:
+                s += 1
+            s -= 1
+            Vk[0] = self.yi[k]/float_factorial(s)
+            for i in range(k-s):
+                if xi[i] == xi[k]:
+                    raise ValueError("Elements of `xi` can't be equal.")
+                if s == 0:
+                    Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k])
+                else:
+                    Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k])
+            c[k] = Vk[k-s]
+        self.c = c
+
+    def _evaluate(self, x):
+        pi = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0,np.newaxis,:]
+        for k in range(1, self.n):
+            w = x - self.xi[k-1]
+            pi = w*pi
+            p += pi[:,np.newaxis] * self.c[k]
+        return p
+
+    def _evaluate_derivatives(self, x, der=None):
+        n = self.n
+        r = self.r
+
+        if der is None:
+            der = self.n
+
+        pi = np.zeros((n, len(x)))
+        w = np.zeros((n, len(x)))
+        pi[0] = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0, np.newaxis, :]
+
+        for k in range(1, n):
+            w[k-1] = x - self.xi[k-1]
+            pi[k] = w[k-1] * pi[k-1]
+            p += pi[k, :, np.newaxis] * self.c[k]
+
+        cn = np.zeros((max(der, n+1), len(x), r), dtype=self.dtype)
+        cn[:n+1, :, :] += self.c[:n+1, np.newaxis, :]
+        cn[0] = p
+        for k in range(1, n):
+            for i in range(1, n-k+1):
+                pi[i] = w[k+i-1]*pi[i-1] + pi[i]
+                cn[k] = cn[k] + pi[i, :, np.newaxis]*cn[k+i]
+            cn[k] *= float_factorial(k)
+
+        cn[n, :, :] = 0
+        return cn[:der]
+
+
+def krogh_interpolate(xi, yi, x, der=0, axis=0):
+    """
+    Convenience function for polynomial interpolation.
+
+    See `KroghInterpolator` for more details.
+
+    Parameters
+    ----------
+    xi : array_like
+        Interpolation points (known x-coordinates).
+    yi : array_like
+        Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as
+        vectors of length R, or scalars if R=1.
+    x : array_like
+        Point or points at which to evaluate the derivatives.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    d : ndarray
+        If the interpolator's values are R-D then the
+        returned array will be the number of derivatives by N by R.
+        If `x` is a scalar, the middle dimension will be dropped; if
+        the `yi` are scalars then the last dimension will be dropped.
+
+    See Also
+    --------
+    KroghInterpolator : Krogh interpolator
+
+    Notes
+    -----
+    Construction of the interpolating polynomial is a relatively expensive
+    process. If you want to evaluate it repeatedly consider using the class
+    KroghInterpolator (which is what this function uses).
+
+    Examples
+    --------
+    We can interpolate 2D observed data using Krogh interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import krogh_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = krogh_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="krogh interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+
+    P = KroghInterpolator(xi, yi, axis=axis)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
+
+
+def approximate_taylor_polynomial(f,x,degree,scale,order=None):
+    """
+    Estimate the Taylor polynomial of f at x by polynomial fitting.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Taylor polynomial is sought. Should accept
+        a vector of `x` values.
+    x : scalar
+        The point at which the polynomial is to be evaluated.
+    degree : int
+        The degree of the Taylor polynomial
+    scale : scalar
+        The width of the interval to use to evaluate the Taylor polynomial.
+        Function values spread over a range this wide are used to fit the
+        polynomial. Must be chosen carefully.
+    order : int or None, optional
+        The order of the polynomial to be used in the fitting; `f` will be
+        evaluated ``order+1`` times. If None, use `degree`.
+
+    Returns
+    -------
+    p : poly1d instance
+        The Taylor polynomial (translated to the origin, so that
+        for example p(0)=f(x)).
+
+    Notes
+    -----
+    The appropriate choice of "scale" is a trade-off; too large and the
+    function differs from its Taylor polynomial too much to get a good
+    answer, too small and round-off errors overwhelm the higher-order terms.
+    The algorithm used becomes numerically unstable around order 30 even
+    under ideal circumstances.
+
+    Choosing order somewhat larger than degree may improve the higher-order
+    terms.
+
+    Examples
+    --------
+    We can calculate Taylor approximation polynomials of sin function with
+    various degrees:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import approximate_taylor_polynomial
+    >>> x = np.linspace(-10.0, 10.0, num=100)
+    >>> plt.plot(x, np.sin(x), label="sin curve")
+    >>> for degree in np.arange(1, 15, step=2):
+    ...     sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1,
+    ...                                                order=degree + 2)
+    ...     plt.plot(x, sin_taylor(x), label=f"degree={degree}")
+    >>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',
+    ...            borderaxespad=0.0, shadow=True)
+    >>> plt.tight_layout()
+    >>> plt.axis([-10, 10, -10, 10])
+    >>> plt.show()
+
+    """
+    if order is None:
+        order = degree
+
+    n = order+1
+    # Choose n points that cluster near the endpoints of the interval in
+    # a way that avoids the Runge phenomenon. Ensure, by including the
+    # endpoint or not as appropriate, that one point always falls at x
+    # exactly.
+    xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n % 1)) + x
+
+    P = KroghInterpolator(xs, f(xs))
+    d = P.derivatives(x,der=degree+1)
+
+    return np.poly1d((d/factorial(np.arange(degree+1)))[::-1])
+
+
+class BarycentricInterpolator(_Interpolator1DWithDerivatives):
+    r"""Interpolating polynomial for a set of points.
+
+    Constructs a polynomial that passes through a given set of points.
+    Allows evaluation of the polynomial and all its derivatives,
+    efficient changing of the y-values to be interpolated,
+    and updating by adding more x- and y-values.
+
+    For reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial.
+
+    The values `yi` need to be provided before the function is
+    evaluated, but none of the preprocessing depends on them, so rapid
+    updates are possible.
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        1-D array of x coordinates of the points the polynomial
+        should pass through
+    yi : array_like, shape (..., npoints, ...), optional
+        N-D array of y coordinates of the points the polynomial should pass through.
+        If None, the y values will be supplied later via the `set_y` method.
+        The length of `yi` along the interpolation axis must be equal to the length
+        of `xi`. Use the ``axis`` parameter to select correct axis.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    wi : array_like, optional
+        The barycentric weights for the chosen interpolation points `xi`.
+        If absent or None, the weights will be computed from `xi` (default).
+        This allows for the reuse of the weights `wi` if several interpolants
+        are being calculated using the same nodes `xi`, without re-computation.
+    rng : {None, int, `numpy.random.Generator`}, optional
+        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 interpolation.
+
+        If this argument `random_state` is passed by keyword,
+        legacy behavior for the argument `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` 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 `random_state` to `rng`.
+            For an interim period, both keywords will continue to work (only specify
+            one of them). After the interim period using the `random_state` keyword will emit
+            warnings. The behavior of the `random_state` and `rng` keywords is outlined above.
+
+    Notes
+    -----
+    This class uses a "barycentric interpolation" method that treats
+    the problem as a special case of rational function interpolation.
+    This algorithm is quite stable, numerically, but even in a world of
+    exact computation, unless the x coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon.
+
+    Based on Berrut and Trefethen 2004, "Barycentric Lagrange Interpolation".
+
+    Examples
+    --------
+    To produce a quintic barycentric interpolant approximating the function
+    :math:`\sin x`, and its first four derivatives, using six randomly-spaced
+    nodes in :math:`(0, \frac{\pi}{2})`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BarycentricInterpolator
+    >>> rng = np.random.default_rng()
+    >>> xi = rng.random(6) * np.pi/2
+    >>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin
+    >>> P = BarycentricInterpolator(xi, f(xi), random_state=rng)
+    >>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))
+    >>> x = np.linspace(0, np.pi, 100)
+    >>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')
+    >>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')
+    >>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')
+    >>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')
+    >>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')
+    >>> axs[0].set_xlim(0, np.pi)
+    >>> axs[4].set_xlabel(r"$x$")
+    >>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)],
+    ...                   ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"])
+    >>> axs[0].set_ylabel("$f(x)$")
+    >>> axs[1].set_ylabel("$f'(x)$")
+    >>> axs[2].set_ylabel("$f''(x)$")
+    >>> axs[3].set_ylabel("$f^{(3)}(x)$")
+    >>> axs[4].set_ylabel("$f^{(4)}(x)$")
+    >>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']
+    >>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),
+    ...               loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False)
+    >>> plt.show()
+    """ # numpy/numpydoc#87  # noqa: E501
+
+    @_transition_to_rng("random_state", replace_doc=False)
+    def __init__(self, xi, yi=None, axis=0, *, wi=None, rng=None):
+        super().__init__(xi, yi, axis)
+
+        rng = check_random_state(rng)
+
+        self.xi = np.asarray(xi, dtype=np.float64)
+        self.set_yi(yi)
+        self.n = len(self.xi)
+
+        # cache derivative object to avoid re-computing the weights with every call.
+        self._diff_cij = None
+
+        if wi is not None:
+            self.wi = wi
+        else:
+            # See page 510 of Berrut and Trefethen 2004 for an explanation of the
+            # capacity scaling and the suggestion of using a random permutation of
+            # the input factors.
+            # At the moment, the permutation is not performed for xi that are
+            # appended later through the add_xi interface. It's not clear to me how
+            # to implement that and it seems that most situations that require
+            # these numerical stability improvements will be able to provide all
+            # the points to the constructor.
+            self._inv_capacity = 4.0 / (np.max(self.xi) - np.min(self.xi))
+            permute = rng.permutation(self.n, )
+            inv_permute = np.zeros(self.n, dtype=np.int32)
+            inv_permute[permute] = np.arange(self.n)
+            self.wi = np.zeros(self.n)
+
+            for i in range(self.n):
+                dist = self._inv_capacity * (self.xi[i] - self.xi[permute])
+                dist[inv_permute[i]] = 1.0
+                prod = np.prod(dist)
+                if prod == 0.0:
+                    raise ValueError("Interpolation points xi must be"
+                                     " distinct.")
+                self.wi[i] = 1.0 / prod
+
+    def set_yi(self, yi, axis=None):
+        """
+        Update the y values to be interpolated
+
+        The barycentric interpolation algorithm requires the calculation
+        of weights, but these depend only on the `xi`. The `yi` can be changed
+        at any time.
+
+        Parameters
+        ----------
+        yi : array_like
+            The y-coordinates of the points the polynomial will pass through.
+            If None, the y values must be supplied later.
+        axis : int, optional
+            Axis in the `yi` array corresponding to the x-coordinate values.
+
+        """
+        if yi is None:
+            self.yi = None
+            return
+        self._set_yi(yi, xi=self.xi, axis=axis)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+        self._diff_baryint = None
+
+    def add_xi(self, xi, yi=None):
+        """
+        Add more x values to the set to be interpolated
+
+        The barycentric interpolation algorithm allows easy updating by
+        adding more points for the polynomial to pass through.
+
+        Parameters
+        ----------
+        xi : array_like
+            The x coordinates of the points that the polynomial should pass
+            through.
+        yi : array_like, optional
+            The y coordinates of the points the polynomial should pass through.
+            Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is
+            vector-valued.
+            If `yi` is not given, the y values will be supplied later. `yi`
+            should be given if and only if the interpolator has y values
+            specified.
+
+        Notes
+        -----
+        The new points added by `add_xi` are not randomly permuted
+        so there is potential for numerical instability,
+        especially for a large number of points. If this
+        happens, please reconstruct interpolation from scratch instead.
+        """
+        if yi is not None:
+            if self.yi is None:
+                raise ValueError("No previous yi value to update!")
+            yi = self._reshape_yi(yi, check=True)
+            self.yi = np.vstack((self.yi,yi))
+        else:
+            if self.yi is not None:
+                raise ValueError("No update to yi provided!")
+        old_n = self.n
+        self.xi = np.concatenate((self.xi,xi))
+        self.n = len(self.xi)
+        self.wi **= -1
+        old_wi = self.wi
+        self.wi = np.zeros(self.n)
+        self.wi[:old_n] = old_wi
+        for j in range(old_n, self.n):
+            self.wi[:j] *= self._inv_capacity * (self.xi[j]-self.xi[:j])
+            self.wi[j] = np.multiply.reduce(
+                self._inv_capacity * (self.xi[:j]-self.xi[j])
+            )
+        self.wi **= -1
+        self._diff_cij = None
+        self._diff_baryint = None
+
+    def __call__(self, x):
+        """Evaluate the interpolating polynomial at the points x
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Currently the code computes an outer product between `x` and the
+        weights, that is, it constructs an intermediate array of size
+        ``(N, len(x))``, where N is the degree of the polynomial.
+        """
+        return _Interpolator1D.__call__(self, x)
+
+    def _evaluate(self, x):
+        if x.size == 0:
+            p = np.zeros((0, self.r), dtype=self.dtype)
+        else:
+            c = x[..., np.newaxis] - self.xi
+            z = c == 0
+            c[z] = 1
+            c = self.wi / c
+            with np.errstate(divide='ignore'):
+                p = np.dot(c, self.yi) / np.sum(c, axis=-1)[..., np.newaxis]
+            # Now fix where x==some xi
+            r = np.nonzero(z)
+            if len(r) == 1:  # evaluation at a scalar
+                if len(r[0]) > 0:  # equals one of the points
+                    p = self.yi[r[0][0]]
+            else:
+                p[r[:-1]] = self.yi[r[-1]]
+        return p
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point x.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : integer, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1, all_lower=False)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate_derivatives(self, x, der=None, all_lower=True):
+        # NB: der here is not the order of the highest derivative;
+        # instead, it is the size of the derivatives matrix that
+        # would be returned with all_lower=True, including the
+        # '0th' derivative (the undifferentiated function).
+        # E.g. to evaluate the 5th derivative alone, call
+        # _evaluate_derivatives(x, der=6, all_lower=False).
+
+        if (not all_lower) and (x.size == 0 or self.r == 0):
+            return np.zeros((0, self.r), dtype=self.dtype)
+
+        if (not all_lower) and der == 1:
+            return self._evaluate(x)
+
+        if (not all_lower) and (der > self.n):
+            return np.zeros((len(x), self.r), dtype=self.dtype)
+
+        if der is None:
+            der = self.n
+
+        if all_lower and (x.size == 0 or self.r == 0):
+            return np.zeros((der, len(x), self.r), dtype=self.dtype)
+
+        if self._diff_cij is None:
+            # c[i,j] = xi[i] - xi[j]
+            c = self.xi[:, np.newaxis] - self.xi
+
+            # avoid division by 0 (diagonal entries are so far zero by construction)
+            np.fill_diagonal(c, 1)
+
+            # c[i,j] = (w[j] / w[i]) / (xi[i] - xi[j]) (equation 9.4)
+            c = self.wi/ (c * self.wi[..., np.newaxis])
+
+            # fill in correct diagonal entries: each column sums to 0
+            np.fill_diagonal(c, 0)
+
+            # calculate diagonal
+            # c[j,j] = -sum_{i != j} c[i,j] (equation 9.5)
+            d = -c.sum(axis=1)
+            # c[i,j] = l_j(x_i)
+            np.fill_diagonal(c, d)
+
+            self._diff_cij = c
+
+        if self._diff_baryint is None:
+            # initialise and cache derivative interpolator and cijs;
+            # reuse weights wi (which depend only on interpolation points xi),
+            # to avoid unnecessary re-computation
+            self._diff_baryint = BarycentricInterpolator(xi=self.xi,
+                                                         yi=self._diff_cij @ self.yi,
+                                                         wi=self.wi)
+            self._diff_baryint._diff_cij = self._diff_cij
+
+        if all_lower:
+            # assemble matrix of derivatives from order 0 to order der-1,
+            # in the format required by _Interpolator1DWithDerivatives.
+            cn = np.zeros((der, len(x), self.r), dtype=self.dtype)
+            for d in range(der):
+                cn[d, :, :] = self._evaluate_derivatives(x, d+1, all_lower=False)
+            return cn
+
+        # recursively evaluate only the derivative requested
+        return self._diff_baryint._evaluate_derivatives(x, der-1, all_lower=False)
+
+
+def barycentric_interpolate(xi, yi, x, axis=0, *, der=0, rng=None):
+    """
+    Convenience function for polynomial interpolation.
+
+    Constructs a polynomial that passes through a given set of points,
+    then evaluates the polynomial. For reasons of numerical stability,
+    this function does not compute the coefficients of the polynomial.
+
+    This function uses a "barycentric interpolation" method that treats
+    the problem as a special case of rational function interpolation.
+    This algorithm is quite stable, numerically, but even in a world of
+    exact computation, unless the `x` coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon.
+
+    Parameters
+    ----------
+    xi : array_like
+        1-D array of x coordinates of the points the polynomial should
+        pass through
+    yi : array_like
+        The y coordinates of the points the polynomial should pass through.
+    x : scalar or array_like
+        Point or points at which to evaluate the interpolant.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    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
+    -------
+    y : scalar or array_like
+        Interpolated values. Shape is determined by replacing
+        the interpolation axis in the original array with the shape of `x`.
+
+    See Also
+    --------
+    BarycentricInterpolator : Barycentric interpolator
+
+    Notes
+    -----
+    Construction of the interpolation weights is a relatively slow process.
+    If you want to call this many times with the same xi (but possibly
+    varying yi or x) you should use the class `BarycentricInterpolator`.
+    This is what this function uses internally.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using barycentric interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import barycentric_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = barycentric_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="barycentric interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = BarycentricInterpolator(xi, yi, axis=axis, rng=rng)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_ppoly.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_ppoly.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..33c53dc39b966a982ec2f9ea8973d504e2fe156d
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_ppoly.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_rbf.py b/python_embeded/Lib/site-packages/scipy/interpolate/_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa8568b8b4b971ef0b83dea1b2458290e5225ca4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_rbf.py
@@ -0,0 +1,290 @@
+"""rbf - Radial basis functions for interpolation/smoothing scattered N-D data.
+
+Written by John Travers , February 2007
+Based closely on Matlab code by Alex Chirokov
+Additional, large, improvements by Robert Hetland
+Some additional alterations by Travis Oliphant
+Interpolation with multi-dimensional target domain by Josua Sassen
+
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+Copyright (c) 2006-2007, Robert Hetland 
+Copyright (c) 2007, John Travers 
+
+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 Robert Hetland nor the names of any
+       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 numpy as np
+
+from scipy import linalg
+from scipy.special import xlogy
+from scipy.spatial.distance import cdist, pdist, squareform
+
+__all__ = ['Rbf']
+
+
+class Rbf:
+    """
+    Rbf(*args, **kwargs)
+
+    A class for radial basis function interpolation of functions from
+    N-D scattered data to an M-D domain.
+
+    .. legacy:: class
+
+        `Rbf` is legacy code, for new usage please use `RBFInterpolator`
+        instead.
+
+    Parameters
+    ----------
+    *args : arrays
+        x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
+        and d is the array of values at the nodes
+    function : str or callable, optional
+        The radial basis function, based on the radius, r, given by the norm
+        (default is Euclidean distance); the default is 'multiquadric'::
+
+            'multiquadric': sqrt((r/self.epsilon)**2 + 1)
+            'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
+            'gaussian': exp(-(r/self.epsilon)**2)
+            'linear': r
+            'cubic': r**3
+            'quintic': r**5
+            'thin_plate': r**2 * log(r)
+
+        If callable, then it must take 2 arguments (self, r). The epsilon
+        parameter will be available as self.epsilon. Other keyword
+        arguments passed in will be available as well.
+
+    epsilon : float, optional
+        Adjustable constant for gaussian or multiquadrics functions
+        - defaults to approximate average distance between nodes (which is
+        a good start).
+    smooth : float, optional
+        Values greater than zero increase the smoothness of the
+        approximation. 0 is for interpolation (default), the function will
+        always go through the nodal points in this case.
+    norm : str, callable, optional
+        A function that returns the 'distance' between two points, with
+        inputs as arrays of positions (x, y, z, ...), and an output as an
+        array of distance. E.g., the default: 'euclidean', such that the result
+        is a matrix of the distances from each point in ``x1`` to each point in
+        ``x2``. For more options, see documentation of
+        `scipy.spatial.distances.cdist`.
+    mode : str, optional
+        Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
+        '1-D' the data `d` will be considered as 1-D and flattened
+        internally. When it is 'N-D' the data `d` is assumed to be an array of
+        shape (n_samples, m), where m is the dimension of the target domain.
+
+
+    Attributes
+    ----------
+    N : int
+        The number of data points (as determined by the input arrays).
+    di : ndarray
+        The 1-D array of data values at each of the data coordinates `xi`.
+    xi : ndarray
+        The 2-D array of data coordinates.
+    function : str or callable
+        The radial basis function. See description under Parameters.
+    epsilon : float
+        Parameter used by gaussian or multiquadrics functions. See Parameters.
+    smooth : float
+        Smoothing parameter. See description under Parameters.
+    norm : str or callable
+        The distance function. See description under Parameters.
+    mode : str
+        Mode of the interpolation. See description under Parameters.
+    nodes : ndarray
+        A 1-D array of node values for the interpolation.
+    A : internal property, do not use
+
+    See Also
+    --------
+    RBFInterpolator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import Rbf
+    >>> rng = np.random.default_rng()
+    >>> x, y, z, d = rng.random((4, 50))
+    >>> rbfi = Rbf(x, y, z, d)  # radial basis function interpolator instance
+    >>> xi = yi = zi = np.linspace(0, 1, 20)
+    >>> di = rbfi(xi, yi, zi)   # interpolated values
+    >>> di.shape
+    (20,)
+
+    """
+    # Available radial basis functions that can be selected as strings;
+    # they all start with _h_ (self._init_function relies on that)
+    def _h_multiquadric(self, r):
+        return np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_inverse_multiquadric(self, r):
+        return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_gaussian(self, r):
+        return np.exp(-(1.0/self.epsilon*r)**2)
+
+    def _h_linear(self, r):
+        return r
+
+    def _h_cubic(self, r):
+        return r**3
+
+    def _h_quintic(self, r):
+        return r**5
+
+    def _h_thin_plate(self, r):
+        return xlogy(r**2, r)
+
+    # Setup self._function and do smoke test on initial r
+    def _init_function(self, r):
+        if isinstance(self.function, str):
+            self.function = self.function.lower()
+            _mapped = {'inverse': 'inverse_multiquadric',
+                       'inverse multiquadric': 'inverse_multiquadric',
+                       'thin-plate': 'thin_plate'}
+            if self.function in _mapped:
+                self.function = _mapped[self.function]
+
+            func_name = "_h_" + self.function
+            if hasattr(self, func_name):
+                self._function = getattr(self, func_name)
+            else:
+                functionlist = [x[3:] for x in dir(self)
+                                if x.startswith('_h_')]
+                raise ValueError("function must be a callable or one of " +
+                                 ", ".join(functionlist))
+            self._function = getattr(self, "_h_"+self.function)
+        elif callable(self.function):
+            allow_one = False
+            if hasattr(self.function, 'func_code') or \
+               hasattr(self.function, '__code__'):
+                val = self.function
+                allow_one = True
+            elif hasattr(self.function, "__call__"):
+                val = self.function.__call__.__func__
+            else:
+                raise ValueError("Cannot determine number of arguments to "
+                                 "function")
+
+            argcount = val.__code__.co_argcount
+            if allow_one and argcount == 1:
+                self._function = self.function
+            elif argcount == 2:
+                self._function = self.function.__get__(self, Rbf)
+            else:
+                raise ValueError("Function argument must take 1 or 2 "
+                                 "arguments.")
+
+        a0 = self._function(r)
+        if a0.shape != r.shape:
+            raise ValueError("Callable must take array and return array of "
+                             "the same shape")
+        return a0
+
+    def __init__(self, *args, **kwargs):
+        # `args` can be a variable number of arrays; we flatten them and store
+        # them as a single 2-D array `xi` of shape (n_args-1, array_size),
+        # plus a 1-D array `di` for the values.
+        # All arrays must have the same number of elements
+        self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
+                              for a in args[:-1]])
+        self.N = self.xi.shape[-1]
+
+        self.mode = kwargs.pop('mode', '1-D')
+
+        if self.mode == '1-D':
+            self.di = np.asarray(args[-1]).flatten()
+            self._target_dim = 1
+        elif self.mode == 'N-D':
+            self.di = np.asarray(args[-1])
+            self._target_dim = self.di.shape[-1]
+        else:
+            raise ValueError("Mode has to be 1-D or N-D.")
+
+        if not all([x.size == self.di.shape[0] for x in self.xi]):
+            raise ValueError("All arrays must be equal length.")
+
+        self.norm = kwargs.pop('norm', 'euclidean')
+        self.epsilon = kwargs.pop('epsilon', None)
+        if self.epsilon is None:
+            # default epsilon is the "the average distance between nodes" based
+            # on a bounding hypercube
+            ximax = np.amax(self.xi, axis=1)
+            ximin = np.amin(self.xi, axis=1)
+            edges = ximax - ximin
+            edges = edges[np.nonzero(edges)]
+            self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
+
+        self.smooth = kwargs.pop('smooth', 0.0)
+        self.function = kwargs.pop('function', 'multiquadric')
+
+        # attach anything left in kwargs to self for use by any user-callable
+        # function or to save on the object returned.
+        for item, value in kwargs.items():
+            setattr(self, item, value)
+
+        # Compute weights
+        if self._target_dim > 1:  # If we have more than one target dimension,
+            # we first factorize the matrix
+            self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
+            lu, piv = linalg.lu_factor(self.A)
+            for i in range(self._target_dim):
+                self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
+        else:
+            self.nodes = linalg.solve(self.A, self.di)
+
+    @property
+    def A(self):
+        # this only exists for backwards compatibility: self.A was available
+        # and, at least technically, public.
+        r = squareform(pdist(self.xi.T, self.norm))  # Pairwise norm
+        return self._init_function(r) - np.eye(self.N)*self.smooth
+
+    def _call_norm(self, x1, x2):
+        return cdist(x1.T, x2.T, self.norm)
+
+    def __call__(self, *args):
+        args = [np.asarray(x) for x in args]
+        if not all([x.shape == y.shape for x in args for y in args]):
+            raise ValueError("Array lengths must be equal")
+        if self._target_dim > 1:
+            shp = args[0].shape + (self._target_dim,)
+        else:
+            shp = args[0].shape
+        xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
+        r = self._call_norm(xa, self.xi)
+        return np.dot(self._function(r), self.nodes).reshape(shp)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp.py b/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c879dd2bdc8310e9f66c0ed9bd69b54802ee7679
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp.py
@@ -0,0 +1,550 @@
+"""Module for RBF interpolation."""
+import warnings
+from itertools import combinations_with_replacement
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.spatial import KDTree
+from scipy.special import comb
+from scipy.linalg.lapack import dgesv  # type: ignore[attr-defined]
+
+from ._rbfinterp_pythran import (_build_system,
+                                 _build_evaluation_coefficients,
+                                 _polynomial_matrix)
+
+
+__all__ = ["RBFInterpolator"]
+
+
+# These RBFs are implemented.
+_AVAILABLE = {
+    "linear",
+    "thin_plate_spline",
+    "cubic",
+    "quintic",
+    "multiquadric",
+    "inverse_multiquadric",
+    "inverse_quadratic",
+    "gaussian"
+    }
+
+
+# The shape parameter does not need to be specified when using these RBFs.
+_SCALE_INVARIANT = {"linear", "thin_plate_spline", "cubic", "quintic"}
+
+
+# For RBFs that are conditionally positive definite of order m, the interpolant
+# should include polynomial terms with degree >= m - 1. Define the minimum
+# degrees here. These values are from Chapter 8 of Fasshauer's "Meshfree
+# Approximation Methods with MATLAB". The RBFs that are not in this dictionary
+# are positive definite and do not need polynomial terms.
+_NAME_TO_MIN_DEGREE = {
+    "multiquadric": 0,
+    "linear": 0,
+    "thin_plate_spline": 1,
+    "cubic": 1,
+    "quintic": 2
+    }
+
+
+def _monomial_powers(ndim, degree):
+    """Return the powers for each monomial in a polynomial.
+
+    Parameters
+    ----------
+    ndim : int
+        Number of variables in the polynomial.
+    degree : int
+        Degree of the polynomial.
+
+    Returns
+    -------
+    (nmonos, ndim) int ndarray
+        Array where each row contains the powers for each variable in a
+        monomial.
+
+    """
+    nmonos = comb(degree + ndim, ndim, exact=True)
+    out = np.zeros((nmonos, ndim), dtype=np.dtype("long"))
+    count = 0
+    for deg in range(degree + 1):
+        for mono in combinations_with_replacement(range(ndim), deg):
+            # `mono` is a tuple of variables in the current monomial with
+            # multiplicity indicating power (e.g., (0, 1, 1) represents x*y**2)
+            for var in mono:
+                out[count, var] += 1
+
+            count += 1
+
+    return out
+
+
+def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers):
+    """Build and solve the RBF interpolation system of equations.
+
+    Parameters
+    ----------
+    y : (P, N) float ndarray
+        Data point coordinates.
+    d : (P, S) float ndarray
+        Data values at `y`.
+    smoothing : (P,) float ndarray
+        Smoothing parameter for each data point.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+
+    Returns
+    -------
+    coeffs : (P + R, S) float ndarray
+        Coefficients for each RBF and monomial.
+    shift : (N,) float ndarray
+        Domain shift used to create the polynomial matrix.
+    scale : (N,) float ndarray
+        Domain scaling used to create the polynomial matrix.
+
+    """
+    lhs, rhs, shift, scale = _build_system(
+        y, d, smoothing, kernel, epsilon, powers
+        )
+    _, _, coeffs, info = dgesv(lhs, rhs, overwrite_a=True, overwrite_b=True)
+    if info < 0:
+        raise ValueError(f"The {-info}-th argument had an illegal value.")
+    elif info > 0:
+        msg = "Singular matrix."
+        nmonos = powers.shape[0]
+        if nmonos > 0:
+            pmat = _polynomial_matrix((y - shift)/scale, powers)
+            rank = np.linalg.matrix_rank(pmat)
+            if rank < nmonos:
+                msg = (
+                    "Singular matrix. The matrix of monomials evaluated at "
+                    "the data point coordinates does not have full column "
+                    f"rank ({rank}/{nmonos})."
+                    )
+
+        raise LinAlgError(msg)
+
+    return shift, scale, coeffs
+
+
+class RBFInterpolator:
+    """Radial basis function (RBF) interpolation in N dimensions.
+
+    Parameters
+    ----------
+    y : (npoints, ndims) array_like
+        2-D array of data point coordinates.
+    d : (npoints, ...) array_like
+        N-D array of data values at `y`. The length of `d` along the first
+        axis must be equal to the length of `y`. Unlike some interpolators, the
+        interpolation axis cannot be changed.
+    neighbors : int, optional
+        If specified, the value of the interpolant at each evaluation point
+        will be computed using only this many nearest data points. All the data
+        points are used by default.
+    smoothing : float or (npoints, ) array_like, optional
+        Smoothing parameter. The interpolant perfectly fits the data when this
+        is set to 0. For large values, the interpolant approaches a least
+        squares fit of a polynomial with the specified degree. Default is 0.
+    kernel : str, optional
+        Type of RBF. This should be one of
+
+            - 'linear'               : ``-r``
+            - 'thin_plate_spline'    : ``r**2 * log(r)``
+            - 'cubic'                : ``r**3``
+            - 'quintic'              : ``-r**5``
+            - 'multiquadric'         : ``-sqrt(1 + r**2)``
+            - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)``
+            - 'inverse_quadratic'    : ``1/(1 + r**2)``
+            - 'gaussian'             : ``exp(-r**2)``
+
+        Default is 'thin_plate_spline'.
+    epsilon : float, optional
+        Shape parameter that scales the input to the RBF. If `kernel` is
+        'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to
+        1 and can be ignored because it has the same effect as scaling the
+        smoothing parameter. Otherwise, this must be specified.
+    degree : int, optional
+        Degree of the added polynomial. For some RBFs the interpolant may not
+        be well-posed if the polynomial degree is too small. Those RBFs and
+        their corresponding minimum degrees are
+
+            - 'multiquadric'      : 0
+            - 'linear'            : 0
+            - 'thin_plate_spline' : 1
+            - 'cubic'             : 1
+            - 'quintic'           : 2
+
+        The default value is the minimum degree for `kernel` or 0 if there is
+        no minimum degree. Set this to -1 for no added polynomial.
+
+    Notes
+    -----
+    An RBF is a scalar valued function in N-dimensional space whose value at
+    :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c`
+    is the center of the RBF.
+
+    An RBF interpolant for the vector of data values :math:`d`, which are from
+    locations :math:`y`, is a linear combination of RBFs centered at :math:`y`
+    plus a polynomial with a specified degree. The RBF interpolant is written
+    as
+
+    .. math::
+        f(x) = K(x, y) a + P(x) b,
+
+    where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y`
+    evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of
+    monomials, which span polynomials with the specified degree, evaluated at
+    :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the
+    linear equations
+
+    .. math::
+        (K(y, y) + \\lambda I) a + P(y) b = d
+
+    and
+
+    .. math::
+        P(y)^T a = 0,
+
+    where :math:`\\lambda` is a non-negative smoothing parameter that controls
+    how well we want to fit the data. The data are fit exactly when the
+    smoothing parameter is 0.
+
+    The above system is uniquely solvable if the following requirements are
+    met:
+
+        - :math:`P(y)` must have full column rank. :math:`P(y)` always has full
+          column rank when `degree` is -1 or 0. When `degree` is 1,
+          :math:`P(y)` has full column rank if the data point locations are not
+          all collinear (N=2), coplanar (N=3), etc.
+        - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline',
+          'cubic', or 'quintic', then `degree` must not be lower than the
+          minimum value listed above.
+        - If `smoothing` is 0, then each data point location must be distinct.
+
+    When using an RBF that is not scale invariant ('multiquadric',
+    'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate
+    shape parameter must be chosen (e.g., through cross validation). Smaller
+    values for the shape parameter correspond to wider RBFs. The problem can
+    become ill-conditioned or singular when the shape parameter is too small.
+
+    The memory required to solve for the RBF interpolation coefficients
+    increases quadratically with the number of data points, which can become
+    impractical when interpolating more than about a thousand data points.
+    To overcome memory limitations for large interpolation problems, the
+    `neighbors` argument can be specified to compute an RBF interpolant for
+    each evaluation point using only the nearest data points.
+
+    .. versionadded:: 1.7.0
+
+    See Also
+    --------
+    NearestNDInterpolator
+    LinearNDInterpolator
+    CloughTocher2DInterpolator
+
+    References
+    ----------
+    .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab.
+        World Scientific Publishing Co.
+
+    .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf
+
+    .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM.
+
+    .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf
+
+    Examples
+    --------
+    Demonstrate interpolating scattered data to a grid in 2-D.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import RBFInterpolator
+    >>> from scipy.stats.qmc import Halton
+
+    >>> rng = np.random.default_rng()
+    >>> xobs = 2*Halton(2, seed=rng).random(100) - 1
+    >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1))
+
+    >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j]
+    >>> xflat = xgrid.reshape(2, -1).T
+    >>> yflat = RBFInterpolator(xobs, yobs)(xflat)
+    >>> ygrid = yflat.reshape(50, 50)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud')
+    >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25)
+    >>> fig.colorbar(p)
+    >>> plt.show()
+
+    """
+
+    def __init__(self, y, d,
+                 neighbors=None,
+                 smoothing=0.0,
+                 kernel="thin_plate_spline",
+                 epsilon=None,
+                 degree=None):
+        y = np.asarray(y, dtype=float, order="C")
+        if y.ndim != 2:
+            raise ValueError("`y` must be a 2-dimensional array.")
+
+        ny, ndim = y.shape
+
+        d_dtype = complex if np.iscomplexobj(d) else float
+        d = np.asarray(d, dtype=d_dtype, order="C")
+        if d.shape[0] != ny:
+            raise ValueError(
+                f"Expected the first axis of `d` to have length {ny}."
+                )
+
+        d_shape = d.shape[1:]
+        d = d.reshape((ny, -1))
+        # If `d` is complex, convert it to a float array with twice as many
+        # columns. Otherwise, the LHS matrix would need to be converted to
+        # complex and take up 2x more memory than necessary.
+        d = d.view(float)
+
+        if np.isscalar(smoothing):
+            smoothing = np.full(ny, smoothing, dtype=float)
+        else:
+            smoothing = np.asarray(smoothing, dtype=float, order="C")
+            if smoothing.shape != (ny,):
+                raise ValueError(
+                    "Expected `smoothing` to be a scalar or have shape "
+                    f"({ny},)."
+                    )
+
+        kernel = kernel.lower()
+        if kernel not in _AVAILABLE:
+            raise ValueError(f"`kernel` must be one of {_AVAILABLE}.")
+
+        if epsilon is None:
+            if kernel in _SCALE_INVARIANT:
+                epsilon = 1.0
+            else:
+                raise ValueError(
+                    "`epsilon` must be specified if `kernel` is not one of "
+                    f"{_SCALE_INVARIANT}."
+                    )
+        else:
+            epsilon = float(epsilon)
+
+        min_degree = _NAME_TO_MIN_DEGREE.get(kernel, -1)
+        if degree is None:
+            degree = max(min_degree, 0)
+        else:
+            degree = int(degree)
+            if degree < -1:
+                raise ValueError("`degree` must be at least -1.")
+            elif -1 < degree < min_degree:
+                warnings.warn(
+                    f"`degree` should not be below {min_degree} except -1 "
+                    f"when `kernel` is '{kernel}'."
+                    f"The interpolant may not be uniquely "
+                    f"solvable, and the smoothing parameter may have an "
+                    f"unintuitive effect.",
+                    UserWarning, stacklevel=2
+                )
+
+        if neighbors is None:
+            nobs = ny
+        else:
+            # Make sure the number of nearest neighbors used for interpolation
+            # does not exceed the number of observations.
+            neighbors = int(min(neighbors, ny))
+            nobs = neighbors
+
+        powers = _monomial_powers(ndim, degree)
+        # The polynomial matrix must have full column rank in order for the
+        # interpolant to be well-posed, which is not possible if there are
+        # fewer observations than monomials.
+        if powers.shape[0] > nobs:
+            raise ValueError(
+                f"At least {powers.shape[0]} data points are required when "
+                f"`degree` is {degree} and the number of dimensions is {ndim}."
+                )
+
+        if neighbors is None:
+            shift, scale, coeffs = _build_and_solve_system(
+                y, d, smoothing, kernel, epsilon, powers
+                )
+
+            # Make these attributes private since they do not always exist.
+            self._shift = shift
+            self._scale = scale
+            self._coeffs = coeffs
+
+        else:
+            self._tree = KDTree(y)
+
+        self.y = y
+        self.d = d
+        self.d_shape = d_shape
+        self.d_dtype = d_dtype
+        self.neighbors = neighbors
+        self.smoothing = smoothing
+        self.kernel = kernel
+        self.epsilon = epsilon
+        self.powers = powers
+
+    def _chunk_evaluator(
+            self,
+            x,
+            y,
+            shift,
+            scale,
+            coeffs,
+            memory_budget=1000000
+    ):
+        """
+        Evaluate the interpolation while controlling memory consumption.
+        We chunk the input if we need more memory than specified.
+
+        Parameters
+        ----------
+        x : (Q, N) float ndarray
+            array of points on which to evaluate
+        y: (P, N) float ndarray
+            array of points on which we know function values
+        shift: (N, ) ndarray
+            Domain shift used to create the polynomial matrix.
+        scale : (N,) float ndarray
+            Domain scaling used to create the polynomial matrix.
+        coeffs: (P+R, S) float ndarray
+            Coefficients in front of basis functions
+        memory_budget: int
+            Total amount of memory (in units of sizeof(float)) we wish
+            to devote for storing the array of coefficients for
+            interpolated points. If we need more memory than that, we
+            chunk the input.
+
+        Returns
+        -------
+        (Q, S) float ndarray
+        Interpolated array
+        """
+        nx, ndim = x.shape
+        if self.neighbors is None:
+            nnei = len(y)
+        else:
+            nnei = self.neighbors
+        # in each chunk we consume the same space we already occupy
+        chunksize = memory_budget // (self.powers.shape[0] + nnei) + 1
+        if chunksize <= nx:
+            out = np.empty((nx, self.d.shape[1]), dtype=float)
+            for i in range(0, nx, chunksize):
+                vec = _build_evaluation_coefficients(
+                    x[i:i + chunksize, :],
+                    y,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                    shift,
+                    scale)
+                out[i:i + chunksize, :] = np.dot(vec, coeffs)
+        else:
+            vec = _build_evaluation_coefficients(
+                x,
+                y,
+                self.kernel,
+                self.epsilon,
+                self.powers,
+                shift,
+                scale)
+            out = np.dot(vec, coeffs)
+        return out
+
+    def __call__(self, x):
+        """Evaluate the interpolant at `x`.
+
+        Parameters
+        ----------
+        x : (Q, N) array_like
+            Evaluation point coordinates.
+
+        Returns
+        -------
+        (Q, ...) ndarray
+            Values of the interpolant at `x`.
+
+        """
+        x = np.asarray(x, dtype=float, order="C")
+        if x.ndim != 2:
+            raise ValueError("`x` must be a 2-dimensional array.")
+
+        nx, ndim = x.shape
+        if ndim != self.y.shape[1]:
+            raise ValueError("Expected the second axis of `x` to have length "
+                             f"{self.y.shape[1]}.")
+
+        # Our memory budget for storing RBF coefficients is
+        # based on how many floats in memory we already occupy
+        # If this number is below 1e6 we just use 1e6
+        # This memory budget is used to decide how we chunk
+        # the inputs
+        memory_budget = max(x.size + self.y.size + self.d.size, 1000000)
+
+        if self.neighbors is None:
+            out = self._chunk_evaluator(
+                x,
+                self.y,
+                self._shift,
+                self._scale,
+                self._coeffs,
+                memory_budget=memory_budget)
+        else:
+            # Get the indices of the k nearest observation points to each
+            # evaluation point.
+            _, yindices = self._tree.query(x, self.neighbors)
+            if self.neighbors == 1:
+                # `KDTree` squeezes the output when neighbors=1.
+                yindices = yindices[:, None]
+
+            # Multiple evaluation points may have the same neighborhood of
+            # observation points. Make the neighborhoods unique so that we only
+            # compute the interpolation coefficients once for each
+            # neighborhood.
+            yindices = np.sort(yindices, axis=1)
+            yindices, inv = np.unique(yindices, return_inverse=True, axis=0)
+            inv = np.reshape(inv, (-1,))  # flatten, we need 1-D indices
+            # `inv` tells us which neighborhood will be used by each evaluation
+            # point. Now we find which evaluation points will be using each
+            # neighborhood.
+            xindices = [[] for _ in range(len(yindices))]
+            for i, j in enumerate(inv):
+                xindices[j].append(i)
+
+            out = np.empty((nx, self.d.shape[1]), dtype=float)
+            for xidx, yidx in zip(xindices, yindices):
+                # `yidx` are the indices of the observations in this
+                # neighborhood. `xidx` are the indices of the evaluation points
+                # that are using this neighborhood.
+                xnbr = x[xidx]
+                ynbr = self.y[yidx]
+                dnbr = self.d[yidx]
+                snbr = self.smoothing[yidx]
+                shift, scale, coeffs = _build_and_solve_system(
+                    ynbr,
+                    dnbr,
+                    snbr,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                )
+                out[xidx] = self._chunk_evaluator(
+                    xnbr,
+                    ynbr,
+                    shift,
+                    scale,
+                    coeffs,
+                    memory_budget=memory_budget)
+
+        out = out.view(self.d_dtype)
+        out = out.reshape((nx, ) + self.d_shape)
+        return out
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp_pythran.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp_pythran.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..55a75d48254bf7a0e0b33b5c421278ada0da2ba9
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_rbfinterp_pythran.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_rgi.py b/python_embeded/Lib/site-packages/scipy/interpolate/_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..d99ffc1ebab78ec604c4a88b30327e33a14d9dc7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/_rgi.py
@@ -0,0 +1,759 @@
+__all__ = ['RegularGridInterpolator', 'interpn']
+
+import itertools
+
+import numpy as np
+
+import scipy.sparse.linalg as ssl
+
+from ._interpnd import _ndim_coords_from_arrays
+from ._cubic import PchipInterpolator
+from ._rgi_cython import evaluate_linear_2d, find_indices
+from ._bsplines import make_interp_spline
+from ._fitpack2 import RectBivariateSpline
+from ._ndbspline import make_ndbspl
+
+
+def _check_points(points):
+    descending_dimensions = []
+    grid = []
+    for i, p in enumerate(points):
+        # early make points float
+        # see https://github.com/scipy/scipy/pull/17230
+        p = np.asarray(p, dtype=float)
+        if not np.all(p[1:] > p[:-1]):
+            if np.all(p[1:] < p[:-1]):
+                # input is descending, so make it ascending
+                descending_dimensions.append(i)
+                p = np.flip(p)
+            else:
+                raise ValueError(
+                    "The points in dimension %d must be strictly "
+                    "ascending or descending" % i)
+        # see https://github.com/scipy/scipy/issues/17716
+        p = np.ascontiguousarray(p)
+        grid.append(p)
+    return tuple(grid), tuple(descending_dimensions)
+
+
+def _check_dimensionality(points, values):
+    if len(points) > values.ndim:
+        raise ValueError("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), values.ndim))
+    for i, p in enumerate(points):
+        if not np.asarray(p).ndim == 1:
+            raise ValueError("The points in dimension %d must be "
+                             "1-dimensional" % i)
+        if not values.shape[i] == len(p):
+            raise ValueError("There are %d points and %d values in "
+                             "dimension %d" % (len(p), values.shape[i], i))
+
+
+class RegularGridInterpolator:
+    """
+    Interpolator on a regular or rectilinear grid in arbitrary dimensions.
+
+    The data must be defined on a rectilinear grid; that is, a rectangular
+    grid with even or uneven spacing. Linear, nearest-neighbor, spline
+    interpolations are supported. After setting up the interpolator object,
+    the interpolation method may be chosen at each evaluation.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic" and "pchip". This
+        parameter will become the default for the object's ``__call__``
+        method. Default is "linear".
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+        Default is True.
+
+    fill_value : float or None, optional
+        The value to use for points outside of the interpolation domain.
+        If None, values outside the domain are extrapolated.
+        Default is ``np.nan``.
+
+    solver : callable, optional
+        Only used for methods "slinear", "cubic" and "quintic".
+        Sparse linear algebra solver for construction of the NdBSpline instance.
+        Default is the iterative solver `scipy.sparse.linalg.gcrotmk`.
+
+        .. versionadded:: 1.13
+
+    solver_args: dict, optional
+        Additional arguments to pass to `solver`, if any.
+
+        .. versionadded:: 1.13
+
+    Methods
+    -------
+    __call__
+
+    Attributes
+    ----------
+    grid : tuple of ndarrays
+        The points defining the regular grid in n dimensions.
+        This tuple defines the full grid via
+        ``np.meshgrid(*grid, indexing='ij')``
+    values : ndarray
+        Data values at the grid.
+    method : str
+        Interpolation method.
+    fill_value : float or ``None``
+        Use this value for out-of-bounds arguments to `__call__`.
+    bounds_error : bool
+        If ``True``, out-of-bounds argument raise a ``ValueError``.
+
+    Notes
+    -----
+    Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class
+    avoids expensive triangulation of the input data by taking advantage of the
+    regular grid structure.
+
+    In other words, this class assumes that the data is defined on a
+    *rectilinear* grid.
+
+    .. versionadded:: 0.14
+
+    The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are
+    tensor-product spline interpolators, where `k` is the spline degree,
+    If any dimension has fewer points than `k` + 1, an error will be raised.
+
+    .. versionadded:: 1.9
+
+    If the input data is such that dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    **Choosing a solver for spline methods**
+
+    Spline methods, "slinear", "cubic" and "quintic" involve solving a
+    large sparse linear system at instantiation time. Depending on data,
+    the default solver may or may not be adequate. When it is not, you may
+    need to experiment with an optional `solver` argument, where you may
+    choose between the direct solver (`scipy.sparse.linalg.spsolve`) or
+    iterative solvers from `scipy.sparse.linalg`. You may need to supply
+    additional parameters via the optional `solver_args` parameter (for instance,
+    you may supply the starting value or target tolerance). See the
+    `scipy.sparse.linalg` documentation for the full list of available options.
+
+    Alternatively, you may instead use the legacy methods, "slinear_legacy",
+    "cubic_legacy" and "quintic_legacy". These methods allow faster construction
+    but evaluations will be much slower.
+
+    Examples
+    --------
+    **Evaluate a function on the points of a 3-D grid**
+
+    As a first example, we evaluate a simple example function on the points of
+    a 3-D grid:
+
+    >>> from scipy.interpolate import RegularGridInterpolator
+    >>> import numpy as np
+    >>> def f(x, y, z):
+    ...     return 2 * x**3 + 3 * y**2 - z
+    >>> x = np.linspace(1, 4, 11)
+    >>> y = np.linspace(4, 7, 22)
+    >>> z = np.linspace(7, 9, 33)
+    >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
+    >>> data = f(xg, yg, zg)
+
+    ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``.
+    Next, define an interpolating function from this data:
+
+    >>> interp = RegularGridInterpolator((x, y, z), data)
+
+    Evaluate the interpolating function at the two points
+    ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``:
+
+    >>> pts = np.array([[2.1, 6.2, 8.3],
+    ...                 [3.3, 5.2, 7.1]])
+    >>> interp(pts)
+    array([ 125.80469388,  146.30069388])
+
+    which is indeed a close approximation to
+
+    >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)
+    (125.54200000000002, 145.894)
+
+    **Interpolate and extrapolate a 2D dataset**
+
+    As a second example, we interpolate and extrapolate a 2D data set:
+
+    >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5])
+    >>> def ff(x, y):
+    ...     return x**2 + y**2
+
+    >>> xg, yg = np.meshgrid(x, y, indexing='ij')
+    >>> data = ff(xg, yg)
+    >>> interp = RegularGridInterpolator((x, y), data,
+    ...                                  bounds_error=False, fill_value=None)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(projection='3d')
+    >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(),
+    ...            s=60, c='k', label='data')
+
+    Evaluate and plot the interpolator on a finer grid
+
+    >>> xx = np.linspace(-4, 9, 31)
+    >>> yy = np.linspace(-4, 9, 31)
+    >>> X, Y = np.meshgrid(xx, yy, indexing='ij')
+
+    >>> # interpolator
+    >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3,
+    ...                   alpha=0.4, color='m', label='linear interp')
+
+    >>> # ground truth
+    >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3,
+    ...                   alpha=0.4, label='ground truth')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Other examples are given
+    :ref:`in the tutorial `.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolator on *unstructured*
+                            data in N dimensions
+
+    LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data
+                           in N dimensions
+
+    interpn : a convenience function which wraps `RegularGridInterpolator`
+
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    References
+    ----------
+    .. [1] Python package *regulargrid* by Johannes Buchner, see
+           https://pypi.python.org/pypi/regulargrid/
+    .. [2] Wikipedia, "Trilinear interpolation",
+           https://en.wikipedia.org/wiki/Trilinear_interpolation
+    .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear
+           and multilinear table interpolation in many dimensions." MATH.
+           COMPUT. 50.181 (1988): 189-196.
+           https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf
+           :doi:`10.1090/S0025-5718-1988-0917826-0`
+
+    """
+    # this class is based on code originally programmed by Johannes Buchner,
+    # see https://github.com/JohannesBuchner/regulargrid
+
+    _SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3,
+                          "slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,}
+    _SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy",
+                                "quintic_legacy", "pchip"}
+    _SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"}
+    _SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys())
+    _ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS
+
+    def __init__(self, points, values, method="linear", bounds_error=True,
+                 fill_value=np.nan, *, solver=None, solver_args=None):
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        elif method in self._SPLINE_METHODS:
+            self._validate_grid_dimensions(points, method)
+        self.method = method
+        self._spline = None
+        self.bounds_error = bounds_error
+        self.grid, self._descending_dimensions = _check_points(points)
+        self.values = self._check_values(values)
+        self._check_dimensionality(self.grid, self.values)
+        self.fill_value = self._check_fill_value(self.values, fill_value)
+        if self._descending_dimensions:
+            self.values = np.flip(values, axis=self._descending_dimensions)
+        if self.method == "pchip" and np.iscomplexobj(self.values):
+            msg = ("`PchipInterpolator` only works with real values. If you are trying "
+                   "to use the real components of the passed array, use `np.real` on "
+                   "the array before passing to `RegularGridInterpolator`.")
+            raise ValueError(msg)
+        if method in self._SPLINE_METHODS_ndbspl:
+            if solver_args is None:
+                solver_args = {}
+            self._spline = self._construct_spline(method, solver, **solver_args)
+        else:
+            if solver is not None or solver_args:
+                raise ValueError(
+                    f"{method =} does not accept the 'solver' argument. Got "
+                    f" {solver = } and with arguments {solver_args}."
+                )
+
+    def _construct_spline(self, method, solver=None, **solver_args):
+        if solver is None:
+            solver = ssl.gcrotmk
+        spl = make_ndbspl(
+                self.grid, self.values, self._SPLINE_DEGREE_MAP[method],
+                solver=solver, **solver_args
+              )
+        return spl
+
+    def _check_dimensionality(self, grid, values):
+        _check_dimensionality(grid, values)
+
+    def _check_points(self, points):
+        return _check_points(points)
+
+    def _check_values(self, values):
+        if not hasattr(values, 'ndim'):
+            # allow reasonable duck-typed values
+            values = np.asarray(values)
+
+        if hasattr(values, 'dtype') and hasattr(values, 'astype'):
+            if not np.issubdtype(values.dtype, np.inexact):
+                values = values.astype(float)
+
+        return values
+
+    def _check_fill_value(self, values, fill_value):
+        if fill_value is not None:
+            fill_value_dtype = np.asarray(fill_value).dtype
+            if (hasattr(values, 'dtype') and not
+                    np.can_cast(fill_value_dtype, values.dtype,
+                                casting='same_kind')):
+                raise ValueError("fill_value must be either 'None' or "
+                                 "of a type compatible with values")
+        return fill_value
+
+    def __call__(self, xi, method=None, *, nu=None):
+        """
+        Interpolation at coordinates.
+
+        Parameters
+        ----------
+        xi : ndarray of shape (..., ndim)
+            The coordinates to evaluate the interpolator at.
+
+        method : str, optional
+            The method of interpolation to perform. Supported are "linear",
+            "nearest", "slinear", "cubic", "quintic" and "pchip". Default is
+            the method chosen when the interpolator was created.
+
+        nu : sequence of ints, length ndim, optional
+            If not None, the orders of the derivatives to evaluate.
+            Each entry must be non-negative.
+            Only allowed for methods "slinear", "cubic" and "quintic".
+
+            .. versionadded:: 1.13
+
+        Returns
+        -------
+        values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+            Interpolated values at `xi`. See notes for behaviour when
+            ``xi.ndim == 1``.
+
+        Notes
+        -----
+        In the case that ``xi.ndim == 1`` a new axis is inserted into
+        the 0 position of the returned array, values_x, so its shape is
+        instead ``(1,) + values.shape[ndim:]``.
+
+        Examples
+        --------
+        Here we define a nearest-neighbor interpolator of a simple function
+
+        >>> import numpy as np
+        >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
+        >>> def f(x, y):
+        ...     return x**2 + y**2
+        >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
+        >>> from scipy.interpolate import RegularGridInterpolator
+        >>> interp = RegularGridInterpolator((x, y), data, method='nearest')
+
+        By construction, the interpolator uses the nearest-neighbor
+        interpolation
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]])
+        array([2., 9.])
+
+        We can however evaluate the linear interpolant by overriding the
+        `method` parameter
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear')
+        array([ 4.7, 24.3])
+        """
+        _spline = self._spline
+        method = self.method if method is None else method
+        is_method_changed = self.method != method
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        if is_method_changed and method in self._SPLINE_METHODS_ndbspl:
+            _spline = self._construct_spline(method)
+
+        if nu is not None and method not in self._SPLINE_METHODS_ndbspl:
+            raise ValueError(
+                f"Can only compute derivatives for methods "
+                f"{self._SPLINE_METHODS_ndbspl}, got {method =}."
+            )
+
+        xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi)
+
+        if method == "linear":
+            indices, norm_distances = self._find_indices(xi.T)
+            if (ndim == 2 and hasattr(self.values, 'dtype') and
+                    self.values.ndim == 2 and self.values.flags.writeable and
+                    self.values.dtype in (np.float64, np.complex128) and
+                    self.values.dtype.byteorder == '='):
+                # until cython supports const fused types, the fast path
+                # cannot support non-writeable values
+                # a fast path
+                out = np.empty(indices.shape[1], dtype=self.values.dtype)
+                result = evaluate_linear_2d(self.values,
+                                            indices,
+                                            norm_distances,
+                                            self.grid,
+                                            out)
+            else:
+                result = self._evaluate_linear(indices, norm_distances)
+        elif method == "nearest":
+            indices, norm_distances = self._find_indices(xi.T)
+            result = self._evaluate_nearest(indices, norm_distances)
+        elif method in self._SPLINE_METHODS:
+            if is_method_changed:
+                self._validate_grid_dimensions(self.grid, method)
+            if method in self._SPLINE_METHODS_recursive:
+                result = self._evaluate_spline(xi, method)
+            else:
+                result = _spline(xi, nu=nu)
+
+        if not self.bounds_error and self.fill_value is not None:
+            result[out_of_bounds] = self.fill_value
+
+        # f(nan) = nan, if any
+        if np.any(nans):
+            result[nans] = np.nan
+        return result.reshape(xi_shape[:-1] + self.values.shape[ndim:])
+
+    def _prepare_xi(self, xi):
+        ndim = len(self.grid)
+        xi = _ndim_coords_from_arrays(xi, ndim=ndim)
+        if xi.shape[-1] != len(self.grid):
+            raise ValueError("The requested sample points xi have dimension "
+                             f"{xi.shape[-1]} but this "
+                             f"RegularGridInterpolator has dimension {ndim}")
+
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.asarray(xi, dtype=float)
+
+        # find nans in input
+        nans = np.any(np.isnan(xi), axis=-1)
+
+        if self.bounds_error:
+            for i, p in enumerate(xi.T):
+                if not np.logical_and(np.all(self.grid[i][0] <= p),
+                                      np.all(p <= self.grid[i][-1])):
+                    raise ValueError("One of the requested xi is out of bounds "
+                                     "in dimension %d" % i)
+            out_of_bounds = None
+        else:
+            out_of_bounds = self._find_out_of_bounds(xi.T)
+
+        return xi, xi_shape, ndim, nans, out_of_bounds
+
+    def _evaluate_linear(self, indices, norm_distances):
+        # slice for broadcasting over trailing dimensions in self.values
+        vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices))
+
+        # Compute shifting up front before zipping everything together
+        shift_norm_distances = [1 - yi for yi in norm_distances]
+        shift_indices = [i + 1 for i in indices]
+
+        # The formula for linear interpolation in 2d takes the form:
+        # values = self.values[(i0, i1)] * (1 - y0) * (1 - y1) + \
+        #          self.values[(i0, i1 + 1)] * (1 - y0) * y1 + \
+        #          self.values[(i0 + 1, i1)] * y0 * (1 - y1) + \
+        #          self.values[(i0 + 1, i1 + 1)] * y0 * y1
+        # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2)
+        zipped1 = zip(indices, shift_norm_distances)
+        zipped2 = zip(shift_indices, norm_distances)
+
+        # Take all products of zipped1 and zipped2 and iterate over them
+        # to get the terms in the above formula. This corresponds to iterating
+        # over the vertices of a hypercube.
+        hypercube = itertools.product(*zip(zipped1, zipped2))
+        value = np.array([0.])
+        for h in hypercube:
+            edge_indices, weights = zip(*h)
+            weight = np.array([1.])
+            for w in weights:
+                weight = weight * w
+            term = np.asarray(self.values[edge_indices]) * weight[vslice]
+            value = value + term   # cannot use += because broadcasting
+        return value
+
+    def _evaluate_nearest(self, indices, norm_distances):
+        idx_res = [np.where(yi <= .5, i, i + 1)
+                   for i, yi in zip(indices, norm_distances)]
+        return self.values[tuple(idx_res)]
+
+    def _validate_grid_dimensions(self, points, method):
+        k = self._SPLINE_DEGREE_MAP[method]
+        for i, point in enumerate(points):
+            ndim = len(np.atleast_1d(point))
+            if ndim <= k:
+                raise ValueError(f"There are {ndim} points in dimension {i},"
+                                 f" but method {method} requires at least "
+                                 f" {k+1} points per dimension.")
+
+    def _evaluate_spline(self, xi, method):
+        # ensure xi is 2D list of points to evaluate (`m` is the number of
+        # points and `n` is the number of interpolation dimensions,
+        # ``n == len(self.grid)``.)
+        if xi.ndim == 1:
+            xi = xi.reshape((1, xi.size))
+        m, n = xi.shape
+
+        # Reorder the axes: n-dimensional process iterates over the
+        # interpolation axes from the last axis downwards: E.g. for a 4D grid
+        # the order of axes is 3, 2, 1, 0. Each 1D interpolation works along
+        # the 0th axis of its argument array (for 1D routine it's its ``y``
+        # array). Thus permute the interpolation axes of `values` *and keep
+        # trailing dimensions trailing*.
+        axes = tuple(range(self.values.ndim))
+        axx = axes[:n][::-1] + axes[n:]
+        values = self.values.transpose(axx)
+
+        if method == 'pchip':
+            _eval_func = self._do_pchip
+        else:
+            _eval_func = self._do_spline_fit
+        k = self._SPLINE_DEGREE_MAP[method]
+
+        # Non-stationary procedure: difficult to vectorize this part entirely
+        # into numpy-level operations. Unfortunately this requires explicit
+        # looping over each point in xi.
+
+        # can at least vectorize the first pass across all points in the
+        # last variable of xi.
+        last_dim = n - 1
+        first_values = _eval_func(self.grid[last_dim],
+                                  values,
+                                  xi[:, last_dim],
+                                  k)
+
+        # the rest of the dimensions have to be on a per point-in-xi basis
+        shape = (m, *self.values.shape[n:])
+        result = np.empty(shape, dtype=self.values.dtype)
+        for j in range(m):
+            # Main process: Apply 1D interpolate in each dimension
+            # sequentially, starting with the last dimension.
+            # These are then "folded" into the next dimension in-place.
+            folded_values = first_values[j, ...]
+            for i in range(last_dim-1, -1, -1):
+                # Interpolate for each 1D from the last dimensions.
+                # This collapses each 1D sequence into a scalar.
+                folded_values = _eval_func(self.grid[i],
+                                           folded_values,
+                                           xi[j, i],
+                                           k)
+            result[j, ...] = folded_values
+
+        return result
+
+    @staticmethod
+    def _do_spline_fit(x, y, pt, k):
+        local_interp = make_interp_spline(x, y, k=k, axis=0)
+        values = local_interp(pt)
+        return values
+
+    @staticmethod
+    def _do_pchip(x, y, pt, k):
+        local_interp = PchipInterpolator(x, y, axis=0)
+        values = local_interp(pt)
+        return values
+
+    def _find_indices(self, xi):
+        return find_indices(self.grid, xi)
+
+    def _find_out_of_bounds(self, xi):
+        # check for out of bounds xi
+        out_of_bounds = np.zeros((xi.shape[1]), dtype=bool)
+        # iterate through dimensions
+        for x, grid in zip(xi, self.grid):
+            out_of_bounds += x < grid[0]
+            out_of_bounds += x > grid[-1]
+        return out_of_bounds
+
+
+def interpn(points, values, xi, method="linear", bounds_error=True,
+            fill_value=np.nan):
+    """
+    Multidimensional interpolation on regular or rectilinear grids.
+
+    Strictly speaking, not all regular grids are supported - this function
+    works on *rectilinear* grids, that is, a rectangular grid with even or
+    uneven spacing.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated with ``method="pchip"`` and will raise an
+            error in SciPy 1.15.0. This is because ``PchipInterpolator`` only
+            works with real values. If you are trying to use the real components of
+            the passed array, use ``np.real`` on ``values``.
+
+    xi : ndarray of shape (..., ndim)
+        The coordinates to sample the gridded data at
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d".
+        "splinef2d" is only supported for 2-dimensional data.
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+
+    fill_value : number, optional
+        If provided, the value to use for points outside of the
+        interpolation domain. If None, values outside
+        the domain are extrapolated.  Extrapolation is not supported by method
+        "splinef2d".
+
+    Returns
+    -------
+    values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+        Interpolated values at `xi`. See notes for behaviour when
+        ``xi.ndim == 1``.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolation on unstructured
+                            data in N dimensions
+    LinearNDInterpolator : Piecewise linear interpolant on unstructured data
+                           in N dimensions
+    RegularGridInterpolator : interpolation on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+    RectBivariateSpline : Bivariate spline approximation over a rectangular mesh
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14
+
+    In the case that ``xi.ndim == 1`` a new axis is inserted into
+    the 0 position of the returned array, values_x, so its shape is
+    instead ``(1,) + values.shape[ndim:]``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    Examples
+    --------
+    Evaluate a simple example function on the points of a regular 3-D grid:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import interpn
+    >>> def value_func_3d(x, y, z):
+    ...     return 2 * x + 3 * y - z
+    >>> x = np.linspace(0, 4, 5)
+    >>> y = np.linspace(0, 5, 6)
+    >>> z = np.linspace(0, 6, 7)
+    >>> points = (x, y, z)
+    >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij'))
+
+    Evaluate the interpolating function at a point
+
+    >>> point = np.array([2.21, 3.12, 1.15])
+    >>> print(interpn(points, values, point))
+    [12.63]
+
+    """
+    # sanity check 'method' kwarg
+    if method not in ["linear", "nearest", "cubic", "quintic", "pchip",
+                      "splinef2d", "slinear",
+                      "slinear_legacy", "cubic_legacy", "quintic_legacy"]:
+        raise ValueError("interpn only understands the methods 'linear', "
+                         "'nearest', 'slinear', 'cubic', 'quintic', 'pchip', "
+                         f"and 'splinef2d'. You provided {method}.")
+
+    if not hasattr(values, 'ndim'):
+        values = np.asarray(values)
+
+    ndim = values.ndim
+    if ndim > 2 and method == "splinef2d":
+        raise ValueError("The method splinef2d can only be used for "
+                         "2-dimensional input data")
+    if not bounds_error and fill_value is None and method == "splinef2d":
+        raise ValueError("The method splinef2d does not support extrapolation.")
+
+    # sanity check consistency of input dimensions
+    if len(points) > ndim:
+        raise ValueError("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), ndim))
+    if len(points) != ndim and method == 'splinef2d':
+        raise ValueError("The method splinef2d can only be used for "
+                         "scalar data with one point per coordinate")
+
+    grid, descending_dimensions = _check_points(points)
+    _check_dimensionality(grid, values)
+
+    # sanity check requested xi
+    xi = _ndim_coords_from_arrays(xi, ndim=len(grid))
+    if xi.shape[-1] != len(grid):
+        raise ValueError("The requested sample points xi have dimension "
+                         "%d, but this RegularGridInterpolator has "
+                         "dimension %d" % (xi.shape[-1], len(grid)))
+
+    if bounds_error:
+        for i, p in enumerate(xi.T):
+            if not np.logical_and(np.all(grid[i][0] <= p),
+                                  np.all(p <= grid[i][-1])):
+                raise ValueError("One of the requested xi is out of bounds "
+                                 "in dimension %d" % i)
+
+    # perform interpolation
+    if method in RegularGridInterpolator._ALL_METHODS:
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=bounds_error,
+                                         fill_value=fill_value)
+        return interp(xi)
+    elif method == "splinef2d":
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi.shape[-1])
+
+        # RectBivariateSpline doesn't support fill_value; we need to wrap here
+        idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1],
+                            grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]),
+                           axis=0)
+        result = np.empty_like(xi[:, 0])
+
+        # make a copy of values for RectBivariateSpline
+        interp = RectBivariateSpline(points[0], points[1], values[:])
+        result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1])
+        result[np.logical_not(idx_valid)] = fill_value
+
+        return result.reshape(xi_shape[:-1])
+    else:
+        raise ValueError(f"unknown {method = }")
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/_rgi_cython.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/interpolate/_rgi_cython.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..0b65d818a2521d487502b1f0e923ed7aa8319a13
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/interpolate/_rgi_cython.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/dfitpack.py b/python_embeded/Lib/site-packages/scipy/interpolate/dfitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..401efc97dd9abf65c2926100a01a2929a8901fd4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/dfitpack.py
@@ -0,0 +1,44 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'bispeu',
+    'bispev',
+    'curfit',
+    'dblint',
+    'fpchec',
+    'fpcurf0',
+    'fpcurf1',
+    'fpcurfm1',
+    'parcur',
+    'parder',
+    'pardeu',
+    'pardtc',
+    'percur',
+    'regrid_smth',
+    'regrid_smth_spher',
+    'spalde',
+    'spherfit_lsq',
+    'spherfit_smth',
+    'splder',
+    'splev',
+    'splint',
+    'sproot',
+    'surfit_lsq',
+    'surfit_smth',
+    'types',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="dfitpack",
+                                   private_modules=["_dfitpack"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/fitpack.py b/python_embeded/Lib/site-packages/scipy/interpolate/fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f115ded4234431eda2e632b9e653d115a1f2e1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/fitpack.py
@@ -0,0 +1,31 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BSpline',
+    'bisplev',
+    'bisplrep',
+    'insert',
+    'spalde',
+    'splantider',
+    'splder',
+    'splev',
+    'splint',
+    'splprep',
+    'splrep',
+    'sproot',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack",
+                                   private_modules=["_fitpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/fitpack2.py b/python_embeded/Lib/site-packages/scipy/interpolate/fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e095df6ab33143ccc2fcb515db76ae46419c05d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/fitpack2.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.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'LSQUnivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline',
+    'SmoothBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'UnivariateSpline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack2",
+                                   private_modules=["_fitpack2"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/interpnd.py b/python_embeded/Lib/site-packages/scipy/interpolate/interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9887310634bad2103aff3e909ede019c2f01bb6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/interpnd.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'GradientEstimationWarning',
+    'LinearNDInterpolator',
+    'NDInterpolatorBase',
+    'estimate_gradients_2d_global',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpnd",
+                                   private_modules=["_interpnd"], all=__all__,
+                                   attribute=name)
+
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/interpolate.py b/python_embeded/Lib/site-packages/scipy/interpolate/interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a628bea79ff32093712511bc3a2d4dbdf429b7e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/interpolate.py
@@ -0,0 +1,30 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BPoly',
+    'BSpline',
+    'NdPPoly',
+    'PPoly',
+    'RectBivariateSpline',
+    'RegularGridInterpolator',
+    'interp1d',
+    'interp2d',
+    'interpn',
+    'lagrange',
+    'make_interp_spline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpolate",
+                                   private_modules=["_interpolate", "fitpack2", "_rgi"],
+                                   all=__all__, attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/ndgriddata.py b/python_embeded/Lib/site-packages/scipy/interpolate/ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..44467f3052869e8c052a6b0217b6e984b97c40f9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/ndgriddata.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.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'LinearNDInterpolator',
+    'NearestNDInterpolator',
+    'griddata',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="ndgriddata",
+                                   private_modules=["_ndgriddata"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/polyint.py b/python_embeded/Lib/site-packages/scipy/interpolate/polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..db8e9ab1466e24c009797a2d7dd4783bd48c72ed
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/polyint.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.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BarycentricInterpolator',
+    'KroghInterpolator',
+    'approximate_taylor_polynomial',
+    'barycentric_interpolate',
+    'krogh_interpolate',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="polyint",
+                                   private_modules=["_polyint"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/interpolate/rbf.py b/python_embeded/Lib/site-packages/scipy/interpolate/rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc5e8448507dd11c03d9937c4a06ecf50d0f4785
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/interpolate/rbf.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["Rbf"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="rbf",
+                                   private_modules=["_rbf"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/io/__init__.py b/python_embeded/Lib/site-packages/scipy/io/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dfe6ccaa68b02f91c5e1f93c146155b1d8082f5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/__init__.py
@@ -0,0 +1,116 @@
+"""
+==================================
+Input and output (:mod:`scipy.io`)
+==================================
+
+.. currentmodule:: scipy.io
+
+SciPy has many modules, classes, and functions available to read data
+from and write data to a variety of file formats.
+
+.. seealso:: `NumPy IO routines `__
+
+MATLAB® files
+=============
+
+.. autosummary::
+   :toctree: generated/
+
+   loadmat - Read a MATLAB style mat file (version 4 through 7.1)
+   savemat - Write a MATLAB style mat file (version 4 through 7.1)
+   whosmat - List contents of a MATLAB style mat file (version 4 through 7.1)
+
+For low-level MATLAB reading and writing utilities, see `scipy.io.matlab`.
+
+IDL® files
+==========
+
+.. autosummary::
+   :toctree: generated/
+
+   readsav - Read an IDL 'save' file
+
+Matrix Market files
+===================
+
+.. autosummary::
+   :toctree: generated/
+
+   mminfo - Query matrix info from Matrix Market formatted file
+   mmread - Read matrix from Matrix Market formatted file
+   mmwrite - Write matrix to Matrix Market formatted file
+
+Unformatted Fortran files
+===============================
+
+.. autosummary::
+   :toctree: generated/
+
+   FortranFile - A file object for unformatted sequential Fortran files
+   FortranEOFError - Exception indicating the end of a well-formed file
+   FortranFormattingError - Exception indicating an inappropriate end
+
+Netcdf
+======
+
+.. autosummary::
+   :toctree: generated/
+
+   netcdf_file - A file object for NetCDF data
+   netcdf_variable - A data object for the netcdf module
+
+Harwell-Boeing files
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   hb_read   -- read H-B file
+   hb_write  -- write H-B file
+
+Wav sound files (:mod:`scipy.io.wavfile`)
+=========================================
+
+.. module:: scipy.io.wavfile
+
+.. autosummary::
+   :toctree: generated/
+
+   read
+   write
+   WavFileWarning
+
+Arff files (:mod:`scipy.io.arff`)
+=================================
+
+.. module:: scipy.io.arff
+
+.. autosummary::
+   :toctree: generated/
+
+   loadarff
+   MetaData
+   ArffError
+   ParseArffError
+"""
+# matfile read and write
+from .matlab import loadmat, savemat, whosmat
+
+# netCDF file support
+from ._netcdf import netcdf_file, netcdf_variable
+
+# Fortran file support
+from ._fortran import FortranFile, FortranEOFError, FortranFormattingError
+
+from ._fast_matrix_market import mminfo, mmread, mmwrite
+from ._idl import readsav
+from ._harwell_boeing import hb_read, hb_write
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import arff, harwell_boeing, idl, mmio, netcdf, wavfile
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/io/_fortran.py b/python_embeded/Lib/site-packages/scipy/io/_fortran.py
new file mode 100644
index 0000000000000000000000000000000000000000..532a7bf5e4c987bcd048dfe7639137c07c1c20fb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/_fortran.py
@@ -0,0 +1,354 @@
+"""
+Module to read / write Fortran unformatted sequential files.
+
+This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.
+
+"""
+import warnings
+import numpy as np
+
+__all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
+
+
+class FortranEOFError(TypeError, OSError):
+    """Indicates that the file ended properly.
+
+    This error descends from TypeError because the code used to raise
+    TypeError (and this was the only way to know that the file had
+    ended) so users might have ``except TypeError:``.
+
+    """
+    pass
+
+
+class FortranFormattingError(TypeError, OSError):
+    """Indicates that the file ended mid-record.
+
+    Descends from TypeError for backward compatibility.
+
+    """
+    pass
+
+
+class FortranFile:
+    """
+    A file object for unformatted sequential files from Fortran code.
+
+    Parameters
+    ----------
+    filename : file or str
+        Open file object or filename.
+    mode : {'r', 'w'}, optional
+        Read-write mode, default is 'r'.
+    header_dtype : dtype, optional
+        Data type of the header. Size and endianness must match the input/output file.
+
+    Notes
+    -----
+    These files are broken up into records of unspecified types. The size of
+    each record is given at the start (although the size of this header is not
+    standard) and the data is written onto disk without any formatting. Fortran
+    compilers supporting the BACKSPACE statement will write a second copy of
+    the size to facilitate backwards seeking.
+
+    This class only supports files written with both sizes for the record.
+    It also does not support the subrecords used in Intel and gfortran compilers
+    for records which are greater than 2GB with a 4-byte header.
+
+    An example of an unformatted sequential file in Fortran would be written as::
+
+        OPEN(1, FILE=myfilename, FORM='unformatted')
+
+        WRITE(1) myvariable
+
+    Since this is a non-standard file format, whose contents depend on the
+    compiler and the endianness of the machine, caution is advised. Files from
+    gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.
+
+    Consider using Fortran direct-access files or files from the newer Stream
+    I/O, which can be easily read by `numpy.fromfile`.
+
+    Examples
+    --------
+    To create an unformatted sequential Fortran file:
+
+    >>> from scipy.io import FortranFile
+    >>> import numpy as np
+    >>> f = FortranFile('test.unf', 'w')
+    >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
+    >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
+    >>> f.close()
+
+    To read this file:
+
+    >>> f = FortranFile('test.unf', 'r')
+    >>> print(f.read_ints(np.int32))
+    [1 2 3 4 5]
+    >>> print(f.read_reals(float).reshape((5,4), order="F"))
+    [[0.         0.05263158 0.10526316 0.15789474]
+     [0.21052632 0.26315789 0.31578947 0.36842105]
+     [0.42105263 0.47368421 0.52631579 0.57894737]
+     [0.63157895 0.68421053 0.73684211 0.78947368]
+     [0.84210526 0.89473684 0.94736842 1.        ]]
+    >>> f.close()
+
+    Or, in Fortran::
+
+        integer :: a(5), i
+        double precision :: b(5,4)
+        open(1, file='test.unf', form='unformatted')
+        read(1) a
+        read(1) b
+        close(1)
+        write(*,*) a
+        do i = 1, 5
+            write(*,*) b(i,:)
+        end do
+
+    """
+    def __init__(self, filename, mode='r', header_dtype=np.uint32):
+        if header_dtype is None:
+            raise ValueError('Must specify dtype')
+
+        header_dtype = np.dtype(header_dtype)
+        if header_dtype.kind != 'u':
+            warnings.warn("Given a dtype which is not unsigned.", stacklevel=2)
+
+        if mode not in 'rw' or len(mode) != 1:
+            raise ValueError('mode must be either r or w')
+
+        if hasattr(filename, 'seek'):
+            self._fp = filename
+        else:
+            self._fp = open(filename, f'{mode}b')
+
+        self._header_dtype = header_dtype
+
+    def _read_size(self, eof_ok=False):
+        n = self._header_dtype.itemsize
+        b = self._fp.read(n)
+        if (not b) and eof_ok:
+            raise FortranEOFError("End of file occurred at end of record")
+        elif len(b) < n:
+            raise FortranFormattingError(
+                "End of file in the middle of the record size")
+        return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0])
+
+    def write_record(self, *items):
+        """
+        Write a record (including sizes) to the file.
+
+        Parameters
+        ----------
+        *items : array_like
+            The data arrays to write.
+
+        Notes
+        -----
+        Writes data items to a file::
+
+            write_record(a.T, b.T, c.T, ...)
+
+            write(1) a, b, c, ...
+
+        Note that data in multidimensional arrays is written in
+        row-major order --- to make them read correctly by Fortran
+        programs, you need to transpose the arrays yourself when
+        writing them.
+
+        """
+        items = tuple(np.asarray(item) for item in items)
+        total_size = sum(item.nbytes for item in items)
+
+        nb = np.array([total_size], dtype=self._header_dtype)
+
+        nb.tofile(self._fp)
+        for item in items:
+            item.tofile(self._fp)
+        nb.tofile(self._fp)
+
+    def read_record(self, *dtypes, **kwargs):
+        """
+        Reads a record of a given type from the file.
+
+        Parameters
+        ----------
+        *dtypes : dtypes, optional
+            Data type(s) specifying the size and endianness of the data.
+
+        Returns
+        -------
+        data : ndarray
+            A 1-D array object.
+
+        Raises
+        ------
+        FortranEOFError
+            To signal that no further records are available
+        FortranFormattingError
+            To signal that the end of the file was encountered
+            part-way through a record
+
+        Notes
+        -----
+        If the record contains a multidimensional array, you can specify
+        the size in the dtype. For example::
+
+            INTEGER var(5,4)
+
+        can be read with::
+
+            read_record('(4,5)i4').T
+
+        Note that this function does **not** assume the file data is in Fortran
+        column major order, so you need to (i) swap the order of dimensions
+        when reading and (ii) transpose the resulting array.
+
+        Alternatively, you can read the data as a 1-D array and handle the
+        ordering yourself. For example::
+
+            read_record('i4').reshape(5, 4, order='F')
+
+        For records that contain several variables or mixed types (as opposed
+        to single scalar or array types), give them as separate arguments::
+
+            double precision :: a
+            integer :: b
+            write(1) a, b
+
+            record = f.read_record('u1',
+              2: '>i2',
+              3: '>i4',
+              4: '>f4',
+              5: '>f8',
+              6: '>c8',
+              7: '|O',
+              8: '|O',
+              9: '>c16',
+              10: '|O',
+              11: '|O',
+              12: '>u2',
+              13: '>u4',
+              14: '>i8',
+              15: '>u8'}
+
+# Define the different record types that can be found in an IDL save file
+RECTYPE_DICT = {0: "START_MARKER",
+                1: "COMMON_VARIABLE",
+                2: "VARIABLE",
+                3: "SYSTEM_VARIABLE",
+                6: "END_MARKER",
+                10: "TIMESTAMP",
+                12: "COMPILED",
+                13: "IDENTIFICATION",
+                14: "VERSION",
+                15: "HEAP_HEADER",
+                16: "HEAP_DATA",
+                17: "PROMOTE64",
+                19: "NOTICE",
+                20: "DESCRIPTION"}
+
+# Define a dictionary to contain structure definitions
+STRUCT_DICT = {}
+
+
+def _align_32(f):
+    '''Align to the next 32-bit position in a file'''
+
+    pos = f.tell()
+    if pos % 4 != 0:
+        f.seek(pos + 4 - pos % 4)
+    return
+
+
+def _skip_bytes(f, n):
+    '''Skip `n` bytes'''
+    f.read(n)
+    return
+
+
+def _read_bytes(f, n):
+    '''Read the next `n` bytes'''
+    return f.read(n)
+
+
+def _read_byte(f):
+    '''Read a single byte'''
+    return np.uint8(struct.unpack('>B', f.read(4)[:1])[0])
+
+
+def _read_long(f):
+    '''Read a signed 32-bit integer'''
+    return np.int32(struct.unpack('>l', f.read(4))[0])
+
+
+def _read_int16(f):
+    '''Read a signed 16-bit integer'''
+    return np.int16(struct.unpack('>h', f.read(4)[2:4])[0])
+
+
+def _read_int32(f):
+    '''Read a signed 32-bit integer'''
+    return np.int32(struct.unpack('>i', f.read(4))[0])
+
+
+def _read_int64(f):
+    '''Read a signed 64-bit integer'''
+    return np.int64(struct.unpack('>q', f.read(8))[0])
+
+
+def _read_uint16(f):
+    '''Read an unsigned 16-bit integer'''
+    return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0])
+
+
+def _read_uint32(f):
+    '''Read an unsigned 32-bit integer'''
+    return np.uint32(struct.unpack('>I', f.read(4))[0])
+
+
+def _read_uint64(f):
+    '''Read an unsigned 64-bit integer'''
+    return np.uint64(struct.unpack('>Q', f.read(8))[0])
+
+
+def _read_float32(f):
+    '''Read a 32-bit float'''
+    return np.float32(struct.unpack('>f', f.read(4))[0])
+
+
+def _read_float64(f):
+    '''Read a 64-bit float'''
+    return np.float64(struct.unpack('>d', f.read(8))[0])
+
+
+class Pointer:
+    '''Class used to define pointers'''
+
+    def __init__(self, index):
+        self.index = index
+        return
+
+
+class ObjectPointer(Pointer):
+    '''Class used to define object pointers'''
+    pass
+
+
+def _read_string(f):
+    '''Read a string'''
+    length = _read_long(f)
+    if length > 0:
+        chars = _read_bytes(f, length).decode('latin1')
+        _align_32(f)
+    else:
+        chars = ''
+    return chars
+
+
+def _read_string_data(f):
+    '''Read a data string (length is specified twice)'''
+    length = _read_long(f)
+    if length > 0:
+        length = _read_long(f)
+        string_data = _read_bytes(f, length)
+        _align_32(f)
+    else:
+        string_data = ''
+    return string_data
+
+
+def _read_data(f, dtype):
+    '''Read a variable with a specified data type'''
+    if dtype == 1:
+        if _read_int32(f) != 1:
+            raise Exception("Error occurred while reading byte variable")
+        return _read_byte(f)
+    elif dtype == 2:
+        return _read_int16(f)
+    elif dtype == 3:
+        return _read_int32(f)
+    elif dtype == 4:
+        return _read_float32(f)
+    elif dtype == 5:
+        return _read_float64(f)
+    elif dtype == 6:
+        real = _read_float32(f)
+        imag = _read_float32(f)
+        return np.complex64(real + imag * 1j)
+    elif dtype == 7:
+        return _read_string_data(f)
+    elif dtype == 8:
+        raise Exception("Should not be here - please report this")
+    elif dtype == 9:
+        real = _read_float64(f)
+        imag = _read_float64(f)
+        return np.complex128(real + imag * 1j)
+    elif dtype == 10:
+        return Pointer(_read_int32(f))
+    elif dtype == 11:
+        return ObjectPointer(_read_int32(f))
+    elif dtype == 12:
+        return _read_uint16(f)
+    elif dtype == 13:
+        return _read_uint32(f)
+    elif dtype == 14:
+        return _read_int64(f)
+    elif dtype == 15:
+        return _read_uint64(f)
+    else:
+        raise Exception("Unknown IDL type: %i - please report this" % dtype)
+
+
+def _read_structure(f, array_desc, struct_desc):
+    '''
+    Read a structure, with the array and structure descriptors given as
+    `array_desc` and `structure_desc` respectively.
+    '''
+
+    nrows = array_desc['nelements']
+    columns = struct_desc['tagtable']
+
+    dtype = []
+    for col in columns:
+        if col['structure'] or col['array']:
+            dtype.append(((col['name'].lower(), col['name']), np.object_))
+        else:
+            if col['typecode'] in DTYPE_DICT:
+                dtype.append(((col['name'].lower(), col['name']),
+                                    DTYPE_DICT[col['typecode']]))
+            else:
+                raise Exception("Variable type %i not implemented" %
+                                                            col['typecode'])
+
+    structure = np.rec.recarray((nrows, ), dtype=dtype)
+
+    for i in range(nrows):
+        for col in columns:
+            dtype = col['typecode']
+            if col['structure']:
+                structure[col['name']][i] = _read_structure(f,
+                                      struct_desc['arrtable'][col['name']],
+                                      struct_desc['structtable'][col['name']])
+            elif col['array']:
+                structure[col['name']][i] = _read_array(f, dtype,
+                                      struct_desc['arrtable'][col['name']])
+            else:
+                structure[col['name']][i] = _read_data(f, dtype)
+
+    # Reshape structure if needed
+    if array_desc['ndims'] > 1:
+        dims = array_desc['dims'][:int(array_desc['ndims'])]
+        dims.reverse()
+        structure = structure.reshape(dims)
+
+    return structure
+
+
+def _read_array(f, typecode, array_desc):
+    '''
+    Read an array of type `typecode`, with the array descriptor given as
+    `array_desc`.
+    '''
+
+    if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]:
+
+        if typecode == 1:
+            nbytes = _read_int32(f)
+            if nbytes != array_desc['nbytes']:
+                warnings.warn("Not able to verify number of bytes from header",
+                              stacklevel=3)
+
+        # Read bytes as numpy array
+        array = np.frombuffer(f.read(array_desc['nbytes']),
+                              dtype=DTYPE_DICT[typecode])
+
+    elif typecode in [2, 12]:
+
+        # These are 2 byte types, need to skip every two as they are not packed
+
+        array = np.frombuffer(f.read(array_desc['nbytes']*2),
+                              dtype=DTYPE_DICT[typecode])[1::2]
+
+    else:
+
+        # Read bytes into list
+        array = []
+        for i in range(array_desc['nelements']):
+            dtype = typecode
+            data = _read_data(f, dtype)
+            array.append(data)
+
+        array = np.array(array, dtype=np.object_)
+
+    # Reshape array if needed
+    if array_desc['ndims'] > 1:
+        dims = array_desc['dims'][:int(array_desc['ndims'])]
+        dims.reverse()
+        array = array.reshape(dims)
+
+    # Go to next alignment position
+    _align_32(f)
+
+    return array
+
+
+def _read_record(f):
+    '''Function to read in a full record'''
+
+    record = {'rectype': _read_long(f)}
+
+    nextrec = _read_uint32(f)
+    nextrec += _read_uint32(f).astype(np.int64) * 2**32
+
+    _skip_bytes(f, 4)
+
+    if record['rectype'] not in RECTYPE_DICT:
+        raise Exception("Unknown RECTYPE: %i" % record['rectype'])
+
+    record['rectype'] = RECTYPE_DICT[record['rectype']]
+
+    if record['rectype'] in ["VARIABLE", "HEAP_DATA"]:
+
+        if record['rectype'] == "VARIABLE":
+            record['varname'] = _read_string(f)
+        else:
+            record['heap_index'] = _read_long(f)
+            _skip_bytes(f, 4)
+
+        rectypedesc = _read_typedesc(f)
+
+        if rectypedesc['typecode'] == 0:
+
+            if nextrec == f.tell():
+                record['data'] = None  # Indicates NULL value
+            else:
+                raise ValueError("Unexpected type code: 0")
+
+        else:
+
+            varstart = _read_long(f)
+            if varstart != 7:
+                raise Exception("VARSTART is not 7")
+
+            if rectypedesc['structure']:
+                record['data'] = _read_structure(f, rectypedesc['array_desc'],
+                                                    rectypedesc['struct_desc'])
+            elif rectypedesc['array']:
+                record['data'] = _read_array(f, rectypedesc['typecode'],
+                                                rectypedesc['array_desc'])
+            else:
+                dtype = rectypedesc['typecode']
+                record['data'] = _read_data(f, dtype)
+
+    elif record['rectype'] == "TIMESTAMP":
+
+        _skip_bytes(f, 4*256)
+        record['date'] = _read_string(f)
+        record['user'] = _read_string(f)
+        record['host'] = _read_string(f)
+
+    elif record['rectype'] == "VERSION":
+
+        record['format'] = _read_long(f)
+        record['arch'] = _read_string(f)
+        record['os'] = _read_string(f)
+        record['release'] = _read_string(f)
+
+    elif record['rectype'] == "IDENTIFICATON":
+
+        record['author'] = _read_string(f)
+        record['title'] = _read_string(f)
+        record['idcode'] = _read_string(f)
+
+    elif record['rectype'] == "NOTICE":
+
+        record['notice'] = _read_string(f)
+
+    elif record['rectype'] == "DESCRIPTION":
+
+        record['description'] = _read_string_data(f)
+
+    elif record['rectype'] == "HEAP_HEADER":
+
+        record['nvalues'] = _read_long(f)
+        record['indices'] = [_read_long(f) for _ in range(record['nvalues'])]
+
+    elif record['rectype'] == "COMMONBLOCK":
+
+        record['nvars'] = _read_long(f)
+        record['name'] = _read_string(f)
+        record['varnames'] = [_read_string(f) for _ in range(record['nvars'])]
+
+    elif record['rectype'] == "END_MARKER":
+
+        record['end'] = True
+
+    elif record['rectype'] == "UNKNOWN":
+
+        warnings.warn("Skipping UNKNOWN record", stacklevel=3)
+
+    elif record['rectype'] == "SYSTEM_VARIABLE":
+
+        warnings.warn("Skipping SYSTEM_VARIABLE record", stacklevel=3)
+
+    else:
+
+        raise Exception(f"record['rectype']={record['rectype']} not implemented")
+
+    f.seek(nextrec)
+
+    return record
+
+
+def _read_typedesc(f):
+    '''Function to read in a type descriptor'''
+
+    typedesc = {'typecode': _read_long(f), 'varflags': _read_long(f)}
+
+    if typedesc['varflags'] & 2 == 2:
+        raise Exception("System variables not implemented")
+
+    typedesc['array'] = typedesc['varflags'] & 4 == 4
+    typedesc['structure'] = typedesc['varflags'] & 32 == 32
+
+    if typedesc['structure']:
+        typedesc['array_desc'] = _read_arraydesc(f)
+        typedesc['struct_desc'] = _read_structdesc(f)
+    elif typedesc['array']:
+        typedesc['array_desc'] = _read_arraydesc(f)
+
+    return typedesc
+
+
+def _read_arraydesc(f):
+    '''Function to read in an array descriptor'''
+
+    arraydesc = {'arrstart': _read_long(f)}
+
+    if arraydesc['arrstart'] == 8:
+
+        _skip_bytes(f, 4)
+
+        arraydesc['nbytes'] = _read_long(f)
+        arraydesc['nelements'] = _read_long(f)
+        arraydesc['ndims'] = _read_long(f)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nmax'] = _read_long(f)
+
+        arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])]
+
+    elif arraydesc['arrstart'] == 18:
+
+        warnings.warn("Using experimental 64-bit array read", stacklevel=3)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nbytes'] = _read_uint64(f)
+        arraydesc['nelements'] = _read_uint64(f)
+        arraydesc['ndims'] = _read_long(f)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nmax'] = 8
+
+        arraydesc['dims'] = []
+        for d in range(arraydesc['nmax']):
+            v = _read_long(f)
+            if v != 0:
+                raise Exception("Expected a zero in ARRAY_DESC")
+            arraydesc['dims'].append(_read_long(f))
+
+    else:
+
+        raise Exception("Unknown ARRSTART: %i" % arraydesc['arrstart'])
+
+    return arraydesc
+
+
+def _read_structdesc(f):
+    '''Function to read in a structure descriptor'''
+
+    structdesc = {}
+
+    structstart = _read_long(f)
+    if structstart != 9:
+        raise Exception("STRUCTSTART should be 9")
+
+    structdesc['name'] = _read_string(f)
+    predef = _read_long(f)
+    structdesc['ntags'] = _read_long(f)
+    structdesc['nbytes'] = _read_long(f)
+
+    structdesc['predef'] = predef & 1
+    structdesc['inherits'] = predef & 2
+    structdesc['is_super'] = predef & 4
+
+    if not structdesc['predef']:
+
+        structdesc['tagtable'] = [_read_tagdesc(f)
+                                  for _ in range(structdesc['ntags'])]
+
+        for tag in structdesc['tagtable']:
+            tag['name'] = _read_string(f)
+
+        structdesc['arrtable'] = {tag['name']: _read_arraydesc(f)
+                                  for tag in structdesc['tagtable']
+                                  if tag['array']}
+
+        structdesc['structtable'] = {tag['name']: _read_structdesc(f)
+                                     for tag in structdesc['tagtable']
+                                     if tag['structure']}
+
+        if structdesc['inherits'] or structdesc['is_super']:
+            structdesc['classname'] = _read_string(f)
+            structdesc['nsupclasses'] = _read_long(f)
+            structdesc['supclassnames'] = [
+                _read_string(f) for _ in range(structdesc['nsupclasses'])]
+            structdesc['supclasstable'] = [
+                _read_structdesc(f) for _ in range(structdesc['nsupclasses'])]
+
+        STRUCT_DICT[structdesc['name']] = structdesc
+
+    else:
+
+        if structdesc['name'] not in STRUCT_DICT:
+            raise Exception("PREDEF=1 but can't find definition")
+
+        structdesc = STRUCT_DICT[structdesc['name']]
+
+    return structdesc
+
+
+def _read_tagdesc(f):
+    '''Function to read in a tag descriptor'''
+
+    tagdesc = {'offset': _read_long(f)}
+
+    if tagdesc['offset'] == -1:
+        tagdesc['offset'] = _read_uint64(f)
+
+    tagdesc['typecode'] = _read_long(f)
+    tagflags = _read_long(f)
+
+    tagdesc['array'] = tagflags & 4 == 4
+    tagdesc['structure'] = tagflags & 32 == 32
+    tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
+    # Assume '10'x is scalar
+
+    return tagdesc
+
+
+def _replace_heap(variable, heap):
+
+    if isinstance(variable, Pointer):
+
+        while isinstance(variable, Pointer):
+
+            if variable.index == 0:
+                variable = None
+            else:
+                if variable.index in heap:
+                    variable = heap[variable.index]
+                else:
+                    warnings.warn("Variable referenced by pointer not found "
+                                  "in heap: variable will be set to None",
+                                  stacklevel=3)
+                    variable = None
+
+        replace, new = _replace_heap(variable, heap)
+
+        if replace:
+            variable = new
+
+        return True, variable
+
+    elif isinstance(variable, np.rec.recarray):
+
+        # Loop over records
+        for ir, record in enumerate(variable):
+
+            replace, new = _replace_heap(record, heap)
+
+            if replace:
+                variable[ir] = new
+
+        return False, variable
+
+    elif isinstance(variable, np.record):
+
+        # Loop over values
+        for iv, value in enumerate(variable):
+
+            replace, new = _replace_heap(value, heap)
+
+            if replace:
+                variable[iv] = new
+
+        return False, variable
+
+    elif isinstance(variable, np.ndarray):
+
+        # Loop over values if type is np.object_
+        if variable.dtype.type is np.object_:
+
+            for iv in range(variable.size):
+
+                replace, new = _replace_heap(variable.item(iv), heap)
+
+                if replace:
+                    variable.reshape(-1)[iv] = new
+
+        return False, variable
+
+    else:
+
+        return False, variable
+
+
+class AttrDict(dict):
+    '''
+    A case-insensitive dictionary with access via item, attribute, and call
+    notations:
+
+        >>> from scipy.io._idl import AttrDict
+        >>> d = AttrDict()
+        >>> d['Variable'] = 123
+        >>> d['Variable']
+        123
+        >>> d.Variable
+        123
+        >>> d.variable
+        123
+        >>> d('VARIABLE')
+        123
+        >>> d['missing']
+        Traceback (most recent error last):
+        ...
+        KeyError: 'missing'
+        >>> d.missing
+        Traceback (most recent error last):
+        ...
+        AttributeError: 'AttrDict' object has no attribute 'missing'
+    '''
+
+    def __init__(self, init=None):
+        if init is None:
+            init = {}
+        dict.__init__(self, init)
+
+    def __getitem__(self, name):
+        return super().__getitem__(name.lower())
+
+    def __setitem__(self, key, value):
+        return super().__setitem__(key.lower(), value)
+
+    def __getattr__(self, name):
+        try:
+            return self.__getitem__(name)
+        except KeyError:
+            raise AttributeError(
+                f"'{type(self)}' object has no attribute '{name}'") from None
+
+    __setattr__ = __setitem__
+    __call__ = __getitem__
+
+
+def readsav(file_name, idict=None, python_dict=False,
+            uncompressed_file_name=None, verbose=False):
+    """
+    Read an IDL .sav file.
+
+    Parameters
+    ----------
+    file_name : str
+        Name of the IDL save file.
+    idict : dict, optional
+        Dictionary in which to insert .sav file variables.
+    python_dict : bool, optional
+        By default, the object return is not a Python dictionary, but a
+        case-insensitive dictionary with item, attribute, and call access
+        to variables. To get a standard Python dictionary, set this option
+        to True.
+    uncompressed_file_name : str, optional
+        This option only has an effect for .sav files written with the
+        /compress option. If a file name is specified, compressed .sav
+        files are uncompressed to this file. Otherwise, readsav will use
+        the `tempfile` module to determine a temporary filename
+        automatically, and will remove the temporary file upon successfully
+        reading it in.
+    verbose : bool, optional
+        Whether to print out information about the save file, including
+        the records read, and available variables.
+
+    Returns
+    -------
+    idl_dict : AttrDict or dict
+        If `python_dict` is set to False (default), this function returns a
+        case-insensitive dictionary with item, attribute, and call access
+        to variables. If `python_dict` is set to True, this function
+        returns a Python dictionary with all variable names in lowercase.
+        If `idict` was specified, then variables are written to the
+        dictionary specified, and the updated dictionary is returned.
+
+    Examples
+    --------
+    >>> from os.path import dirname, join as pjoin
+    >>> import scipy.io as sio
+    >>> from scipy.io import readsav
+
+    Get the filename for an example .sav file from the tests/data directory.
+
+    >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
+    >>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav')
+
+    Load the .sav file contents.
+
+    >>> sav_data = readsav(sav_fname)
+
+    Get keys of the .sav file contents.
+
+    >>> print(sav_data.keys())
+    dict_keys(['array1d'])
+
+    Access a content with a key.
+
+    >>> print(sav_data['array1d'])
+    [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0.]
+
+    """
+
+    # Initialize record and variable holders
+    records = []
+    if python_dict or idict:
+        variables = {}
+    else:
+        variables = AttrDict()
+
+    # Open the IDL file
+    f = open(file_name, 'rb')
+
+    # Read the signature, which should be 'SR'
+    signature = _read_bytes(f, 2)
+    if signature != b'SR':
+        raise Exception(f"Invalid SIGNATURE: {signature}")
+
+    # Next, the record format, which is '\x00\x04' for normal .sav
+    # files, and '\x00\x06' for compressed .sav files.
+    recfmt = _read_bytes(f, 2)
+
+    if recfmt == b'\x00\x04':
+        pass
+
+    elif recfmt == b'\x00\x06':
+
+        if verbose:
+            print("IDL Save file is compressed")
+
+        if uncompressed_file_name:
+            fout = open(uncompressed_file_name, 'w+b')
+        else:
+            fout = tempfile.NamedTemporaryFile(suffix='.sav')
+
+        if verbose:
+            print(f" -> expanding to {fout.name}")
+
+        # Write header
+        fout.write(b'SR\x00\x04')
+
+        # Cycle through records
+        while True:
+
+            # Read record type
+            rectype = _read_long(f)
+            fout.write(struct.pack('>l', int(rectype)))
+
+            # Read position of next record and return as int
+            nextrec = _read_uint32(f)
+            nextrec += _read_uint32(f).astype(np.int64) * 2**32
+
+            # Read the unknown 4 bytes
+            unknown = f.read(4)
+
+            # Check if the end of the file has been reached
+            if RECTYPE_DICT[rectype] == 'END_MARKER':
+                modval = np.int64(2**32)
+                fout.write(struct.pack('>I', int(nextrec) % modval))
+                fout.write(
+                    struct.pack('>I', int((nextrec - (nextrec % modval)) / modval))
+                )
+                fout.write(unknown)
+                break
+
+            # Find current position
+            pos = f.tell()
+
+            # Decompress record
+            rec_string = zlib.decompress(f.read(nextrec-pos))
+
+            # Find new position of next record
+            nextrec = fout.tell() + len(rec_string) + 12
+
+            # Write out record
+            fout.write(struct.pack('>I', int(nextrec % 2**32)))
+            fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
+            fout.write(unknown)
+            fout.write(rec_string)
+
+        # Close the original compressed file
+        f.close()
+
+        # Set f to be the decompressed file, and skip the first four bytes
+        f = fout
+        f.seek(4)
+
+    else:
+        raise Exception(f"Invalid RECFMT: {recfmt}")
+
+    # Loop through records, and add them to the list
+    while True:
+        r = _read_record(f)
+        records.append(r)
+        if 'end' in r:
+            if r['end']:
+                break
+
+    # Close the file
+    f.close()
+
+    # Find heap data variables
+    heap = {}
+    for r in records:
+        if r['rectype'] == "HEAP_DATA":
+            heap[r['heap_index']] = r['data']
+
+    # Find all variables
+    for r in records:
+        if r['rectype'] == "VARIABLE":
+            replace, new = _replace_heap(r['data'], heap)
+            if replace:
+                r['data'] = new
+            variables[r['varname'].lower()] = r['data']
+
+    if verbose:
+
+        # Print out timestamp info about the file
+        for record in records:
+            if record['rectype'] == "TIMESTAMP":
+                print("-"*50)
+                print(f"Date: {record['date']}")
+                print(f"User: {record['user']}")
+                print(f"Host: {record['host']}")
+                break
+
+        # Print out version info about the file
+        for record in records:
+            if record['rectype'] == "VERSION":
+                print("-"*50)
+                print(f"Format: {record['format']}")
+                print(f"Architecture: {record['arch']}")
+                print(f"Operating System: {record['os']}")
+                print(f"IDL Version: {record['release']}")
+                break
+
+        # Print out identification info about the file
+        for record in records:
+            if record['rectype'] == "IDENTIFICATON":
+                print("-"*50)
+                print(f"Author: {record['author']}")
+                print(f"Title: {record['title']}")
+                print(f"ID Code: {record['idcode']}")
+                break
+
+        # Print out descriptions saved with the file
+        for record in records:
+            if record['rectype'] == "DESCRIPTION":
+                print("-"*50)
+                print(f"Description: {record['description']}")
+                break
+
+        print("-"*50)
+        print(f"Successfully read {len(records)} records of which:")
+
+        # Create convenience list of record types
+        rectypes = [r['rectype'] for r in records]
+
+        for rt in set(rectypes):
+            if rt != 'END_MARKER':
+                print(" - %i are of type %s" % (rectypes.count(rt), rt))
+        print("-"*50)
+
+        if 'VARIABLE' in rectypes:
+            print("Available variables:")
+            for var in variables:
+                print(f" - {var} [{type(variables[var])}]")
+            print("-"*50)
+
+    if idict:
+        for var in variables:
+            idict[var] = variables[var]
+        return idict
+    else:
+        return variables
diff --git a/python_embeded/Lib/site-packages/scipy/io/_mmio.py b/python_embeded/Lib/site-packages/scipy/io/_mmio.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d45831076909e527aafd4e7a219f94466a9910a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/_mmio.py
@@ -0,0 +1,968 @@
+"""
+  Matrix Market I/O in Python.
+  See http://math.nist.gov/MatrixMarket/formats.html
+  for information about the Matrix Market format.
+"""
+#
+# Author: Pearu Peterson 
+# Created: October, 2004
+#
+# References:
+#  http://math.nist.gov/MatrixMarket/
+#
+import os
+
+import numpy as np
+from numpy import (asarray, real, imag, conj, zeros, ndarray, concatenate,
+                   ones, can_cast)
+
+from scipy.sparse import coo_array, issparse, coo_matrix
+
+__all__ = ['mminfo', 'mmread', 'mmwrite', 'MMFile']
+
+
+# -----------------------------------------------------------------------------
+def asstr(s):
+    if isinstance(s, bytes):
+        return s.decode('latin1')
+    return str(s)
+
+
+def mminfo(source):
+    """
+    Return size and storage parameters from Matrix Market file-like 'source'.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object
+
+    Returns
+    -------
+    rows : int
+        Number of matrix rows.
+    cols : int
+        Number of matrix columns.
+    entries : int
+        Number of non-zero entries of a sparse matrix
+        or rows*cols for a dense matrix.
+    format : str
+        Either 'coordinate' or 'array'.
+    field : str
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    symmetry : str
+        Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mminfo
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+
+    ``mminfo(source)`` returns the number of rows, number of columns,
+    format, field type and symmetry attribute of the source file.
+
+    >>> mminfo(StringIO(text))
+    (5, 5, 7, 'coordinate', 'real', 'general')
+    """
+    return MMFile.info(source)
+
+# -----------------------------------------------------------------------------
+
+
+def mmread(source, *, spmatrix=True):
+    """
+    Reads the contents of a Matrix Market file-like 'source' into a matrix.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extensions .mtx, .mtz.gz)
+        or open file-like object.
+    spmatrix : bool, optional (default: True)
+        If ``True``, return sparse ``coo_matrix``. Otherwise return ``coo_array``.
+
+    Returns
+    -------
+    a : ndarray or coo_array or coo_matrix
+        Dense or sparse array depending on the matrix format in the
+        Matrix Market file.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mmread
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+    ``mmread(source)`` returns the data as sparse matrix in COO format.
+
+    >>> m = mmread(StringIO(text), spmatrix=False)
+    >>> m
+    
+    >>> m.toarray()
+    array([[0., 0., 0., 0., 0.],
+           [0., 0., 1., 0., 0.],
+           [0., 0., 0., 2., 3.],
+           [4., 5., 6., 7., 0.],
+           [0., 0., 0., 0., 0.]])
+    """
+    return MMFile().read(source, spmatrix=spmatrix)
+
+# -----------------------------------------------------------------------------
+
+
+def mmwrite(target, a, comment='', field=None, precision=None, symmetry=None):
+    r"""
+    Writes the sparse or dense array `a` to Matrix Market file-like `target`.
+
+    Parameters
+    ----------
+    target : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object.
+    a : array like
+        Sparse or dense 2-D array.
+    comment : str, optional
+        Comments to be prepended to the Matrix Market file.
+    field : None or str, optional
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    precision : None or int, optional
+        Number of digits to display for real or complex values.
+    symmetry : None or str, optional
+        Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+        If symmetry is None the symmetry type of 'a' is determined by its
+        values.
+
+    Returns
+    -------
+    None
+
+    Examples
+    --------
+    >>> from io import BytesIO
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_array
+    >>> from scipy.io import mmwrite
+
+    Write a small NumPy array to a matrix market file.  The file will be
+    written in the ``'array'`` format.
+
+    >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
+    >>> target = BytesIO()
+    >>> mmwrite(target, a)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    2 4
+    1
+    0
+    0
+    2.5
+    0
+    0
+    0
+    6.25
+
+    Add a comment to the output file, and set the precision to 3.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    % Some test data.
+    %
+    2 4
+    1.00e+00
+    0.00e+00
+    0.00e+00
+    2.50e+00
+    0.00e+00
+    0.00e+00
+    0.00e+00
+    6.25e+00
+
+    Convert to a sparse matrix before calling ``mmwrite``.  This will
+    result in the output format being ``'coordinate'`` rather than
+    ``'array'``.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, coo_array(a), precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix coordinate real general
+    %
+    2 4 3
+    1 1 1.00e+00
+    2 2 2.50e+00
+    2 4 6.25e+00
+
+    Write a complex Hermitian array to a matrix market file.  Note that
+    only six values are actually written to the file; the other values
+    are implied by the symmetry.
+
+    >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
+    >>> z
+    array([[ 3. +0.j,  1. +2.j,  4. -3.j],
+           [ 1. -2.j,  1. +0.j, -0. -5.j],
+           [ 4. +3.j,  0. +5.j,  2.5+0.j]])
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, z, precision=2)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array complex hermitian
+    %
+    3 3
+    3.0e+00 0.0e+00
+    1.0e+00 -2.0e+00
+    4.0e+00 3.0e+00
+    1.0e+00 0.0e+00
+    0.0e+00 5.0e+00
+    2.5e+00 0.0e+00
+
+    """
+    MMFile().write(target, a, comment, field, precision, symmetry)
+
+
+###############################################################################
+class MMFile:
+    __slots__ = ('_rows',
+                 '_cols',
+                 '_entries',
+                 '_format',
+                 '_field',
+                 '_symmetry')
+
+    @property
+    def rows(self):
+        return self._rows
+
+    @property
+    def cols(self):
+        return self._cols
+
+    @property
+    def entries(self):
+        return self._entries
+
+    @property
+    def format(self):
+        return self._format
+
+    @property
+    def field(self):
+        return self._field
+
+    @property
+    def symmetry(self):
+        return self._symmetry
+
+    @property
+    def has_symmetry(self):
+        return self._symmetry in (self.SYMMETRY_SYMMETRIC,
+                                  self.SYMMETRY_SKEW_SYMMETRIC,
+                                  self.SYMMETRY_HERMITIAN)
+
+    # format values
+    FORMAT_COORDINATE = 'coordinate'
+    FORMAT_ARRAY = 'array'
+    FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY)
+
+    @classmethod
+    def _validate_format(self, format):
+        if format not in self.FORMAT_VALUES:
+            msg = f'unknown format type {format}, must be one of {self.FORMAT_VALUES}'
+            raise ValueError(msg)
+
+    # field values
+    FIELD_INTEGER = 'integer'
+    FIELD_UNSIGNED = 'unsigned-integer'
+    FIELD_REAL = 'real'
+    FIELD_COMPLEX = 'complex'
+    FIELD_PATTERN = 'pattern'
+    FIELD_VALUES = (FIELD_INTEGER, FIELD_UNSIGNED, FIELD_REAL, FIELD_COMPLEX,
+                    FIELD_PATTERN)
+
+    @classmethod
+    def _validate_field(self, field):
+        if field not in self.FIELD_VALUES:
+            msg = f'unknown field type {field}, must be one of {self.FIELD_VALUES}'
+            raise ValueError(msg)
+
+    # symmetry values
+    SYMMETRY_GENERAL = 'general'
+    SYMMETRY_SYMMETRIC = 'symmetric'
+    SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric'
+    SYMMETRY_HERMITIAN = 'hermitian'
+    SYMMETRY_VALUES = (SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC,
+                       SYMMETRY_SKEW_SYMMETRIC, SYMMETRY_HERMITIAN)
+
+    @classmethod
+    def _validate_symmetry(self, symmetry):
+        if symmetry not in self.SYMMETRY_VALUES:
+            raise ValueError(f'unknown symmetry type {symmetry}, '
+                             f'must be one of {self.SYMMETRY_VALUES}')
+
+    DTYPES_BY_FIELD = {FIELD_INTEGER: 'intp',
+                       FIELD_UNSIGNED: 'uint64',
+                       FIELD_REAL: 'd',
+                       FIELD_COMPLEX: 'D',
+                       FIELD_PATTERN: 'd'}
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def reader():
+        pass
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def writer():
+        pass
+
+    # -------------------------------------------------------------------------
+    @classmethod
+    def info(self, source):
+        """
+        Return size, storage parameters from Matrix Market file-like 'source'.
+
+        Parameters
+        ----------
+        source : str or file-like
+            Matrix Market filename (extension .mtx) or open file-like object
+
+        Returns
+        -------
+        rows : int
+            Number of matrix rows.
+        cols : int
+            Number of matrix columns.
+        entries : int
+            Number of non-zero entries of a sparse matrix
+            or rows*cols for a dense matrix.
+        format : str
+            Either 'coordinate' or 'array'.
+        field : str
+            Either 'real', 'complex', 'pattern', or 'integer'.
+        symmetry : str
+            Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+        """
+
+        stream, close_it = self._open(source)
+
+        try:
+
+            # read and validate header line
+            line = stream.readline()
+            mmid, matrix, format, field, symmetry = \
+                (asstr(part.strip()) for part in line.split())
+            if not mmid.startswith('%%MatrixMarket'):
+                raise ValueError('source is not in Matrix Market format')
+            if not matrix.lower() == 'matrix':
+                raise ValueError("Problem reading file header: " + line)
+
+            # http://math.nist.gov/MatrixMarket/formats.html
+            if format.lower() == 'array':
+                format = self.FORMAT_ARRAY
+            elif format.lower() == 'coordinate':
+                format = self.FORMAT_COORDINATE
+
+            # skip comments
+            # line.startswith('%')
+            while line:
+                if line.lstrip() and line.lstrip()[0] in ['%', 37]:
+                    line = stream.readline()
+                else:
+                    break
+
+            # skip empty lines
+            while not line.strip():
+                line = stream.readline()
+
+            split_line = line.split()
+            if format == self.FORMAT_ARRAY:
+                if not len(split_line) == 2:
+                    raise ValueError("Header line not of length 2: " +
+                                     line.decode('ascii'))
+                rows, cols = map(int, split_line)
+                entries = rows * cols
+            else:
+                if not len(split_line) == 3:
+                    raise ValueError("Header line not of length 3: " +
+                                     line.decode('ascii'))
+                rows, cols, entries = map(int, split_line)
+
+            return (rows, cols, entries, format, field.lower(),
+                    symmetry.lower())
+
+        finally:
+            if close_it:
+                stream.close()
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _open(filespec, mode='rb'):
+        """ Return an open file stream for reading based on source.
+
+        If source is a file name, open it (after trying to find it with mtx and
+        gzipped mtx extensions). Otherwise, just return source.
+
+        Parameters
+        ----------
+        filespec : str or file-like
+            String giving file name or file-like object
+        mode : str, optional
+            Mode with which to open file, if `filespec` is a file name.
+
+        Returns
+        -------
+        fobj : file-like
+            Open file-like object.
+        close_it : bool
+            True if the calling function should close this file when done,
+            false otherwise.
+        """
+        # If 'filespec' is path-like (str, pathlib.Path, os.DirEntry, other class
+        # implementing a '__fspath__' method), try to convert it to str. If this
+        # fails by throwing a 'TypeError', assume it's an open file handle and
+        # return it as-is.
+        try:
+            filespec = os.fspath(filespec)
+        except TypeError:
+            return filespec, False
+
+        # 'filespec' is definitely a str now
+
+        # open for reading
+        if mode[0] == 'r':
+
+            # determine filename plus extension
+            if not os.path.isfile(filespec):
+                if os.path.isfile(filespec+'.mtx'):
+                    filespec = filespec + '.mtx'
+                elif os.path.isfile(filespec+'.mtx.gz'):
+                    filespec = filespec + '.mtx.gz'
+                elif os.path.isfile(filespec+'.mtx.bz2'):
+                    filespec = filespec + '.mtx.bz2'
+            # open filename
+            if filespec.endswith('.gz'):
+                import gzip
+                stream = gzip.open(filespec, mode)
+            elif filespec.endswith('.bz2'):
+                import bz2
+                stream = bz2.BZ2File(filespec, 'rb')
+            else:
+                stream = open(filespec, mode)
+
+        # open for writing
+        else:
+            if filespec[-4:] != '.mtx':
+                filespec = filespec + '.mtx'
+            stream = open(filespec, mode)
+
+        return stream, True
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _get_symmetry(a):
+        m, n = a.shape
+        if m != n:
+            return MMFile.SYMMETRY_GENERAL
+        issymm = True
+        isskew = True
+        isherm = a.dtype.char in 'FD'
+
+        # sparse input
+        if issparse(a):
+            # check if number of nonzero entries of lower and upper triangle
+            # matrix are equal
+            a = a.tocoo()
+            (row, col) = a.nonzero()
+            if (row < col).sum() != (row > col).sum():
+                return MMFile.SYMMETRY_GENERAL
+
+            # define iterator over symmetric pair entries
+            a = a.todok()
+
+            def symm_iterator():
+                for ((i, j), aij) in a.items():
+                    if i > j:
+                        aji = a[j, i]
+                        yield (aij, aji, False)
+                    elif i == j:
+                        yield (aij, aij, True)
+
+        # non-sparse input
+        else:
+            # define iterator over symmetric pair entries
+            def symm_iterator():
+                for j in range(n):
+                    for i in range(j, n):
+                        aij, aji = a[i][j], a[j][i]
+                        yield (aij, aji, i == j)
+
+        # check for symmetry
+        # yields aij, aji, is_diagonal
+        for (aij, aji, is_diagonal) in symm_iterator():
+            if isskew and is_diagonal and aij != 0:
+                isskew = False
+            else:
+                if issymm and aij != aji:
+                    issymm = False
+                with np.errstate(over="ignore"):
+                    # This can give a warning for uint dtypes, so silence that
+                    if isskew and aij != -aji:
+                        isskew = False
+                if isherm and aij != conj(aji):
+                    isherm = False
+            if not (issymm or isskew or isherm):
+                break
+
+        # return symmetry value
+        if issymm:
+            return MMFile.SYMMETRY_SYMMETRIC
+        if isskew:
+            return MMFile.SYMMETRY_SKEW_SYMMETRIC
+        if isherm:
+            return MMFile.SYMMETRY_HERMITIAN
+        return MMFile.SYMMETRY_GENERAL
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _field_template(field, precision):
+        return {MMFile.FIELD_REAL: '%%.%ie\n' % precision,
+                MMFile.FIELD_INTEGER: '%i\n',
+                MMFile.FIELD_UNSIGNED: '%u\n',
+                MMFile.FIELD_COMPLEX: '%%.%ie %%.%ie\n' %
+                    (precision, precision)
+                }.get(field, None)
+
+    # -------------------------------------------------------------------------
+    def __init__(self, **kwargs):
+        self._init_attrs(**kwargs)
+
+    # -------------------------------------------------------------------------
+    def read(self, source, *, spmatrix=True):
+        """
+        Reads the contents of a Matrix Market file-like 'source' into a matrix.
+
+        Parameters
+        ----------
+        source : str or file-like
+            Matrix Market filename (extensions .mtx, .mtz.gz)
+            or open file object.
+        spmatrix : bool, optional (default: True)
+            If ``True``, return sparse ``coo_matrix``. Otherwise return ``coo_array``.
+
+        Returns
+        -------
+        a : ndarray or coo_array or coo_matrix
+            Dense or sparse array depending on the matrix format in the
+            Matrix Market file.
+        """
+        stream, close_it = self._open(source)
+
+        try:
+            self._parse_header(stream)
+            data = self._parse_body(stream)
+
+        finally:
+            if close_it:
+                stream.close()
+        if spmatrix and isinstance(data, coo_array):
+            data = coo_matrix(data)
+        return data
+
+
+    # -------------------------------------------------------------------------
+    def write(self, target, a, comment='', field=None, precision=None,
+              symmetry=None):
+        """
+        Writes sparse or dense array `a` to Matrix Market file-like `target`.
+
+        Parameters
+        ----------
+        target : str or file-like
+            Matrix Market filename (extension .mtx) or open file-like object.
+        a : array like
+            Sparse or dense 2-D array.
+        comment : str, optional
+            Comments to be prepended to the Matrix Market file.
+        field : None or str, optional
+            Either 'real', 'complex', 'pattern', or 'integer'.
+        precision : None or int, optional
+            Number of digits to display for real or complex values.
+        symmetry : None or str, optional
+            Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+            If symmetry is None the symmetry type of 'a' is determined by its
+            values.
+        """
+
+        stream, close_it = self._open(target, 'wb')
+
+        try:
+            self._write(stream, a, comment, field, precision, symmetry)
+
+        finally:
+            if close_it:
+                stream.close()
+            else:
+                stream.flush()
+
+    # -------------------------------------------------------------------------
+    def _init_attrs(self, **kwargs):
+        """
+        Initialize each attributes with the corresponding keyword arg value
+        or a default of None
+        """
+
+        attrs = self.__class__.__slots__
+        public_attrs = [attr[1:] for attr in attrs]
+        invalid_keys = set(kwargs.keys()) - set(public_attrs)
+
+        if invalid_keys:
+            raise ValueError(f"found {tuple(invalid_keys)} invalid keyword "
+                             f"arguments, please only use {public_attrs}")
+
+        for attr in attrs:
+            setattr(self, attr, kwargs.get(attr[1:], None))
+
+    # -------------------------------------------------------------------------
+    def _parse_header(self, stream):
+        rows, cols, entries, format, field, symmetry = \
+            self.__class__.info(stream)
+        self._init_attrs(rows=rows, cols=cols, entries=entries, format=format,
+                         field=field, symmetry=symmetry)
+
+    # -------------------------------------------------------------------------
+    def _parse_body(self, stream):
+        rows, cols, entries, format, field, symm = (self.rows, self.cols,
+                                                    self.entries, self.format,
+                                                    self.field, self.symmetry)
+
+        dtype = self.DTYPES_BY_FIELD.get(field, None)
+
+        has_symmetry = self.has_symmetry
+        is_integer = field == self.FIELD_INTEGER
+        is_unsigned_integer = field == self.FIELD_UNSIGNED
+        is_complex = field == self.FIELD_COMPLEX
+        is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC
+        is_herm = symm == self.SYMMETRY_HERMITIAN
+        is_pattern = field == self.FIELD_PATTERN
+
+        if format == self.FORMAT_ARRAY:
+            a = zeros((rows, cols), dtype=dtype)
+            line = 1
+            i, j = 0, 0
+            if is_skew:
+                a[i, j] = 0
+                if i < rows - 1:
+                    i += 1
+            while line:
+                line = stream.readline()
+                # line.startswith('%')
+                if not line or line[0] in ['%', 37] or not line.strip():
+                    continue
+                if is_integer:
+                    aij = int(line)
+                elif is_unsigned_integer:
+                    aij = int(line)
+                elif is_complex:
+                    aij = complex(*map(float, line.split()))
+                else:
+                    aij = float(line)
+                a[i, j] = aij
+                if has_symmetry and i != j:
+                    if is_skew:
+                        a[j, i] = -aij
+                    elif is_herm:
+                        a[j, i] = conj(aij)
+                    else:
+                        a[j, i] = aij
+                if i < rows-1:
+                    i = i + 1
+                else:
+                    j = j + 1
+                    if not has_symmetry:
+                        i = 0
+                    else:
+                        i = j
+                        if is_skew:
+                            a[i, j] = 0
+                            if i < rows-1:
+                                i += 1
+
+            if is_skew:
+                if not (i in [0, j] and j == cols - 1):
+                    raise ValueError("Parse error, did not read all lines.")
+            else:
+                if not (i in [0, j] and j == cols):
+                    raise ValueError("Parse error, did not read all lines.")
+
+        elif format == self.FORMAT_COORDINATE:
+            # Read sparse COOrdinate format
+
+            if entries == 0:
+                # empty matrix
+                return coo_array((rows, cols), dtype=dtype)
+
+            I = zeros(entries, dtype='intc')
+            J = zeros(entries, dtype='intc')
+            if is_pattern:
+                V = ones(entries, dtype='int8')
+            elif is_integer:
+                V = zeros(entries, dtype='intp')
+            elif is_unsigned_integer:
+                V = zeros(entries, dtype='uint64')
+            elif is_complex:
+                V = zeros(entries, dtype='complex')
+            else:
+                V = zeros(entries, dtype='float')
+
+            entry_number = 0
+            for line in stream:
+                # line.startswith('%')
+                if not line or line[0] in ['%', 37] or not line.strip():
+                    continue
+
+                if entry_number+1 > entries:
+                    raise ValueError("'entries' in header is smaller than "
+                                     "number of entries")
+                l = line.split()
+                I[entry_number], J[entry_number] = map(int, l[:2])
+
+                if not is_pattern:
+                    if is_integer:
+                        V[entry_number] = int(l[2])
+                    elif is_unsigned_integer:
+                        V[entry_number] = int(l[2])
+                    elif is_complex:
+                        V[entry_number] = complex(*map(float, l[2:]))
+                    else:
+                        V[entry_number] = float(l[2])
+                entry_number += 1
+            if entry_number < entries:
+                raise ValueError("'entries' in header is larger than "
+                                 "number of entries")
+
+            I -= 1  # adjust indices (base 1 -> base 0)
+            J -= 1
+
+            if has_symmetry:
+                mask = (I != J)       # off diagonal mask
+                od_I = I[mask]
+                od_J = J[mask]
+                od_V = V[mask]
+
+                I = concatenate((I, od_J))
+                J = concatenate((J, od_I))
+
+                if is_skew:
+                    od_V *= -1
+                elif is_herm:
+                    od_V = od_V.conjugate()
+
+                V = concatenate((V, od_V))
+
+            a = coo_array((V, (I, J)), shape=(rows, cols), dtype=dtype)
+        else:
+            raise NotImplementedError(format)
+
+        return a
+
+    #  ------------------------------------------------------------------------
+    def _write(self, stream, a, comment='', field=None, precision=None,
+               symmetry=None):
+        if isinstance(a, list) or isinstance(a, ndarray) or \
+           isinstance(a, tuple) or hasattr(a, '__array__'):
+            rep = self.FORMAT_ARRAY
+            a = asarray(a)
+            if len(a.shape) != 2:
+                raise ValueError('Expected 2 dimensional array')
+            rows, cols = a.shape
+
+            if field is not None:
+
+                if field == self.FIELD_INTEGER:
+                    if not can_cast(a.dtype, 'intp'):
+                        raise OverflowError("mmwrite does not support integer "
+                                            "dtypes larger than native 'intp'.")
+                    a = a.astype('intp')
+                elif field == self.FIELD_REAL:
+                    if a.dtype.char not in 'fd':
+                        a = a.astype('d')
+                elif field == self.FIELD_COMPLEX:
+                    if a.dtype.char not in 'FD':
+                        a = a.astype('D')
+
+        else:
+            if not issparse(a):
+                raise ValueError(f'unknown matrix type: {type(a)}')
+
+            rep = 'coordinate'
+            rows, cols = a.shape
+
+        typecode = a.dtype.char
+
+        if precision is None:
+            if typecode in 'fF':
+                precision = 8
+            else:
+                precision = 16
+        if field is None:
+            kind = a.dtype.kind
+            if kind == 'i':
+                if not can_cast(a.dtype, 'intp'):
+                    raise OverflowError("mmwrite does not support integer "
+                                        "dtypes larger than native 'intp'.")
+                field = 'integer'
+            elif kind == 'f':
+                field = 'real'
+            elif kind == 'c':
+                field = 'complex'
+            elif kind == 'u':
+                field = 'unsigned-integer'
+            else:
+                raise TypeError('unexpected dtype kind ' + kind)
+
+        if symmetry is None:
+            symmetry = self._get_symmetry(a)
+
+        # validate rep, field, and symmetry
+        self.__class__._validate_format(rep)
+        self.__class__._validate_field(field)
+        self.__class__._validate_symmetry(symmetry)
+
+        # write initial header line
+        data = f'%%MatrixMarket matrix {rep} {field} {symmetry}\n'
+        stream.write(data.encode('latin1'))
+
+        # write comments
+        for line in comment.split('\n'):
+            data = f'%{line}\n'
+            stream.write(data.encode('latin1'))
+
+        template = self._field_template(field, precision)
+        # write dense format
+        if rep == self.FORMAT_ARRAY:
+            # write shape spec
+            data = '%i %i\n' % (rows, cols)
+            stream.write(data.encode('latin1'))
+
+            if field in (self.FIELD_INTEGER, self.FIELD_REAL,
+                         self.FIELD_UNSIGNED):
+                if symmetry == self.SYMMETRY_GENERAL:
+                    for j in range(cols):
+                        for i in range(rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+                elif symmetry == self.SYMMETRY_SKEW_SYMMETRIC:
+                    for j in range(cols):
+                        for i in range(j + 1, rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+                else:
+                    for j in range(cols):
+                        for i in range(j, rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+            elif field == self.FIELD_COMPLEX:
+
+                if symmetry == self.SYMMETRY_GENERAL:
+                    for j in range(cols):
+                        for i in range(rows):
+                            aij = a[i, j]
+                            data = template % (real(aij), imag(aij))
+                            stream.write(data.encode('latin1'))
+                else:
+                    for j in range(cols):
+                        for i in range(j, rows):
+                            aij = a[i, j]
+                            data = template % (real(aij), imag(aij))
+                            stream.write(data.encode('latin1'))
+
+            elif field == self.FIELD_PATTERN:
+                raise ValueError('pattern type inconsisted with dense format')
+
+            else:
+                raise TypeError(f'Unknown field type {field}')
+
+        # write sparse format
+        else:
+            coo = a.tocoo()  # convert to COOrdinate format
+
+            # if symmetry format used, remove values above main diagonal
+            if symmetry != self.SYMMETRY_GENERAL:
+                lower_triangle_mask = coo.row >= coo.col
+                coo = coo_array((coo.data[lower_triangle_mask],
+                                (coo.row[lower_triangle_mask],
+                                 coo.col[lower_triangle_mask])),
+                                shape=coo.shape)
+
+            # write shape spec
+            data = '%i %i %i\n' % (rows, cols, coo.nnz)
+            stream.write(data.encode('latin1'))
+
+            template = self._field_template(field, precision-1)
+
+            if field == self.FIELD_PATTERN:
+                for r, c in zip(coo.row+1, coo.col+1):
+                    data = "%i %i\n" % (r, c)
+                    stream.write(data.encode('latin1'))
+            elif field in (self.FIELD_INTEGER, self.FIELD_REAL,
+                           self.FIELD_UNSIGNED):
+                for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
+                    data = ("%i %i " % (r, c)) + (template % d)
+                    stream.write(data.encode('latin1'))
+            elif field == self.FIELD_COMPLEX:
+                for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
+                    data = ("%i %i " % (r, c)) + (template % (d.real, d.imag))
+                    stream.write(data.encode('latin1'))
+            else:
+                raise TypeError(f'Unknown field type {field}')
+
+
+def _is_fromfile_compatible(stream):
+    """
+    Check whether `stream` is compatible with numpy.fromfile.
+
+    Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with
+    Python 3.
+    """
+
+    bad_cls = []
+    try:
+        import gzip
+        bad_cls.append(gzip.GzipFile)
+    except ImportError:
+        pass
+    try:
+        import bz2
+        bad_cls.append(bz2.BZ2File)
+    except ImportError:
+        pass
+
+    bad_cls = tuple(bad_cls)
+    return not isinstance(stream, bad_cls)
diff --git a/python_embeded/Lib/site-packages/scipy/io/_netcdf.py b/python_embeded/Lib/site-packages/scipy/io/_netcdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..365b22217a07f3acf1a9ef8ca6e31b139b60e60c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/_netcdf.py
@@ -0,0 +1,1094 @@
+"""
+NetCDF reader/writer module.
+
+This module is used to read and create NetCDF files. NetCDF files are
+accessed through the `netcdf_file` object. Data written to and from NetCDF
+files are contained in `netcdf_variable` objects. Attributes are given
+as member variables of the `netcdf_file` and `netcdf_variable` objects.
+
+This module implements the Scientific.IO.NetCDF API to read and create
+NetCDF files. The same API is also used in the PyNIO and pynetcdf
+modules, allowing these modules to be used interchangeably when working
+with NetCDF files.
+
+Only NetCDF3 is supported here; for NetCDF4 see
+`netCDF4-python `__,
+which has a similar API.
+
+"""
+
+# TODO:
+# * properly implement ``_FillValue``.
+# * fix character variables.
+# * implement PAGESIZE for Python 2.6?
+
+# The Scientific.IO.NetCDF API allows attributes to be added directly to
+# instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate
+# between user-set attributes and instance attributes, user-set attributes
+# are automatically stored in the ``_attributes`` attribute by overloading
+#``__setattr__``. This is the reason why the code sometimes uses
+#``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``;
+# otherwise the key would be inserted into userspace attributes.
+
+
+__all__ = ['netcdf_file', 'netcdf_variable']
+
+
+import warnings
+import weakref
+from operator import mul
+from platform import python_implementation
+
+import mmap as mm
+
+import numpy as np
+from numpy import frombuffer, dtype, empty, array, asarray
+from numpy import little_endian as LITTLE_ENDIAN
+from functools import reduce
+
+
+IS_PYPY = python_implementation() == 'PyPy'
+
+ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00'
+ZERO = b'\x00\x00\x00\x00'
+NC_BYTE = b'\x00\x00\x00\x01'
+NC_CHAR = b'\x00\x00\x00\x02'
+NC_SHORT = b'\x00\x00\x00\x03'
+NC_INT = b'\x00\x00\x00\x04'
+NC_FLOAT = b'\x00\x00\x00\x05'
+NC_DOUBLE = b'\x00\x00\x00\x06'
+NC_DIMENSION = b'\x00\x00\x00\n'
+NC_VARIABLE = b'\x00\x00\x00\x0b'
+NC_ATTRIBUTE = b'\x00\x00\x00\x0c'
+FILL_BYTE = b'\x81'
+FILL_CHAR = b'\x00'
+FILL_SHORT = b'\x80\x01'
+FILL_INT = b'\x80\x00\x00\x01'
+FILL_FLOAT = b'\x7C\xF0\x00\x00'
+FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00'
+
+TYPEMAP = {NC_BYTE: ('b', 1),
+           NC_CHAR: ('c', 1),
+           NC_SHORT: ('h', 2),
+           NC_INT: ('i', 4),
+           NC_FLOAT: ('f', 4),
+           NC_DOUBLE: ('d', 8)}
+
+FILLMAP = {NC_BYTE: FILL_BYTE,
+           NC_CHAR: FILL_CHAR,
+           NC_SHORT: FILL_SHORT,
+           NC_INT: FILL_INT,
+           NC_FLOAT: FILL_FLOAT,
+           NC_DOUBLE: FILL_DOUBLE}
+
+REVERSE = {('b', 1): NC_BYTE,
+           ('B', 1): NC_CHAR,
+           ('c', 1): NC_CHAR,
+           ('h', 2): NC_SHORT,
+           ('i', 4): NC_INT,
+           ('f', 4): NC_FLOAT,
+           ('d', 8): NC_DOUBLE,
+
+           # these come from asarray(1).dtype.char and asarray('foo').dtype.char,
+           # used when getting the types from generic attributes.
+           ('l', 4): NC_INT,
+           ('S', 1): NC_CHAR}
+
+
+class netcdf_file:
+    """
+    A file object for NetCDF data.
+
+    A `netcdf_file` object has two standard attributes: `dimensions` and
+    `variables`. The values of both are dictionaries, mapping dimension
+    names to their associated lengths and variable names to variables,
+    respectively. Application programs should never modify these
+    dictionaries.
+
+    All other attributes correspond to global attributes defined in the
+    NetCDF file. Global file attributes are created by assigning to an
+    attribute of the `netcdf_file` object.
+
+    Parameters
+    ----------
+    filename : string or file-like
+        string -> filename
+    mode : {'r', 'w', 'a'}, optional
+        read-write-append mode, default is 'r'
+    mmap : None or bool, optional
+        Whether to mmap `filename` when reading.  Default is True
+        when `filename` is a file name, False when `filename` is a
+        file-like object. Note that when mmap is in use, data arrays
+        returned refer directly to the mmapped data on disk, and the
+        file cannot be closed as long as references to it exist.
+    version : {1, 2}, optional
+        version of netcdf to read / write, where 1 means *Classic
+        format* and 2 means *64-bit offset format*.  Default is 1.  See
+        `here `__
+        for more info.
+    maskandscale : bool, optional
+        Whether to automatically scale and/or mask data based on attributes.
+        Default is False.
+
+    Notes
+    -----
+    The major advantage of this module over other modules is that it doesn't
+    require the code to be linked to the NetCDF libraries. This module is
+    derived from `pupynere `_.
+
+    NetCDF files are a self-describing binary data format. The file contains
+    metadata that describes the dimensions and variables in the file. More
+    details about NetCDF files can be found `here
+    `__. There
+    are three main sections to a NetCDF data structure:
+
+    1. Dimensions
+    2. Variables
+    3. Attributes
+
+    The dimensions section records the name and length of each dimension used
+    by the variables. The variables would then indicate which dimensions it
+    uses and any attributes such as data units, along with containing the data
+    values for the variable. It is good practice to include a
+    variable that is the same name as a dimension to provide the values for
+    that axes. Lastly, the attributes section would contain additional
+    information such as the name of the file creator or the instrument used to
+    collect the data.
+
+    When writing data to a NetCDF file, there is often the need to indicate the
+    'record dimension'. A record dimension is the unbounded dimension for a
+    variable. For example, a temperature variable may have dimensions of
+    latitude, longitude and time. If one wants to add more temperature data to
+    the NetCDF file as time progresses, then the temperature variable should
+    have the time dimension flagged as the record dimension.
+
+    In addition, the NetCDF file header contains the position of the data in
+    the file, so access can be done in an efficient manner without loading
+    unnecessary data into memory. It uses the ``mmap`` module to create
+    Numpy arrays mapped to the data on disk, for the same purpose.
+
+    Note that when `netcdf_file` is used to open a file with mmap=True
+    (default for read-only), arrays returned by it refer to data
+    directly on the disk. The file should not be closed, and cannot be cleanly
+    closed when asked, if such arrays are alive. You may want to copy data arrays
+    obtained from mmapped Netcdf file if they are to be processed after the file
+    is closed, see the example below.
+
+    Examples
+    --------
+    To create a NetCDF file:
+
+    >>> from scipy.io import netcdf_file
+    >>> import numpy as np
+    >>> f = netcdf_file('simple.nc', 'w')
+    >>> f.history = 'Created for a test'
+    >>> f.createDimension('time', 10)
+    >>> time = f.createVariable('time', 'i', ('time',))
+    >>> time[:] = np.arange(10)
+    >>> time.units = 'days since 2008-01-01'
+    >>> f.close()
+
+    Note the assignment of ``arange(10)`` to ``time[:]``.  Exposing the slice
+    of the time variable allows for the data to be set in the object, rather
+    than letting ``arange(10)`` overwrite the ``time`` variable.
+
+    To read the NetCDF file we just created:
+
+    >>> from scipy.io import netcdf_file
+    >>> f = netcdf_file('simple.nc', 'r')
+    >>> print(f.history)
+    b'Created for a test'
+    >>> time = f.variables['time']
+    >>> print(time.units)
+    b'days since 2008-01-01'
+    >>> print(time.shape)
+    (10,)
+    >>> print(time[-1])
+    9
+
+    NetCDF files, when opened read-only, return arrays that refer
+    directly to memory-mapped data on disk:
+
+    >>> data = time[:]
+
+    If the data is to be processed after the file is closed, it needs
+    to be copied to main memory:
+
+    >>> data = time[:].copy()
+    >>> del time
+    >>> f.close()
+    >>> data.mean()
+    4.5
+
+    A NetCDF file can also be used as context manager:
+
+    >>> from scipy.io import netcdf_file
+    >>> with netcdf_file('simple.nc', 'r') as f:
+    ...     print(f.history)
+    b'Created for a test'
+
+    """
+    def __init__(self, filename, mode='r', mmap=None, version=1,
+                 maskandscale=False):
+        """Initialize netcdf_file from fileobj (str or file-like)."""
+        if mode not in 'rwa':
+            raise ValueError("Mode must be either 'r', 'w' or 'a'.")
+
+        if hasattr(filename, 'seek'):  # file-like
+            self.fp = filename
+            self.filename = 'None'
+            if mmap is None:
+                mmap = False
+            elif mmap and not hasattr(filename, 'fileno'):
+                raise ValueError('Cannot use file object for mmap')
+        else:  # maybe it's a string
+            self.filename = filename
+            omode = 'r+' if mode == 'a' else mode
+            self.fp = open(self.filename, f'{omode}b')
+            if mmap is None:
+                # Mmapped files on PyPy cannot be usually closed
+                # before the GC runs, so it's better to use mmap=False
+                # as the default.
+                mmap = (not IS_PYPY)
+
+        if mode != 'r':
+            # Cannot read write-only files
+            mmap = False
+
+        self.use_mmap = mmap
+        self.mode = mode
+        self.version_byte = version
+        self.maskandscale = maskandscale
+
+        self.dimensions = {}
+        self.variables = {}
+
+        self._dims = []
+        self._recs = 0
+        self._recsize = 0
+
+        self._mm = None
+        self._mm_buf = None
+        if self.use_mmap:
+            self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ)
+            self._mm_buf = np.frombuffer(self._mm, dtype=np.int8)
+
+        self._attributes = {}
+
+        if mode in 'ra':
+            self._read()
+
+    def __setattr__(self, attr, value):
+        # Store user defined attributes in a separate dict,
+        # so we can save them to file later.
+        try:
+            self._attributes[attr] = value
+        except AttributeError:
+            pass
+        self.__dict__[attr] = value
+
+    def close(self):
+        """Closes the NetCDF file."""
+        if hasattr(self, 'fp') and not self.fp.closed:
+            try:
+                self.flush()
+            finally:
+                self.variables = {}
+                if self._mm_buf is not None:
+                    ref = weakref.ref(self._mm_buf)
+                    self._mm_buf = None
+                    if ref() is None:
+                        # self._mm_buf is gc'd, and we can close the mmap
+                        self._mm.close()
+                    else:
+                        # we cannot close self._mm, since self._mm_buf is
+                        # alive and there may still be arrays referring to it
+                        warnings.warn(
+                            "Cannot close a netcdf_file opened with mmap=True, when "
+                            "netcdf_variables or arrays referring to its data still "
+                            "exist. All data arrays obtained from such files refer "
+                            "directly to data on disk, and must be copied before the "
+                            "file can be cleanly closed. "
+                            "(See netcdf_file docstring for more information on mmap.)",
+                            category=RuntimeWarning, stacklevel=2,
+                        )
+                self._mm = None
+                self.fp.close()
+    __del__ = close
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.close()
+
+    def createDimension(self, name, length):
+        """
+        Adds a dimension to the Dimension section of the NetCDF data structure.
+
+        Note that this function merely adds a new dimension that the variables can
+        reference. The values for the dimension, if desired, should be added as
+        a variable using `createVariable`, referring to this dimension.
+
+        Parameters
+        ----------
+        name : str
+            Name of the dimension (Eg, 'lat' or 'time').
+        length : int
+            Length of the dimension.
+
+        See Also
+        --------
+        createVariable
+
+        """
+        if length is None and self._dims:
+            raise ValueError("Only first dimension may be unlimited!")
+
+        self.dimensions[name] = length
+        self._dims.append(name)
+
+    def createVariable(self, name, type, dimensions):
+        """
+        Create an empty variable for the `netcdf_file` object, specifying its data
+        type and the dimensions it uses.
+
+        Parameters
+        ----------
+        name : str
+            Name of the new variable.
+        type : dtype or str
+            Data type of the variable.
+        dimensions : sequence of str
+            List of the dimension names used by the variable, in the desired order.
+
+        Returns
+        -------
+        variable : netcdf_variable
+            The newly created ``netcdf_variable`` object.
+            This object has also been added to the `netcdf_file` object as well.
+
+        See Also
+        --------
+        createDimension
+
+        Notes
+        -----
+        Any dimensions to be used by the variable should already exist in the
+        NetCDF data structure or should be created by `createDimension` prior to
+        creating the NetCDF variable.
+
+        """
+        shape = tuple([self.dimensions[dim] for dim in dimensions])
+        shape_ = tuple([dim or 0 for dim in shape])  # replace None with 0 for NumPy
+
+        type = dtype(type)
+        typecode, size = type.char, type.itemsize
+        if (typecode, size) not in REVERSE:
+            raise ValueError(f"NetCDF 3 does not support type {type}")
+
+        # convert to big endian always for NetCDF 3
+        data = empty(shape_, dtype=type.newbyteorder("B"))
+        self.variables[name] = netcdf_variable(
+                data, typecode, size, shape, dimensions,
+                maskandscale=self.maskandscale)
+        return self.variables[name]
+
+    def flush(self):
+        """
+        Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
+
+        See Also
+        --------
+        sync : Identical function
+
+        """
+        if hasattr(self, 'mode') and self.mode in 'wa':
+            self._write()
+    sync = flush
+
+    def _write(self):
+        self.fp.seek(0)
+        self.fp.write(b'CDF')
+        self.fp.write(array(self.version_byte, '>b').tobytes())
+
+        # Write headers and data.
+        self._write_numrecs()
+        self._write_dim_array()
+        self._write_gatt_array()
+        self._write_var_array()
+
+    def _write_numrecs(self):
+        # Get highest record count from all record variables.
+        for var in self.variables.values():
+            if var.isrec and len(var.data) > self._recs:
+                self.__dict__['_recs'] = len(var.data)
+        self._pack_int(self._recs)
+
+    def _write_dim_array(self):
+        if self.dimensions:
+            self.fp.write(NC_DIMENSION)
+            self._pack_int(len(self.dimensions))
+            for name in self._dims:
+                self._pack_string(name)
+                length = self.dimensions[name]
+                self._pack_int(length or 0)  # replace None with 0 for record dimension
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_gatt_array(self):
+        self._write_att_array(self._attributes)
+
+    def _write_att_array(self, attributes):
+        if attributes:
+            self.fp.write(NC_ATTRIBUTE)
+            self._pack_int(len(attributes))
+            for name, values in attributes.items():
+                self._pack_string(name)
+                self._write_att_values(values)
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_var_array(self):
+        if self.variables:
+            self.fp.write(NC_VARIABLE)
+            self._pack_int(len(self.variables))
+
+            # Sort variable names non-recs first, then recs.
+            def sortkey(n):
+                v = self.variables[n]
+                if v.isrec:
+                    return (-1,)
+                return v._shape
+            variables = sorted(self.variables, key=sortkey, reverse=True)
+
+            # Set the metadata for all variables.
+            for name in variables:
+                self._write_var_metadata(name)
+            # Now that we have the metadata, we know the vsize of
+            # each record variable, so we can calculate recsize.
+            self.__dict__['_recsize'] = sum([
+                    var._vsize for var in self.variables.values()
+                    if var.isrec])
+            # Set the data for all variables.
+            for name in variables:
+                self._write_var_data(name)
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_var_metadata(self, name):
+        var = self.variables[name]
+
+        self._pack_string(name)
+        self._pack_int(len(var.dimensions))
+        for dimname in var.dimensions:
+            dimid = self._dims.index(dimname)
+            self._pack_int(dimid)
+
+        self._write_att_array(var._attributes)
+
+        nc_type = REVERSE[var.typecode(), var.itemsize()]
+        self.fp.write(nc_type)
+
+        if not var.isrec:
+            vsize = var.data.size * var.data.itemsize
+            vsize += -vsize % 4
+        else:  # record variable
+            try:
+                vsize = var.data[0].size * var.data.itemsize
+            except IndexError:
+                vsize = 0
+            rec_vars = len([v for v in self.variables.values()
+                            if v.isrec])
+            if rec_vars > 1:
+                vsize += -vsize % 4
+        self.variables[name].__dict__['_vsize'] = vsize
+        self._pack_int(vsize)
+
+        # Pack a bogus begin, and set the real value later.
+        self.variables[name].__dict__['_begin'] = self.fp.tell()
+        self._pack_begin(0)
+
+    def _write_var_data(self, name):
+        var = self.variables[name]
+
+        # Set begin in file header.
+        the_beguine = self.fp.tell()
+        self.fp.seek(var._begin)
+        self._pack_begin(the_beguine)
+        self.fp.seek(the_beguine)
+
+        # Write data.
+        if not var.isrec:
+            self.fp.write(var.data.tobytes())
+            count = var.data.size * var.data.itemsize
+            self._write_var_padding(var, var._vsize - count)
+        else:  # record variable
+            # Handle rec vars with shape[0] < nrecs.
+            if self._recs > len(var.data):
+                shape = (self._recs,) + var.data.shape[1:]
+                # Resize in-place does not always work since
+                # the array might not be single-segment
+                try:
+                    var.data.resize(shape)
+                except ValueError:
+                    dtype = var.data.dtype
+                    var.__dict__['data'] = np.resize(var.data, shape).astype(dtype)
+
+            pos0 = pos = self.fp.tell()
+            for rec in var.data:
+                # Apparently scalars cannot be converted to big endian. If we
+                # try to convert a ``=i4`` scalar to, say, '>i4' the dtype
+                # will remain as ``=i4``.
+                if not rec.shape and (rec.dtype.byteorder == '<' or
+                        (rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
+                    rec = rec.byteswap()
+                self.fp.write(rec.tobytes())
+                # Padding
+                count = rec.size * rec.itemsize
+                self._write_var_padding(var, var._vsize - count)
+                pos += self._recsize
+                self.fp.seek(pos)
+            self.fp.seek(pos0 + var._vsize)
+
+    def _write_var_padding(self, var, size):
+        encoded_fill_value = var._get_encoded_fill_value()
+        num_fills = size // len(encoded_fill_value)
+        self.fp.write(encoded_fill_value * num_fills)
+
+    def _write_att_values(self, values):
+        if hasattr(values, 'dtype'):
+            nc_type = REVERSE[values.dtype.char, values.dtype.itemsize]
+        else:
+            types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)]
+
+            # bytes index into scalars in py3k. Check for "string" types
+            if isinstance(values, (str, bytes)):
+                sample = values
+            else:
+                try:
+                    sample = values[0]  # subscriptable?
+                except TypeError:
+                    sample = values     # scalar
+
+            for class_, nc_type in types:
+                if isinstance(sample, class_):
+                    break
+
+        typecode, size = TYPEMAP[nc_type]
+        dtype_ = f'>{typecode}'
+        # asarray() dies with bytes and '>c' in py3k. Change to 'S'
+        dtype_ = 'S' if dtype_ == '>c' else dtype_
+
+        values = asarray(values, dtype=dtype_)
+
+        self.fp.write(nc_type)
+
+        if values.dtype.char == 'S':
+            nelems = values.itemsize
+        else:
+            nelems = values.size
+        self._pack_int(nelems)
+
+        if not values.shape and (values.dtype.byteorder == '<' or
+                (values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
+            values = values.byteswap()
+        self.fp.write(values.tobytes())
+        count = values.size * values.itemsize
+        self.fp.write(b'\x00' * (-count % 4))  # pad
+
+    def _read(self):
+        # Check magic bytes and version
+        magic = self.fp.read(3)
+        if not magic == b'CDF':
+            raise TypeError(f"Error: {self.filename} is not a valid NetCDF 3 file")
+        self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0]
+
+        # Read file headers and set data.
+        self._read_numrecs()
+        self._read_dim_array()
+        self._read_gatt_array()
+        self._read_var_array()
+
+    def _read_numrecs(self):
+        self.__dict__['_recs'] = self._unpack_int()
+
+    def _read_dim_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_DIMENSION]:
+            raise ValueError("Unexpected header.")
+        count = self._unpack_int()
+
+        for dim in range(count):
+            name = self._unpack_string().decode('latin1')
+            length = self._unpack_int() or None  # None for record dimension
+            self.dimensions[name] = length
+            self._dims.append(name)  # preserve order
+
+    def _read_gatt_array(self):
+        for k, v in self._read_att_array().items():
+            self.__setattr__(k, v)
+
+    def _read_att_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_ATTRIBUTE]:
+            raise ValueError("Unexpected header.")
+        count = self._unpack_int()
+
+        attributes = {}
+        for attr in range(count):
+            name = self._unpack_string().decode('latin1')
+            attributes[name] = self._read_att_values()
+        return attributes
+
+    def _read_var_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_VARIABLE]:
+            raise ValueError("Unexpected header.")
+
+        begin = 0
+        dtypes = {'names': [], 'formats': []}
+        rec_vars = []
+        count = self._unpack_int()
+        for var in range(count):
+            (name, dimensions, shape, attributes,
+             typecode, size, dtype_, begin_, vsize) = self._read_var()
+            # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
+            # Note that vsize is the product of the dimension lengths
+            # (omitting the record dimension) and the number of bytes
+            # per value (determined from the type), increased to the
+            # next multiple of 4, for each variable. If a record
+            # variable, this is the amount of space per record. The
+            # netCDF "record size" is calculated as the sum of the
+            # vsize's of all the record variables.
+            #
+            # The vsize field is actually redundant, because its value
+            # may be computed from other information in the header. The
+            # 32-bit vsize field is not large enough to contain the size
+            # of variables that require more than 2^32 - 4 bytes, so
+            # 2^32 - 1 is used in the vsize field for such variables.
+            if shape and shape[0] is None:  # record variable
+                rec_vars.append(name)
+                # The netCDF "record size" is calculated as the sum of
+                # the vsize's of all the record variables.
+                self.__dict__['_recsize'] += vsize
+                if begin == 0:
+                    begin = begin_
+                dtypes['names'].append(name)
+                dtypes['formats'].append(str(shape[1:]) + dtype_)
+
+                # Handle padding with a virtual variable.
+                if typecode in 'bch':
+                    actual_size = reduce(mul, (1,) + shape[1:]) * size
+                    padding = -actual_size % 4
+                    if padding:
+                        dtypes['names'].append('_padding_%d' % var)
+                        dtypes['formats'].append('(%d,)>b' % padding)
+
+                # Data will be set later.
+                data = None
+            else:  # not a record variable
+                # Calculate size to avoid problems with vsize (above)
+                a_size = reduce(mul, shape, 1) * size
+                if self.use_mmap:
+                    data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_)
+                    data.shape = shape
+                else:
+                    pos = self.fp.tell()
+                    self.fp.seek(begin_)
+                    data = frombuffer(self.fp.read(a_size), dtype=dtype_
+                                      ).copy()
+                    data.shape = shape
+                    self.fp.seek(pos)
+
+            # Add variable.
+            self.variables[name] = netcdf_variable(
+                    data, typecode, size, shape, dimensions, attributes,
+                    maskandscale=self.maskandscale)
+
+        if rec_vars:
+            # Remove padding when only one record variable.
+            if len(rec_vars) == 1:
+                dtypes['names'] = dtypes['names'][:1]
+                dtypes['formats'] = dtypes['formats'][:1]
+
+            # Build rec array.
+            if self.use_mmap:
+                buf = self._mm_buf[begin:begin+self._recs*self._recsize]
+                rec_array = buf.view(dtype=dtypes)
+                rec_array.shape = (self._recs,)
+            else:
+                pos = self.fp.tell()
+                self.fp.seek(begin)
+                rec_array = frombuffer(self.fp.read(self._recs*self._recsize),
+                                       dtype=dtypes).copy()
+                rec_array.shape = (self._recs,)
+                self.fp.seek(pos)
+
+            for var in rec_vars:
+                self.variables[var].__dict__['data'] = rec_array[var]
+
+    def _read_var(self):
+        name = self._unpack_string().decode('latin1')
+        dimensions = []
+        shape = []
+        dims = self._unpack_int()
+
+        for i in range(dims):
+            dimid = self._unpack_int()
+            dimname = self._dims[dimid]
+            dimensions.append(dimname)
+            dim = self.dimensions[dimname]
+            shape.append(dim)
+        dimensions = tuple(dimensions)
+        shape = tuple(shape)
+
+        attributes = self._read_att_array()
+        nc_type = self.fp.read(4)
+        vsize = self._unpack_int()
+        begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]()
+
+        typecode, size = TYPEMAP[nc_type]
+        dtype_ = f'>{typecode}'
+
+        return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize
+
+    def _read_att_values(self):
+        nc_type = self.fp.read(4)
+        n = self._unpack_int()
+
+        typecode, size = TYPEMAP[nc_type]
+
+        count = n*size
+        values = self.fp.read(int(count))
+        self.fp.read(-count % 4)  # read padding
+
+        if typecode != 'c':
+            values = frombuffer(values, dtype=f'>{typecode}').copy()
+            if values.shape == (1,):
+                values = values[0]
+        else:
+            values = values.rstrip(b'\x00')
+        return values
+
+    def _pack_begin(self, begin):
+        if self.version_byte == 1:
+            self._pack_int(begin)
+        elif self.version_byte == 2:
+            self._pack_int64(begin)
+
+    def _pack_int(self, value):
+        self.fp.write(array(value, '>i').tobytes())
+    _pack_int32 = _pack_int
+
+    def _unpack_int(self):
+        return int(frombuffer(self.fp.read(4), '>i')[0])
+    _unpack_int32 = _unpack_int
+
+    def _pack_int64(self, value):
+        self.fp.write(array(value, '>q').tobytes())
+
+    def _unpack_int64(self):
+        return frombuffer(self.fp.read(8), '>q')[0]
+
+    def _pack_string(self, s):
+        count = len(s)
+        self._pack_int(count)
+        self.fp.write(s.encode('latin1'))
+        self.fp.write(b'\x00' * (-count % 4))  # pad
+
+    def _unpack_string(self):
+        count = self._unpack_int()
+        s = self.fp.read(count).rstrip(b'\x00')
+        self.fp.read(-count % 4)  # read padding
+        return s
+
+
+class netcdf_variable:
+    """
+    A data object for netcdf files.
+
+    `netcdf_variable` objects are constructed by calling the method
+    `netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
+    objects behave much like array objects defined in numpy, except that their
+    data resides in a file. Data is read by indexing and written by assigning
+    to an indexed subset; the entire array can be accessed by the index ``[:]``
+    or (for scalars) by using the methods `getValue` and `assignValue`.
+    `netcdf_variable` objects also have attribute `shape` with the same meaning
+    as for arrays, but the shape cannot be modified. There is another read-only
+    attribute `dimensions`, whose value is the tuple of dimension names.
+
+    All other attributes correspond to variable attributes defined in
+    the NetCDF file. Variable attributes are created by assigning to an
+    attribute of the `netcdf_variable` object.
+
+    Parameters
+    ----------
+    data : array_like
+        The data array that holds the values for the variable.
+        Typically, this is initialized as empty, but with the proper shape.
+    typecode : dtype character code
+        Desired data-type for the data array.
+    size : int
+        Desired element size for the data array.
+    shape : sequence of ints
+        The shape of the array. This should match the lengths of the
+        variable's dimensions.
+    dimensions : sequence of strings
+        The names of the dimensions used by the variable. Must be in the
+        same order of the dimension lengths given by `shape`.
+    attributes : dict, optional
+        Attribute values (any type) keyed by string names. These attributes
+        become attributes for the netcdf_variable object.
+    maskandscale : bool, optional
+        Whether to automatically scale and/or mask data based on attributes.
+        Default is False.
+
+
+    Attributes
+    ----------
+    dimensions : list of str
+        List of names of dimensions used by the variable object.
+    isrec, shape
+        Properties
+
+    See also
+    --------
+    isrec, shape
+
+    """
+    def __init__(self, data, typecode, size, shape, dimensions,
+                 attributes=None,
+                 maskandscale=False):
+        self.data = data
+        self._typecode = typecode
+        self._size = size
+        self._shape = shape
+        self.dimensions = dimensions
+        self.maskandscale = maskandscale
+
+        self._attributes = attributes or {}
+        for k, v in self._attributes.items():
+            self.__dict__[k] = v
+
+    def __setattr__(self, attr, value):
+        # Store user defined attributes in a separate dict,
+        # so we can save them to file later.
+        try:
+            self._attributes[attr] = value
+        except AttributeError:
+            pass
+        self.__dict__[attr] = value
+
+    def isrec(self):
+        """Returns whether the variable has a record dimension or not.
+
+        A record dimension is a dimension along which additional data could be
+        easily appended in the netcdf data structure without much rewriting of
+        the data file. This attribute is a read-only property of the
+        `netcdf_variable`.
+
+        """
+        return bool(self.data.shape) and not self._shape[0]
+    isrec = property(isrec)
+
+    def shape(self):
+        """Returns the shape tuple of the data variable.
+
+        This is a read-only attribute and can not be modified in the
+        same manner of other numpy arrays.
+        """
+        return self.data.shape
+    shape = property(shape)
+
+    def getValue(self):
+        """
+        Retrieve a scalar value from a `netcdf_variable` of length one.
+
+        Raises
+        ------
+        ValueError
+            If the netcdf variable is an array of length greater than one,
+            this exception will be raised.
+
+        """
+        return self.data.item()
+
+    def assignValue(self, value):
+        """
+        Assign a scalar value to a `netcdf_variable` of length one.
+
+        Parameters
+        ----------
+        value : scalar
+            Scalar value (of compatible type) to assign to a length-one netcdf
+            variable. This value will be written to file.
+
+        Raises
+        ------
+        ValueError
+            If the input is not a scalar, or if the destination is not a length-one
+            netcdf variable.
+
+        """
+        if not self.data.flags.writeable:
+            # Work-around for a bug in NumPy.  Calling itemset() on a read-only
+            # memory-mapped array causes a seg. fault.
+            # See NumPy ticket #1622, and SciPy ticket #1202.
+            # This check for `writeable` can be removed when the oldest version
+            # of NumPy still supported by scipy contains the fix for #1622.
+            raise RuntimeError("variable is not writeable")
+
+        self.data[:] = value
+
+    def typecode(self):
+        """
+        Return the typecode of the variable.
+
+        Returns
+        -------
+        typecode : char
+            The character typecode of the variable (e.g., 'i' for int).
+
+        """
+        return self._typecode
+
+    def itemsize(self):
+        """
+        Return the itemsize of the variable.
+
+        Returns
+        -------
+        itemsize : int
+            The element size of the variable (e.g., 8 for float64).
+
+        """
+        return self._size
+
+    def __getitem__(self, index):
+        if not self.maskandscale:
+            return self.data[index]
+
+        data = self.data[index].copy()
+        missing_value = self._get_missing_value()
+        data = self._apply_missing_value(data, missing_value)
+        scale_factor = self._attributes.get('scale_factor')
+        add_offset = self._attributes.get('add_offset')
+        if add_offset is not None or scale_factor is not None:
+            data = data.astype(np.float64)
+        if scale_factor is not None:
+            data = data * scale_factor
+        if add_offset is not None:
+            data += add_offset
+
+        return data
+
+    def __setitem__(self, index, data):
+        if self.maskandscale:
+            missing_value = (
+                    self._get_missing_value() or
+                    getattr(data, 'fill_value', 999999))
+            self._attributes.setdefault('missing_value', missing_value)
+            self._attributes.setdefault('_FillValue', missing_value)
+            data = ((data - self._attributes.get('add_offset', 0.0)) /
+                    self._attributes.get('scale_factor', 1.0))
+            data = np.ma.asarray(data).filled(missing_value)
+            if self._typecode not in 'fd' and data.dtype.kind == 'f':
+                data = np.round(data)
+
+        # Expand data for record vars?
+        if self.isrec:
+            if isinstance(index, tuple):
+                rec_index = index[0]
+            else:
+                rec_index = index
+            if isinstance(rec_index, slice):
+                recs = (rec_index.start or 0) + len(data)
+            else:
+                recs = rec_index + 1
+            if recs > len(self.data):
+                shape = (recs,) + self._shape[1:]
+                # Resize in-place does not always work since
+                # the array might not be single-segment
+                try:
+                    self.data.resize(shape)
+                except ValueError:
+                    dtype = self.data.dtype
+                    self.__dict__['data'] = np.resize(self.data, shape).astype(dtype)
+        self.data[index] = data
+
+    def _default_encoded_fill_value(self):
+        """
+        The default encoded fill-value for this Variable's data type.
+        """
+        nc_type = REVERSE[self.typecode(), self.itemsize()]
+        return FILLMAP[nc_type]
+
+    def _get_encoded_fill_value(self):
+        """
+        Returns the encoded fill value for this variable as bytes.
+
+        This is taken from either the _FillValue attribute, or the default fill
+        value for this variable's data type.
+        """
+        if '_FillValue' in self._attributes:
+            fill_value = np.array(self._attributes['_FillValue'],
+                                  dtype=self.data.dtype).tobytes()
+            if len(fill_value) == self.itemsize():
+                return fill_value
+            else:
+                return self._default_encoded_fill_value()
+        else:
+            return self._default_encoded_fill_value()
+
+    def _get_missing_value(self):
+        """
+        Returns the value denoting "no data" for this variable.
+
+        If this variable does not have a missing/fill value, returns None.
+
+        If both _FillValue and missing_value are given, give precedence to
+        _FillValue. The netCDF standard gives special meaning to _FillValue;
+        missing_value is  just used for compatibility with old datasets.
+        """
+
+        if '_FillValue' in self._attributes:
+            missing_value = self._attributes['_FillValue']
+        elif 'missing_value' in self._attributes:
+            missing_value = self._attributes['missing_value']
+        else:
+            missing_value = None
+
+        return missing_value
+
+    @staticmethod
+    def _apply_missing_value(data, missing_value):
+        """
+        Applies the given missing value to the data array.
+
+        Returns a numpy.ma array, with any value equal to missing_value masked
+        out (unless missing_value is None, in which case the original array is
+        returned).
+        """
+
+        if missing_value is None:
+            newdata = data
+        else:
+            try:
+                missing_value_isnan = np.isnan(missing_value)
+            except (TypeError, NotImplementedError):
+                # some data types (e.g., characters) cannot be tested for NaN
+                missing_value_isnan = False
+
+            if missing_value_isnan:
+                mymask = np.isnan(data)
+            else:
+                mymask = (data == missing_value)
+
+            newdata = np.ma.masked_where(mymask, data)
+
+        return newdata
+
+
+NetCDFFile = netcdf_file
+NetCDFVariable = netcdf_variable
diff --git a/python_embeded/Lib/site-packages/scipy/io/_test_fortran.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/io/_test_fortran.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c0d622d2a1c689607b3dc280f4bae6d9db476d53
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/io/_test_fortran.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/io/harwell_boeing.py b/python_embeded/Lib/site-packages/scipy/io/harwell_boeing.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a1248090f99de5854f8c1c916d5cbf66d1f9961
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/harwell_boeing.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.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["hb_read", "hb_write"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="harwell_boeing",
+                                   private_modules=["_harwell_boeing"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/io/idl.py b/python_embeded/Lib/site-packages/scipy/io/idl.py
new file mode 100644
index 0000000000000000000000000000000000000000..73d5192124bb6c56162a5889ed24aa5547c0b1a9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/idl.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.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["readsav"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="idl",
+                                   private_modules=["_idl"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/io/mmio.py b/python_embeded/Lib/site-packages/scipy/io/mmio.py
new file mode 100644
index 0000000000000000000000000000000000000000..8463898ed865289b542d14dd8e24c51e50c4fa5c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/mmio.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.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["mminfo", "mmread", "mmwrite"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="mmio",
+                                   private_modules=["_mmio"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/io/netcdf.py b/python_embeded/Lib/site-packages/scipy/io/netcdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bb597b8fa07f2d3c8b9c9e7f9b2e28d2992274c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/netcdf.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.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["netcdf_file", "netcdf_variable"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="netcdf",
+                                   private_modules=["_netcdf"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/io/wavfile.py b/python_embeded/Lib/site-packages/scipy/io/wavfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..685a33e6e19f56ea5bc959c2d9e5335e395d64b0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/io/wavfile.py
@@ -0,0 +1,891 @@
+"""
+Module to read / write wav files using NumPy arrays
+
+Functions
+---------
+`read`: Return the sample rate (in samples/sec) and data from a WAV file.
+
+`write`: Write a NumPy array as a WAV file.
+
+"""
+import io
+import sys
+import numpy as np
+import struct
+import warnings
+from enum import IntEnum
+
+
+__all__ = [
+    'WavFileWarning',
+    'read',
+    'write'
+]
+
+
+class WavFileWarning(UserWarning):
+    pass
+
+
+class WAVE_FORMAT(IntEnum):
+    """
+    WAVE form wFormatTag IDs
+
+    Complete list is in mmreg.h in Windows 10 SDK.  ALAC and OPUS are the
+    newest additions, in v10.0.14393 2016-07
+    """
+    UNKNOWN = 0x0000
+    PCM = 0x0001
+    ADPCM = 0x0002
+    IEEE_FLOAT = 0x0003
+    VSELP = 0x0004
+    IBM_CVSD = 0x0005
+    ALAW = 0x0006
+    MULAW = 0x0007
+    DTS = 0x0008
+    DRM = 0x0009
+    WMAVOICE9 = 0x000A
+    WMAVOICE10 = 0x000B
+    OKI_ADPCM = 0x0010
+    DVI_ADPCM = 0x0011
+    IMA_ADPCM = 0x0011  # Duplicate
+    MEDIASPACE_ADPCM = 0x0012
+    SIERRA_ADPCM = 0x0013
+    G723_ADPCM = 0x0014
+    DIGISTD = 0x0015
+    DIGIFIX = 0x0016
+    DIALOGIC_OKI_ADPCM = 0x0017
+    MEDIAVISION_ADPCM = 0x0018
+    CU_CODEC = 0x0019
+    HP_DYN_VOICE = 0x001A
+    YAMAHA_ADPCM = 0x0020
+    SONARC = 0x0021
+    DSPGROUP_TRUESPEECH = 0x0022
+    ECHOSC1 = 0x0023
+    AUDIOFILE_AF36 = 0x0024
+    APTX = 0x0025
+    AUDIOFILE_AF10 = 0x0026
+    PROSODY_1612 = 0x0027
+    LRC = 0x0028
+    DOLBY_AC2 = 0x0030
+    GSM610 = 0x0031
+    MSNAUDIO = 0x0032
+    ANTEX_ADPCME = 0x0033
+    CONTROL_RES_VQLPC = 0x0034
+    DIGIREAL = 0x0035
+    DIGIADPCM = 0x0036
+    CONTROL_RES_CR10 = 0x0037
+    NMS_VBXADPCM = 0x0038
+    CS_IMAADPCM = 0x0039
+    ECHOSC3 = 0x003A
+    ROCKWELL_ADPCM = 0x003B
+    ROCKWELL_DIGITALK = 0x003C
+    XEBEC = 0x003D
+    G721_ADPCM = 0x0040
+    G728_CELP = 0x0041
+    MSG723 = 0x0042
+    INTEL_G723_1 = 0x0043
+    INTEL_G729 = 0x0044
+    SHARP_G726 = 0x0045
+    MPEG = 0x0050
+    RT24 = 0x0052
+    PAC = 0x0053
+    MPEGLAYER3 = 0x0055
+    LUCENT_G723 = 0x0059
+    CIRRUS = 0x0060
+    ESPCM = 0x0061
+    VOXWARE = 0x0062
+    CANOPUS_ATRAC = 0x0063
+    G726_ADPCM = 0x0064
+    G722_ADPCM = 0x0065
+    DSAT = 0x0066
+    DSAT_DISPLAY = 0x0067
+    VOXWARE_BYTE_ALIGNED = 0x0069
+    VOXWARE_AC8 = 0x0070
+    VOXWARE_AC10 = 0x0071
+    VOXWARE_AC16 = 0x0072
+    VOXWARE_AC20 = 0x0073
+    VOXWARE_RT24 = 0x0074
+    VOXWARE_RT29 = 0x0075
+    VOXWARE_RT29HW = 0x0076
+    VOXWARE_VR12 = 0x0077
+    VOXWARE_VR18 = 0x0078
+    VOXWARE_TQ40 = 0x0079
+    VOXWARE_SC3 = 0x007A
+    VOXWARE_SC3_1 = 0x007B
+    SOFTSOUND = 0x0080
+    VOXWARE_TQ60 = 0x0081
+    MSRT24 = 0x0082
+    G729A = 0x0083
+    MVI_MVI2 = 0x0084
+    DF_G726 = 0x0085
+    DF_GSM610 = 0x0086
+    ISIAUDIO = 0x0088
+    ONLIVE = 0x0089
+    MULTITUDE_FT_SX20 = 0x008A
+    INFOCOM_ITS_G721_ADPCM = 0x008B
+    CONVEDIA_G729 = 0x008C
+    CONGRUENCY = 0x008D
+    SBC24 = 0x0091
+    DOLBY_AC3_SPDIF = 0x0092
+    MEDIASONIC_G723 = 0x0093
+    PROSODY_8KBPS = 0x0094
+    ZYXEL_ADPCM = 0x0097
+    PHILIPS_LPCBB = 0x0098
+    PACKED = 0x0099
+    MALDEN_PHONYTALK = 0x00A0
+    RACAL_RECORDER_GSM = 0x00A1
+    RACAL_RECORDER_G720_A = 0x00A2
+    RACAL_RECORDER_G723_1 = 0x00A3
+    RACAL_RECORDER_TETRA_ACELP = 0x00A4
+    NEC_AAC = 0x00B0
+    RAW_AAC1 = 0x00FF
+    RHETOREX_ADPCM = 0x0100
+    IRAT = 0x0101
+    VIVO_G723 = 0x0111
+    VIVO_SIREN = 0x0112
+    PHILIPS_CELP = 0x0120
+    PHILIPS_GRUNDIG = 0x0121
+    DIGITAL_G723 = 0x0123
+    SANYO_LD_ADPCM = 0x0125
+    SIPROLAB_ACEPLNET = 0x0130
+    SIPROLAB_ACELP4800 = 0x0131
+    SIPROLAB_ACELP8V3 = 0x0132
+    SIPROLAB_G729 = 0x0133
+    SIPROLAB_G729A = 0x0134
+    SIPROLAB_KELVIN = 0x0135
+    VOICEAGE_AMR = 0x0136
+    G726ADPCM = 0x0140
+    DICTAPHONE_CELP68 = 0x0141
+    DICTAPHONE_CELP54 = 0x0142
+    QUALCOMM_PUREVOICE = 0x0150
+    QUALCOMM_HALFRATE = 0x0151
+    TUBGSM = 0x0155
+    MSAUDIO1 = 0x0160
+    WMAUDIO2 = 0x0161
+    WMAUDIO3 = 0x0162
+    WMAUDIO_LOSSLESS = 0x0163
+    WMASPDIF = 0x0164
+    UNISYS_NAP_ADPCM = 0x0170
+    UNISYS_NAP_ULAW = 0x0171
+    UNISYS_NAP_ALAW = 0x0172
+    UNISYS_NAP_16K = 0x0173
+    SYCOM_ACM_SYC008 = 0x0174
+    SYCOM_ACM_SYC701_G726L = 0x0175
+    SYCOM_ACM_SYC701_CELP54 = 0x0176
+    SYCOM_ACM_SYC701_CELP68 = 0x0177
+    KNOWLEDGE_ADVENTURE_ADPCM = 0x0178
+    FRAUNHOFER_IIS_MPEG2_AAC = 0x0180
+    DTS_DS = 0x0190
+    CREATIVE_ADPCM = 0x0200
+    CREATIVE_FASTSPEECH8 = 0x0202
+    CREATIVE_FASTSPEECH10 = 0x0203
+    UHER_ADPCM = 0x0210
+    ULEAD_DV_AUDIO = 0x0215
+    ULEAD_DV_AUDIO_1 = 0x0216
+    QUARTERDECK = 0x0220
+    ILINK_VC = 0x0230
+    RAW_SPORT = 0x0240
+    ESST_AC3 = 0x0241
+    GENERIC_PASSTHRU = 0x0249
+    IPI_HSX = 0x0250
+    IPI_RPELP = 0x0251
+    CS2 = 0x0260
+    SONY_SCX = 0x0270
+    SONY_SCY = 0x0271
+    SONY_ATRAC3 = 0x0272
+    SONY_SPC = 0x0273
+    TELUM_AUDIO = 0x0280
+    TELUM_IA_AUDIO = 0x0281
+    NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285
+    FM_TOWNS_SND = 0x0300
+    MICRONAS = 0x0350
+    MICRONAS_CELP833 = 0x0351
+    BTV_DIGITAL = 0x0400
+    INTEL_MUSIC_CODER = 0x0401
+    INDEO_AUDIO = 0x0402
+    QDESIGN_MUSIC = 0x0450
+    ON2_VP7_AUDIO = 0x0500
+    ON2_VP6_AUDIO = 0x0501
+    VME_VMPCM = 0x0680
+    TPC = 0x0681
+    LIGHTWAVE_LOSSLESS = 0x08AE
+    OLIGSM = 0x1000
+    OLIADPCM = 0x1001
+    OLICELP = 0x1002
+    OLISBC = 0x1003
+    OLIOPR = 0x1004
+    LH_CODEC = 0x1100
+    LH_CODEC_CELP = 0x1101
+    LH_CODEC_SBC8 = 0x1102
+    LH_CODEC_SBC12 = 0x1103
+    LH_CODEC_SBC16 = 0x1104
+    NORRIS = 0x1400
+    ISIAUDIO_2 = 0x1401
+    SOUNDSPACE_MUSICOMPRESS = 0x1500
+    MPEG_ADTS_AAC = 0x1600
+    MPEG_RAW_AAC = 0x1601
+    MPEG_LOAS = 0x1602
+    NOKIA_MPEG_ADTS_AAC = 0x1608
+    NOKIA_MPEG_RAW_AAC = 0x1609
+    VODAFONE_MPEG_ADTS_AAC = 0x160A
+    VODAFONE_MPEG_RAW_AAC = 0x160B
+    MPEG_HEAAC = 0x1610
+    VOXWARE_RT24_SPEECH = 0x181C
+    SONICFOUNDRY_LOSSLESS = 0x1971
+    INNINGS_TELECOM_ADPCM = 0x1979
+    LUCENT_SX8300P = 0x1C07
+    LUCENT_SX5363S = 0x1C0C
+    CUSEEME = 0x1F03
+    NTCSOFT_ALF2CM_ACM = 0x1FC4
+    DVM = 0x2000
+    DTS2 = 0x2001
+    MAKEAVIS = 0x3313
+    DIVIO_MPEG4_AAC = 0x4143
+    NOKIA_ADAPTIVE_MULTIRATE = 0x4201
+    DIVIO_G726 = 0x4243
+    LEAD_SPEECH = 0x434C
+    LEAD_VORBIS = 0x564C
+    WAVPACK_AUDIO = 0x5756
+    OGG_VORBIS_MODE_1 = 0x674F
+    OGG_VORBIS_MODE_2 = 0x6750
+    OGG_VORBIS_MODE_3 = 0x6751
+    OGG_VORBIS_MODE_1_PLUS = 0x676F
+    OGG_VORBIS_MODE_2_PLUS = 0x6770
+    OGG_VORBIS_MODE_3_PLUS = 0x6771
+    ALAC = 0x6C61
+    _3COM_NBX = 0x7000  # Can't have leading digit
+    OPUS = 0x704F
+    FAAD_AAC = 0x706D
+    AMR_NB = 0x7361
+    AMR_WB = 0x7362
+    AMR_WP = 0x7363
+    GSM_AMR_CBR = 0x7A21
+    GSM_AMR_VBR_SID = 0x7A22
+    COMVERSE_INFOSYS_G723_1 = 0xA100
+    COMVERSE_INFOSYS_AVQSBC = 0xA101
+    COMVERSE_INFOSYS_SBC = 0xA102
+    SYMBOL_G729_A = 0xA103
+    VOICEAGE_AMR_WB = 0xA104
+    INGENIENT_G726 = 0xA105
+    MPEG4_AAC = 0xA106
+    ENCORE_G726 = 0xA107
+    ZOLL_ASAO = 0xA108
+    SPEEX_VOICE = 0xA109
+    VIANIX_MASC = 0xA10A
+    WM9_SPECTRUM_ANALYZER = 0xA10B
+    WMF_SPECTRUM_ANAYZER = 0xA10C
+    GSM_610 = 0xA10D
+    GSM_620 = 0xA10E
+    GSM_660 = 0xA10F
+    GSM_690 = 0xA110
+    GSM_ADAPTIVE_MULTIRATE_WB = 0xA111
+    POLYCOM_G722 = 0xA112
+    POLYCOM_G728 = 0xA113
+    POLYCOM_G729_A = 0xA114
+    POLYCOM_SIREN = 0xA115
+    GLOBAL_IP_ILBC = 0xA116
+    RADIOTIME_TIME_SHIFT_RADIO = 0xA117
+    NICE_ACA = 0xA118
+    NICE_ADPCM = 0xA119
+    VOCORD_G721 = 0xA11A
+    VOCORD_G726 = 0xA11B
+    VOCORD_G722_1 = 0xA11C
+    VOCORD_G728 = 0xA11D
+    VOCORD_G729 = 0xA11E
+    VOCORD_G729_A = 0xA11F
+    VOCORD_G723_1 = 0xA120
+    VOCORD_LBC = 0xA121
+    NICE_G728 = 0xA122
+    FRACE_TELECOM_G729 = 0xA123
+    CODIAN = 0xA124
+    FLAC = 0xF1AC
+    EXTENSIBLE = 0xFFFE
+    DEVELOPMENT = 0xFFFF
+
+
+KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT}
+
+
+def _raise_bad_format(format_tag):
+    try:
+        format_name = WAVE_FORMAT(format_tag).name
+    except ValueError:
+        format_name = f'{format_tag:#06x}'
+    raise ValueError(f"Unknown wave file format: {format_name}. Supported "
+                     "formats: " +
+                     ', '.join(x.name for x in KNOWN_WAVE_FORMATS))
+
+
+def _read_fmt_chunk(fid, is_big_endian):
+    """
+    Returns
+    -------
+    size : int
+        size of format subchunk in bytes (minus 8 for "fmt " and itself)
+    format_tag : int
+        PCM, float, or compressed format
+    channels : int
+        number of channels
+    fs : int
+        sampling frequency in samples per second
+    bytes_per_second : int
+        overall byte rate for the file
+    block_align : int
+        bytes per sample, including all channels
+    bit_depth : int
+        bits per sample
+
+    Notes
+    -----
+    Assumes file pointer is immediately after the 'fmt ' id
+    """
+    if is_big_endian:
+        fmt = '>'
+    else:
+        fmt = '<'
+
+    size = struct.unpack(fmt+'I', fid.read(4))[0]
+
+    if size < 16:
+        raise ValueError("Binary structure of wave file is not compliant")
+
+    res = struct.unpack(fmt+'HHIIHH', fid.read(16))
+    bytes_read = 16
+
+    format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res
+
+    if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2):
+        ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0]
+        bytes_read += 2
+        if ext_chunk_size >= 22:
+            extensible_chunk_data = fid.read(22)
+            bytes_read += 22
+            raw_guid = extensible_chunk_data[2+4:2+4+16]
+            # GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361)
+            # MS GUID byte order: first three groups are native byte order,
+            # rest is Big Endian
+            if is_big_endian:
+                tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71'
+            else:
+                tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71'
+            if raw_guid.endswith(tail):
+                format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0]
+        else:
+            raise ValueError("Binary structure of wave file is not compliant")
+
+    if format_tag not in KNOWN_WAVE_FORMATS:
+        _raise_bad_format(format_tag)
+
+    # move file pointer to next chunk
+    if size > bytes_read:
+        fid.read(size - bytes_read)
+
+    # fmt should always be 16, 18 or 40, but handle it just in case
+    _handle_pad_byte(fid, size)
+
+    if format_tag == WAVE_FORMAT.PCM:
+        if bytes_per_second != fs * block_align:
+            raise ValueError("WAV header is invalid: nAvgBytesPerSec must"
+                             " equal product of nSamplesPerSec and"
+                             " nBlockAlign, but file has nSamplesPerSec ="
+                             f" {fs}, nBlockAlign = {block_align}, and"
+                             f" nAvgBytesPerSec = {bytes_per_second}")
+
+    return (size, format_tag, channels, fs, bytes_per_second, block_align,
+            bit_depth)
+
+
+def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, is_rf64,
+                     block_align, mmap=False):
+    """
+    Notes
+    -----
+    Assumes file pointer is immediately after the 'data' id
+
+    It's possible to not use all available bits in a container, or to store
+    samples in a container bigger than necessary, so bytes_per_sample uses
+    the actual reported container size (nBlockAlign / nChannels).  Real-world
+    examples:
+
+    Adobe Audition's "24-bit packed int (type 1, 20-bit)"
+
+        nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20
+
+    http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav
+    is:
+
+        nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12
+
+    http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
+    gives an example of:
+
+        nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20
+    """
+    if is_big_endian:
+        fmt = '>'
+    else:
+        fmt = '<'
+
+    # Size of the data subchunk in bytes
+    if not is_rf64:
+        size = struct.unpack(fmt+'I', fid.read(4))[0]
+    else:
+        pos = fid.tell()
+        # chunk size is stored in global file header for RF64
+        fid.seek(28)
+        size = struct.unpack(' 1:
+        data = data.reshape(-1, channels)
+    return data
+
+
+def _skip_unknown_chunk(fid, is_big_endian):
+    if is_big_endian:
+        fmt = '>I'
+    else:
+        fmt = '>> from os.path import dirname, join as pjoin
+    >>> from scipy.io import wavfile
+    >>> import scipy.io
+
+    Get the filename for an example .wav file from the tests/data directory.
+
+    >>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data')
+    >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
+
+    Load the .wav file contents.
+
+    >>> samplerate, data = wavfile.read(wav_fname)
+    >>> print(f"number of channels = {data.shape[1]}")
+    number of channels = 2
+    >>> length = data.shape[0] / samplerate
+    >>> print(f"length = {length}s")
+    length = 0.01s
+
+    Plot the waveform.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> time = np.linspace(0., length, data.shape[0])
+    >>> plt.plot(time, data[:, 0], label="Left channel")
+    >>> plt.plot(time, data[:, 1], label="Right channel")
+    >>> plt.legend()
+    >>> plt.xlabel("Time [s]")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.show()
+
+    """
+    if hasattr(filename, 'read'):
+        fid = filename
+        mmap = False
+    else:
+        fid = open(filename, 'rb')
+
+    try:
+        file_size, is_big_endian, is_rf64 = _read_riff_chunk(fid)
+        fmt_chunk_received = False
+        data_chunk_received = False
+        while fid.tell() < file_size:
+            # read the next chunk
+            chunk_id = fid.read(4)
+
+            if not chunk_id:
+                if data_chunk_received:
+                    # End of file but data successfully read
+                    warnings.warn(
+                        f"Reached EOF prematurely; finished at {fid.tell():d} bytes, "
+                        f"expected {file_size:d} bytes from header.",
+                        WavFileWarning, stacklevel=2)
+                    break
+                else:
+                    raise ValueError("Unexpected end of file.")
+            elif len(chunk_id) < 4:
+                msg = f"Incomplete chunk ID: {repr(chunk_id)}"
+                # If we have the data, ignore the broken chunk
+                if fmt_chunk_received and data_chunk_received:
+                    warnings.warn(msg + ", ignoring it.", WavFileWarning,
+                                  stacklevel=2)
+                else:
+                    raise ValueError(msg)
+
+            if chunk_id == b'fmt ':
+                fmt_chunk_received = True
+                fmt_chunk = _read_fmt_chunk(fid, is_big_endian)
+                format_tag, channels, fs = fmt_chunk[1:4]
+                bit_depth = fmt_chunk[6]
+                block_align = fmt_chunk[5]
+            elif chunk_id == b'fact':
+                _skip_unknown_chunk(fid, is_big_endian)
+            elif chunk_id == b'data':
+                data_chunk_received = True
+                if not fmt_chunk_received:
+                    raise ValueError("No fmt chunk before data")
+                data = _read_data_chunk(fid, format_tag, channels, bit_depth,
+                                        is_big_endian, is_rf64, block_align, mmap)
+            elif chunk_id == b'LIST':
+                # Someday this could be handled properly but for now skip it
+                _skip_unknown_chunk(fid, is_big_endian)
+            elif chunk_id in {b'JUNK', b'Fake'}:
+                # Skip alignment chunks without warning
+                _skip_unknown_chunk(fid, is_big_endian)
+            else:
+                warnings.warn("Chunk (non-data) not understood, skipping it.",
+                              WavFileWarning, stacklevel=2)
+                _skip_unknown_chunk(fid, is_big_endian)
+    finally:
+        if not hasattr(filename, 'read'):
+            fid.close()
+        else:
+            fid.seek(0)
+
+    return fs, data
+
+
+def write(filename, rate, data):
+    """
+    Write a NumPy array as a WAV file.
+
+    Parameters
+    ----------
+    filename : string or open file handle
+        Output wav file.
+    rate : int
+        The sample rate (in samples/sec).
+    data : ndarray
+        A 1-D or 2-D NumPy array of either integer or float data-type.
+
+    Notes
+    -----
+    * Writes a simple uncompressed WAV file.
+    * To write multiple-channels, use a 2-D array of shape
+      (Nsamples, Nchannels).
+    * The bits-per-sample and PCM/float will be determined by the data-type.
+
+    Common data types: [1]_
+
+    =====================  ===========  ===========  =============
+         WAV format            Min          Max       NumPy dtype
+    =====================  ===========  ===========  =============
+    32-bit floating-point  -1.0         +1.0         float32
+    32-bit PCM             -2147483648  +2147483647  int32
+    16-bit PCM             -32768       +32767       int16
+    8-bit PCM              0            255          uint8
+    =====================  ===========  ===========  =============
+
+    Note that 8-bit PCM is unsigned.
+
+    References
+    ----------
+    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
+       Interface and Data Specifications 1.0", section "Data Format of the
+       Samples", August 1991
+       http://www.tactilemedia.com/info/MCI_Control_Info.html
+
+    Examples
+    --------
+    Create a 100Hz sine wave, sampled at 44100Hz.
+    Write to 16-bit PCM, Mono.
+
+    >>> from scipy.io.wavfile import write
+    >>> import numpy as np
+    >>> samplerate = 44100; fs = 100
+    >>> t = np.linspace(0., 1., samplerate)
+    >>> amplitude = np.iinfo(np.int16).max
+    >>> data = amplitude * np.sin(2. * np.pi * fs * t)
+    >>> write("example.wav", samplerate, data.astype(np.int16))
+
+    """
+    if hasattr(filename, 'write'):
+        fid = filename
+    else:
+        fid = open(filename, 'wb')
+
+    fs = rate
+
+    try:
+        dkind = data.dtype.kind
+        allowed_dtypes = ['float32', 'float64',
+                          'uint8', 'int16', 'int32', 'int64']
+        if data.dtype.name not in allowed_dtypes:
+            raise ValueError(f"Unsupported data type '{data.dtype}'")
+
+        header_data = b''
+
+        header_data += b'RIFF'
+        header_data += b'\x00\x00\x00\x00'
+        header_data += b'WAVE'
+
+        # fmt chunk
+        header_data += b'fmt '
+        if dkind == 'f':
+            format_tag = WAVE_FORMAT.IEEE_FLOAT
+        else:
+            format_tag = WAVE_FORMAT.PCM
+        if data.ndim == 1:
+            channels = 1
+        else:
+            channels = data.shape[1]
+        bit_depth = data.dtype.itemsize * 8
+        bytes_per_second = fs*(bit_depth // 8)*channels
+        block_align = channels * (bit_depth // 8)
+
+        fmt_chunk_data = struct.pack(' 0xFFFFFFFF
+        if is_rf64:
+            header_data = b''
+            header_data += b'RF64'
+            header_data += b'\xFF\xFF\xFF\xFF'
+            header_data += b'WAVE'
+            header_data += b'ds64'
+            # size of ds64 chunk
+            header_data += struct.pack('' or (data.dtype.byteorder == '=' and
+                                           sys.byteorder == 'big'):
+            data = data.byteswap()
+        _array_tofile(fid, data)
+
+        # Determine file size and place it in correct
+        # position at start of the file or the data chunk.
+        size = fid.tell()
+        if not is_rf64:
+            fid.seek(4)
+            fid.write(struct.pack('`__
+   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/python_embeded/Lib/site-packages/scipy/linalg/_basic.py b/python_embeded/Lib/site-packages/scipy/linalg/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d17b4af2ad674879490f3ee310a2eb3bee475e68
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_blas_subroutines.h b/python_embeded/Lib/site-packages/scipy/linalg/_blas_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..824f77ff1f2dd0dcfc92858a6717494a16491298
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..68a4f8529e54296b6a234d521acc9a371113d7c4
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..44e134c838b06681a199a5a86aea914b6cf61acd
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/python_embeded/Lib/site-packages/scipy/linalg/_cythonized_array_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..63f329d3ce7ca7e781f629726e9d71e96cdb5e5d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..164a99470b296796e25cf32f2882a675e46239e3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_cholesky.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..3364f0af92118b85a9b3319c141cdb24f90cbcd3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_cossin.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..8af026c809927f600b485a09d6c8a670b0fabdef
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_interpolative.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_interpolative.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..cb2e9b6a9503f7b4d8f8f8a25771d40309326384
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_interpolative.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_decomp_ldl.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..13896b5ff11b6d97c4d66ee73627582fa201c77c
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bbf2414cc9d38722f5271fae3cf88c40da24ac0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu_cython.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu_cython.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..bb94f93233c1cf0490fce2920e8e2eb8913d973f
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu_cython.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu_cython.pyi b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_lu_cython.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..7edb310b234ffb0076d9cb12d8567a125fb85076
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_polar.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..f41e8735336d11fc7c096d3460d1dbb79d5b90ab
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_qr.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..c78a4c4a87499bc030216897221ae9e31f84f017
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_qz.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_qz.py
new file mode 100644
index 0000000000000000000000000000000000000000..613faeef43e005b7241a062013fb468d4c57c16a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_schur.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf79837feb2b96672a947840f0f7fc0358f5dbee
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_svd.py b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..f16b1f05590d033705f6e173a9f494e4a220482a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_decomp_update.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_update.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..13765b1df356cb031edfae161becd2fa978f6cd9
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_decomp_update.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_expm_frechet.py b/python_embeded/Lib/site-packages/scipy/linalg/_expm_frechet.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3fe009da3ce0bf392138ace0ddab94136b5d96a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_fblas.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_fblas.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dcb4ef9741634a51ea712286723d7c032306d4ed
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_fblas.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_flapack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_flapack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..12c0c1a3447fa6bb3f5273325a4a0db0404ab0bc
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_flapack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_lapack_subroutines.h b/python_embeded/Lib/site-packages/scipy/linalg/_lapack_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbbf85428e965d23366c3278d35cce0242f09619
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_linalg_pythran.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_linalg_pythran.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dd99f4951fe3e1bdd4c1a3402438a0063208063e
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_linalg_pythran.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs.py b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b08eb2c6731bd55de533aa6aa1d664f49d5925
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_expm.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_expm.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9f99eb4bb4e8493612dd3f6e9ee032c5c9ecc47b
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_expm.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_expm.pyi b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_expm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1d77dfae40c3c0c84e331d1cddc80e986ec603ab
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
new file mode 100644
index 0000000000000000000000000000000000000000..0da2888beefba5797f5519ab5d795c4ff2884b17
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_sqrtm.py
new file mode 100644
index 0000000000000000000000000000000000000000..dce2f51adf982536f84394d19202cb72ac0d0c6d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..16a4500d72808d0ee656bf5a0fa458c3f23f7c12
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_misc.py b/python_embeded/Lib/site-packages/scipy/linalg/_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d828f6f449aa4b180488436912306294fb853f9
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_procrustes.py b/python_embeded/Lib/site-packages/scipy/linalg/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c1fcbe3ad80e7afabc7f338e1f43e68d4c12817
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_sketches.py b/python_embeded/Lib/site-packages/scipy/linalg/_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7f9597b6762a1c723ad8ad1154d46eb253d7b32
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_solve_toeplitz.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/_solve_toeplitz.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..fe51e36a4fa40a3fddea6b4f3ca50b791dd880ff
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/_solve_toeplitz.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/_solvers.py b/python_embeded/Lib/site-packages/scipy/linalg/_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9036710c301ad943caf71af84a4a81a278ff8ff
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_special_matrices.py b/python_embeded/Lib/site-packages/scipy/linalg/_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..938b22e8da69c112723ffdc1b50c65b09c95c86a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/_testutils.py b/python_embeded/Lib/site-packages/scipy/linalg/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0bcac0d3fde9d6646820b15c045659792a1236d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/basic.py b/python_embeded/Lib/site-packages/scipy/linalg/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..1faec2e4d198240a4ac547c5269af320d1d69218
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/blas.py b/python_embeded/Lib/site-packages/scipy/linalg/blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..04e08c0972e65fdc7449f8e78d59217efe70b5e8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..667ae8600fc9cae0758966be7715ae506c6097d4
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.pxd b/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7b9a7f2c568bbfc858231105d9a43396de43a518
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.pyx b/python_embeded/Lib/site-packages/scipy/linalg/cython_blas.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..c45629e612f6c56f4f9029834aaae162bc650e13
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..0d8cb94687fbf31d8d4ec31b2e97cae7eeb0ff62
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.pxd b/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..300673823fa0f476248507eebea3d1526542b4a0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.pyx b/python_embeded/Lib/site-packages/scipy/linalg/cython_lapack.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..6add8cf8f9dcec0c105fd6085b4bca67d1c56ceb
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d5a374fe6a9c26c7ea13a3e8bbee0f36ea744af
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp_cholesky.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..c96e715e858cfac8de5bb336d5218fcb2f56ed12
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp_lu.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..0379a392204a31f1e4bc985ba45ed623b67917a8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp_qr.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..163e14cf40f64cf2704d00097329f8fa676bec94
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp_schur.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4cf5cd379f56379cccc4a283dfcbc2c1087c15e
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/decomp_svd.py b/python_embeded/Lib/site-packages/scipy/linalg/decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9b276075bd1dc0dd2cb5b4b8754dda9e4bfbad1
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/interpolative.py b/python_embeded/Lib/site-packages/scipy/linalg/interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..d15889fb1e564f51e7585c61c63b3cb296c6bb26
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/lapack.py b/python_embeded/Lib/site-packages/scipy/linalg/lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10c23c84bb7b59aba7bba319d0e2b140ab4eac3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/matfuncs.py b/python_embeded/Lib/site-packages/scipy/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..666dda9b513f19b9b12ae74d5c95412091bf8789
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/misc.py b/python_embeded/Lib/site-packages/scipy/linalg/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..013c9eb4139c2e016d9c6071e9db7331df9c727e
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/linalg/special_matrices.py b/python_embeded/Lib/site-packages/scipy/linalg/special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae2d34580301e95939350798243d731d81a6949c
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/misc/__init__.py b/python_embeded/Lib/site-packages/scipy/misc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..83ade1f84fdb777cf6c34f102c53f272aca849d5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/misc/__init__.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/python_embeded/Lib/site-packages/scipy/misc/common.py b/python_embeded/Lib/site-packages/scipy/misc/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..abb5e56dff997dfcf692701ce07a13623cb09c92
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/misc/common.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.common is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/python_embeded/Lib/site-packages/scipy/misc/doccer.py b/python_embeded/Lib/site-packages/scipy/misc/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc5b34b7042c24ba203471c2fd23e4303837aeec
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/misc/doccer.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.doccer is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/__init__.py b/python_embeded/Lib/site-packages/scipy/ndimage/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5da888601c27957da8aed550615200e34a1abd0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_ctest.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/ndimage/_ctest.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..27363c1b051dd4fa82d1031783ac93a3a8d14433
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/ndimage/_ctest.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/_cytest.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/ndimage/_cytest.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..504348d055793a7756484e7d1bf50978b13be6e8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/ndimage/_cytest.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/_delegators.py b/python_embeded/Lib/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f4b151ee43827d4d1009ccd6f7ed6f16cc3af35
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_filters.py b/python_embeded/Lib/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..5247bb9110c609ae43049301f8cf6fc76863753b
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_fourier.py b/python_embeded/Lib/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..79c976a948978bb6106fd91c22be80a947fe0ccb
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_interpolation.py b/python_embeded/Lib/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f11bbf649b0766e65f821c4b90df36c20660c640
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_measurements.py b/python_embeded/Lib/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..321476af49f2b9d9dd8c78d49c723d10ca345f29
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_morphology.py b/python_embeded/Lib/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ff162df2817065a11a83fcea1fd678e8eb94f0d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_nd_image.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/ndimage/_nd_image.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dc8bb36910b7fab6491a1ce73c00d92997faa8b8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/ndimage/_nd_image.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/_ndimage_api.py b/python_embeded/Lib/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1529ab9cc9f49ad0531213feeba0653e772dac45
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_ni_docstrings.py b/python_embeded/Lib/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..d091428824d1ced6a5ba98d7cd1dbce7ad06dde9
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_ni_label.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/ndimage/_ni_label.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..846dadb4dbab568daf2b71cd45751f7ade9f1dde
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/ndimage/_ni_label.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/_ni_support.py b/python_embeded/Lib/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3cc13fdb3f8d08630877004de324f4d99a2dff3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/_rank_filter_1d.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/ndimage/_rank_filter_1d.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..b46f0a181b0e29db3563eee035b0c3e11ff338f0
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/ndimage/_rank_filter_1d.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/ndimage/_support_alternative_backends.py b/python_embeded/Lib/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b5db3d27eedbeacb2c5ad43ec2e16d2e9bc8e4a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/filters.py b/python_embeded/Lib/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..a110ed99267b180e1168fb04a32a4db68b303a6b
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/fourier.py b/python_embeded/Lib/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f7ddce75db00de09d354c14aa42eb6ef8bd093a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/interpolation.py b/python_embeded/Lib/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..58881c645b681cbd0f2c38f5e5215a17bdcc984f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/measurements.py b/python_embeded/Lib/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4c0ede2eeafa2455fe67294fe0823becb1689f0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/ndimage/morphology.py b/python_embeded/Lib/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f94e2c6d9a00672330973fbda3fefc5a78fead1
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/__init__.py b/python_embeded/Lib/site-packages/scipy/odr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1f7851339db2a8c88e4a9992027a72f62dae818
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/__odrpack.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/odr/__odrpack.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..f5ecba43bdb39b1eeb37e9ff820cc7593dcf0704
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/odr/__odrpack.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/odr/_add_newdocs.py b/python_embeded/Lib/site-packages/scipy/odr/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..54f74a8b3463ea52d890f09bce6e5e72c647c374
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/_models.py b/python_embeded/Lib/site-packages/scipy/odr/_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..b56122285c6ad3443a4a5367cd4bf53a5bac3f30
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/_odrpack.py b/python_embeded/Lib/site-packages/scipy/odr/_odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..579aabaf20133e4f7c043428988f6881e4be020f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/models.py b/python_embeded/Lib/site-packages/scipy/odr/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf15148d35e840e96aa8f5e463060b3988e2428
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/odr/odrpack.py b/python_embeded/Lib/site-packages/scipy/odr/odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..334998b4effdaa240c97a8b751ae4baf67cabd21
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_basinhopping.py b/python_embeded/Lib/site-packages/scipy/optimize/_basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..294d39d6eba892ca0e0d69b502e1b81d1f5c8ea6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/_basinhopping.py
@@ -0,0 +1,735 @@
+"""
+basinhopping: The basinhopping global optimization algorithm
+"""
+import numpy as np
+import math
+import inspect
+import scipy.optimize
+from scipy._lib._util import check_random_state, _transition_to_rng
+
+__all__ = ['basinhopping']
+
+
+_params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY),
+           inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY))
+_new_accept_test_signature = inspect.Signature(parameters=_params)
+
+
+class Storage:
+    """
+    Class used to store the lowest energy structure
+    """
+    def __init__(self, minres):
+        self._add(minres)
+
+    def _add(self, minres):
+        self.minres = minres
+        self.minres.x = np.copy(minres.x)
+
+    def update(self, minres):
+        if minres.success and (minres.fun < self.minres.fun
+                               or not self.minres.success):
+            self._add(minres)
+            return True
+        else:
+            return False
+
+    def get_lowest(self):
+        return self.minres
+
+
+class BasinHoppingRunner:
+    """This class implements the core of the basinhopping algorithm.
+
+    x0 : ndarray
+        The starting coordinates.
+    minimizer : callable
+        The local minimizer, with signature ``result = minimizer(x)``.
+        The return value is an `optimize.OptimizeResult` object.
+    step_taking : callable
+        This function displaces the coordinates randomly. Signature should
+        be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
+    accept_tests : list of callables
+        Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
+        `x_old`. These tests will be used to judge whether or not to accept
+        the step. The acceptable return values are True, False, or ``"force
+        accept"``. If any of the tests return False then the step is rejected.
+        If ``"force accept"``, then this will override any other tests in
+        order to accept the step. This can be used, for example, to forcefully
+        escape from a local minimum that ``basinhopping`` is trapped in.
+    disp : bool, optional
+        Display status messages.
+
+    """
+    def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False):
+        self.x = np.copy(x0)
+        self.minimizer = minimizer
+        self.step_taking = step_taking
+        self.accept_tests = accept_tests
+        self.disp = disp
+
+        self.nstep = 0
+
+        # initialize return object
+        self.res = scipy.optimize.OptimizeResult()
+        self.res.minimization_failures = 0
+
+        # do initial minimization
+        minres = minimizer(self.x)
+        if not minres.success:
+            self.res.minimization_failures += 1
+            if self.disp:
+                print("warning: basinhopping: local minimization failure")
+        self.x = np.copy(minres.x)
+        self.energy = minres.fun
+        self.incumbent_minres = minres  # best minimize result found so far
+        if self.disp:
+            print("basinhopping step %d: f %g" % (self.nstep, self.energy))
+
+        # initialize storage class
+        self.storage = Storage(minres)
+
+        if hasattr(minres, "nfev"):
+            self.res.nfev = minres.nfev
+        if hasattr(minres, "njev"):
+            self.res.njev = minres.njev
+        if hasattr(minres, "nhev"):
+            self.res.nhev = minres.nhev
+
+    def _monte_carlo_step(self):
+        """Do one Monte Carlo iteration
+
+        Randomly displace the coordinates, minimize, and decide whether
+        or not to accept the new coordinates.
+        """
+        # Take a random step.  Make a copy of x because the step_taking
+        # algorithm might change x in place
+        x_after_step = np.copy(self.x)
+        x_after_step = self.step_taking(x_after_step)
+
+        # do a local minimization
+        minres = self.minimizer(x_after_step)
+        x_after_quench = minres.x
+        energy_after_quench = minres.fun
+        if not minres.success:
+            self.res.minimization_failures += 1
+            if self.disp:
+                print("warning: basinhopping: local minimization failure")
+        if hasattr(minres, "nfev"):
+            self.res.nfev += minres.nfev
+        if hasattr(minres, "njev"):
+            self.res.njev += minres.njev
+        if hasattr(minres, "nhev"):
+            self.res.nhev += minres.nhev
+
+        # accept the move based on self.accept_tests. If any test is False,
+        # then reject the step.  If any test returns the special string
+        # 'force accept', then accept the step regardless. This can be used
+        # to forcefully escape from a local minimum if normal basin hopping
+        # steps are not sufficient.
+        accept = True
+        for test in self.accept_tests:
+            if inspect.signature(test) == _new_accept_test_signature:
+                testres = test(res_new=minres, res_old=self.incumbent_minres)
+            else:
+                testres = test(f_new=energy_after_quench, x_new=x_after_quench,
+                               f_old=self.energy, x_old=self.x)
+
+            if testres == 'force accept':
+                accept = True
+                break
+            elif testres is None:
+                raise ValueError("accept_tests must return True, False, or "
+                                 "'force accept'")
+            elif not testres:
+                accept = False
+
+        # Report the result of the acceptance test to the take step class.
+        # This is for adaptive step taking
+        if hasattr(self.step_taking, "report"):
+            self.step_taking.report(accept, f_new=energy_after_quench,
+                                    x_new=x_after_quench, f_old=self.energy,
+                                    x_old=self.x)
+
+        return accept, minres
+
+    def one_cycle(self):
+        """Do one cycle of the basinhopping algorithm
+        """
+        self.nstep += 1
+        new_global_min = False
+
+        accept, minres = self._monte_carlo_step()
+
+        if accept:
+            self.energy = minres.fun
+            self.x = np.copy(minres.x)
+            self.incumbent_minres = minres  # best minimize result found so far
+            new_global_min = self.storage.update(minres)
+
+        # print some information
+        if self.disp:
+            self.print_report(minres.fun, accept)
+            if new_global_min:
+                print("found new global minimum on step %d with function"
+                      " value %g" % (self.nstep, self.energy))
+
+        # save some variables as BasinHoppingRunner attributes
+        self.xtrial = minres.x
+        self.energy_trial = minres.fun
+        self.accept = accept
+
+        return new_global_min
+
+    def print_report(self, energy_trial, accept):
+        """print a status update"""
+        minres = self.storage.get_lowest()
+        print("basinhopping step %d: f %g trial_f %g accepted %d "
+              " lowest_f %g" % (self.nstep, self.energy, energy_trial,
+                                accept, minres.fun))
+
+
+class AdaptiveStepsize:
+    """
+    Class to implement adaptive stepsize.
+
+    This class wraps the step taking class and modifies the stepsize to
+    ensure the true acceptance rate is as close as possible to the target.
+
+    Parameters
+    ----------
+    takestep : callable
+        The step taking routine.  Must contain modifiable attribute
+        takestep.stepsize
+    accept_rate : float, optional
+        The target step acceptance rate
+    interval : int, optional
+        Interval for how often to update the stepsize
+    factor : float, optional
+        The step size is multiplied or divided by this factor upon each
+        update.
+    verbose : bool, optional
+        Print information about each update
+
+    """
+    def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9,
+                 verbose=True):
+        self.takestep = takestep
+        self.target_accept_rate = accept_rate
+        self.interval = interval
+        self.factor = factor
+        self.verbose = verbose
+
+        self.nstep = 0
+        self.nstep_tot = 0
+        self.naccept = 0
+
+    def __call__(self, x):
+        return self.take_step(x)
+
+    def _adjust_step_size(self):
+        old_stepsize = self.takestep.stepsize
+        accept_rate = float(self.naccept) / self.nstep
+        if accept_rate > self.target_accept_rate:
+            # We're accepting too many steps. This generally means we're
+            # trapped in a basin. Take bigger steps.
+            self.takestep.stepsize /= self.factor
+        else:
+            # We're not accepting enough steps. Take smaller steps.
+            self.takestep.stepsize *= self.factor
+        if self.verbose:
+            print(f"adaptive stepsize: acceptance rate {accept_rate:f} target "
+                  f"{self.target_accept_rate:f} new stepsize "
+                  f"{self.takestep.stepsize:g} old stepsize {old_stepsize:g}")
+
+    def take_step(self, x):
+        self.nstep += 1
+        self.nstep_tot += 1
+        if self.nstep % self.interval == 0:
+            self._adjust_step_size()
+        return self.takestep(x)
+
+    def report(self, accept, **kwargs):
+        "called by basinhopping to report the result of the step"
+        if accept:
+            self.naccept += 1
+
+
+class RandomDisplacement:
+    """Add a random displacement of maximum size `stepsize` to each coordinate.
+
+    Calling this updates `x` in-place.
+
+    Parameters
+    ----------
+    stepsize : float, optional
+        Maximum stepsize in any dimension
+    rng : {None, int, `numpy.random.Generator`}, optional
+        Random number generator
+    """
+
+    def __init__(self, stepsize=0.5, rng=None):
+        self.stepsize = stepsize
+        self.rng = check_random_state(rng)
+
+    def __call__(self, x):
+        x += self.rng.uniform(-self.stepsize, self.stepsize,
+                              np.shape(x))
+        return x
+
+
+class MinimizerWrapper:
+    """
+    wrap a minimizer function as a minimizer class
+    """
+    def __init__(self, minimizer, func=None, **kwargs):
+        self.minimizer = minimizer
+        self.func = func
+        self.kwargs = kwargs
+
+    def __call__(self, x0):
+        if self.func is None:
+            return self.minimizer(x0, **self.kwargs)
+        else:
+            return self.minimizer(self.func, x0, **self.kwargs)
+
+
+class Metropolis:
+    """Metropolis acceptance criterion.
+
+    Parameters
+    ----------
+    T : float
+        The "temperature" parameter for the accept or reject criterion.
+    rng : {None, int, `numpy.random.Generator`}, optional
+        Random number generator used for acceptance test.
+
+    """
+
+    def __init__(self, T, rng=None):
+        # Avoid ZeroDivisionError since "MBH can be regarded as a special case
+        # of the BH framework with the Metropolis criterion, where temperature
+        # T = 0." (Reject all steps that increase energy.)
+        self.beta = 1.0 / T if T != 0 else float('inf')
+        self.rng = check_random_state(rng)
+
+    def accept_reject(self, res_new, res_old):
+        """
+        Assuming the local search underlying res_new was successful:
+        If new energy is lower than old, it will always be accepted.
+        If new is higher than old, there is a chance it will be accepted,
+        less likely for larger differences.
+        """
+        with np.errstate(invalid='ignore'):
+            # The energy values being fed to Metropolis are 1-length arrays, and if
+            # they are equal, their difference is 0, which gets multiplied by beta,
+            # which is inf, and array([0]) * float('inf') causes
+            #
+            # RuntimeWarning: invalid value encountered in multiply
+            #
+            # Ignore this warning so when the algorithm is on a flat plane, it always
+            # accepts the step, to try to move off the plane.
+            prod = -(res_new.fun - res_old.fun) * self.beta
+            w = math.exp(min(0, prod))
+
+        rand = self.rng.uniform()
+        return w >= rand and (res_new.success or not res_old.success)
+
+    def __call__(self, *, res_new, res_old):
+        """
+        f_new and f_old are mandatory in kwargs
+        """
+        return bool(self.accept_reject(res_new, res_old))
+
+
+@_transition_to_rng("seed", position_num=12, replace_doc=True)
+def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
+                 minimizer_kwargs=None, take_step=None, accept_test=None,
+                 callback=None, interval=50, disp=False, niter_success=None,
+                 rng=None, *, target_accept_rate=0.5, stepwise_factor=0.9):
+    """Find the global minimum of a function using the basin-hopping algorithm.
+
+    Basin-hopping is a two-phase method that combines a global stepping
+    algorithm with local minimization at each step. Designed to mimic
+    the natural process of energy minimization of clusters of atoms, it works
+    well for similar problems with "funnel-like, but rugged" energy landscapes
+    [5]_.
+
+    As the step-taking, step acceptance, and minimization methods are all
+    customizable, this function can also be used to implement other two-phase
+    methods.
+
+    Parameters
+    ----------
+    func : callable ``f(x, *args)``
+        Function to be optimized.  ``args`` can be passed as an optional item
+        in the dict `minimizer_kwargs`
+    x0 : array_like
+        Initial guess.
+    niter : integer, optional
+        The number of basin-hopping iterations. There will be a total of
+        ``niter + 1`` runs of the local minimizer.
+    T : float, optional
+        The "temperature" parameter for the acceptance or rejection criterion.
+        Higher "temperatures" mean that larger jumps in function value will be
+        accepted.  For best results `T` should be comparable to the
+        separation (in function value) between local minima.
+    stepsize : float, optional
+        Maximum step size for use in the random displacement.
+    minimizer_kwargs : dict, optional
+        Extra keyword arguments to be passed to the local minimizer
+        `scipy.optimize.minimize` Some important options could be:
+
+        method : str
+            The minimization method (e.g. ``"L-BFGS-B"``)
+        args : tuple
+            Extra arguments passed to the objective function (`func`) and
+            its derivatives (Jacobian, Hessian).
+
+    take_step : callable ``take_step(x)``, optional
+        Replace the default step-taking routine with this routine. The default
+        step-taking routine is a random displacement of the coordinates, but
+        other step-taking algorithms may be better for some systems.
+        `take_step` can optionally have the attribute ``take_step.stepsize``.
+        If this attribute exists, then `basinhopping` will adjust
+        ``take_step.stepsize`` in order to try to optimize the global minimum
+        search.
+    accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
+        Define a test which will be used to judge whether to accept the
+        step. This will be used in addition to the Metropolis test based on
+        "temperature" `T`. The acceptable return values are True,
+        False, or ``"force accept"``. If any of the tests return False
+        then the step is rejected. If the latter, then this will override any
+        other tests in order to accept the step. This can be used, for example,
+        to forcefully escape from a local minimum that `basinhopping` is
+        trapped in.
+    callback : callable, ``callback(x, f, accept)``, optional
+        A callback function which will be called for all minima found. ``x``
+        and ``f`` are the coordinates and function value of the trial minimum,
+        and ``accept`` is whether that minimum was accepted. This can
+        be used, for example, to save the lowest N minima found. Also,
+        `callback` can be used to specify a user defined stop criterion by
+        optionally returning True to stop the `basinhopping` routine.
+    interval : integer, optional
+        interval for how often to update the `stepsize`
+    disp : bool, optional
+        Set to True to print status messages
+    niter_success : integer, optional
+        Stop the run if the global minimum candidate remains the same for this
+        number of iterations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        The random numbers generated only affect the default Metropolis
+        `accept_test` and the default `take_step`. If you supply your own
+        `take_step` and `accept_test`, and these functions use random
+        number generation, then those functions are responsible for the state
+        of their random number generator.
+    target_accept_rate : float, optional
+        The target acceptance rate that is used to adjust the `stepsize`.
+        If the current acceptance rate is greater than the target,
+        then the `stepsize` is increased. Otherwise, it is decreased.
+        Range is (0, 1). Default is 0.5.
+
+        .. versionadded:: 1.8.0
+
+    stepwise_factor : float, optional
+        The `stepsize` is multiplied or divided by this stepwise factor upon
+        each update. Range is (0, 1). Default is 0.9.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    res : OptimizeResult
+        The optimization result represented as a `OptimizeResult` object.
+        Important attributes are: ``x`` the solution array, ``fun`` the value
+        of the function at the solution, and ``message`` which describes the
+        cause of the termination. The ``OptimizeResult`` object returned by the
+        selected minimizer at the lowest minimum is also contained within this
+        object and can be accessed through the ``lowest_optimization_result``
+        attribute.  See `OptimizeResult` for a description of other attributes.
+
+    See Also
+    --------
+    minimize :
+        The local minimization function called once for each basinhopping step.
+        `minimizer_kwargs` is passed to this routine.
+
+    Notes
+    -----
+    Basin-hopping is a stochastic algorithm which attempts to find the global
+    minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
+    [4]_. The algorithm in its current form was described by David Wales and
+    Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
+
+    The algorithm is iterative with each cycle composed of the following
+    features
+
+    1) random perturbation of the coordinates
+
+    2) local minimization
+
+    3) accept or reject the new coordinates based on the minimized function
+       value
+
+    The acceptance test used here is the Metropolis criterion of standard Monte
+    Carlo algorithms, although there are many other possibilities [3]_.
+
+    This global minimization method has been shown to be extremely efficient
+    for a wide variety of problems in physics and chemistry. It is
+    particularly useful when the function has many minima separated by large
+    barriers. See the `Cambridge Cluster Database
+    `_ for databases of molecular
+    systems that have been optimized primarily using basin-hopping. This
+    database includes minimization problems exceeding 300 degrees of freedom.
+
+    See the free software program `GMIN `_
+    for a Fortran implementation of basin-hopping. This implementation has many
+    variations of the procedure described above, including more
+    advanced step taking algorithms and alternate acceptance criterion.
+
+    For stochastic global optimization there is no way to determine if the true
+    global minimum has actually been found. Instead, as a consistency check,
+    the algorithm can be run from a number of different random starting points
+    to ensure the lowest minimum found in each example has converged to the
+    global minimum. For this reason, `basinhopping` will by default simply
+    run for the number of iterations `niter` and return the lowest minimum
+    found. It is left to the user to ensure that this is in fact the global
+    minimum.
+
+    Choosing `stepsize`:  This is a crucial parameter in `basinhopping` and
+    depends on the problem being solved. The step is chosen uniformly in the
+    region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
+    should be comparable to the typical separation (in argument values) between
+    local minima of the function being optimized. `basinhopping` will, by
+    default, adjust `stepsize` to find an optimal value, but this may take
+    many iterations. You will get quicker results if you set a sensible
+    initial value for ``stepsize``.
+
+    Choosing `T`: The parameter `T` is the "temperature" used in the
+    Metropolis criterion. Basinhopping steps are always accepted if
+    ``func(xnew) < func(xold)``. Otherwise, they are accepted with
+    probability::
+
+        exp( -(func(xnew) - func(xold)) / T )
+
+    So, for best results, `T` should to be comparable to the typical
+    difference (in function values) between local minima. (The height of
+    "walls" between local minima is irrelevant.)
+
+    If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
+    steps that increase energy are rejected.
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
+        Cambridge, UK.
+    .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
+        the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
+        110 Atoms.  Journal of Physical Chemistry A, 1997, 101, 5111.
+    .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
+        multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
+        1987, 84, 6611.
+    .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
+        crystals, and biomolecules, Science, 1999, 285, 1368.
+    .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
+        a General and Versatile Optimization Framework for the Characterization
+        of Biological Macromolecules, Advances in Artificial Intelligence,
+        Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`
+
+    Examples
+    --------
+    The following example is a 1-D minimization problem, with many
+    local minima superimposed on a parabola.
+
+    >>> import numpy as np
+    >>> from scipy.optimize import basinhopping
+    >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
+    >>> x0 = [1.]
+
+    Basinhopping, internally, uses a local minimization algorithm. We will use
+    the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
+    use and how to set up that minimizer. This parameter will be passed to
+    `scipy.optimize.minimize`.
+
+    >>> minimizer_kwargs = {"method": "BFGS"}
+    >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
+    ...                    niter=200)
+    >>> # the global minimum is:
+    >>> ret.x, ret.fun
+    -0.1951, -1.0009
+
+    Next consider a 2-D minimization problem. Also, this time, we
+    will use gradient information to significantly speed up the search.
+
+    >>> def func2d(x):
+    ...     f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
+    ...                                                            0.2) * x[0]
+    ...     df = np.zeros(2)
+    ...     df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
+    ...     df[1] = 2. * x[1] + 0.2
+    ...     return f, df
+
+    We'll also use a different local minimization algorithm. Also, we must tell
+    the minimizer that our function returns both energy and gradient (Jacobian).
+
+    >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
+    >>> x0 = [1.0, 1.0]
+    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+    ...                    niter=200)
+    >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+    ...                                                           ret.x[1],
+    ...                                                           ret.fun))
+    global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+    Here is an example using a custom step-taking routine. Imagine you want
+    the first coordinate to take larger steps than the rest of the coordinates.
+    This can be implemented like so:
+
+    >>> class MyTakeStep:
+    ...    def __init__(self, stepsize=0.5):
+    ...        self.stepsize = stepsize
+    ...        self.rng = np.random.default_rng()
+    ...    def __call__(self, x):
+    ...        s = self.stepsize
+    ...        x[0] += self.rng.uniform(-2.*s, 2.*s)
+    ...        x[1:] += self.rng.uniform(-s, s, x[1:].shape)
+    ...        return x
+
+    Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
+    of `stepsize` to optimize the search. We'll use the same 2-D function as
+    before
+
+    >>> mytakestep = MyTakeStep()
+    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+    ...                    niter=200, take_step=mytakestep)
+    >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+    ...                                                           ret.x[1],
+    ...                                                           ret.fun))
+    global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+    Now, let's do an example using a custom callback function which prints the
+    value of every minimum found
+
+    >>> def print_fun(x, f, accepted):
+    ...         print("at minimum %.4f accepted %d" % (f, int(accepted)))
+
+    We'll run it for only 10 basinhopping steps this time.
+
+    >>> rng = np.random.default_rng()
+    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+    ...                    niter=10, callback=print_fun, rng=rng)
+    at minimum 0.4159 accepted 1
+    at minimum -0.4317 accepted 1
+    at minimum -1.0109 accepted 1
+    at minimum -0.9073 accepted 1
+    at minimum -0.4317 accepted 0
+    at minimum -0.1021 accepted 1
+    at minimum -0.7425 accepted 1
+    at minimum -0.9073 accepted 1
+    at minimum -0.4317 accepted 0
+    at minimum -0.7425 accepted 1
+    at minimum -0.9073 accepted 1
+
+    The minimum at -1.0109 is actually the global minimum, found already on the
+    8th iteration.
+
+    """ # numpy/numpydoc#87  # noqa: E501
+    if target_accept_rate <= 0. or target_accept_rate >= 1.:
+        raise ValueError('target_accept_rate has to be in range (0, 1)')
+    if stepwise_factor <= 0. or stepwise_factor >= 1.:
+        raise ValueError('stepwise_factor has to be in range (0, 1)')
+
+    x0 = np.array(x0)
+
+    # set up the np.random generator
+    rng = check_random_state(rng)
+
+    # set up minimizer
+    if minimizer_kwargs is None:
+        minimizer_kwargs = dict()
+    wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
+                                         **minimizer_kwargs)
+
+    # set up step-taking algorithm
+    if take_step is not None:
+        if not callable(take_step):
+            raise TypeError("take_step must be callable")
+        # if take_step.stepsize exists then use AdaptiveStepsize to control
+        # take_step.stepsize
+        if hasattr(take_step, "stepsize"):
+            take_step_wrapped = AdaptiveStepsize(
+                take_step, interval=interval,
+                accept_rate=target_accept_rate,
+                factor=stepwise_factor,
+                verbose=disp)
+        else:
+            take_step_wrapped = take_step
+    else:
+        # use default
+        displace = RandomDisplacement(stepsize=stepsize, rng=rng)
+        take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
+                                             accept_rate=target_accept_rate,
+                                             factor=stepwise_factor,
+                                             verbose=disp)
+
+    # set up accept tests
+    accept_tests = []
+    if accept_test is not None:
+        if not callable(accept_test):
+            raise TypeError("accept_test must be callable")
+        accept_tests = [accept_test]
+
+    # use default
+    metropolis = Metropolis(T, rng=rng)
+    accept_tests.append(metropolis)
+
+    if niter_success is None:
+        niter_success = niter + 2
+
+    bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
+                            accept_tests, disp=disp)
+
+    # The wrapped minimizer is called once during construction of
+    # BasinHoppingRunner, so run the callback
+    if callable(callback):
+        callback(bh.storage.minres.x, bh.storage.minres.fun, True)
+
+    # start main iteration loop
+    count, i = 0, 0
+    message = ["requested number of basinhopping iterations completed"
+               " successfully"]
+    for i in range(niter):
+        new_global_min = bh.one_cycle()
+
+        if callable(callback):
+            # should we pass a copy of x?
+            val = callback(bh.xtrial, bh.energy_trial, bh.accept)
+            if val is not None:
+                if val:
+                    message = ["callback function requested stop early by"
+                               "returning True"]
+                    break
+
+        count += 1
+        if new_global_min:
+            count = 0
+        elif count > niter_success:
+            message = ["success condition satisfied"]
+            break
+
+    # prepare return object
+    res = bh.res
+    res.lowest_optimization_result = bh.storage.get_lowest()
+    res.x = np.copy(res.lowest_optimization_result.x)
+    res.fun = res.lowest_optimization_result.fun
+    res.message = message
+    res.nit = i + 1
+    res.success = res.lowest_optimization_result.success
+    return res
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_bglu_dense.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_bglu_dense.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..af1b5211016a14b6de2fad0de19052bb4d1700db
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_bglu_dense.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_bracket.py b/python_embeded/Lib/site-packages/scipy/optimize/_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..3095fa5f61e32acb702e050376346ee257ddf172
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_chandrupatla.py b/python_embeded/Lib/site-packages/scipy/optimize/_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c9cccdc463a11413d18e056bdc79f50b8d10d25
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_cobyla.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_cobyla.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..510fd1cbd61565c8950b986b1980cd77dfdeaae9
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_cobyla.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_cobyla_py.py b/python_embeded/Lib/site-packages/scipy/optimize/_cobyla_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..876db14b3017eb28fed570bdddf4609ef2f80cc1
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_cobyqa_py.py b/python_embeded/Lib/site-packages/scipy/optimize/_cobyqa_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..19b1687ec211ef5239b5fe6ec3ecfea96c592989
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_constraints.py b/python_embeded/Lib/site-packages/scipy/optimize/_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..2159f30da4ceacfbeb60e86fecbe9377f7d786e1
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_cython_nnls.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_cython_nnls.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..cdc4983c84b19ca2ad0b5006a8e98d73741bc159
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_cython_nnls.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_dcsrch.py b/python_embeded/Lib/site-packages/scipy/optimize/_dcsrch.py
new file mode 100644
index 0000000000000000000000000000000000000000..314f607371f2bf43477c96fada1ba91e8fa7b0e8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_differentiable_functions.py b/python_embeded/Lib/site-packages/scipy/optimize/_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e4611949a782e212708d09f59476c160278778a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_differentialevolution.py b/python_embeded/Lib/site-packages/scipy/optimize/_differentialevolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..80e643f3dab7aff559b2b62689c2c6e93130787f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/_differentialevolution.py
@@ -0,0 +1,1969 @@
+"""
+differential_evolution: The differential evolution global optimization algorithm
+Added by Andrew Nelson 2014
+"""
+import warnings
+
+import numpy as np
+from scipy.optimize import OptimizeResult, minimize
+from scipy.optimize._optimize import _status_message, _wrap_callback
+from scipy._lib._util import (check_random_state, MapWrapper, _FunctionWrapper,
+                              rng_integers, _transition_to_rng)
+
+from scipy.optimize._constraints import (Bounds, new_bounds_to_old,
+                                         NonlinearConstraint, LinearConstraint)
+from scipy.sparse import issparse
+
+__all__ = ['differential_evolution']
+
+
+_MACHEPS = np.finfo(np.float64).eps
+
+
+@_transition_to_rng("seed", position_num=9)
+def differential_evolution(func, bounds, args=(), strategy='best1bin',
+                           maxiter=1000, popsize=15, tol=0.01,
+                           mutation=(0.5, 1), recombination=0.7, rng=None,
+                           callback=None, disp=False, polish=True,
+                           init='latinhypercube', atol=0, updating='immediate',
+                           workers=1, constraints=(), x0=None, *,
+                           integrality=None, vectorized=False):
+    r"""Finds the global minimum of a multivariate function.
+
+    The differential evolution method [1]_ is stochastic in nature. It does
+    not use gradient methods to find the minimum, and can search large areas
+    of candidate space, but often requires larger numbers of function
+    evaluations than conventional gradient-based techniques.
+
+    The algorithm is due to Storn and Price [2]_.
+
+    Parameters
+    ----------
+    func : callable
+        The objective function to be minimized. Must be in the form
+        ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+        and ``args`` is a tuple of any additional fixed parameters needed to
+        completely specify the function. The number of parameters, N, is equal
+        to ``len(x)``.
+    bounds : sequence or `Bounds`
+        Bounds for variables. There are two ways to specify the bounds:
+
+        1. Instance of `Bounds` class.
+        2. ``(min, max)`` pairs for each element in ``x``, defining the
+           finite lower and upper bounds for the optimizing argument of
+           `func`.
+
+        The total number of bounds is used to determine the number of
+        parameters, N. If there are parameters whose bounds are equal the total
+        number of free parameters is ``N - N_equal``.
+
+    args : tuple, optional
+        Any additional fixed parameters needed to
+        completely specify the objective function.
+    strategy : {str, callable}, optional
+        The differential evolution strategy to use. Should be one of:
+
+        - 'best1bin'
+        - 'best1exp'
+        - 'rand1bin'
+        - 'rand1exp'
+        - 'rand2bin'
+        - 'rand2exp'
+        - 'randtobest1bin'
+        - 'randtobest1exp'
+        - 'currenttobest1bin'
+        - 'currenttobest1exp'
+        - 'best2exp'
+        - 'best2bin'
+
+        The default is 'best1bin'. Strategies that may be implemented are
+        outlined in 'Notes'.
+        Alternatively the differential evolution strategy can be customized by
+        providing a callable that constructs a trial vector. The callable must
+        have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+        where ``candidate`` is an integer specifying which entry of the
+        population is being evolved, ``population`` is an array of shape
+        ``(S, N)`` containing all the population members (where S is the
+        total population size), and ``rng`` is the random number generator
+        being used within the solver.
+        ``candidate`` will be in the range ``[0, S)``.
+        ``strategy`` must return a trial vector with shape ``(N,)``. The
+        fitness of this trial vector is compared against the fitness of
+        ``population[candidate]``.
+
+        .. versionchanged:: 1.12.0
+            Customization of evolution strategy via a callable.
+
+    maxiter : int, optional
+        The maximum number of generations over which the entire population is
+        evolved. The maximum number of function evaluations (with no polishing)
+        is: ``(maxiter + 1) * popsize * (N - N_equal)``
+    popsize : int, optional
+        A multiplier for setting the total population size. The population has
+        ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+        an initial population is supplied via the `init` keyword. When using
+        ``init='sobol'`` the population size is calculated as the next power
+        of 2 after ``popsize * (N - N_equal)``.
+    tol : float, optional
+        Relative tolerance for convergence, the solving stops when
+        ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+        where and `atol` and `tol` are the absolute and relative tolerance
+        respectively.
+    mutation : float or tuple(float, float), optional
+        The mutation constant. In the literature this is also known as
+        differential weight, being denoted by :math:`F`.
+        If specified as a float it should be in the range [0, 2).
+        If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+        randomly changes the mutation constant on a generation by generation
+        basis. The mutation constant for that generation is taken from
+        ``U[min, max)``. Dithering can help speed convergence significantly.
+        Increasing the mutation constant increases the search radius, but will
+        slow down convergence.
+    recombination : float, optional
+        The recombination constant, should be in the range [0, 1]. In the
+        literature this is also known as the crossover probability, being
+        denoted by CR. Increasing this value allows a larger number of mutants
+        to progress into the next generation, but at the risk of population
+        stability.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    disp : bool, optional
+        Prints the evaluated `func` at every iteration.
+    callback : callable, optional
+        A callable called after each iteration. Has the signature::
+
+            callback(intermediate_result: OptimizeResult)
+
+        where ``intermediate_result`` is a keyword parameter containing an
+        `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+        found so far and the objective function. Note that the name
+        of the parameter must be ``intermediate_result`` for the callback
+        to be passed an `OptimizeResult`.
+
+        The callback also supports a signature like::
+
+            callback(x, convergence: float=val)
+
+        ``val`` represents the fractional value of the population convergence.
+        When ``val`` is greater than ``1.0``, the function halts.
+
+        Introspection is used to determine which of the signatures is invoked.
+
+        Global minimization will halt if the callback raises ``StopIteration``
+        or returns ``True``; any polishing is still carried out.
+
+        .. versionchanged:: 1.12.0
+            callback accepts the ``intermediate_result`` keyword.
+
+    polish : bool, optional
+        If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+        method is used to polish the best population member at the end, which
+        can improve the minimization slightly. If a constrained problem is
+        being studied then the `trust-constr` method is used instead. For large
+        problems with many constraints, polishing can take a long time due to
+        the Jacobian computations.
+
+        .. versionchanged:: 1.15.0
+            If `workers` is specified then the map-like callable that wraps
+            `func` is supplied to `minimize` instead of it using `func`
+            directly. This allows the caller to control how and where the
+            invocations actually run.
+
+    init : str or array-like, optional
+        Specify which type of population initialization is performed. Should be
+        one of:
+
+        - 'latinhypercube'
+        - 'sobol'
+        - 'halton'
+        - 'random'
+        - array specifying the initial population. The array should have
+          shape ``(S, N)``, where S is the total population size and N is
+          the number of parameters.
+
+        `init` is clipped to `bounds` before use.
+
+        The default is 'latinhypercube'. Latin Hypercube sampling tries to
+        maximize coverage of the available parameter space.
+
+        'sobol' and 'halton' are superior alternatives and maximize even more
+        the parameter space. 'sobol' will enforce an initial population
+        size which is calculated as the next power of 2 after
+        ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+        less efficient. See `scipy.stats.qmc` for more details.
+
+        'random' initializes the population randomly - this has the drawback
+        that clustering can occur, preventing the whole of parameter space
+        being covered. Use of an array to specify a population could be used,
+        for example, to create a tight bunch of initial guesses in an location
+        where the solution is known to exist, thereby reducing time for
+        convergence.
+    atol : float, optional
+        Absolute tolerance for convergence, the solving stops when
+        ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,
+        where and `atol` and `tol` are the absolute and relative tolerance
+        respectively.
+    updating : {'immediate', 'deferred'}, optional
+        If ``'immediate'``, the best solution vector is continuously updated
+        within a single generation [4]_. This can lead to faster convergence as
+        trial vectors can take advantage of continuous improvements in the best
+        solution.
+        With ``'deferred'``, the best solution vector is updated once per
+        generation. Only ``'deferred'`` is compatible with parallelization or
+        vectorization, and the `workers` and `vectorized` keywords can
+        over-ride this option.
+
+        .. versionadded:: 1.2.0
+
+    workers : int or map-like callable, optional
+        If `workers` is an int the population is subdivided into `workers`
+        sections and evaluated in parallel
+        (uses `multiprocessing.Pool `).
+        Supply -1 to use all available CPU cores.
+        Alternatively supply a map-like callable, such as
+        `multiprocessing.Pool.map` for evaluating the population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+        This option will override the `updating` keyword to
+        ``updating='deferred'`` if ``workers != 1``.
+        This option overrides the `vectorized` keyword if ``workers != 1``.
+        Requires that `func` be pickleable.
+
+        .. versionadded:: 1.2.0
+
+    constraints : {NonLinearConstraint, LinearConstraint, Bounds}
+        Constraints on the solver, over and above those applied by the `bounds`
+        kwd. Uses the approach by Lampinen [5]_.
+
+        .. versionadded:: 1.4.0
+
+    x0 : None or array-like, optional
+        Provides an initial guess to the minimization. Once the population has
+        been initialized this vector replaces the first (best) member. This
+        replacement is done even if `init` is given an initial population.
+        ``x0.shape == (N,)``.
+
+        .. versionadded:: 1.7.0
+
+    integrality : 1-D array, optional
+        For each decision variable, a boolean value indicating whether the
+        decision variable is constrained to integer values. The array is
+        broadcast to ``(N,)``.
+        If any decision variables are constrained to be integral, they will not
+        be changed during polishing.
+        Only integer values lying between the lower and upper bounds are used.
+        If there are no integer values lying between the bounds then a
+        `ValueError` is raised.
+
+        .. versionadded:: 1.9.0
+
+    vectorized : bool, optional
+        If ``vectorized is True``, `func` is sent an `x` array with
+        ``x.shape == (N, S)``, and is expected to return an array of shape
+        ``(S,)``, where `S` is the number of solution vectors to be calculated.
+        If constraints are applied, each of the functions used to construct
+        a `Constraint` object should accept an `x` array with
+        ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
+        `M` is the number of constraint components.
+        This option is an alternative to the parallelization offered by
+        `workers`, and may help in optimization speed by reducing interpreter
+        overhead from multiple function calls. This keyword is ignored if
+        ``workers != 1``.
+        This option will override the `updating` keyword to
+        ``updating='deferred'``.
+        See the notes section for further discussion on when to use
+        ``'vectorized'``, and when to use ``'workers'``.
+
+        .. versionadded:: 1.9.0
+
+    Returns
+    -------
+    res : OptimizeResult
+        The optimization result represented as a `OptimizeResult` object.
+        Important attributes are: ``x`` the solution array, ``success`` a
+        Boolean flag indicating if the optimizer exited successfully,
+        ``message`` which describes the cause of the termination,
+        ``population`` the solution vectors present in the population, and
+        ``population_energies`` the value of the objective function for each
+        entry in ``population``.
+        See `OptimizeResult` for a description of other attributes. If `polish`
+        was employed, and a lower minimum was obtained by the polishing, then
+        OptimizeResult also contains the ``jac`` attribute.
+        If the eventual solution does not satisfy the applied constraints
+        ``success`` will be `False`.
+
+    Notes
+    -----
+    Differential evolution is a stochastic population based method that is
+    useful for global optimization problems. At each pass through the
+    population the algorithm mutates each candidate solution by mixing with
+    other candidate solutions to create a trial candidate. There are several
+    strategies [3]_ for creating trial candidates, which suit some problems
+    more than others. The 'best1bin' strategy is a good starting point for
+    many systems. In this strategy two members of the population are randomly
+    chosen. Their difference is used to mutate the best member (the 'best' in
+    'best1bin'), :math:`x_0`, so far:
+
+    .. math::
+
+        b' = x_0 + F \cdot (x_{r_0} - x_{r_1})
+
+    where :math:`F` is the `mutation` parameter.
+    A trial vector is then constructed. Starting with a randomly chosen ith
+    parameter the trial is sequentially filled (in modulo) with parameters
+    from ``b'`` or the original candidate. The choice of whether to use ``b'``
+    or the original candidate is made with a binomial distribution (the 'bin'
+    in 'best1bin') - a random number in [0, 1) is generated. If this number is
+    less than the `recombination` constant then the parameter is loaded from
+    ``b'``, otherwise it is loaded from the original candidate. The final
+    parameter is always loaded from ``b'``. Once the trial candidate is built
+    its fitness is assessed. If the trial is better than the original candidate
+    then it takes its place. If it is also better than the best overall
+    candidate it also replaces that.
+
+    The other strategies available are outlined in Qiang and
+    Mitchell (2014) [3]_.
+
+
+    - ``rand1`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} - x_{r_2})`
+    - ``rand2`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} + x_{r_2} - x_{r_3} - x_{r_4})`
+    - ``best1`` : :math:`b' = x_0 + F \cdot (x_{r_0} - x_{r_1})`
+    - ``best2`` : :math:`b' = x_0 + F \cdot (x_{r_0} + x_{r_1} - x_{r_2} - x_{r_3})`
+    - ``currenttobest1`` : :math:`b' = x_i + F \cdot (x_0 - x_i + x_{r_0} - x_{r_1})`
+    - ``randtobest1`` : :math:`b' = x_{r_0} + F \cdot (x_0 - x_{r_0} + x_{r_1} - x_{r_2})`
+
+    where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly
+    from the interval [0, NP) with `NP` being the total population size and
+    the original candidate having index `i`. The user can fully customize the
+    generation of the trial candidates by supplying a callable to ``strategy``.
+
+    To improve your chances of finding a global minimum use higher `popsize`
+    values, with higher `mutation` and (dithering), but lower `recombination`
+    values. This has the effect of widening the search radius, but slowing
+    convergence.
+
+    By default the best solution vector is updated continuously within a single
+    iteration (``updating='immediate'``). This is a modification [4]_ of the
+    original differential evolution algorithm which can lead to faster
+    convergence as trial vectors can immediately benefit from improved
+    solutions. To use the original Storn and Price behaviour, updating the best
+    solution once per iteration, set ``updating='deferred'``.
+    The ``'deferred'`` approach is compatible with both parallelization and
+    vectorization (``'workers'`` and ``'vectorized'`` keywords). These may
+    improve minimization speed by using computer resources more efficiently.
+    The ``'workers'`` distribute calculations over multiple processors. By
+    default the Python `multiprocessing` module is used, but other approaches
+    are also possible, such as the Message Passing Interface (MPI) used on
+    clusters [6]_ [7]_. The overhead from these approaches (creating new
+    Processes, etc) may be significant, meaning that computational speed
+    doesn't necessarily scale with the number of processors used.
+    Parallelization is best suited to computationally expensive objective
+    functions. If the objective function is less expensive, then
+    ``'vectorized'`` may aid by only calling the objective function once per
+    iteration, rather than multiple times for all the population members; the
+    interpreter overhead is reduced.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Differential evolution, Wikipedia,
+           http://en.wikipedia.org/wiki/Differential_evolution
+    .. [2] Storn, R and Price, K, Differential Evolution - a Simple and
+           Efficient Heuristic for Global Optimization over Continuous Spaces,
+           Journal of Global Optimization, 1997, 11, 341 - 359.
+    .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm
+            for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659
+    .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., -
+           Characterization of structures from X-ray scattering data using
+           genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357,
+           2827-2848
+    .. [5] Lampinen, J., A constraint handling approach for the differential
+           evolution algorithm. Proceedings of the 2002 Congress on
+           Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE,
+           2002.
+    .. [6] https://mpi4py.readthedocs.io/en/stable/
+    .. [7] https://schwimmbad.readthedocs.io/en/latest/
+ 
+
+    Examples
+    --------
+    Let us consider the problem of minimizing the Rosenbrock function. This
+    function is implemented in `rosen` in `scipy.optimize`.
+
+    >>> import numpy as np
+    >>> from scipy.optimize import rosen, differential_evolution
+    >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
+    >>> result = differential_evolution(rosen, bounds)
+    >>> result.x, result.fun
+    (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+    Now repeat, but with parallelization.
+
+    >>> result = differential_evolution(rosen, bounds, updating='deferred',
+    ...                                 workers=2)
+    >>> result.x, result.fun
+    (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+    Let's do a constrained minimization.
+
+    >>> from scipy.optimize import LinearConstraint, Bounds
+
+    We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less
+    than or equal to 1.9.  This is a linear constraint, which may be written
+    ``A @ x <= 1.9``, where ``A = array([[1, 1]])``.  This can be encoded as
+    a `LinearConstraint` instance:
+
+    >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9)
+
+    Specify limits using a `Bounds` object.
+
+    >>> bounds = Bounds([0., 0.], [2., 2.])
+    >>> result = differential_evolution(rosen, bounds, constraints=lc,
+    ...                                 rng=1)
+    >>> result.x, result.fun
+    (array([0.96632622, 0.93367155]), 0.0011352416852625719)
+
+    Next find the minimum of the Ackley function
+    (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
+
+    >>> def ackley(x):
+    ...     arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
+    ...     arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
+    ...     return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e
+    >>> bounds = [(-5, 5), (-5, 5)]
+    >>> result = differential_evolution(ackley, bounds, rng=1)
+    >>> result.x, result.fun
+    (array([0., 0.]), 4.440892098500626e-16)
+
+    The Ackley function is written in a vectorized manner, so the
+    ``'vectorized'`` keyword can be employed. Note the reduced number of
+    function evaluations.
+
+    >>> result = differential_evolution(
+    ...     ackley, bounds, vectorized=True, updating='deferred', rng=1
+    ... )
+    >>> result.x, result.fun
+    (array([0., 0.]), 4.440892098500626e-16)
+
+    The following custom strategy function mimics 'best1bin':
+
+    >>> def custom_strategy_fn(candidate, population, rng=None):
+    ...     parameter_count = population.shape(-1)
+    ...     mutation, recombination = 0.7, 0.9
+    ...     trial = np.copy(population[candidate])
+    ...     fill_point = rng.choice(parameter_count)
+    ...
+    ...     pool = np.arange(len(population))
+    ...     rng.shuffle(pool)
+    ...
+    ...     # two unique random numbers that aren't the same, and
+    ...     # aren't equal to candidate.
+    ...     idxs = []
+    ...     while len(idxs) < 2 and len(pool) > 0:
+    ...         idx = pool[0]
+    ...         pool = pool[1:]
+    ...         if idx != candidate:
+    ...             idxs.append(idx)
+    ...
+    ...     r0, r1 = idxs[:2]
+    ...
+    ...     bprime = (population[0] + mutation *
+    ...               (population[r0] - population[r1]))
+    ...
+    ...     crossovers = rng.uniform(size=parameter_count)
+    ...     crossovers = crossovers < recombination
+    ...     crossovers[fill_point] = True
+    ...     trial = np.where(crossovers, bprime, trial)
+    ...     return trial
+
+    """# noqa: E501
+
+    # using a context manager means that any created Pool objects are
+    # cleared up.
+    with DifferentialEvolutionSolver(func, bounds, args=args,
+                                     strategy=strategy,
+                                     maxiter=maxiter,
+                                     popsize=popsize, tol=tol,
+                                     mutation=mutation,
+                                     recombination=recombination,
+                                     rng=rng, polish=polish,
+                                     callback=callback,
+                                     disp=disp, init=init, atol=atol,
+                                     updating=updating,
+                                     workers=workers,
+                                     constraints=constraints,
+                                     x0=x0,
+                                     integrality=integrality,
+                                     vectorized=vectorized) as solver:
+        ret = solver.solve()
+
+    return ret
+
+
+class DifferentialEvolutionSolver:
+
+    """This class implements the differential evolution solver
+
+    Parameters
+    ----------
+    func : callable
+        The objective function to be minimized. Must be in the form
+        ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+        and ``args`` is a tuple of any additional fixed parameters needed to
+        completely specify the function. The number of parameters, N, is equal
+        to ``len(x)``.
+    bounds : sequence or `Bounds`
+        Bounds for variables. There are two ways to specify the bounds:
+
+            1. Instance of `Bounds` class.
+            2. ``(min, max)`` pairs for each element in ``x``, defining the
+               finite lower and upper bounds for the optimizing argument of
+               `func`.
+
+        The total number of bounds is used to determine the number of
+        parameters, N. If there are parameters whose bounds are equal the total
+        number of free parameters is ``N - N_equal``.
+    args : tuple, optional
+        Any additional fixed parameters needed to
+        completely specify the objective function.
+    strategy : {str, callable}, optional
+        The differential evolution strategy to use. Should be one of:
+
+            - 'best1bin'
+            - 'best1exp'
+            - 'rand1bin'
+            - 'rand1exp'
+            - 'rand2bin'
+            - 'rand2exp'
+            - 'randtobest1bin'
+            - 'randtobest1exp'
+            - 'currenttobest1bin'
+            - 'currenttobest1exp'
+            - 'best2exp'
+            - 'best2bin'
+
+        The default is 'best1bin'. Strategies that may be
+        implemented are outlined in 'Notes'.
+
+        Alternatively the differential evolution strategy can be customized
+        by providing a callable that constructs a trial vector. The callable
+        must have the form
+        ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+        where ``candidate`` is an integer specifying which entry of the
+        population is being evolved, ``population`` is an array of shape
+        ``(S, N)`` containing all the population members (where S is the
+        total population size), and ``rng`` is the random number generator
+        being used within the solver.
+        ``candidate`` will be in the range ``[0, S)``.
+        ``strategy`` must return a trial vector with shape ``(N,)``. The
+        fitness of this trial vector is compared against the fitness of
+        ``population[candidate]``.
+    maxiter : int, optional
+        The maximum number of generations over which the entire population is
+        evolved. The maximum number of function evaluations (with no polishing)
+        is: ``(maxiter + 1) * popsize * (N - N_equal)``
+    popsize : int, optional
+        A multiplier for setting the total population size. The population has
+        ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+        an initial population is supplied via the `init` keyword. When using
+        ``init='sobol'`` the population size is calculated as the next power
+        of 2 after ``popsize * (N - N_equal)``.
+    tol : float, optional
+        Relative tolerance for convergence, the solving stops when
+        ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+        where and `atol` and `tol` are the absolute and relative tolerance
+        respectively.
+    mutation : float or tuple(float, float), optional
+        The mutation constant. In the literature this is also known as
+        differential weight, being denoted by F.
+        If specified as a float it should be in the range [0, 2].
+        If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+        randomly changes the mutation constant on a generation by generation
+        basis. The mutation constant for that generation is taken from
+        U[min, max). Dithering can help speed convergence significantly.
+        Increasing the mutation constant increases the search radius, but will
+        slow down convergence.
+    recombination : float, optional
+        The recombination constant, should be in the range [0, 1]. In the
+        literature this is also known as the crossover probability, being
+        denoted by CR. Increasing this value allows a larger number of mutants
+        to progress into the next generation, but at the risk of population
+        stability.
+
+    rng : {None, int, `numpy.random.Generator`}, optional
+        
+        ..versionchanged:: 1.15.0
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator` this keyword was changed from `seed` to `rng`.
+            For an interim period both keywords will continue to work (only specify
+            one of them). After the interim period using the `seed` keyword will emit
+            warnings. The behavior of the `seed` and `rng` keywords is outlined below.
+
+        If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a `Generator`.
+        If `rng` is already a `Generator` instance, then the provided instance is
+        used.
+        
+        If this argument is passed by position or `seed` is passed by keyword, the
+        behavior is:
+        
+        - If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `seed` is an int, a new `RandomState` instance is used,
+          seeded with `seed`.
+        - If `seed` is already a `Generator` or `RandomState` instance then
+          that instance is used.
+        
+        Specify `seed`/`rng` for repeatable minimizations.
+    disp : bool, optional
+        Prints the evaluated `func` at every iteration.
+    callback : callable, optional
+        A callable called after each iteration. Has the signature:
+
+            ``callback(intermediate_result: OptimizeResult)``
+
+        where ``intermediate_result`` is a keyword parameter containing an
+        `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+        found so far and the objective function. Note that the name
+        of the parameter must be ``intermediate_result`` for the callback
+        to be passed an `OptimizeResult`.
+
+        The callback also supports a signature like:
+
+            ``callback(x, convergence: float=val)``
+
+        ``val`` represents the fractional value of the population convergence.
+         When ``val`` is greater than ``1.0``, the function halts.
+
+        Introspection is used to determine which of the signatures is invoked.
+
+        Global minimization will halt if the callback raises ``StopIteration``
+        or returns ``True``; any polishing is still carried out.
+
+        .. versionchanged:: 1.12.0
+            callback accepts the ``intermediate_result`` keyword.
+
+    polish : bool, optional
+        If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+        method is used to polish the best population member at the end, which
+        can improve the minimization slightly. If a constrained problem is
+        being studied then the `trust-constr` method is used instead. For large
+        problems with many constraints, polishing can take a long time due to
+        the Jacobian computations.
+    maxfun : int, optional
+        Set the maximum number of function evaluations. However, it probably
+        makes more sense to set `maxiter` instead.
+    init : str or array-like, optional
+        Specify which type of population initialization is performed. Should be
+        one of:
+
+            - 'latinhypercube'
+            - 'sobol'
+            - 'halton'
+            - 'random'
+            - array specifying the initial population. The array should have
+              shape ``(S, N)``, where S is the total population size and
+              N is the number of parameters.
+              `init` is clipped to `bounds` before use.
+
+        The default is 'latinhypercube'. Latin Hypercube sampling tries to
+        maximize coverage of the available parameter space.
+
+        'sobol' and 'halton' are superior alternatives and maximize even more
+        the parameter space. 'sobol' will enforce an initial population
+        size which is calculated as the next power of 2 after
+        ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+        less efficient. See `scipy.stats.qmc` for more details.
+
+        'random' initializes the population randomly - this has the drawback
+        that clustering can occur, preventing the whole of parameter space
+        being covered. Use of an array to specify a population could be used,
+        for example, to create a tight bunch of initial guesses in an location
+        where the solution is known to exist, thereby reducing time for
+        convergence.
+    atol : float, optional
+        Absolute tolerance for convergence, the solving stops when
+        ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,
+        where and `atol` and `tol` are the absolute and relative tolerance
+        respectively.
+    updating : {'immediate', 'deferred'}, optional
+        If ``'immediate'``, the best solution vector is continuously updated
+        within a single generation [4]_. This can lead to faster convergence as
+        trial vectors can take advantage of continuous improvements in the best
+        solution.
+        With ``'deferred'``, the best solution vector is updated once per
+        generation. Only ``'deferred'`` is compatible with parallelization or
+        vectorization, and the `workers` and `vectorized` keywords can
+        over-ride this option.
+    workers : int or map-like callable, optional
+        If `workers` is an int the population is subdivided into `workers`
+        sections and evaluated in parallel
+        (uses `multiprocessing.Pool `).
+        Supply `-1` to use all cores available to the Process.
+        Alternatively supply a map-like callable, such as
+        `multiprocessing.Pool.map` for evaluating the population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+        This option will override the `updating` keyword to
+        `updating='deferred'` if `workers != 1`.
+        Requires that `func` be pickleable.
+    constraints : {NonLinearConstraint, LinearConstraint, Bounds}
+        Constraints on the solver, over and above those applied by the `bounds`
+        kwd. Uses the approach by Lampinen.
+    x0 : None or array-like, optional
+        Provides an initial guess to the minimization. Once the population has
+        been initialized this vector replaces the first (best) member. This
+        replacement is done even if `init` is given an initial population.
+        ``x0.shape == (N,)``.
+    integrality : 1-D array, optional
+        For each decision variable, a boolean value indicating whether the
+        decision variable is constrained to integer values. The array is
+        broadcast to ``(N,)``.
+        If any decision variables are constrained to be integral, they will not
+        be changed during polishing.
+        Only integer values lying between the lower and upper bounds are used.
+        If there are no integer values lying between the bounds then a
+        `ValueError` is raised.
+    vectorized : bool, optional
+        If ``vectorized is True``, `func` is sent an `x` array with
+        ``x.shape == (N, S)``, and is expected to return an array of shape
+        ``(S,)``, where `S` is the number of solution vectors to be calculated.
+        If constraints are applied, each of the functions used to construct
+        a `Constraint` object should accept an `x` array with
+        ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
+        `M` is the number of constraint components.
+        This option is an alternative to the parallelization offered by
+        `workers`, and may help in optimization speed. This keyword is
+        ignored if ``workers != 1``.
+        This option will override the `updating` keyword to
+        ``updating='deferred'``.
+    """ # noqa: E501
+
+    # Dispatch of mutation strategy method (binomial or exponential).
+    _binomial = {'best1bin': '_best1',
+                 'randtobest1bin': '_randtobest1',
+                 'currenttobest1bin': '_currenttobest1',
+                 'best2bin': '_best2',
+                 'rand2bin': '_rand2',
+                 'rand1bin': '_rand1'}
+    _exponential = {'best1exp': '_best1',
+                    'rand1exp': '_rand1',
+                    'randtobest1exp': '_randtobest1',
+                    'currenttobest1exp': '_currenttobest1',
+                    'best2exp': '_best2',
+                    'rand2exp': '_rand2'}
+
+    __init_error_msg = ("The population initialization method must be one of "
+                        "'latinhypercube' or 'random', or an array of shape "
+                        "(S, N) where N is the number of parameters and S>5")
+
+    def __init__(self, func, bounds, args=(),
+                 strategy='best1bin', maxiter=1000, popsize=15,
+                 tol=0.01, mutation=(0.5, 1), recombination=0.7, rng=None,
+                 maxfun=np.inf, callback=None, disp=False, polish=True,
+                 init='latinhypercube', atol=0, updating='immediate',
+                 workers=1, constraints=(), x0=None, *, integrality=None,
+                 vectorized=False):
+
+        if callable(strategy):
+            # a callable strategy is going to be stored in self.strategy anyway
+            pass
+        elif strategy in self._binomial:
+            self.mutation_func = getattr(self, self._binomial[strategy])
+        elif strategy in self._exponential:
+            self.mutation_func = getattr(self, self._exponential[strategy])
+        else:
+            raise ValueError("Please select a valid mutation strategy")
+        self.strategy = strategy
+
+        self.callback = _wrap_callback(callback, "differential_evolution")
+        self.polish = polish
+
+        # set the updating / parallelisation options
+        if updating in ['immediate', 'deferred']:
+            self._updating = updating
+
+        self.vectorized = vectorized
+
+        # want to use parallelisation, but updating is immediate
+        if workers != 1 and updating == 'immediate':
+            warnings.warn("differential_evolution: the 'workers' keyword has"
+                          " overridden updating='immediate' to"
+                          " updating='deferred'", UserWarning, stacklevel=2)
+            self._updating = 'deferred'
+
+        if vectorized and workers != 1:
+            warnings.warn("differential_evolution: the 'workers' keyword"
+                          " overrides the 'vectorized' keyword", stacklevel=2)
+            self.vectorized = vectorized = False
+
+        if vectorized and updating == 'immediate':
+            warnings.warn("differential_evolution: the 'vectorized' keyword"
+                          " has overridden updating='immediate' to updating"
+                          "='deferred'", UserWarning, stacklevel=2)
+            self._updating = 'deferred'
+
+        # an object with a map method.
+        if vectorized:
+            def maplike_for_vectorized_func(func, x):
+                # send an array (N, S) to the user func,
+                # expect to receive (S,). Transposition is required because
+                # internally the population is held as (S, N)
+                return np.atleast_1d(func(x.T))
+            workers = maplike_for_vectorized_func
+
+        self._mapwrapper = MapWrapper(workers)
+
+        # relative and absolute tolerances for convergence
+        self.tol, self.atol = tol, atol
+
+        # Mutation constant should be in [0, 2). If specified as a sequence
+        # then dithering is performed.
+        self.scale = mutation
+        if (not np.all(np.isfinite(mutation)) or
+                np.any(np.array(mutation) >= 2) or
+                np.any(np.array(mutation) < 0)):
+            raise ValueError('The mutation constant must be a float in '
+                             'U[0, 2), or specified as a tuple(min, max)'
+                             ' where min < max and min, max are in U[0, 2).')
+
+        self.dither = None
+        if hasattr(mutation, '__iter__') and len(mutation) > 1:
+            self.dither = [mutation[0], mutation[1]]
+            self.dither.sort()
+
+        self.cross_over_probability = recombination
+
+        # we create a wrapped function to allow the use of map (and Pool.map
+        # in the future)
+        self.func = _FunctionWrapper(func, args)
+        self.args = args
+
+        # convert tuple of lower and upper bounds to limits
+        # [(low_0, high_0), ..., (low_n, high_n]
+        #     -> [[low_0, ..., low_n], [high_0, ..., high_n]]
+        if isinstance(bounds, Bounds):
+            self.limits = np.array(new_bounds_to_old(bounds.lb,
+                                                     bounds.ub,
+                                                     len(bounds.lb)),
+                                   dtype=float).T
+        else:
+            self.limits = np.array(bounds, dtype='float').T
+
+        if (np.size(self.limits, 0) != 2 or not
+                np.all(np.isfinite(self.limits))):
+            raise ValueError('bounds should be a sequence containing finite '
+                             'real valued (min, max) pairs for each value'
+                             ' in x')
+
+        if maxiter is None:  # the default used to be None
+            maxiter = 1000
+        self.maxiter = maxiter
+        if maxfun is None:  # the default used to be None
+            maxfun = np.inf
+        self.maxfun = maxfun
+
+        # population is scaled to between [0, 1].
+        # We have to scale between parameter <-> population
+        # save these arguments for _scale_parameter and
+        # _unscale_parameter. This is an optimization
+        self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1])
+        self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1])
+        with np.errstate(divide='ignore'):
+            # if lb == ub then the following line will be 1/0, which is why
+            # we ignore the divide by zero warning. The result from 1/0 is
+            # inf, so replace those values by 0.
+            self.__recip_scale_arg2 = 1 / self.__scale_arg2
+            self.__recip_scale_arg2[~np.isfinite(self.__recip_scale_arg2)] = 0
+
+        self.parameter_count = np.size(self.limits, 1)
+
+        self.random_number_generator = check_random_state(rng)
+
+        # Which parameters are going to be integers?
+        if np.any(integrality):
+            # # user has provided a truth value for integer constraints
+            integrality = np.broadcast_to(
+                integrality,
+                self.parameter_count
+            )
+            integrality = np.asarray(integrality, bool)
+            # For integrality parameters change the limits to only allow
+            # integer values lying between the limits.
+            lb, ub = np.copy(self.limits)
+
+            lb = np.ceil(lb)
+            ub = np.floor(ub)
+            if not (lb[integrality] <= ub[integrality]).all():
+                # there's a parameter that doesn't have an integer value
+                # lying between the limits
+                raise ValueError("One of the integrality constraints does not"
+                                 " have any possible integer values between"
+                                 " the lower/upper bounds.")
+            nlb = np.nextafter(lb[integrality] - 0.5, np.inf)
+            nub = np.nextafter(ub[integrality] + 0.5, -np.inf)
+
+            self.integrality = integrality
+            self.limits[0, self.integrality] = nlb
+            self.limits[1, self.integrality] = nub
+        else:
+            self.integrality = False
+
+        # check for equal bounds
+        eb = self.limits[0] == self.limits[1]
+        eb_count = np.count_nonzero(eb)
+
+        # default population initialization is a latin hypercube design, but
+        # there are other population initializations possible.
+        # the minimum is 5 because 'best2bin' requires a population that's at
+        # least 5 long
+        # 202301 - reduced population size to account for parameters with
+        # equal bounds. If there are no varying parameters set N to at least 1
+        self.num_population_members = max(
+            5,
+            popsize * max(1, self.parameter_count - eb_count)
+        )
+        self.population_shape = (self.num_population_members,
+                                 self.parameter_count)
+
+        self._nfev = 0
+        # check first str otherwise will fail to compare str with array
+        if isinstance(init, str):
+            if init == 'latinhypercube':
+                self.init_population_lhs()
+            elif init == 'sobol':
+                # must be Ns = 2**m for Sobol'
+                n_s = int(2 ** np.ceil(np.log2(self.num_population_members)))
+                self.num_population_members = n_s
+                self.population_shape = (self.num_population_members,
+                                         self.parameter_count)
+                self.init_population_qmc(qmc_engine='sobol')
+            elif init == 'halton':
+                self.init_population_qmc(qmc_engine='halton')
+            elif init == 'random':
+                self.init_population_random()
+            else:
+                raise ValueError(self.__init_error_msg)
+        else:
+            self.init_population_array(init)
+
+        if x0 is not None:
+            # scale to within unit interval and
+            # ensure parameters are within bounds.
+            x0_scaled = self._unscale_parameters(np.asarray(x0))
+            if ((x0_scaled > 1.0) | (x0_scaled < 0.0)).any():
+                raise ValueError(
+                    "Some entries in x0 lay outside the specified bounds"
+                )
+            self.population[0] = x0_scaled
+
+        # infrastructure for constraints
+        self.constraints = constraints
+        self._wrapped_constraints = []
+
+        if hasattr(constraints, '__len__'):
+            # sequence of constraints, this will also deal with default
+            # keyword parameter
+            for c in constraints:
+                self._wrapped_constraints.append(
+                    _ConstraintWrapper(c, self.x)
+                )
+        else:
+            self._wrapped_constraints = [
+                _ConstraintWrapper(constraints, self.x)
+            ]
+        self.total_constraints = np.sum(
+            [c.num_constr for c in self._wrapped_constraints]
+        )
+        self.constraint_violation = np.zeros((self.num_population_members, 1))
+        self.feasible = np.ones(self.num_population_members, bool)
+
+        # an array to shuffle when selecting candidates. Create it here
+        # rather than repeatedly creating it in _select_samples.
+        self._random_population_index = np.arange(self.num_population_members)
+        self.disp = disp
+
+    def init_population_lhs(self):
+        """
+        Initializes the population with Latin Hypercube Sampling.
+        Latin Hypercube Sampling ensures that each parameter is uniformly
+        sampled over its range.
+        """
+        rng = self.random_number_generator
+
+        # Each parameter range needs to be sampled uniformly. The scaled
+        # parameter range ([0, 1)) needs to be split into
+        # `self.num_population_members` segments, each of which has the following
+        # size:
+        segsize = 1.0 / self.num_population_members
+
+        # Within each segment we sample from a uniform random distribution.
+        # We need to do this sampling for each parameter.
+        samples = (segsize * rng.uniform(size=self.population_shape)
+
+        # Offset each segment to cover the entire parameter range [0, 1)
+                   + np.linspace(0., 1., self.num_population_members,
+                                 endpoint=False)[:, np.newaxis])
+
+        # Create an array for population of candidate solutions.
+        self.population = np.zeros_like(samples)
+
+        # Initialize population of candidate solutions by permutation of the
+        # random samples.
+        for j in range(self.parameter_count):
+            order = rng.permutation(range(self.num_population_members))
+            self.population[:, j] = samples[order, j]
+
+        # reset population energies
+        self.population_energies = np.full(self.num_population_members,
+                                           np.inf)
+
+        # reset number of function evaluations counter
+        self._nfev = 0
+
+    def init_population_qmc(self, qmc_engine):
+        """Initializes the population with a QMC method.
+
+        QMC methods ensures that each parameter is uniformly
+        sampled over its range.
+
+        Parameters
+        ----------
+        qmc_engine : str
+            The QMC method to use for initialization. Can be one of
+            ``latinhypercube``, ``sobol`` or ``halton``.
+
+        """
+        from scipy.stats import qmc
+
+        rng = self.random_number_generator
+
+        # Create an array for population of candidate solutions.
+        if qmc_engine == 'latinhypercube':
+            sampler = qmc.LatinHypercube(d=self.parameter_count, seed=rng)
+        elif qmc_engine == 'sobol':
+            sampler = qmc.Sobol(d=self.parameter_count, seed=rng)
+        elif qmc_engine == 'halton':
+            sampler = qmc.Halton(d=self.parameter_count, seed=rng)
+        else:
+            raise ValueError(self.__init_error_msg)
+
+        self.population = sampler.random(n=self.num_population_members)
+
+        # reset population energies
+        self.population_energies = np.full(self.num_population_members,
+                                           np.inf)
+
+        # reset number of function evaluations counter
+        self._nfev = 0
+
+    def init_population_random(self):
+        """
+        Initializes the population at random. This type of initialization
+        can possess clustering, Latin Hypercube sampling is generally better.
+        """
+        rng = self.random_number_generator
+        self.population = rng.uniform(size=self.population_shape)
+
+        # reset population energies
+        self.population_energies = np.full(self.num_population_members,
+                                           np.inf)
+
+        # reset number of function evaluations counter
+        self._nfev = 0
+
+    def init_population_array(self, init):
+        """
+        Initializes the population with a user specified population.
+
+        Parameters
+        ----------
+        init : np.ndarray
+            Array specifying subset of the initial population. The array should
+            have shape (S, N), where N is the number of parameters.
+            The population is clipped to the lower and upper bounds.
+        """
+        # make sure you're using a float array
+        popn = np.asarray(init, dtype=np.float64)
+
+        if (np.size(popn, 0) < 5 or
+                popn.shape[1] != self.parameter_count or
+                len(popn.shape) != 2):
+            raise ValueError("The population supplied needs to have shape"
+                             " (S, len(x)), where S > 4.")
+
+        # scale values and clip to bounds, assigning to population
+        self.population = np.clip(self._unscale_parameters(popn), 0, 1)
+
+        self.num_population_members = np.size(self.population, 0)
+
+        self.population_shape = (self.num_population_members,
+                                 self.parameter_count)
+
+        # reset population energies
+        self.population_energies = np.full(self.num_population_members,
+                                           np.inf)
+
+        # reset number of function evaluations counter
+        self._nfev = 0
+
+    @property
+    def x(self):
+        """
+        The best solution from the solver
+        """
+        return self._scale_parameters(self.population[0])
+
+    @property
+    def convergence(self):
+        """
+        The standard deviation of the population energies divided by their
+        mean.
+        """
+        if np.any(np.isinf(self.population_energies)):
+            return np.inf
+        return (np.std(self.population_energies) /
+                (np.abs(np.mean(self.population_energies)) + _MACHEPS))
+
+    def converged(self):
+        """
+        Return True if the solver has converged.
+        """
+        if np.any(np.isinf(self.population_energies)):
+            return False
+
+        return (np.std(self.population_energies) <=
+                self.atol +
+                self.tol * np.abs(np.mean(self.population_energies)))
+
+    def solve(self):
+        """
+        Runs the DifferentialEvolutionSolver.
+
+        Returns
+        -------
+        res : OptimizeResult
+            The optimization result represented as a `OptimizeResult` object.
+            Important attributes are: ``x`` the solution array, ``success`` a
+            Boolean flag indicating if the optimizer exited successfully,
+            ``message`` which describes the cause of the termination,
+            ``population`` the solution vectors present in the population, and
+            ``population_energies`` the value of the objective function for
+            each entry in ``population``.
+            See `OptimizeResult` for a description of other attributes. If
+            `polish` was employed, and a lower minimum was obtained by the
+            polishing, then OptimizeResult also contains the ``jac`` attribute.
+            If the eventual solution does not satisfy the applied constraints
+            ``success`` will be `False`.
+        """
+        nit, warning_flag = 0, False
+        status_message = _status_message['success']
+
+        # The population may have just been initialized (all entries are
+        # np.inf). If it has you have to calculate the initial energies.
+        # Although this is also done in the evolve generator it's possible
+        # that someone can set maxiter=0, at which point we still want the
+        # initial energies to be calculated (the following loop isn't run).
+        if np.all(np.isinf(self.population_energies)):
+            self.feasible, self.constraint_violation = (
+                self._calculate_population_feasibilities(self.population))
+
+            # only work out population energies for feasible solutions
+            self.population_energies[self.feasible] = (
+                self._calculate_population_energies(
+                    self.population[self.feasible]))
+
+            self._promote_lowest_energy()
+
+        # do the optimization.
+        for nit in range(1, self.maxiter + 1):
+            # evolve the population by a generation
+            try:
+                next(self)
+            except StopIteration:
+                warning_flag = True
+                if self._nfev > self.maxfun:
+                    status_message = _status_message['maxfev']
+                elif self._nfev == self.maxfun:
+                    status_message = ('Maximum number of function evaluations'
+                                      ' has been reached.')
+                break
+
+            if self.disp:
+                print(f"differential_evolution step {nit}: f(x)="
+                      f" {self.population_energies[0]}"
+                      )
+
+            if self.callback:
+                c = self.tol / (self.convergence + _MACHEPS)
+                res = self._result(nit=nit, message="in progress")
+                res.convergence = c
+                try:
+                    warning_flag = bool(self.callback(res))
+                except StopIteration:
+                    warning_flag = True
+
+                if warning_flag:
+                    status_message = 'callback function requested stop early'
+
+            # should the solver terminate?
+            if warning_flag or self.converged():
+                break
+
+        else:
+            status_message = _status_message['maxiter']
+            warning_flag = True
+
+        DE_result = self._result(
+            nit=nit, message=status_message, warning_flag=warning_flag
+        )
+
+        if self.polish and not np.all(self.integrality):
+            # can't polish if all the parameters are integers
+            if np.any(self.integrality):
+                # set the lower/upper bounds equal so that any integrality
+                # constraints work.
+                limits, integrality = self.limits, self.integrality
+                limits[0, integrality] = DE_result.x[integrality]
+                limits[1, integrality] = DE_result.x[integrality]
+
+            polish_method = 'L-BFGS-B'
+
+            if self._wrapped_constraints:
+                polish_method = 'trust-constr'
+
+                constr_violation = self._constraint_violation_fn(DE_result.x)
+                if np.any(constr_violation > 0.):
+                    warnings.warn("differential evolution didn't find a "
+                                  "solution satisfying the constraints, "
+                                  "attempting to polish from the least "
+                                  "infeasible solution",
+                                  UserWarning, stacklevel=2)
+            if self.disp:
+                print(f"Polishing solution with '{polish_method}'")
+            result = minimize(lambda x:
+                                list(self._mapwrapper(self.func, np.atleast_2d(x)))[0],
+                              np.copy(DE_result.x),
+                              method=polish_method,
+                              bounds=self.limits.T,
+                              constraints=self.constraints)
+
+            self._nfev += result.nfev
+            DE_result.nfev = self._nfev
+
+            # Polishing solution is only accepted if there is an improvement in
+            # cost function, the polishing was successful and the solution lies
+            # within the bounds.
+            if (result.fun < DE_result.fun and
+                    result.success and
+                    np.all(result.x <= self.limits[1]) and
+                    np.all(self.limits[0] <= result.x)):
+                DE_result.fun = result.fun
+                DE_result.x = result.x
+                DE_result.jac = result.jac
+                # to keep internal state consistent
+                self.population_energies[0] = result.fun
+                self.population[0] = self._unscale_parameters(result.x)
+
+        if self._wrapped_constraints:
+            DE_result.constr = [c.violation(DE_result.x) for
+                                c in self._wrapped_constraints]
+            DE_result.constr_violation = np.max(
+                np.concatenate(DE_result.constr))
+            DE_result.maxcv = DE_result.constr_violation
+            if DE_result.maxcv > 0:
+                # if the result is infeasible then success must be False
+                DE_result.success = False
+                DE_result.message = ("The solution does not satisfy the "
+                                     f"constraints, MAXCV = {DE_result.maxcv}")
+
+        return DE_result
+
+    def _result(self, **kwds):
+        # form an intermediate OptimizeResult
+        nit = kwds.get('nit', None)
+        message = kwds.get('message', None)
+        warning_flag = kwds.get('warning_flag', False)
+        result = OptimizeResult(
+            x=self.x,
+            fun=self.population_energies[0],
+            nfev=self._nfev,
+            nit=nit,
+            message=message,
+            success=(warning_flag is not True),
+            population=self._scale_parameters(self.population),
+            population_energies=self.population_energies
+        )
+        if self._wrapped_constraints:
+            result.constr = [c.violation(result.x)
+                             for c in self._wrapped_constraints]
+            result.constr_violation = np.max(np.concatenate(result.constr))
+            result.maxcv = result.constr_violation
+            if result.maxcv > 0:
+                result.success = False
+
+        return result
+
+    def _calculate_population_energies(self, population):
+        """
+        Calculate the energies of a population.
+
+        Parameters
+        ----------
+        population : ndarray
+            An array of parameter vectors normalised to [0, 1] using lower
+            and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+        Returns
+        -------
+        energies : ndarray
+            An array of energies corresponding to each population member. If
+            maxfun will be exceeded during this call, then the number of
+            function evaluations will be reduced and energies will be
+            right-padded with np.inf. Has shape ``(np.size(population, 0),)``
+        """
+        num_members = np.size(population, 0)
+        # S is the number of function evals left to stay under the
+        # maxfun budget
+        S = min(num_members, self.maxfun - self._nfev)
+
+        energies = np.full(num_members, np.inf)
+
+        parameters_pop = self._scale_parameters(population)
+        try:
+            calc_energies = list(
+                self._mapwrapper(self.func, parameters_pop[0:S])
+            )
+            calc_energies = np.squeeze(calc_energies)
+        except (TypeError, ValueError) as e:
+            # wrong number of arguments for _mapwrapper
+            # or wrong length returned from the mapper
+            raise RuntimeError(
+                "The map-like callable must be of the form f(func, iterable), "
+                "returning a sequence of numbers the same length as 'iterable'"
+            ) from e
+
+        if calc_energies.size != S:
+            if self.vectorized:
+                raise RuntimeError("The vectorized function must return an"
+                                   " array of shape (S,) when given an array"
+                                   " of shape (len(x), S)")
+            raise RuntimeError("func(x, *args) must return a scalar value")
+
+        energies[0:S] = calc_energies
+
+        if self.vectorized:
+            self._nfev += 1
+        else:
+            self._nfev += S
+
+        return energies
+
+    def _promote_lowest_energy(self):
+        # swaps 'best solution' into first population entry
+
+        idx = np.arange(self.num_population_members)
+        feasible_solutions = idx[self.feasible]
+        if feasible_solutions.size:
+            # find the best feasible solution
+            idx_t = np.argmin(self.population_energies[feasible_solutions])
+            l = feasible_solutions[idx_t]
+        else:
+            # no solution was feasible, use 'best' infeasible solution, which
+            # will violate constraints the least
+            l = np.argmin(np.sum(self.constraint_violation, axis=1))
+
+        self.population_energies[[0, l]] = self.population_energies[[l, 0]]
+        self.population[[0, l], :] = self.population[[l, 0], :]
+        self.feasible[[0, l]] = self.feasible[[l, 0]]
+        self.constraint_violation[[0, l], :] = (
+        self.constraint_violation[[l, 0], :])
+
+    def _constraint_violation_fn(self, x):
+        """
+        Calculates total constraint violation for all the constraints, for a
+        set of solutions.
+
+        Parameters
+        ----------
+        x : ndarray
+            Solution vector(s). Has shape (S, N), or (N,), where S is the
+            number of solutions to investigate and N is the number of
+            parameters.
+
+        Returns
+        -------
+        cv : ndarray
+            Total violation of constraints. Has shape ``(S, M)``, where M is
+            the total number of constraint components (which is not necessarily
+            equal to len(self._wrapped_constraints)).
+        """
+        # how many solution vectors you're calculating constraint violations
+        # for
+        S = np.size(x) // self.parameter_count
+        _out = np.zeros((S, self.total_constraints))
+        offset = 0
+        for con in self._wrapped_constraints:
+            # the input/output of the (vectorized) constraint function is
+            # {(N, S), (N,)} --> (M, S)
+            # The input to _constraint_violation_fn is (S, N) or (N,), so
+            # transpose to pass it to the constraint. The output is transposed
+            # from (M, S) to (S, M) for further use.
+            c = con.violation(x.T).T
+
+            # The shape of c should be (M,), (1, M), or (S, M). Check for
+            # those shapes, as an incorrect shape indicates that the
+            # user constraint function didn't return the right thing, and
+            # the reshape operation will fail. Intercept the wrong shape
+            # to give a reasonable error message. I'm not sure what failure
+            # modes an inventive user will come up with.
+            if c.shape[-1] != con.num_constr or (S > 1 and c.shape[0] != S):
+                raise RuntimeError("An array returned from a Constraint has"
+                                   " the wrong shape. If `vectorized is False`"
+                                   " the Constraint should return an array of"
+                                   " shape (M,). If `vectorized is True` then"
+                                   " the Constraint must return an array of"
+                                   " shape (M, S), where S is the number of"
+                                   " solution vectors and M is the number of"
+                                   " constraint components in a given"
+                                   " Constraint object.")
+
+            # the violation function may return a 1D array, but is it a
+            # sequence of constraints for one solution (S=1, M>=1), or the
+            # value of a single constraint for a sequence of solutions
+            # (S>=1, M=1)
+            c = np.reshape(c, (S, con.num_constr))
+            _out[:, offset:offset + con.num_constr] = c
+            offset += con.num_constr
+
+        return _out
+
+    def _calculate_population_feasibilities(self, population):
+        """
+        Calculate the feasibilities of a population.
+
+        Parameters
+        ----------
+        population : ndarray
+            An array of parameter vectors normalised to [0, 1] using lower
+            and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+        Returns
+        -------
+        feasible, constraint_violation : ndarray, ndarray
+            Boolean array of feasibility for each population member, and an
+            array of the constraint violation for each population member.
+            constraint_violation has shape ``(np.size(population, 0), M)``,
+            where M is the number of constraints.
+        """
+        num_members = np.size(population, 0)
+        if not self._wrapped_constraints:
+            # shortcut for no constraints
+            return np.ones(num_members, bool), np.zeros((num_members, 1))
+
+        # (S, N)
+        parameters_pop = self._scale_parameters(population)
+
+        if self.vectorized:
+            # (S, M)
+            constraint_violation = np.array(
+                self._constraint_violation_fn(parameters_pop)
+            )
+        else:
+            # (S, 1, M)
+            constraint_violation = np.array([self._constraint_violation_fn(x)
+                                             for x in parameters_pop])
+            # if you use the list comprehension in the line above it will
+            # create an array of shape (S, 1, M), because each iteration
+            # generates an array of (1, M). In comparison the vectorized
+            # version returns (S, M). It's therefore necessary to remove axis 1
+            constraint_violation = constraint_violation[:, 0]
+
+        feasible = ~(np.sum(constraint_violation, axis=1) > 0)
+
+        return feasible, constraint_violation
+
+    def __iter__(self):
+        return self
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        return self._mapwrapper.__exit__(*args)
+
+    def _accept_trial(self, energy_trial, feasible_trial, cv_trial,
+                      energy_orig, feasible_orig, cv_orig):
+        """
+        Trial is accepted if:
+        * it satisfies all constraints and provides a lower or equal objective
+          function value, while both the compared solutions are feasible
+        - or -
+        * it is feasible while the original solution is infeasible,
+        - or -
+        * it is infeasible, but provides a lower or equal constraint violation
+          for all constraint functions.
+
+        This test corresponds to section III of Lampinen [1]_.
+
+        Parameters
+        ----------
+        energy_trial : float
+            Energy of the trial solution
+        feasible_trial : float
+            Feasibility of trial solution
+        cv_trial : array-like
+            Excess constraint violation for the trial solution
+        energy_orig : float
+            Energy of the original solution
+        feasible_orig : float
+            Feasibility of original solution
+        cv_orig : array-like
+            Excess constraint violation for the original solution
+
+        Returns
+        -------
+        accepted : bool
+
+        """
+        if feasible_orig and feasible_trial:
+            return energy_trial <= energy_orig
+        elif feasible_trial and not feasible_orig:
+            return True
+        elif not feasible_trial and (cv_trial <= cv_orig).all():
+            # cv_trial < cv_orig would imply that both trial and orig are not
+            # feasible
+            return True
+
+        return False
+
+    def __next__(self):
+        """
+        Evolve the population by a single generation
+
+        Returns
+        -------
+        x : ndarray
+            The best solution from the solver.
+        fun : float
+            Value of objective function obtained from the best solution.
+        """
+        # the population may have just been initialized (all entries are
+        # np.inf). If it has you have to calculate the initial energies
+        if np.all(np.isinf(self.population_energies)):
+            self.feasible, self.constraint_violation = (
+                self._calculate_population_feasibilities(self.population))
+
+            # only need to work out population energies for those that are
+            # feasible
+            self.population_energies[self.feasible] = (
+                self._calculate_population_energies(
+                    self.population[self.feasible]))
+
+            self._promote_lowest_energy()
+
+        if self.dither is not None:
+            self.scale = self.random_number_generator.uniform(self.dither[0],
+                                                              self.dither[1])
+
+        if self._updating == 'immediate':
+            # update best solution immediately
+            for candidate in range(self.num_population_members):
+                if self._nfev > self.maxfun:
+                    raise StopIteration
+
+                # create a trial solution
+                trial = self._mutate(candidate)
+
+                # ensuring that it's in the range [0, 1)
+                self._ensure_constraint(trial)
+
+                # scale from [0, 1) to the actual parameter value
+                parameters = self._scale_parameters(trial)
+
+                # determine the energy of the objective function
+                if self._wrapped_constraints:
+                    cv = self._constraint_violation_fn(parameters)
+                    feasible = False
+                    energy = np.inf
+                    if not np.sum(cv) > 0:
+                        # solution is feasible
+                        feasible = True
+                        energy = self.func(parameters)
+                        self._nfev += 1
+                else:
+                    feasible = True
+                    cv = np.atleast_2d([0.])
+                    energy = self.func(parameters)
+                    self._nfev += 1
+
+                # compare trial and population member
+                if self._accept_trial(energy, feasible, cv,
+                                      self.population_energies[candidate],
+                                      self.feasible[candidate],
+                                      self.constraint_violation[candidate]):
+                    self.population[candidate] = trial
+                    self.population_energies[candidate] = np.squeeze(energy)
+                    self.feasible[candidate] = feasible
+                    self.constraint_violation[candidate] = cv
+
+                    # if the trial candidate is also better than the best
+                    # solution then promote it.
+                    if self._accept_trial(energy, feasible, cv,
+                                          self.population_energies[0],
+                                          self.feasible[0],
+                                          self.constraint_violation[0]):
+                        self._promote_lowest_energy()
+
+        elif self._updating == 'deferred':
+            # update best solution once per generation
+            if self._nfev >= self.maxfun:
+                raise StopIteration
+
+            # 'deferred' approach, vectorised form.
+            # create trial solutions
+            trial_pop = self._mutate_many(
+                np.arange(self.num_population_members)
+            )
+
+            # enforce bounds
+            self._ensure_constraint(trial_pop)
+
+            # determine the energies of the objective function, but only for
+            # feasible trials
+            feasible, cv = self._calculate_population_feasibilities(trial_pop)
+            trial_energies = np.full(self.num_population_members, np.inf)
+
+            # only calculate for feasible entries
+            trial_energies[feasible] = self._calculate_population_energies(
+                trial_pop[feasible])
+
+            # which solutions are 'improved'?
+            loc = [self._accept_trial(*val) for val in
+                   zip(trial_energies, feasible, cv, self.population_energies,
+                       self.feasible, self.constraint_violation)]
+            loc = np.array(loc)
+            self.population = np.where(loc[:, np.newaxis],
+                                       trial_pop,
+                                       self.population)
+            self.population_energies = np.where(loc,
+                                                trial_energies,
+                                                self.population_energies)
+            self.feasible = np.where(loc,
+                                     feasible,
+                                     self.feasible)
+            self.constraint_violation = np.where(loc[:, np.newaxis],
+                                                 cv,
+                                                 self.constraint_violation)
+
+            # make sure the best solution is updated if updating='deferred'.
+            # put the lowest energy into the best solution position.
+            self._promote_lowest_energy()
+
+        return self.x, self.population_energies[0]
+
+    def _scale_parameters(self, trial):
+        """Scale from a number between 0 and 1 to parameters."""
+        # trial either has shape (N, ) or (L, N), where L is the number of
+        # solutions being scaled
+        scaled = self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2
+        if np.count_nonzero(self.integrality):
+            i = np.broadcast_to(self.integrality, scaled.shape)
+            scaled[i] = np.round(scaled[i])
+        return scaled
+
+    def _unscale_parameters(self, parameters):
+        """Scale from parameters to a number between 0 and 1."""
+        return (parameters - self.__scale_arg1) * self.__recip_scale_arg2 + 0.5
+
+    def _ensure_constraint(self, trial):
+        """Make sure the parameters lie between the limits."""
+        mask = np.bitwise_or(trial > 1, trial < 0)
+        if oob := np.count_nonzero(mask):
+            trial[mask] = self.random_number_generator.uniform(size=oob)
+
+    def _mutate_custom(self, candidate):
+        rng = self.random_number_generator
+        msg = (
+            "strategy must have signature"
+            " f(candidate: int, population: np.ndarray, rng=None) returning an"
+            " array of shape (N,)"
+        )
+        _population = self._scale_parameters(self.population)
+        if not len(np.shape(candidate)):
+            # single entry in population
+            trial = self.strategy(candidate, _population, rng=rng)
+            if trial.shape != (self.parameter_count,):
+                raise RuntimeError(msg)
+        else:
+            S = candidate.shape[0]
+            trial = np.array(
+                [self.strategy(c, _population, rng=rng) for c in candidate],
+                dtype=float
+            )
+            if trial.shape != (S, self.parameter_count):
+                raise RuntimeError(msg)
+        return self._unscale_parameters(trial)
+
+    def _mutate_many(self, candidates):
+        """Create trial vectors based on a mutation strategy."""
+        rng = self.random_number_generator
+
+        S = len(candidates)
+        if callable(self.strategy):
+            return self._mutate_custom(candidates)
+
+        trial = np.copy(self.population[candidates])
+        samples = np.array([self._select_samples(c, 5) for c in candidates])
+
+        if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+            bprime = self.mutation_func(candidates, samples)
+        else:
+            bprime = self.mutation_func(samples)
+
+        fill_point = rng_integers(rng, self.parameter_count, size=S)
+        crossovers = rng.uniform(size=(S, self.parameter_count))
+        crossovers = crossovers < self.cross_over_probability
+        if self.strategy in self._binomial:
+            # the last one is always from the bprime vector for binomial
+            # If you fill in modulo with a loop you have to set the last one to
+            # true. If you don't use a loop then you can have any random entry
+            # be True.
+            i = np.arange(S)
+            crossovers[i, fill_point[i]] = True
+            trial = np.where(crossovers, bprime, trial)
+            return trial
+
+        elif self.strategy in self._exponential:
+            crossovers[..., 0] = True
+            for j in range(S):
+                i = 0
+                init_fill = fill_point[j]
+                while (i < self.parameter_count and crossovers[j, i]):
+                    trial[j, init_fill] = bprime[j, init_fill]
+                    init_fill = (init_fill + 1) % self.parameter_count
+                    i += 1
+
+            return trial
+
+    def _mutate(self, candidate):
+        """Create a trial vector based on a mutation strategy."""
+        rng = self.random_number_generator
+
+        if callable(self.strategy):
+            return self._mutate_custom(candidate)
+
+        fill_point = rng_integers(rng, self.parameter_count)
+        samples = self._select_samples(candidate, 5)
+
+        trial = np.copy(self.population[candidate])
+
+        if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+            bprime = self.mutation_func(candidate, samples)
+        else:
+            bprime = self.mutation_func(samples)
+
+        crossovers = rng.uniform(size=self.parameter_count)
+        crossovers = crossovers < self.cross_over_probability
+        if self.strategy in self._binomial:
+            # the last one is always from the bprime vector for binomial
+            # If you fill in modulo with a loop you have to set the last one to
+            # true. If you don't use a loop then you can have any random entry
+            # be True.
+            crossovers[fill_point] = True
+            trial = np.where(crossovers, bprime, trial)
+            return trial
+
+        elif self.strategy in self._exponential:
+            i = 0
+            crossovers[0] = True
+            while i < self.parameter_count and crossovers[i]:
+                trial[fill_point] = bprime[fill_point]
+                fill_point = (fill_point + 1) % self.parameter_count
+                i += 1
+
+            return trial
+
+    def _best1(self, samples):
+        """best1bin, best1exp"""
+        # samples.shape == (S, 5)
+        # or
+        # samples.shape(5,)
+        r0, r1 = samples[..., :2].T
+        return (self.population[0] + self.scale *
+                (self.population[r0] - self.population[r1]))
+
+    def _rand1(self, samples):
+        """rand1bin, rand1exp"""
+        r0, r1, r2 = samples[..., :3].T
+        return (self.population[r0] + self.scale *
+                (self.population[r1] - self.population[r2]))
+
+    def _randtobest1(self, samples):
+        """randtobest1bin, randtobest1exp"""
+        r0, r1, r2 = samples[..., :3].T
+        bprime = np.copy(self.population[r0])
+        bprime += self.scale * (self.population[0] - bprime)
+        bprime += self.scale * (self.population[r1] -
+                                self.population[r2])
+        return bprime
+
+    def _currenttobest1(self, candidate, samples):
+        """currenttobest1bin, currenttobest1exp"""
+        r0, r1 = samples[..., :2].T
+        bprime = (self.population[candidate] + self.scale *
+                  (self.population[0] - self.population[candidate] +
+                   self.population[r0] - self.population[r1]))
+        return bprime
+
+    def _best2(self, samples):
+        """best2bin, best2exp"""
+        r0, r1, r2, r3 = samples[..., :4].T
+        bprime = (self.population[0] + self.scale *
+                  (self.population[r0] + self.population[r1] -
+                   self.population[r2] - self.population[r3]))
+
+        return bprime
+
+    def _rand2(self, samples):
+        """rand2bin, rand2exp"""
+        r0, r1, r2, r3, r4 = samples[..., :5].T
+        bprime = (self.population[r0] + self.scale *
+                  (self.population[r1] + self.population[r2] -
+                   self.population[r3] - self.population[r4]))
+
+        return bprime
+
+    def _select_samples(self, candidate, number_samples):
+        """
+        obtain random integers from range(self.num_population_members),
+        without replacement. You can't have the original candidate either.
+        """
+        self.random_number_generator.shuffle(self._random_population_index)
+        idxs = self._random_population_index[:number_samples + 1]
+        return idxs[idxs != candidate][:number_samples]
+
+
+class _ConstraintWrapper:
+    """Object to wrap/evaluate user defined constraints.
+
+    Very similar in practice to `PreparedConstraint`, except that no evaluation
+    of jac/hess is performed (explicit or implicit).
+
+    If created successfully, it will contain the attributes listed below.
+
+    Parameters
+    ----------
+    constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`}
+        Constraint to check and prepare.
+    x0 : array_like
+        Initial vector of independent variables, shape (N,)
+
+    Attributes
+    ----------
+    fun : callable
+        Function defining the constraint wrapped by one of the convenience
+        classes.
+    bounds : 2-tuple
+        Contains lower and upper bounds for the constraints --- lb and ub.
+        These are converted to ndarray and have a size equal to the number of
+        the constraints.
+
+    Notes
+    -----
+    _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent
+    arrays of shape (N, S) or (N,), where S is the number of vectors of shape
+    (N,) to consider constraints for.
+    """
+    def __init__(self, constraint, x0):
+        self.constraint = constraint
+
+        if isinstance(constraint, NonlinearConstraint):
+            def fun(x):
+                x = np.asarray(x)
+                return np.atleast_1d(constraint.fun(x))
+        elif isinstance(constraint, LinearConstraint):
+            def fun(x):
+                if issparse(constraint.A):
+                    A = constraint.A
+                else:
+                    A = np.atleast_2d(constraint.A)
+
+                res = A.dot(x)
+                # x either has shape (N, S) or (N)
+                # (M, N) x (N, S) --> (M, S)
+                # (M, N) x (N,)   --> (M,)
+                # However, if (M, N) is a matrix then:
+                # (M, N) * (N,)   --> (M, 1), we need this to be (M,)
+                if x.ndim == 1 and res.ndim == 2:
+                    # deal with case that constraint.A is an np.matrix
+                    # see gh20041
+                    res = np.asarray(res)[:, 0]
+
+                return res
+        elif isinstance(constraint, Bounds):
+            def fun(x):
+                return np.asarray(x)
+        else:
+            raise ValueError("`constraint` of an unknown type is passed.")
+
+        self.fun = fun
+
+        lb = np.asarray(constraint.lb, dtype=float)
+        ub = np.asarray(constraint.ub, dtype=float)
+
+        x0 = np.asarray(x0)
+
+        # find out the number of constraints
+        f0 = fun(x0)
+        self.num_constr = m = f0.size
+        self.parameter_count = x0.size
+
+        if lb.ndim == 0:
+            lb = np.resize(lb, m)
+        if ub.ndim == 0:
+            ub = np.resize(ub, m)
+
+        self.bounds = (lb, ub)
+
+    def __call__(self, x):
+        return np.atleast_1d(self.fun(x))
+
+    def violation(self, x):
+        """How much the constraint is exceeded by.
+
+        Parameters
+        ----------
+        x : array-like
+            Vector of independent variables, (N, S), where N is number of
+            parameters and S is the number of solutions to be investigated.
+
+        Returns
+        -------
+        excess : array-like
+            How much the constraint is exceeded by, for each of the
+            constraints specified by `_ConstraintWrapper.fun`.
+            Has shape (M, S) where M is the number of constraint components.
+        """
+        # expect ev to have shape (num_constr, S) or (num_constr,)
+        ev = self.fun(np.asarray(x))
+
+        try:
+            excess_lb = np.maximum(self.bounds[0] - ev.T, 0)
+            excess_ub = np.maximum(ev.T - self.bounds[1], 0)
+        except ValueError as e:
+            raise RuntimeError("An array returned from a Constraint has"
+                               " the wrong shape. If `vectorized is False`"
+                               " the Constraint should return an array of"
+                               " shape (M,). If `vectorized is True` then"
+                               " the Constraint must return an array of"
+                               " shape (M, S), where S is the number of"
+                               " solution vectors and M is the number of"
+                               " constraint components in a given"
+                               " Constraint object.") from e
+
+        v = (excess_lb + excess_ub).T
+        return v
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_direct.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_direct.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c622a559586728ff1852563247ba4c473538aa88
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_direct.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_direct_py.py b/python_embeded/Lib/site-packages/scipy/optimize/_direct_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ef9ab77d6d0fc819a173193aee6188147ff122d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_dual_annealing.py b/python_embeded/Lib/site-packages/scipy/optimize/_dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..17e7193c8634c86f3fe18ed055062b0d94df9f4e
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_elementwise.py b/python_embeded/Lib/site-packages/scipy/optimize/_elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..12b6ae88512cc905b1073f3779c9fd0f77910b0a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_group_columns.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_group_columns.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..0d3900f246a709ef905509b1197a546df69ea446
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_group_columns.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_hessian_update_strategy.py b/python_embeded/Lib/site-packages/scipy/optimize/_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3d375acfb82b4ea76bec7ef5ff980ed9fe575d6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/_hessian_update_strategy.py
@@ -0,0 +1,479 @@
+"""Hessian update strategies for quasi-Newton optimization methods."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import get_blas_funcs, issymmetric
+from warnings import warn
+
+
+__all__ = ['HessianUpdateStrategy', 'BFGS', 'SR1']
+
+
+class HessianUpdateStrategy:
+    """Interface for implementing Hessian update strategies.
+
+    Many optimization methods make use of Hessian (or inverse Hessian)
+    approximations, such as the quasi-Newton methods BFGS, SR1, L-BFGS.
+    Some of these  approximations, however, do not actually need to store
+    the entire matrix or can compute the internal matrix product with a
+    given vector in a very efficiently manner. This class serves as an
+    abstract interface between the optimization algorithm and the
+    quasi-Newton update strategies, giving freedom of implementation
+    to store and update the internal matrix as efficiently as possible.
+    Different choices of initialization and update procedure will result
+    in different quasi-Newton strategies.
+
+    Four methods should be implemented in derived classes: ``initialize``,
+    ``update``, ``dot`` and ``get_matrix``. The matrix multiplication
+    operator ``@`` is also defined to call the ``dot`` method.
+
+    Notes
+    -----
+    Any instance of a class that implements this interface,
+    can be accepted by the method ``minimize`` and used by
+    the compatible solvers to approximate the Hessian (or
+    inverse Hessian) used by the optimization algorithms.
+    """
+
+    def initialize(self, n, approx_type):
+        """Initialize internal matrix.
+
+        Allocate internal memory for storing and updating
+        the Hessian or its inverse.
+
+        Parameters
+        ----------
+        n : int
+            Problem dimension.
+        approx_type : {'hess', 'inv_hess'}
+            Selects either the Hessian or the inverse Hessian.
+            When set to 'hess' the Hessian will be stored and updated.
+            When set to 'inv_hess' its inverse will be used instead.
+        """
+        raise NotImplementedError("The method ``initialize(n, approx_type)``"
+                                  " is not implemented.")
+
+    def update(self, delta_x, delta_grad):
+        """Update internal matrix.
+
+        Update Hessian matrix or its inverse (depending on how 'approx_type'
+        is defined) using information about the last evaluated points.
+
+        Parameters
+        ----------
+        delta_x : ndarray
+            The difference between two points the gradient
+            function have been evaluated at: ``delta_x = x2 - x1``.
+        delta_grad : ndarray
+            The difference between the gradients:
+            ``delta_grad = grad(x2) - grad(x1)``.
+        """
+        raise NotImplementedError("The method ``update(delta_x, delta_grad)``"
+                                  " is not implemented.")
+
+    def dot(self, p):
+        """Compute the product of the internal matrix with the given vector.
+
+        Parameters
+        ----------
+        p : array_like
+            1-D array representing a vector.
+
+        Returns
+        -------
+        Hp : array
+            1-D represents the result of multiplying the approximation matrix
+            by vector p.
+        """
+        raise NotImplementedError("The method ``dot(p)``"
+                                  " is not implemented.")
+
+    def get_matrix(self):
+        """Return current internal matrix.
+
+        Returns
+        -------
+        H : ndarray, shape (n, n)
+            Dense matrix containing either the Hessian
+            or its inverse (depending on how 'approx_type'
+            is defined).
+        """
+        raise NotImplementedError("The method ``get_matrix(p)``"
+                                  " is not implemented.")
+
+    def __matmul__(self, p):
+        return self.dot(p)
+
+
+class FullHessianUpdateStrategy(HessianUpdateStrategy):
+    """Hessian update strategy with full dimensional internal representation.
+    """
+    _syr = get_blas_funcs('syr', dtype='d')  # Symmetric rank 1 update
+    _syr2 = get_blas_funcs('syr2', dtype='d')  # Symmetric rank 2 update
+    # Symmetric matrix-vector product
+    _symv = get_blas_funcs('symv', dtype='d')
+
+    def __init__(self, init_scale='auto'):
+        self.init_scale = init_scale
+        # Until initialize is called we can't really use the class,
+        # so it makes sense to set everything to None.
+        self.first_iteration = None
+        self.approx_type = None
+        self.B = None
+        self.H = None
+
+    def initialize(self, n, approx_type):
+        """Initialize internal matrix.
+
+        Allocate internal memory for storing and updating
+        the Hessian or its inverse.
+
+        Parameters
+        ----------
+        n : int
+            Problem dimension.
+        approx_type : {'hess', 'inv_hess'}
+            Selects either the Hessian or the inverse Hessian.
+            When set to 'hess' the Hessian will be stored and updated.
+            When set to 'inv_hess' its inverse will be used instead.
+        """
+        self.first_iteration = True
+        self.n = n
+        self.approx_type = approx_type
+        if approx_type not in ('hess', 'inv_hess'):
+            raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.")
+        # Create matrix
+        if self.approx_type == 'hess':
+            self.B = np.eye(n, dtype=float)
+        else:
+            self.H = np.eye(n, dtype=float)
+
+    def _auto_scale(self, delta_x, delta_grad):
+        # Heuristic to scale matrix at first iteration.
+        # Described in Nocedal and Wright "Numerical Optimization"
+        # p.143 formula (6.20).
+        s_norm2 = np.dot(delta_x, delta_x)
+        y_norm2 = np.dot(delta_grad, delta_grad)
+        ys = np.abs(np.dot(delta_grad, delta_x))
+        if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0:
+            return 1
+        if self.approx_type == 'hess':
+            return y_norm2 / ys
+        else:
+            return ys / y_norm2
+
+    def _update_implementation(self, delta_x, delta_grad):
+        raise NotImplementedError("The method ``_update_implementation``"
+                                  " is not implemented.")
+
+    def update(self, delta_x, delta_grad):
+        """Update internal matrix.
+
+        Update Hessian matrix or its inverse (depending on how 'approx_type'
+        is defined) using information about the last evaluated points.
+
+        Parameters
+        ----------
+        delta_x : ndarray
+            The difference between two points the gradient
+            function have been evaluated at: ``delta_x = x2 - x1``.
+        delta_grad : ndarray
+            The difference between the gradients:
+            ``delta_grad = grad(x2) - grad(x1)``.
+        """
+        if np.all(delta_x == 0.0):
+            return
+        if np.all(delta_grad == 0.0):
+            warn('delta_grad == 0.0. Check if the approximated '
+                 'function is linear. If the function is linear '
+                 'better results can be obtained by defining the '
+                 'Hessian as zero instead of using quasi-Newton '
+                 'approximations.',
+                 UserWarning, stacklevel=2)
+            return
+        if self.first_iteration:
+            # Get user specific scale
+            if isinstance(self.init_scale, str) and self.init_scale == "auto":
+                scale = self._auto_scale(delta_x, delta_grad)
+            else:
+                scale = self.init_scale
+
+            # Check for complex: numpy will silently cast a complex array to
+            # a real one but not so for scalar as it raises a TypeError.
+            # Checking here brings a consistent behavior.
+            replace = False
+            if np.size(scale) == 1:
+                # to account for the legacy behavior having the exact same cast
+                scale = float(scale)
+            elif np.iscomplexobj(scale):
+                raise TypeError("init_scale contains complex elements, "
+                                "must be real.")
+            else:  # test explicitly for allowed shapes and values
+                replace = True
+                if self.approx_type == 'hess':
+                    shape = np.shape(self.B)
+                    dtype = self.B.dtype
+                else:
+                    shape = np.shape(self.H)
+                    dtype = self.H.dtype
+                # copy, will replace the original
+                scale = np.array(scale, dtype=dtype, copy=True)
+
+                # it has to match the shape of the matrix for the multiplication,
+                # no implicit broadcasting is allowed
+                if shape != (init_shape := np.shape(scale)):
+                    raise ValueError("If init_scale is an array, it must have the "
+                                     f"dimensions of the hess/inv_hess: {shape}."
+                                     f" Got {init_shape}.")
+                if not issymmetric(scale):
+                    raise ValueError("If init_scale is an array, it must be"
+                                     " symmetric (passing scipy.linalg.issymmetric)"
+                                     " to be an approximation of a hess/inv_hess.")
+
+            # Scale initial matrix with ``scale * np.eye(n)`` or replace
+            # This is not ideal, we could assign the scale directly in
+            # initialize, but we would need to
+            if self.approx_type == 'hess':
+                if replace:
+                    self.B = scale
+                else:
+                    self.B *= scale
+            else:
+                if replace:
+                    self.H = scale
+                else:
+                    self.H *= scale
+            self.first_iteration = False
+        self._update_implementation(delta_x, delta_grad)
+
+    def dot(self, p):
+        """Compute the product of the internal matrix with the given vector.
+
+        Parameters
+        ----------
+        p : array_like
+            1-D array representing a vector.
+
+        Returns
+        -------
+        Hp : array
+            1-D represents the result of multiplying the approximation matrix
+            by vector p.
+        """
+        if self.approx_type == 'hess':
+            return self._symv(1, self.B, p)
+        else:
+            return self._symv(1, self.H, p)
+
+    def get_matrix(self):
+        """Return the current internal matrix.
+
+        Returns
+        -------
+        M : ndarray, shape (n, n)
+            Dense matrix containing either the Hessian or its inverse
+            (depending on how `approx_type` was defined).
+        """
+        if self.approx_type == 'hess':
+            M = np.copy(self.B)
+        else:
+            M = np.copy(self.H)
+        li = np.tril_indices_from(M, k=-1)
+        M[li] = M.T[li]
+        return M
+
+
+class BFGS(FullHessianUpdateStrategy):
+    """Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
+
+    Parameters
+    ----------
+    exception_strategy : {'skip_update', 'damp_update'}, optional
+        Define how to proceed when the curvature condition is violated.
+        Set it to 'skip_update' to just skip the update. Or, alternatively,
+        set it to 'damp_update' to interpolate between the actual BFGS
+        result and the unmodified matrix. Both exceptions strategies
+        are explained  in [1]_, p.536-537.
+    min_curvature : float
+        This number, scaled by a normalization factor, defines the
+        minimum curvature ``dot(delta_grad, delta_x)`` allowed to go
+        unaffected by the exception strategy. By default is equal to
+        1e-8 when ``exception_strategy = 'skip_update'`` and equal
+        to 0.2 when ``exception_strategy = 'damp_update'``.
+    init_scale : {float, np.array, 'auto'}
+        This parameter can be used to initialize the Hessian or its
+        inverse. When a float is given, the relevant array is initialized
+        to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+        Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+        this array will be used. Otherwise an error is generated.
+        Set it to 'auto' in order to use an automatic heuristic for choosing
+        the initial scale. The heuristic is described in [1]_, p.143.
+        The default is 'auto'.
+
+    Notes
+    -----
+    The update is based on the description in [1]_, p.140.
+
+    References
+    ----------
+    .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+           Second Edition (2006).
+    """
+
+    def __init__(self, exception_strategy='skip_update', min_curvature=None,
+                 init_scale='auto'):
+        if exception_strategy == 'skip_update':
+            if min_curvature is not None:
+                self.min_curvature = min_curvature
+            else:
+                self.min_curvature = 1e-8
+        elif exception_strategy == 'damp_update':
+            if min_curvature is not None:
+                self.min_curvature = min_curvature
+            else:
+                self.min_curvature = 0.2
+        else:
+            raise ValueError("`exception_strategy` must be 'skip_update' "
+                             "or 'damp_update'.")
+
+        super().__init__(init_scale)
+        self.exception_strategy = exception_strategy
+
+    def _update_inverse_hessian(self, ys, Hy, yHy, s):
+        """Update the inverse Hessian matrix.
+
+        BFGS update using the formula:
+
+            ``H <- H + ((H*y).T*y + s.T*y)/(s.T*y)^2 * (s*s.T)
+                     - 1/(s.T*y) * ((H*y)*s.T + s*(H*y).T)``
+
+        where ``s = delta_x`` and ``y = delta_grad``. This formula is
+        equivalent to (6.17) in [1]_ written in a more efficient way
+        for implementation.
+
+        References
+        ----------
+        .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+               Second Edition (2006).
+        """
+        self.H = self._syr2(-1.0 / ys, s, Hy, a=self.H)
+        self.H = self._syr((ys + yHy) / ys ** 2, s, a=self.H)
+
+    def _update_hessian(self, ys, Bs, sBs, y):
+        """Update the Hessian matrix.
+
+        BFGS update using the formula:
+
+            ``B <- B - (B*s)*(B*s).T/s.T*(B*s) + y*y^T/s.T*y``
+
+        where ``s`` is short for ``delta_x`` and ``y`` is short
+        for ``delta_grad``. Formula (6.19) in [1]_.
+
+        References
+        ----------
+        .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+               Second Edition (2006).
+        """
+        self.B = self._syr(1.0 / ys, y, a=self.B)
+        self.B = self._syr(-1.0 / sBs, Bs, a=self.B)
+
+    def _update_implementation(self, delta_x, delta_grad):
+        # Auxiliary variables w and z
+        if self.approx_type == 'hess':
+            w = delta_x
+            z = delta_grad
+        else:
+            w = delta_grad
+            z = delta_x
+        # Do some common operations
+        wz = np.dot(w, z)
+        Mw = self @ w
+        wMw = Mw.dot(w)
+        # Guarantee that wMw > 0 by reinitializing matrix.
+        # While this is always true in exact arithmetic,
+        # indefinite matrix may appear due to roundoff errors.
+        if wMw <= 0.0:
+            scale = self._auto_scale(delta_x, delta_grad)
+            # Reinitialize matrix
+            if self.approx_type == 'hess':
+                self.B = scale * np.eye(self.n, dtype=float)
+            else:
+                self.H = scale * np.eye(self.n, dtype=float)
+            # Do common operations for new matrix
+            Mw = self @ w
+            wMw = Mw.dot(w)
+        # Check if curvature condition is violated
+        if wz <= self.min_curvature * wMw:
+            # If the option 'skip_update' is set
+            # we just skip the update when the condition
+            # is violated.
+            if self.exception_strategy == 'skip_update':
+                return
+            # If the option 'damp_update' is set we
+            # interpolate between the actual BFGS
+            # result and the unmodified matrix.
+            elif self.exception_strategy == 'damp_update':
+                update_factor = (1-self.min_curvature) / (1 - wz/wMw)
+                z = update_factor*z + (1-update_factor)*Mw
+                wz = np.dot(w, z)
+        # Update matrix
+        if self.approx_type == 'hess':
+            self._update_hessian(wz, Mw, wMw, z)
+        else:
+            self._update_inverse_hessian(wz, Mw, wMw, z)
+
+
+class SR1(FullHessianUpdateStrategy):
+    """Symmetric-rank-1 Hessian update strategy.
+
+    Parameters
+    ----------
+    min_denominator : float
+        This number, scaled by a normalization factor,
+        defines the minimum denominator magnitude allowed
+        in the update. When the condition is violated we skip
+        the update. By default uses ``1e-8``.
+    init_scale : {float, np.array, 'auto'}, optional
+        This parameter can be used to initialize the Hessian or its
+        inverse. When a float is given, the relevant array is initialized
+        to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+        Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+        this array will be used. Otherwise an error is generated.
+        Set it to 'auto' in order to use an automatic heuristic for choosing
+        the initial scale. The heuristic is described in [1]_, p.143.
+        The default is 'auto'.
+
+    Notes
+    -----
+    The update is based on the description in [1]_, p.144-146.
+
+    References
+    ----------
+    .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+           Second Edition (2006).
+    """
+
+    def __init__(self, min_denominator=1e-8, init_scale='auto'):
+        self.min_denominator = min_denominator
+        super().__init__(init_scale)
+
+    def _update_implementation(self, delta_x, delta_grad):
+        # Auxiliary variables w and z
+        if self.approx_type == 'hess':
+            w = delta_x
+            z = delta_grad
+        else:
+            w = delta_grad
+            z = delta_x
+        # Do some common operations
+        Mw = self @ w
+        z_minus_Mw = z - Mw
+        denominator = np.dot(w, z_minus_Mw)
+        # If the denominator is too small
+        # we just skip the update.
+        if np.abs(denominator) <= self.min_denominator*norm(w)*norm(z_minus_Mw):
+            return
+        # Update matrix
+        if self.approx_type == 'hess':
+            self.B = self._syr(1/denominator, z_minus_Mw, a=self.B)
+        else:
+            self.H = self._syr(1/denominator, z_minus_Mw, a=self.H)
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_isotonic.py b/python_embeded/Lib/site-packages/scipy/optimize/_isotonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..3158f4404dd17a3a655d082deaa7c63478442947
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..78b386000daf3e165ba19bfae5e0a171d18b516a
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb_py.py b/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..700ec44a9be8a7880fd2e701cbc83d790dba9e20
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/_lbfgsb_py.py
@@ -0,0 +1,578 @@
+"""
+Functions
+---------
+.. autosummary::
+   :toctree: generated/
+
+    fmin_l_bfgs_b
+
+"""
+
+## License for the Python wrapper
+## ==============================
+
+## Copyright (c) 2004 David M. Cooke 
+
+## Permission is hereby granted, free of charge, to any person obtaining a
+## copy of this software and associated documentation files (the "Software"),
+## to deal in the Software without restriction, including without limitation
+## the rights to use, copy, modify, merge, publish, distribute, sublicense,
+## and/or sell copies of the Software, and to permit persons to whom the
+## Software is furnished to do so, subject to the following conditions:
+
+## The above copyright notice and this permission notice shall be included in
+## all copies or substantial portions of the Software.
+
+## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+## DEALINGS IN THE SOFTWARE.
+
+## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy
+
+import numpy as np
+from numpy import array, asarray, float64, zeros
+from . import _lbfgsb
+from ._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt,
+                        _wrap_callback, _check_unknown_options,
+                        _prepare_scalar_function)
+from ._constraints import old_bound_to_new
+
+from scipy.sparse.linalg import LinearOperator
+
+__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']
+
+
+status_messages = {
+    0 : "START",
+    1 : "NEW_X",
+    2 : "RESTART",
+    3 : "FG",
+    4 : "CONVERGENCE",
+    5 : "STOP",
+    6 : "WARNING",
+    7 : "ERROR",
+    8 : "ABNORMAL"
+}
+
+
+task_messages = {
+    0 : "",
+    301 : "",
+    302 : "",
+    401 : "NORM OF PROJECTED GRADIENT <= PGTOL",
+    402 : "RELATIVE REDUCTION OF F <= FACTR*EPSMCH",
+    501 : "CPU EXCEEDING THE TIME LIMIT",
+    502 : "TOTAL NO. OF F,G EVALUATIONS EXCEEDS LIMIT",
+    503 : "PROJECTED GRADIENT IS SUFFICIENTLY SMALL",
+    504 : "TOTAL NO. OF ITERATIONS REACHED LIMIT",
+    505 : "CALLBACK REQUESTED HALT",
+    601 : "ROUNDING ERRORS PREVENT PROGRESS",
+    602 : "STP = STPMAX",
+    603 : "STP = STPMIN",
+    604 : "XTOL TEST SATISFIED",
+    701 : "NO FEASIBLE SOLUTION",
+    702 : "FACTR < 0",
+    703 : "FTOL < 0",
+    704 : "GTOL < 0",
+    705 : "XTOL < 0",
+    706 : "STP < STPMIN",
+    707 : "STP > STPMAX",
+    708 : "STPMIN < 0",
+    709 : "STPMAX < STPMIN",
+    710 : "INITIAL G >= 0",
+    711 : "M <= 0",
+    712 : "N <= 0",
+    713 : "INVALID NBD",
+}
+
+def fmin_l_bfgs_b(func, x0, fprime=None, args=(),
+                  approx_grad=0,
+                  bounds=None, m=10, factr=1e7, pgtol=1e-5,
+                  epsilon=1e-8,
+                  iprint=-1, maxfun=15000, maxiter=15000, disp=None,
+                  callback=None, maxls=20):
+    """
+    Minimize a function func using the L-BFGS-B algorithm.
+
+    Parameters
+    ----------
+    func : callable f(x,*args)
+        Function to minimize.
+    x0 : ndarray
+        Initial guess.
+    fprime : callable fprime(x,*args), optional
+        The gradient of `func`. If None, then `func` returns the function
+        value and the gradient (``f, g = func(x, *args)``), unless
+        `approx_grad` is True in which case `func` returns only ``f``.
+    args : sequence, optional
+        Arguments to pass to `func` and `fprime`.
+    approx_grad : bool, optional
+        Whether to approximate the gradient numerically (in which case
+        `func` returns only the function value).
+    bounds : list, optional
+        ``(min, max)`` pairs for each element in ``x``, defining
+        the bounds on that parameter. Use None or +-inf for one of ``min`` or
+        ``max`` when there is no bound in that direction.
+    m : int, optional
+        The maximum number of variable metric corrections
+        used to define the limited memory matrix. (The limited memory BFGS
+        method does not store the full hessian but uses this many terms in an
+        approximation to it.)
+    factr : float, optional
+        The iteration stops when
+        ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
+        where ``eps`` is the machine precision, which is automatically
+        generated by the code. Typical values for `factr` are: 1e12 for
+        low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
+        high accuracy. See Notes for relationship to `ftol`, which is exposed
+        (instead of `factr`) by the `scipy.optimize.minimize` interface to
+        L-BFGS-B.
+    pgtol : float, optional
+        The iteration will stop when
+        ``max{|proj g_i | i = 1, ..., n} <= pgtol``
+        where ``proj g_i`` is the i-th component of the projected gradient.
+    epsilon : float, optional
+        Step size used when `approx_grad` is True, for numerically
+        calculating the gradient
+    iprint : int, optional
+        Deprecated option that previously controlled the text printed on the
+        screen during the problem solution. Now the code does not emit any
+        output and this keyword has no function.
+
+        .. deprecated:: 1.15.0
+            This keyword is deprecated and will be removed from SciPy 1.17.0.
+
+    disp : int, optional
+        Deprecated option that previously controlled the text printed on the
+        screen during the problem solution. Now the code does not emit any
+        output and this keyword has no function.
+
+        .. deprecated:: 1.15.0
+            This keyword is deprecated and will be removed from SciPy 1.17.0.
+
+    maxfun : int, optional
+        Maximum number of function evaluations. Note that this function
+        may violate the limit because of evaluating gradients by numerical
+        differentiation.
+    maxiter : int, optional
+        Maximum number of iterations.
+    callback : callable, optional
+        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+        current parameter vector.
+    maxls : int, optional
+        Maximum number of line search steps (per iteration). Default is 20.
+
+    Returns
+    -------
+    x : array_like
+        Estimated position of the minimum.
+    f : float
+        Value of `func` at the minimum.
+    d : dict
+        Information dictionary.
+
+        * d['warnflag'] is
+
+          - 0 if converged,
+          - 1 if too many function evaluations or too many iterations,
+          - 2 if stopped for another reason, given in d['task']
+
+        * d['grad'] is the gradient at the minimum (should be 0 ish)
+        * d['funcalls'] is the number of function calls made.
+        * d['nit'] is the number of iterations.
+
+    See also
+    --------
+    minimize: Interface to minimization algorithms for multivariate
+        functions. See the 'L-BFGS-B' `method` in particular. Note that the
+        `ftol` option is made available via that interface, while `factr` is
+        provided via this interface, where `factr` is the factor multiplying
+        the default machine floating-point precision to arrive at `ftol`:
+        ``ftol = factr * numpy.finfo(float).eps``.
+
+    Notes
+    -----
+    SciPy uses a C-translated and modified version of the Fortran code,
+    L-BFGS-B v3.0 (released April 25, 2011, BSD-3 licensed). Original Fortran
+    version was written by Ciyou Zhu, Richard Byrd, Jorge Nocedal and,
+    Jose Luis Morales.
+
+    References
+    ----------
+    * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
+      Constrained Optimization, (1995), SIAM Journal on Scientific and
+      Statistical Computing, 16, 5, pp. 1190-1208.
+    * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
+      FORTRAN routines for large scale bound constrained optimization (1997),
+      ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
+    * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
+      FORTRAN routines for large scale bound constrained optimization (2011),
+      ACM Transactions on Mathematical Software, 38, 1.
+
+    Examples
+    --------
+    Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we
+    define an objective function ``f(m, b) = (y - y_model)**2``, where `y`
+    describes the observations and `y_model` the prediction of the linear model
+    as ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``,
+    are arbitrarily chosen as ``(0,5)`` and ``(5,10)`` for this example.
+
+    >>> import numpy as np
+    >>> from scipy.optimize import fmin_l_bfgs_b
+    >>> X = np.arange(0, 10, 1)
+    >>> M = 2
+    >>> B = 3
+    >>> Y = M * X + B
+    >>> def func(parameters, *args):
+    ...     x = args[0]
+    ...     y = args[1]
+    ...     m, b = parameters
+    ...     y_model = m*x + b
+    ...     error = sum(np.power((y - y_model), 2))
+    ...     return error
+
+    >>> initial_values = np.array([0.0, 1.0])
+
+    >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
+    ...                                    approx_grad=True)
+    >>> x_opt, f_opt
+    array([1.99999999, 3.00000006]), 1.7746231151323805e-14  # may vary
+
+    The optimized parameters in ``x_opt`` agree with the ground truth parameters
+    ``m`` and ``b``. Next, let us perform a bound constrained optimization using
+    the `bounds` parameter.
+
+    >>> bounds = [(0, 5), (5, 10)]
+    >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
+    ...                                   approx_grad=True, bounds=bounds)
+    >>> x_opt, f_opt
+    array([1.65990508, 5.31649385]), 15.721334516453945  # may vary
+    """
+    # handle fprime/approx_grad
+    if approx_grad:
+        fun = func
+        jac = None
+    elif fprime is None:
+        fun = MemoizeJac(func)
+        jac = fun.derivative
+    else:
+        fun = func
+        jac = fprime
+
+    # build options
+    callback = _wrap_callback(callback)
+    opts = {'maxcor': m,
+            'ftol': factr * np.finfo(float).eps,
+            'gtol': pgtol,
+            'eps': epsilon,
+            'maxfun': maxfun,
+            'maxiter': maxiter,
+            'callback': callback,
+            'maxls': maxls}
+
+    res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
+                           **opts)
+    d = {'grad': res['jac'],
+         'task': res['message'],
+         'funcalls': res['nfev'],
+         'nit': res['nit'],
+         'warnflag': res['status']}
+    f = res['fun']
+    x = res['x']
+
+    return x, f, d
+
+
+def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None,
+                     disp=None, maxcor=10, ftol=2.2204460492503131e-09,
+                     gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000,
+                     iprint=-1, callback=None, maxls=20,
+                     finite_diff_rel_step=None, **unknown_options):
+    """
+    Minimize a scalar function of one or more variables using the L-BFGS-B
+    algorithm.
+
+    Options
+    -------
+    disp : None or int
+        Deprecated option that previously controlled the text printed on the
+        screen during the problem solution. Now the code does not emit any
+        output and this keyword has no function.
+
+        .. deprecated:: 1.15.0
+            This keyword is deprecated and will be removed from SciPy 1.17.0.
+
+    maxcor : int
+        The maximum number of variable metric corrections used to
+        define the limited memory matrix. (The limited memory BFGS
+        method does not store the full hessian but uses this many terms
+        in an approximation to it.)
+    ftol : float
+        The iteration stops when ``(f^k -
+        f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
+    gtol : float
+        The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
+        <= gtol`` where ``proj g_i`` is the i-th component of the
+        projected gradient.
+    eps : float or ndarray
+        If `jac is None` the absolute step size used for numerical
+        approximation of the jacobian via forward differences.
+    maxfun : int
+        Maximum number of function evaluations. Note that this function
+        may violate the limit because of evaluating gradients by numerical
+        differentiation.
+    maxiter : int
+        Maximum number of iterations.
+    iprint : int, optional
+        Deprecated option that previously controlled the text printed on the
+        screen during the problem solution. Now the code does not emit any
+        output and this keyword has no function.
+
+        .. deprecated:: 1.15.0
+            This keyword is deprecated and will be removed from SciPy 1.17.0.
+
+    maxls : int, optional
+        Maximum number of line search steps (per iteration). Default is 20.
+    finite_diff_rel_step : None or array_like, optional
+        If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+        use for numerical approximation of the jacobian. The absolute step
+        size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+        possibly adjusted to fit into the bounds. For ``method='3-point'``
+        the sign of `h` is ignored. If None (default) then step is selected
+        automatically.
+
+    Notes
+    -----
+    The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
+    but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
+    relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
+    I.e., `factr` multiplies the default machine floating-point precision to
+    arrive at `ftol`.
+
+    """
+    _check_unknown_options(unknown_options)
+    m = maxcor
+    pgtol = gtol
+    factr = ftol / np.finfo(float).eps
+
+    x0 = asarray(x0).ravel()
+    n, = x0.shape
+
+    # historically old-style bounds were/are expected by lbfgsb.
+    # That's still the case but we'll deal with new-style from here on,
+    # it's easier
+    if bounds is None:
+        pass
+    elif len(bounds) != n:
+        raise ValueError('length of x0 != length of bounds')
+    else:
+        bounds = np.array(old_bound_to_new(bounds))
+
+        # check bounds
+        if (bounds[0] > bounds[1]).any():
+            raise ValueError(
+                "LBFGSB - one of the lower bounds is greater than an upper bound."
+            )
+
+        # initial vector must lie within the bounds. Otherwise ScalarFunction and
+        # approx_derivative will cause problems
+        x0 = np.clip(x0, bounds[0], bounds[1])
+
+    # _prepare_scalar_function can use bounds=None to represent no bounds
+    sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+                                  bounds=bounds,
+                                  finite_diff_rel_step=finite_diff_rel_step)
+
+    func_and_grad = sf.fun_and_grad
+
+    nbd = zeros(n, np.int32)
+    low_bnd = zeros(n, float64)
+    upper_bnd = zeros(n, float64)
+    bounds_map = {(-np.inf, np.inf): 0,
+                  (1, np.inf): 1,
+                  (1, 1): 2,
+                  (-np.inf, 1): 3}
+
+    if bounds is not None:
+        for i in range(0, n):
+            L, U = bounds[0, i], bounds[1, i]
+            if not np.isinf(L):
+                low_bnd[i] = L
+                L = 1
+            if not np.isinf(U):
+                upper_bnd[i] = U
+                U = 1
+            nbd[i] = bounds_map[L, U]
+
+    if not maxls > 0:
+        raise ValueError('maxls must be positive.')
+
+    x = array(x0, dtype=np.float64)
+    f = array(0.0, dtype=np.int32)
+    g = zeros((n,), dtype=np.int32)
+    wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64)
+    iwa = zeros(3*n, dtype=np.int32)
+    task = zeros(2, dtype=np.int32)
+    ln_task = zeros(2, dtype=np.int32)
+    lsave = zeros(4, dtype=np.int32)
+    isave = zeros(44, dtype=np.int32)
+    dsave = zeros(29, dtype=float64)
+
+    n_iterations = 0
+
+    while True:
+        # g may become float32 if a user provides a function that calculates
+        # the Jacobian in float32 (see gh-18730). The underlying code expects
+        # float64, so upcast it
+        g = g.astype(np.float64)
+        # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \
+        _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
+                       iwa, task, lsave, isave, dsave, maxls, ln_task)
+
+        if task[0] == 3:
+            # The minimization routine wants f and g at the current x.
+            # Note that interruptions due to maxfun are postponed
+            # until the completion of the current minimization iteration.
+            # Overwrite f and g:
+            f, g = func_and_grad(x)
+        elif task[0] == 1:
+            # new iteration
+            n_iterations += 1
+
+            intermediate_result = OptimizeResult(x=x, fun=f)
+            if _call_callback_maybe_halt(callback, intermediate_result):
+                task[0] = 5
+                task[1] = 505
+            if n_iterations >= maxiter:
+                task[0] = 5
+                task[1] = 504
+            elif sf.nfev > maxfun:
+                task[0] = 5
+                task[1] = 502
+        else:
+            break
+
+    if task[0] == 4:
+        warnflag = 0
+    elif sf.nfev > maxfun or n_iterations >= maxiter:
+        warnflag = 1
+    else:
+        warnflag = 2
+
+    # These two portions of the workspace are described in the mainlb
+    # function docstring in "__lbfgsb.c", ws and wy arguments.
+    s = wa[0: m*n].reshape(m, n)
+    y = wa[m*n: 2*m*n].reshape(m, n)
+
+    # isave(31) = the total number of BFGS updates prior the current iteration.
+    n_bfgs_updates = isave[30]
+
+    n_corrs = min(n_bfgs_updates, maxcor)
+    hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs])
+
+    msg = status_messages[task[0]] + ": " + task_messages[task[1]]
+
+    return OptimizeResult(fun=f, jac=g, nfev=sf.nfev,
+                          njev=sf.ngev,
+                          nit=n_iterations, status=warnflag, message=msg,
+                          x=x, success=(warnflag == 0), hess_inv=hess_inv)
+
+
+class LbfgsInvHessProduct(LinearOperator):
+    """Linear operator for the L-BFGS approximate inverse Hessian.
+
+    This operator computes the product of a vector with the approximate inverse
+    of the Hessian of the objective function, using the L-BFGS limited
+    memory approximation to the inverse Hessian, accumulated during the
+    optimization.
+
+    Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
+    interface.
+
+    Parameters
+    ----------
+    sk : array_like, shape=(n_corr, n)
+        Array of `n_corr` most recent updates to the solution vector.
+        (See [1]).
+    yk : array_like, shape=(n_corr, n)
+        Array of `n_corr` most recent updates to the gradient. (See [1]).
+
+    References
+    ----------
+    .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
+       storage." Mathematics of computation 35.151 (1980): 773-782.
+
+    """
+
+    def __init__(self, sk, yk):
+        """Construct the operator."""
+        if sk.shape != yk.shape or sk.ndim != 2:
+            raise ValueError('sk and yk must have matching shape, (n_corrs, n)')
+        n_corrs, n = sk.shape
+
+        super().__init__(dtype=np.float64, shape=(n, n))
+
+        self.sk = sk
+        self.yk = yk
+        self.n_corrs = n_corrs
+        self.rho = 1 / np.einsum('ij,ij->i', sk, yk)
+
+    def _matvec(self, x):
+        """Efficient matrix-vector multiply with the BFGS matrices.
+
+        This calculation is described in Section (4) of [1].
+
+        Parameters
+        ----------
+        x : ndarray
+            An array with shape (n,) or (n,1).
+
+        Returns
+        -------
+        y : ndarray
+            The matrix-vector product
+
+        """
+        s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+        q = np.array(x, dtype=self.dtype, copy=True)
+        if q.ndim == 2 and q.shape[1] == 1:
+            q = q.reshape(-1)
+
+        alpha = np.empty(n_corrs)
+
+        for i in range(n_corrs-1, -1, -1):
+            alpha[i] = rho[i] * np.dot(s[i], q)
+            q = q - alpha[i]*y[i]
+
+        r = q
+        for i in range(n_corrs):
+            beta = rho[i] * np.dot(y[i], r)
+            r = r + s[i] * (alpha[i] - beta)
+
+        return r
+
+    def todense(self):
+        """Return a dense array representation of this operator.
+
+        Returns
+        -------
+        arr : ndarray, shape=(n, n)
+            An array with the same shape and containing
+            the same data represented by this `LinearOperator`.
+
+        """
+        s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+        I_arr = np.eye(*self.shape, dtype=self.dtype)
+        Hk = I_arr
+
+        for i in range(n_corrs):
+            A1 = I_arr - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
+            A2 = I_arr - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
+
+            Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
+                                                        s[i][np.newaxis, :])
+        return Hk
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/_linesearch.py b/python_embeded/Lib/site-packages/scipy/optimize/_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfaebbc995276fb8acf80059521032dc1e0847d4
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/cobyla.py b/python_embeded/Lib/site-packages/scipy/optimize/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..80eeda8c31b4890325deb7da42c5d865c09b9992
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/cython_optimize.pxd b/python_embeded/Lib/site-packages/scipy/optimize/cython_optimize.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..113c406378a4c86a0051aad35ad66ac64e3f4b7d
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/elementwise.py b/python_embeded/Lib/site-packages/scipy/optimize/elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ec5a269fb11bf3b17046829cdbb5c44f7d452f7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/elementwise.py
@@ -0,0 +1,38 @@
+"""
+===================================================================
+Elementwise Scalar Optimization (:mod:`scipy.optimize.elementwise`)
+===================================================================
+
+.. currentmodule:: scipy.optimize.elementwise
+
+This module provides a collection of functions for root finding and
+minimization of scalar, real-valued functions of one variable. Unlike their
+counterparts in the base :mod:`scipy.optimize` namespace, these functions work
+elementwise, enabling the solution of many related problems in an efficient,
+vectorized call. Furthermore, when environment variable ``SCIPY_ARRAY_API=1``,
+these functions can accept non-NumPy, array API standard compatible arrays and
+perform all calculations using the corresponding array library (e.g. PyTorch,
+JAX, CuPy).
+
+Root finding
+============
+
+.. autosummary::
+   :toctree: generated/
+
+   find_root
+   bracket_root
+
+Minimization
+============
+
+.. autosummary::
+   :toctree: generated/
+
+   find_minimum
+   bracket_minimum
+
+"""
+from ._elementwise import find_root, find_minimum, bracket_root, bracket_minimum  # noqa: F401, E501
+
+__all__ = ["find_root", "find_minimum", "bracket_root", "bracket_minimum"]
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/lbfgsb.py b/python_embeded/Lib/site-packages/scipy/optimize/lbfgsb.py
new file mode 100644
index 0000000000000000000000000000000000000000..e638c4832d64cf43e7901c9a411528e4f331825a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/linesearch.py b/python_embeded/Lib/site-packages/scipy/optimize/linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ee059297a299b5fbc0cde047d2191f779a788a4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/linesearch.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["line_search"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="optimize", module="linesearch",
+                                   private_modules=["_linesearch"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/minpack.py b/python_embeded/Lib/site-packages/scipy/optimize/minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..93c21749243869349afd550d2ac21c2d2515ac91
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/minpack2.py b/python_embeded/Lib/site-packages/scipy/optimize/minpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6c03d2dedffc2862daba4c81d5313c66e06fbcd
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/moduleTNC.py b/python_embeded/Lib/site-packages/scipy/optimize/moduleTNC.py
new file mode 100644
index 0000000000000000000000000000000000000000..654491ca5080515359d602c50c8d7fad0ecad0b8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/nonlin.py b/python_embeded/Lib/site-packages/scipy/optimize/nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7a5755279d04e70dc55709bdecdad3af572cb67
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/optimize.py b/python_embeded/Lib/site-packages/scipy/optimize/optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..62185ee59cccaafc367d4101c6bce2b5265d3ec0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/optimize.py
@@ -0,0 +1,40 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'OptimizeResult',
+    'OptimizeWarning',
+    'approx_fprime',
+    'bracket',
+    'brent',
+    'brute',
+    'check_grad',
+    'fmin',
+    'fmin_bfgs',
+    'fmin_cg',
+    'fmin_ncg',
+    'fmin_powell',
+    'fminbound',
+    'golden',
+    'line_search',
+    'rosen',
+    'rosen_der',
+    'rosen_hess',
+    'rosen_hess_prod',
+    'show_options',
+    'zeros',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="optimize", module="optimize",
+                                   private_modules=["_optimize"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/slsqp.py b/python_embeded/Lib/site-packages/scipy/optimize/slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..98f72176da104f9d910271d0bee16050830ca533
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/optimize/tnc.py b/python_embeded/Lib/site-packages/scipy/optimize/tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..b354ea8a0e2f6e455d58f7d32f80c49e97ee0e4c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/tnc.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'OptimizeResult',
+    'fmin_tnc',
+    'zeros',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="optimize", module="tnc",
+                                   private_modules=["_tnc"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/optimize/zeros.py b/python_embeded/Lib/site-packages/scipy/optimize/zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49aafb8338eb3248405b1a8cb92f90eeb45c476
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/optimize/zeros.py
@@ -0,0 +1,26 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'RootResults',
+    'bisect',
+    'brenth',
+    'brentq',
+    'newton',
+    'ridder',
+    'toms748',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="optimize", module="zeros",
+                                   private_modules=["_zeros_py"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/__init__.py b/python_embeded/Lib/site-packages/scipy/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..021169fa0c9ea579a45ff413b44f5cb24bf5029a
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_compressed.py b/python_embeded/Lib/site-packages/scipy/sparse/_compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..545d55cd3c8a81824ff13ca7b9cd38a68bd85503
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_construct.py b/python_embeded/Lib/site-packages/scipy/sparse/_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..e36d011e680912cc5932ab45f35435e66a1f68ad
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_coo.py b/python_embeded/Lib/site-packages/scipy/sparse/_coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..d23ad6327ccc6eb5278daf817ed1cd3c1cba1b63
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/sparse/_coo.py
@@ -0,0 +1,1647 @@
+""" A sparse matrix in COOrdinate or 'triplet' format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['coo_array', 'coo_matrix', 'isspmatrix_coo']
+
+import math
+from warnings import warn
+
+import numpy as np
+
+from .._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._sparsetools import (coo_tocsr, coo_todense, coo_todense_nd,
+                           coo_matvec, coo_matvec_nd, coo_matmat_dense,
+                           coo_matmat_dense_nd)
+from ._base import issparse, SparseEfficiencyWarning, _spbase, sparray
+from ._data import _data_matrix, _minmax_mixin
+from ._sputils import (upcast_char, to_native, isshape, getdtype,
+                       getdata, downcast_intp_index, get_index_dtype,
+                       check_shape, check_reshape_kwargs, isscalarlike, isdense)
+
+import operator
+
+
+class _coo_base(_data_matrix, _minmax_mixin):
+    _format = 'coo'
+    _allow_nd = range(1, 65)
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+        if not copy:
+            copy = copy_if_needed
+
+        if isinstance(arg1, tuple):
+            if isshape(arg1, allow_nd=self._allow_nd):
+                self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+                idx_dtype = self._get_index_dtype(maxval=max(self._shape))
+                data_dtype = getdtype(dtype, default=float)
+                self.coords = tuple(np.array([], dtype=idx_dtype)
+                                     for _ in range(len(self._shape)))
+                self.data = np.array([], dtype=data_dtype)
+                self.has_canonical_format = True
+            else:
+                try:
+                    obj, coords = arg1
+                except (TypeError, ValueError) as e:
+                    raise TypeError('invalid input format') from e
+
+                if shape is None:
+                    if any(len(idx) == 0 for idx in coords):
+                        raise ValueError('cannot infer dimensions from zero '
+                                         'sized index arrays')
+                    shape = tuple(operator.index(np.max(idx)) + 1
+                                  for idx in coords)
+                self._shape = check_shape(shape, allow_nd=self._allow_nd)
+                idx_dtype = self._get_index_dtype(coords,
+                                                  maxval=max(self.shape),
+                                                  check_contents=True)
+                self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype)
+                                     for idx in coords)
+                self.data = getdata(obj, copy=copy, dtype=dtype)
+                self.has_canonical_format = False
+        else:
+            if issparse(arg1):
+                if arg1.format == self.format and copy:
+                    self.coords = tuple(idx.copy() for idx in arg1.coords)
+                    self.data = arg1.data.astype(getdtype(dtype, arg1))  # copy=True
+                    self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+                    self.has_canonical_format = arg1.has_canonical_format
+                else:
+                    coo = arg1.tocoo()
+                    self.coords = tuple(coo.coords)
+                    self.data = coo.data.astype(getdtype(dtype, coo), copy=False)
+                    self._shape = check_shape(coo.shape, allow_nd=self._allow_nd)
+                    self.has_canonical_format = False
+            else:
+                # dense argument
+                M = np.asarray(arg1)
+                if not isinstance(self, sparray):
+                    M = np.atleast_2d(M)
+                    if M.ndim != 2:
+                        raise TypeError(f'expected 2D array or matrix, not {M.ndim}D')
+
+                self._shape = check_shape(M.shape, allow_nd=self._allow_nd)
+                if shape is not None:
+                    if check_shape(shape, allow_nd=self._allow_nd) != self._shape:
+                        message = f'inconsistent shapes: {shape} != {self._shape}'
+                        raise ValueError(message)
+
+                index_dtype = self._get_index_dtype(maxval=max(self._shape))
+                coords = M.nonzero()
+                self.coords = tuple(idx.astype(index_dtype, copy=False)
+                                     for idx in coords)
+                self.data = getdata(M[coords], copy=copy, dtype=dtype)
+                self.has_canonical_format = True
+
+        if len(self._shape) > 2:
+            self.coords = tuple(idx.astype(np.int64, copy=False) for idx in self.coords)
+
+        self._check()
+
+    @property
+    def row(self):
+        if self.ndim > 1:
+            return self.coords[-2]
+        result = np.zeros_like(self.col)
+        result.setflags(write=False)
+        return result
+
+
+    @row.setter
+    def row(self, new_row):
+        if self.ndim < 2:
+            raise ValueError('cannot set row attribute of a 1-dimensional sparse array')
+        new_row = np.asarray(new_row, dtype=self.coords[-2].dtype)
+        self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:]
+
+    @property
+    def col(self):
+        return self.coords[-1]
+
+    @col.setter
+    def col(self, new_col):
+        new_col = np.asarray(new_col, dtype=self.coords[-1].dtype)
+        self.coords = self.coords[:-1] + (new_col,)
+
+    def reshape(self, *args, **kwargs):
+        shape = check_shape(args, self.shape, allow_nd=self._allow_nd)
+        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
+
+        # When reducing the number of dimensions, we need to be careful about
+        # index overflow. This is why we can't simply call
+        # `np.ravel_multi_index()` followed by `np.unravel_index()` here.
+        flat_coords = _ravel_coords(self.coords, self.shape, order=order)
+        if len(shape) == 2:
+            if order == 'C':
+                new_coords = divmod(flat_coords, shape[1])
+            else:
+                new_coords = divmod(flat_coords, shape[0])[::-1]
+        else:
+            new_coords = np.unravel_index(flat_coords, shape, order=order)
+
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(shape))
+        new_coords = tuple(np.asarray(co, dtype=idx_dtype) for co in new_coords)
+
+        # Handle copy here rather than passing on to the constructor so that no
+        # copy will be made of `new_coords` regardless.
+        if copy:
+            new_data = self.data.copy()
+        else:
+            new_data = self.data
+
+        return self.__class__((new_data, new_coords), shape=shape, copy=False)
+
+    reshape.__doc__ = _spbase.reshape.__doc__
+
+    def _getnnz(self, axis=None):
+        if axis is None or (axis == 0 and self.ndim == 1):
+            nnz = len(self.data)
+            if any(len(idx) != nnz for idx in self.coords):
+                raise ValueError('all index and data arrays must have the '
+                                 'same length')
+
+            if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords):
+                raise ValueError('coordinates and data arrays must be 1-D')
+
+            return int(nnz)
+
+        if axis < 0:
+            axis += self.ndim
+        if axis >= self.ndim:
+            raise ValueError('axis out of bounds')
+
+        return np.bincount(downcast_intp_index(self.coords[1 - axis]),
+                           minlength=self.shape[1 - axis])
+
+    _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 axis < 0:
+            axis += self.ndim
+        if axis < 0 or axis >= self.ndim:
+            raise ValueError('axis out of bounds')
+        mask = self.data != 0
+        coord = self.coords[1 - axis][mask]
+        return np.bincount(downcast_intp_index(coord), minlength=self.shape[1 - axis])
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def _check(self):
+        """ Checks data structure for consistency """
+        if self.ndim != len(self.coords):
+            raise ValueError('mismatching number of index arrays for shape; '
+                             f'got {len(self.coords)}, expected {self.ndim}')
+
+        # index arrays should have integer data types
+        for i, idx in enumerate(self.coords):
+            if idx.dtype.kind != 'i':
+                warn(f'index array {i} has non-integer dtype ({idx.dtype.name})',
+                     stacklevel=3)
+
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape))
+        self.coords = tuple(np.asarray(idx, dtype=idx_dtype)
+                             for idx in self.coords)
+        self.data = to_native(self.data)
+
+        if self.nnz > 0:
+            for i, idx in enumerate(self.coords):
+                if idx.max() >= self.shape[i]:
+                    raise ValueError(f'axis {i} index {idx.max()} exceeds '
+                                     f'matrix dimension {self.shape[i]}')
+                if idx.min() < 0:
+                    raise ValueError(f'negative axis {i} index: {idx.min()}')
+
+    def transpose(self, axes=None, copy=False):
+        if axes is None:
+            axes = range(self.ndim)[::-1]
+        elif isinstance(self, sparray):
+            if not hasattr(axes, "__len__") or len(axes) != self.ndim:
+                raise ValueError("axes don't match matrix dimensions")
+            if len(set(axes)) != self.ndim:
+                raise ValueError("repeated axis in transpose")
+        elif axes != (1, 0):
+            raise ValueError("Sparse matrices do not support an 'axes' "
+                             "parameter because swapping dimensions is the "
+                             "only logical permutation.")
+
+        permuted_shape = tuple(self._shape[i] for i in axes)
+        permuted_coords = tuple(self.coords[i] for i in axes)
+        return self.__class__((self.data, permuted_coords),
+                              shape=permuted_shape, copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def resize(self, *shape) -> None:
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+        if self.ndim > 2:
+            raise ValueError("only 1-D or 2-D input accepted")
+        if len(shape) > 2:
+            raise ValueError("shape argument must be 1-D or 2-D")
+        # Check for added dimensions.
+        if len(shape) > self.ndim:
+            flat_coords = _ravel_coords(self.coords, self.shape)
+            max_size = math.prod(shape)
+            self.coords = np.unravel_index(flat_coords[:max_size], shape)
+            self.data = self.data[:max_size]
+            self._shape = shape
+            return
+
+        # Check for removed dimensions.
+        if len(shape) < self.ndim:
+            tmp_shape = (
+                self._shape[:len(shape) - 1]  # Original shape without last axis
+                + (-1,)  # Last axis is used to flatten the array
+                + (1,) * (self.ndim - len(shape))  # Pad with ones
+            )
+            tmp = self.reshape(tmp_shape)
+            self.coords = tmp.coords[:len(shape)]
+            self._shape = tmp.shape[:len(shape)]
+
+        # Handle truncation of existing dimensions.
+        is_truncating = any(old > new for old, new in zip(self.shape, shape))
+        if is_truncating:
+            mask = np.logical_and.reduce([
+                idx < size for idx, size in zip(self.coords, shape)
+            ])
+            if not mask.all():
+                self.coords = tuple(idx[mask] for idx in self.coords)
+                self.data = self.data[mask]
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    def toarray(self, order=None, out=None):
+        B = self._process_toarray_args(order, out)
+        fortran = int(B.flags.f_contiguous)
+        if not fortran and not B.flags.c_contiguous:
+            raise ValueError("Output array must be C or F contiguous")
+        # This handles both 0D and 1D cases correctly regardless of the
+        # original shape.
+        if self.ndim == 1:
+            coo_todense_nd(np.array([1]), self.nnz, self.ndim,
+                           self.coords[0], self.data, B.ravel('A'), fortran)
+        elif self.ndim == 2:
+            M, N = self.shape
+            coo_todense(M, N, self.nnz, self.row, self.col, self.data,
+                        B.ravel('A'), fortran)
+        else:
+            if fortran:
+                strides = np.append(1, np.cumprod(self.shape[:-1]))
+            else:
+                strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1)
+            coords = np.concatenate(self.coords)
+            coo_todense_nd(strides, self.nnz, self.ndim,
+                           coords, self.data, B.ravel('A'), fortran)
+        # Note: reshape() doesn't copy here, but does return a new array (view).
+        return B.reshape(self.shape)
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def tocsc(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Column format
+
+        Duplicate entries will be summed together.
+
+        Examples
+        --------
+        >>> from numpy import array
+        >>> from scipy.sparse import coo_array
+        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
+        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
+        >>> data = array([1, 1, 1, 1, 1, 1, 1])
+        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc()
+        >>> A.toarray()
+        array([[3, 0, 1, 0],
+               [0, 2, 0, 0],
+               [0, 0, 0, 0],
+               [0, 0, 0, 1]])
+
+        """
+        if self.ndim != 2:
+            raise ValueError(f'Cannot convert. CSC format must be 2D. Got {self.ndim}D')
+        if self.nnz == 0:
+            return self._csc_container(self.shape, dtype=self.dtype)
+        else:
+            from ._csc import csc_array
+            indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap)
+
+            x = self._csc_container((data, indices, indptr), shape=shape)
+            if not self.has_canonical_format:
+                x.sum_duplicates()
+            return x
+
+    def tocsr(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Row format
+
+        Duplicate entries will be summed together.
+
+        Examples
+        --------
+        >>> from numpy import array
+        >>> from scipy.sparse import coo_array
+        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
+        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
+        >>> data = array([1, 1, 1, 1, 1, 1, 1])
+        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr()
+        >>> A.toarray()
+        array([[3, 0, 1, 0],
+               [0, 2, 0, 0],
+               [0, 0, 0, 0],
+               [0, 0, 0, 1]])
+
+        """
+        if self.ndim > 2:
+            raise ValueError(f'Cannot convert. CSR must be 1D or 2D. Got {self.ndim}D')
+        if self.nnz == 0:
+            return self._csr_container(self.shape, dtype=self.dtype)
+        else:
+            from ._csr import csr_array
+            arrays = self._coo_to_compressed(csr_array._swap, copy=copy)
+            indptr, indices, data, shape = arrays
+
+            x = self._csr_container((data, indices, indptr), shape=self.shape)
+            if not self.has_canonical_format:
+                x.sum_duplicates()
+            return x
+
+    def _coo_to_compressed(self, swap, copy=False):
+        """convert (shape, coords, data) to (indptr, indices, data, shape)"""
+        M, N = swap(self._shape_as_2d)
+        # convert idx_dtype intc to int32 for pythran.
+        # tested in scipy/optimize/tests/test__numdiff.py::test_group_columns
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N))
+
+        if self.ndim == 1:
+            indices = self.coords[0].copy() if copy else self.coords[0]
+            nnz = len(indices)
+            indptr = np.array([0, nnz], dtype=idx_dtype)
+            data = self.data.copy() if copy else self.data
+            return indptr, indices, data, self.shape
+
+        # ndim == 2
+        major, minor = swap(self.coords)
+        nnz = len(major)
+        major = major.astype(idx_dtype, copy=False)
+        minor = minor.astype(idx_dtype, copy=False)
+
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty_like(minor, dtype=idx_dtype)
+        data = np.empty_like(self.data, dtype=self.dtype)
+
+        coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data)
+        return indptr, indices, data, self.shape
+
+    def tocoo(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def todia(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError(f'Cannot convert. DIA format must be 2D. Got {self.ndim}D')
+        self.sum_duplicates()
+        ks = self.col - self.row  # the diagonal for each nonzero
+        diags, diag_idx = np.unique(ks, return_inverse=True)
+
+        if len(diags) > 100:
+            # probably undesired, should todia() have a maxdiags parameter?
+            warn(f"Constructing a DIA matrix with {len(diags)} diagonals "
+                 "is inefficient",
+                 SparseEfficiencyWarning, stacklevel=2)
+
+        #initialize and fill in data array
+        if self.data.size == 0:
+            data = np.zeros((0, 0), dtype=self.dtype)
+        else:
+            data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype)
+            data[diag_idx, self.col] = self.data
+
+        return self._dia_container((data, diags), shape=self.shape)
+
+    todia.__doc__ = _spbase.todia.__doc__
+
+    def todok(self, copy=False):
+        if self.ndim > 2:
+            raise ValueError(f'Cannot convert. DOK must be 1D or 2D. Got {self.ndim}D')
+        self.sum_duplicates()
+        dok = self._dok_container(self.shape, dtype=self.dtype)
+        # ensure that 1d coordinates are not tuples
+        if self.ndim == 1:
+            coords = self.coords[0]
+        else:
+            coords = zip(*self.coords)
+
+        dok._dict = dict(zip(coords, self.data))
+        return dok
+
+    todok.__doc__ = _spbase.todok.__doc__
+
+    def diagonal(self, k=0):
+        if self.ndim != 2:
+            raise ValueError("diagonal requires two dimensions")
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
+                        dtype=self.dtype)
+        diag_mask = (self.row + k) == self.col
+
+        if self.has_canonical_format:
+            row = self.row[diag_mask]
+            data = self.data[diag_mask]
+        else:
+            inds = tuple(idx[diag_mask] for idx in self.coords)
+            (row, _), data = self._sum_duplicates(inds, self.data[diag_mask])
+        diag[row + min(k, 0)] = data
+
+        return diag
+
+    diagonal.__doc__ = _data_matrix.diagonal.__doc__
+
+    def _setdiag(self, values, k):
+        if self.ndim != 2:
+            raise ValueError("setting a diagonal requires two dimensions")
+        M, N = self.shape
+        if values.ndim and not len(values):
+            return
+        idx_dtype = self.row.dtype
+
+        # Determine which triples to keep and where to put the new ones.
+        full_keep = self.col - self.row != k
+        if k < 0:
+            max_index = min(M+k, N)
+            if values.ndim:
+                max_index = min(max_index, len(values))
+            keep = np.logical_or(full_keep, self.col >= max_index)
+            new_row = np.arange(-k, -k + max_index, dtype=idx_dtype)
+            new_col = np.arange(max_index, dtype=idx_dtype)
+        else:
+            max_index = min(M, N-k)
+            if values.ndim:
+                max_index = min(max_index, len(values))
+            keep = np.logical_or(full_keep, self.row >= max_index)
+            new_row = np.arange(max_index, dtype=idx_dtype)
+            new_col = np.arange(k, k + max_index, dtype=idx_dtype)
+
+        # Define the array of data consisting of the entries to be added.
+        if values.ndim:
+            new_data = values[:max_index]
+        else:
+            new_data = np.empty(max_index, dtype=self.dtype)
+            new_data[:] = values
+
+        # Update the internal structure.
+        self.coords = (np.concatenate((self.row[keep], new_row)),
+                       np.concatenate((self.col[keep], new_col)))
+        self.data = np.concatenate((self.data[keep], new_data))
+        self.has_canonical_format = False
+
+    # 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 index arrays are copied.
+        """
+        if copy:
+            coords = tuple(idx.copy() for idx in self.coords)
+        else:
+            coords = self.coords
+        return self.__class__((data, coords), shape=self.shape, dtype=data.dtype)
+
+    def sum_duplicates(self) -> None:
+        """Eliminate duplicate entries by adding them together
+
+        This is an *in place* operation
+        """
+        if self.has_canonical_format:
+            return
+        summed = self._sum_duplicates(self.coords, self.data)
+        self.coords, self.data = summed
+        self.has_canonical_format = True
+
+    def _sum_duplicates(self, coords, data):
+        # Assumes coords not in canonical format.
+        if len(data) == 0:
+            return coords, data
+        # Sort coords w.r.t. rows, then cols. This corresponds to C-order,
+        # which we rely on for argmin/argmax to return the first index in the
+        # same way that numpy does (in the case of ties).
+        order = np.lexsort(coords[::-1])
+        coords = tuple(idx[order] for idx in coords)
+        data = data[order]
+        unique_mask = np.logical_or.reduce([
+            idx[1:] != idx[:-1] for idx in coords
+        ])
+        unique_mask = np.append(True, unique_mask)
+        coords = tuple(idx[unique_mask] for idx in coords)
+        unique_inds, = np.nonzero(unique_mask)
+        data = np.add.reduceat(data, downcast_intp_index(unique_inds), dtype=self.dtype)
+        return coords, data
+
+    def eliminate_zeros(self):
+        """Remove zero entries from the array/matrix
+
+        This is an *in place* operation
+        """
+        mask = self.data != 0
+        self.data = self.data[mask]
+        self.coords = tuple(idx[mask] for idx in self.coords)
+
+    #######################
+    # Arithmetic handlers #
+    #######################
+
+    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)
+        result = np.array(other, dtype=dtype, copy=True)
+        fortran = int(result.flags.f_contiguous)
+        if self.ndim == 1:
+            coo_todense_nd(np.array([1]), self.nnz, self.ndim,
+                           self.coords[0], self.data, result.ravel('A'), fortran)
+        elif self.ndim == 2:
+            M, N = self._shape_as_2d
+            coo_todense(M, N, self.nnz, self.row, self.col, self.data,
+                        result.ravel('A'), fortran)
+        else:
+            if fortran:
+                strides = np.append(1, np.cumprod(self.shape[:-1]))
+            else:
+                strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1)
+            coords = np.concatenate(self.coords)
+            coo_todense_nd(strides, self.nnz, self.ndim,
+                           coords, self.data, result.ravel('A'), fortran)
+        return self._container(result, copy=False)
+
+
+    def _add_sparse(self, other):
+        if self.ndim < 3:
+            return self.tocsr()._add_sparse(other)
+
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        other = self.__class__(other)
+        new_data = np.concatenate((self.data, other.data))
+        new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1))
+        A = self.__class__((new_data, new_coords), shape=self.shape)
+        return A
+
+
+    def _sub_sparse(self, other):
+        if self.ndim < 3:
+            return self.tocsr()._sub_sparse(other)
+
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        other = self.__class__(other)
+        new_data = np.concatenate((self.data, -other.data))
+        new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1))
+        A = coo_array((new_data, new_coords), shape=self.shape)
+        return A
+
+
+    def _matmul_vector(self, other):
+        if self.ndim > 2:
+            result = np.zeros(math.prod(self.shape[:-1]),
+                              dtype=upcast_char(self.dtype.char, other.dtype.char))
+            shape = np.array(self.shape)
+            strides = np.append(np.cumprod(shape[:-1][::-1])[::-1][1:], 1)
+            coords = np.concatenate(self.coords)
+            coo_matvec_nd(self.nnz, len(self.shape), strides, coords, self.data,
+                          other, result)
+
+            result = result.reshape(self.shape[:-1])
+            return result
+
+        # self.ndim <= 2
+        result_shape = self.shape[0] if self.ndim > 1 else 1
+        result = np.zeros(result_shape,
+                          dtype=upcast_char(self.dtype.char, other.dtype.char))
+        if self.ndim == 2:
+            col = self.col
+            row = self.row
+        elif self.ndim == 1:
+            col = self.coords[0]
+            row = np.zeros_like(col)
+        else:
+            raise NotImplementedError(
+                f"coo_matvec not implemented for ndim={self.ndim}")
+
+        coo_matvec(self.nnz, row, col, self.data, other, result)
+        # Array semantics return a scalar here, not a single-element array.
+        if isinstance(self, sparray) and result_shape == 1:
+            return result[0]
+        return result
+
+
+    def _rmatmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        else:
+            # Don't use asarray unless we have to
+            try:
+                o_ndim = other.ndim
+            except AttributeError:
+                other = np.asarray(other)
+                o_ndim = other.ndim
+            perm = tuple(range(o_ndim)[:-2]) + tuple(range(o_ndim)[-2:][::-1])
+            tr = other.transpose(perm)
+
+            s_ndim = self.ndim
+            perm = tuple(range(s_ndim)[:-2]) + tuple(range(s_ndim)[-2:][::-1])
+            ret = self.transpose(perm)._matmul_dispatch(tr)
+            if ret is NotImplemented:
+                return NotImplemented
+
+            if s_ndim == 1 or o_ndim == 1:
+                perm = range(ret.ndim)
+            else:
+                perm = tuple(range(ret.ndim)[:-2]) + tuple(range(ret.ndim)[-2:][::-1])
+            return ret.transpose(perm)
+
+
+    def _matmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self.multiply(other)
+
+        if not (issparse(other) or isdense(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 self.ndim < 3 and other.ndim < 3:
+            return _spbase._matmul_dispatch(self, other)
+
+        N = self.shape[-1]
+        err_prefix = "matmul: dimension mismatch with signature"
+        if other.__class__ is np.ndarray:
+            if other.shape == (N,):
+                return self._matmul_vector(other)
+            if other.shape == (N, 1):
+                result = self._matmul_vector(other.ravel())
+                return result.reshape(*self.shape[:-1], 1)
+            if other.ndim == 1:
+                msg = f"{err_prefix} (n,k={N}),(k={other.shape[0]},)->(n,)"
+                raise ValueError(msg)
+            if other.shape[-2] == N:
+                # check for batch dimensions compatibility
+                batch_shape_A = self.shape[:-2]
+                batch_shape_B = other.shape[:-2]
+                if batch_shape_A != batch_shape_B:
+                    try:
+                        # This will raise an error if the shapes are not broadcastable
+                        np.broadcast_shapes(batch_shape_A, batch_shape_B)
+                    except ValueError:
+                        raise ValueError("Batch dimensions are not broadcastable")
+
+                return self._matmul_multivector(other)
+            else:
+                raise ValueError(
+                    f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)"
+                )
+
+
+        if isscalarlike(other):
+            # scalar value
+            return self._mul_scalar(other)
+
+        if issparse(other):
+            self_is_1d = self.ndim == 1
+            other_is_1d = other.ndim == 1
+
+            # reshape to 2-D if self or other is 1-D
+            if self_is_1d:
+                self = self.reshape(self._shape_as_2d) # prepend 1 to shape
+
+            if other_is_1d:
+                other = other.reshape((other.shape[0], 1)) # append 1 to shape
+
+            # Check if the inner dimensions match for matrix multiplication
+            if N != other.shape[-2]:
+                raise ValueError(
+                    f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)"
+                )
+
+            # If A or B has more than 2 dimensions, check for
+            # batch dimensions compatibility
+            if self.ndim > 2 or other.ndim > 2:
+                batch_shape_A = self.shape[:-2]
+                batch_shape_B = other.shape[:-2]
+                if batch_shape_A != batch_shape_B:
+                    try:
+                        # This will raise an error if the shapes are not broadcastable
+                        np.broadcast_shapes(batch_shape_A, batch_shape_B)
+                    except ValueError:
+                        raise ValueError("Batch dimensions are not broadcastable")
+
+            result = self._matmul_sparse(other)
+
+            # reshape back if a or b were originally 1-D
+            if self_is_1d:
+                # if self was originally 1-D, reshape result accordingly
+                result = result.reshape(tuple(result.shape[:-2]) +
+                                        tuple(result.shape[-1:]))
+            if other_is_1d:
+                result = result.reshape(result.shape[:-1])
+            return result
+
+
+    def _matmul_multivector(self, other):
+        result_dtype = upcast_char(self.dtype.char, other.dtype.char)
+        if self.ndim >= 3 or other.ndim >= 3:
+            # if self has shape (N,), reshape to (1,N)
+            if self.ndim == 1:
+                result = self.reshape(1, self.shape[0])._matmul_multivector(other)
+                return result.reshape(tuple(other.shape[:-2]) + tuple(other.shape[-1:]))
+
+            broadcast_shape = np.broadcast_shapes(self.shape[:-2], other.shape[:-2])
+            self_shape = broadcast_shape + self.shape[-2:]
+            other_shape = broadcast_shape + other.shape[-2:]
+
+            self = self._broadcast_to(self_shape)
+            other = np.broadcast_to(other, other_shape)
+            result_shape = broadcast_shape + self.shape[-2:-1] + other.shape[-1:]
+            result = np.zeros(result_shape, dtype=result_dtype)
+            coo_matmat_dense_nd(self.nnz, len(self.shape), other.shape[-1],
+                                np.array(other_shape), np.array(result_shape),
+                                np.concatenate(self.coords),
+                                self.data, other.ravel('C'), result)
+            return result
+
+        if self.ndim == 2:
+            result_shape = (self.shape[0], other.shape[1])
+            col = self.col
+            row = self.row
+        elif self.ndim == 1:
+            result_shape = (other.shape[1],)
+            col = self.coords[0]
+            row = np.zeros_like(col)
+        result = np.zeros(result_shape, dtype=result_dtype)
+        coo_matmat_dense(self.nnz, other.shape[-1], row, col,
+                         self.data, other.ravel('C'), result)
+        return result.view(type=type(other))
+
+
+    def dot(self, other):
+        """Return the dot product of two arrays.
+
+        Strictly speaking a dot product involves two vectors.
+        But in the sense that an array with ndim >= 1 is a collection
+        of vectors, the function computes the collection of dot products
+        between each vector in the first array with each vector in the
+        second array. The axis upon which the sum of products is performed
+        is the last axis of the first array and the second to last axis of
+        the second array. If the second array is 1-D, the last axis is used.
+
+        Thus, if both arrays are 1-D, the inner product is returned.
+        If both are 2-D, we have matrix multiplication. If `other` is 1-D,
+        the sum product is taken along the last axis of each array. If
+        `other` is N-D for N>=2, the sum product is over the last axis of
+        the first array and the second-to-last axis of the second array.
+
+        Parameters
+        ----------
+        other : array_like (dense or sparse)
+            Second array
+
+        Returns
+        -------
+        output : array (sparse or dense)
+            The dot product of this array with `other`.
+            It will be dense/sparse if `other` is dense/sparse.
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> from scipy.sparse import coo_array
+        >>> A = coo_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)
+
+        For 2-D arrays it is the matrix product:
+
+        >>> A = coo_array([[1, 0], [0, 1]])
+        >>> B = coo_array([[4, 1], [2, 2]])
+        >>> A.dot(B).toarray()
+        array([[4, 1],
+               [2, 2]])
+
+        For 3-D arrays the shape extends unused axes by other unused axes.
+
+        >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6))
+        >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3))
+        >>> A.dot(B).shape
+        (3, 4, 5, 5, 4, 3)
+        """
+        if not (issparse(other) or isdense(other) or isscalarlike(other)):
+            # If it's a list or whatever, treat it like an array
+            o_array = np.asanyarray(other)
+
+            if o_array.ndim == 0 and o_array.dtype == np.object_:
+                raise TypeError(f"dot argument not supported type: '{type(other)}'")
+            try:
+                other.shape
+            except AttributeError:
+                other = o_array
+
+        if self.ndim < 3 and (np.isscalar(other) or other.ndim<3):
+            return _spbase.dot(self, other)
+        # Handle scalar multiplication
+        if np.isscalar(other):
+            return self * other
+        if isdense(other):
+            return self._dense_dot(other)
+        elif other.format != "coo":
+            raise TypeError("input must be a COO matrix/array")
+        elif self.ndim == 1 and other.ndim == 1:
+            # Handle inner product of vectors (1-D arrays)
+            if self.shape[0] != other.shape[0]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for inner product")
+            return self @ other
+        elif self.ndim == 2 and other.ndim == 2:
+            # Handle matrix multiplication (2-D arrays)
+            if self.shape[1] != other.shape[0]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for matmul")
+            return self @ other
+        else:
+            return self._sparse_dot(other)
+
+
+    def _sparse_dot(self, other):
+        self_is_1d = self.ndim == 1
+        other_is_1d = other.ndim == 1
+
+        # reshape to 2-D if self or other is 1-D
+        if self_is_1d:
+            self = self.reshape(self._shape_as_2d)  # prepend 1 to shape
+        if other_is_1d:
+            other = other.reshape((other.shape[0], 1))  # append 1 to shape
+
+        if self.shape[-1] != other.shape[-2]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for n-D dot")
+
+        # Prepare the tensors for dot operation
+        # Ravel non-reduced axes coordinates
+        self_raveled_coords = _ravel_non_reduced_axes(self.coords,
+                                                      self.shape, [self.ndim-1])
+        other_raveled_coords = _ravel_non_reduced_axes(other.coords,
+                                                       other.shape, [other.ndim-2])
+
+        # Get the shape of the non-reduced axes
+        self_nonreduced_shape = self.shape[:-1]
+        other_nonreduced_shape = other.shape[:-2] + other.shape[-1:]
+
+        # Create 2D coords arrays
+        ravel_coords_shape_self = (math.prod(self_nonreduced_shape), self.shape[-1])
+        ravel_coords_shape_other = (other.shape[-2], math.prod(other_nonreduced_shape))
+
+        self_2d_coords = (self_raveled_coords, self.coords[-1])
+        other_2d_coords = (other.coords[-2], other_raveled_coords)
+
+        self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self)
+        other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other)
+
+        prod = (self_2d @ other_2d).tocoo() # routes via 2-D CSR
+
+        # Combine the shapes of the non-reduced axes
+        combined_shape = self_nonreduced_shape + other_nonreduced_shape
+
+        # Unravel the 2D coordinates to get multi-dimensional coordinates
+        shapes = (self_nonreduced_shape, other_nonreduced_shape)
+        prod_coords = []
+        for c, s in zip(prod.coords, shapes):
+            prod_coords.extend(np.unravel_index(c, s))
+
+        prod_arr = coo_array((prod.data, prod_coords), combined_shape)
+
+        # reshape back if a or b were originally 1-D
+        # TODO: Move this logic before computation of prod_coords for efficiency
+        if self_is_1d:
+            prod_arr = prod_arr.reshape(combined_shape[1:])
+        if other_is_1d:
+            prod_arr = prod_arr.reshape(combined_shape[:-1])
+
+        return prod_arr
+
+    def _dense_dot(self, other):
+        self_is_1d = self.ndim == 1
+        other_is_1d = other.ndim == 1
+
+        # reshape to 2-D if self or other is 1-D
+        if self_is_1d:
+            self = self.reshape(self._shape_as_2d)  # prepend 1 to shape
+        if other_is_1d:
+            other = other.reshape((other.shape[0], 1))  # append 1 to shape
+
+        if self.shape[-1] != other.shape[-2]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for n-D dot")
+
+        new_shape_self = (
+            self.shape[:-1] + (1,) * (len(other.shape) - 1) + self.shape[-1:]
+        )
+        new_shape_other = (1,) * (len(self.shape) - 1) + other.shape
+
+        result_shape = self.shape[:-1] + other.shape[:-2] + other.shape[-1:]
+        result = self.reshape(new_shape_self) @ other.reshape(new_shape_other)
+        prod_arr = result.reshape(result_shape)
+
+        # reshape back if a or b were originally 1-D
+        if self_is_1d:
+            prod_arr = prod_arr.reshape(result_shape[1:])
+        if other_is_1d:
+            prod_arr = prod_arr.reshape(result_shape[:-1])
+
+        return prod_arr
+
+    def tensordot(self, other, axes=2):
+        """Return the tensordot product with another array along the given axes.
+
+        The tensordot differs from dot and matmul in that any axis can be
+        chosen for each of the first and second array and the sum of the
+        products is computed just like for matrix multiplication, only not
+        just for the rows of the first times the columns of the second. It
+        takes the dot product of the collection of vectors along the specified
+        axes.  Here we can even take the sum of the products along two or even
+        more axes if desired. So, tensordot is a dot product computation
+        applied to arrays of any dimension >= 1. It is like matmul but over
+        arbitrary axes for each matrix.
+
+        Given two tensors, `a` and `b`, and the desired axes specified as a
+        2-tuple/list/array containing two sequences of axis numbers,
+        ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements
+        (components) over the axes specified by ``a_axes`` and ``b_axes``.
+        The `axes` input can be a single non-negative integer, ``N``;
+        if it is, then the last ``N`` dimensions of `a` and the first
+        ``N`` dimensions of `b` are summed over.
+
+        Parameters
+        ----------
+        a, b : array_like
+            Tensors to "dot".
+
+        axes : int or (2,) array_like
+            * integer_like
+              If an int N, sum over the last N axes of `a` and the first N axes
+              of `b` in order. The sizes of the corresponding axes must match.
+            * (2,) array_like
+              A 2-tuple of sequences of axes to be summed over, the first applying
+              to `a`, the second to `b`. The sequences must be the same length.
+              The shape of the corresponding axes must match between `a` and `b`.
+
+        Returns
+        -------
+        output : coo_array
+            The tensor dot product of this array with `other`.
+            It will be dense/sparse if `other` is dense/sparse.
+
+        See Also
+        --------
+        dot
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.sparse
+        >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]])
+        >>> A.shape
+        (2, 2, 2)
+
+        Integer axes N are shorthand for (range(-N, 0), range(0, N)):
+
+        >>> A.tensordot(A, axes=1).toarray()
+        array([[[[ 4,  9],
+                 [ 0, 15]],
+        
+                [[ 0,  0],
+                 [ 0,  0]]],
+        
+        
+               [[[ 0,  1],
+                 [ 0,  5]],
+        
+                [[ 0,  5],
+                 [ 0, 25]]]])
+        >>> A.tensordot(A, axes=2).toarray()
+        array([[ 4,  6],
+               [ 0, 25]])
+        >>> A.tensordot(A, axes=3)
+        array(39)
+
+        Using tuple for axes:
+
+        >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5))
+        >>> b = np.arange(24).reshape(4,3,2)
+        >>> c = a.tensordot(b, axes=([1,0],[0,1]))
+        >>> c.shape
+        (5, 2)
+        >>> c
+        array([[4400, 4730],
+               [4532, 4874],
+               [4664, 5018],
+               [4796, 5162],
+               [4928, 5306]])
+
+        """
+        if not isdense(other) and not issparse(other):
+            # If it's a list or whatever, treat it like an array
+            other_array = np.asanyarray(other)
+
+            if other_array.ndim == 0 and other_array.dtype == np.object_:
+                raise TypeError(f"tensordot arg not supported type: '{type(other)}'")
+            try:
+                other.shape
+            except AttributeError:
+                other = other_array
+
+        axes_self, axes_other = _process_axes(self.ndim, other.ndim, axes)
+
+        # Check for shape compatibility along specified axes
+        if any(self.shape[ax] != other.shape[bx]
+               for ax, bx in zip(axes_self, axes_other)):
+            raise ValueError("sizes of the corresponding axes must match")
+
+        if isdense(other):
+            return self._dense_tensordot(other, axes_self, axes_other)
+        else:
+            return self._sparse_tensordot(other, axes_self, axes_other)
+
+
+    def _sparse_tensordot(self, other, axes_self, axes_other):
+        ndim_self = len(self.shape)
+        ndim_other = len(other.shape)
+
+        # Prepare the tensors for tensordot operation
+        # Ravel non-reduced axes coordinates
+        self_non_red_coords = _ravel_non_reduced_axes(self.coords, self.shape,
+                                                      axes_self)
+        self_reduced_coords = np.ravel_multi_index(
+            [self.coords[ax] for ax in axes_self], [self.shape[ax] for ax in axes_self])
+        other_non_red_coords = _ravel_non_reduced_axes(other.coords, other.shape,
+                                                       axes_other)
+        other_reduced_coords = np.ravel_multi_index(
+            [other.coords[a] for a in axes_other], [other.shape[a] for a in axes_other]
+        )
+        # Get the shape of the non-reduced axes
+        self_nonreduced_shape = tuple(self.shape[ax] for ax in range(ndim_self)
+                              if ax not in axes_self)
+        other_nonreduced_shape = tuple(other.shape[ax] for ax in range(ndim_other)
+                               if ax not in axes_other)
+
+        # Create 2D coords arrays
+        ravel_coords_shape_self = (math.prod(self_nonreduced_shape),
+                                math.prod([self.shape[ax] for ax in axes_self]))
+        ravel_coords_shape_other = (math.prod([other.shape[ax] for ax in axes_other]),
+                                    math.prod(other_nonreduced_shape))
+
+        self_2d_coords = (self_non_red_coords, self_reduced_coords)
+        other_2d_coords = (other_reduced_coords, other_non_red_coords)
+
+        self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self)
+        other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other)
+
+        # Perform matrix multiplication (routed via 2-D CSR)
+        prod = (self_2d @ other_2d).tocoo()
+
+        # Combine the shapes of the non-contracted axes
+        combined_shape = self_nonreduced_shape + other_nonreduced_shape
+
+        # Unravel the 2D coordinates to get multi-dimensional coordinates
+        coords = []
+        for c, s in zip(prod.coords, (self_nonreduced_shape, other_nonreduced_shape)):
+            if s:
+                coords.extend(np.unravel_index(c, s))
+
+        if coords == []:  # if result is scalar
+            return sum(prod.data)
+
+        # Construct the resulting COO array with combined coordinates and shape
+        return coo_array((prod.data, coords), shape=combined_shape)
+
+
+    def _dense_tensordot(self, other, axes_self, axes_other):
+        ndim_self = len(self.shape)
+        ndim_other = len(other.shape)
+
+        non_reduced_axes_self = [ax for ax in range(ndim_self) if ax not in axes_self]
+        reduced_shape_self = [self.shape[s] for s in axes_self]
+        non_reduced_shape_self = [self.shape[s] for s in non_reduced_axes_self]
+
+        non_reduced_axes_other = [ax for ax in range(ndim_other)
+                                  if ax not in axes_other]
+        reduced_shape_other = [other.shape[s] for s in axes_other]
+        non_reduced_shape_other = [other.shape[s] for s in non_reduced_axes_other]
+
+        permute_self = non_reduced_axes_self + axes_self
+        permute_other = (
+            non_reduced_axes_other[:-1] + axes_other + non_reduced_axes_other[-1:]
+        )
+        self = self.transpose(permute_self)
+        other = np.transpose(other, permute_other)
+
+        reshape_self = (*non_reduced_shape_self, math.prod(reduced_shape_self))
+        reshape_other = (*non_reduced_shape_other[:-1], math.prod(reduced_shape_other),
+                        *non_reduced_shape_other[-1:])
+
+        return self.reshape(reshape_self).dot(other.reshape(reshape_other))
+
+
+    def _matmul_sparse(self, other):
+        """
+        Perform sparse-sparse matrix multiplication for two n-D COO arrays.
+        The method converts input n-D arrays to 2-D block array format,
+        uses csr_matmat to multiply them, and then converts the
+        result back to n-D COO array.
+
+        Parameters:
+        self (COO): The first n-D sparse array in COO format.
+        other (COO): The second n-D sparse array in COO format.
+
+        Returns:
+        prod (COO): The resulting n-D sparse array after multiplication.
+        """
+        if self.ndim < 3 and other.ndim < 3:
+            return _spbase._matmul_sparse(self, other)
+
+        # Get the shapes of self and other
+        self_shape = self.shape
+        other_shape = other.shape
+
+        # Determine the new shape to broadcast self and other
+        broadcast_shape = np.broadcast_shapes(self_shape[:-2], other_shape[:-2])
+        self_new_shape = tuple(broadcast_shape) + self_shape[-2:]
+        other_new_shape = tuple(broadcast_shape) + other_shape[-2:]
+
+        self_broadcasted = self._broadcast_to(self_new_shape)
+        other_broadcasted = other._broadcast_to(other_new_shape)
+
+        # Convert n-D COO arrays to 2-D block diagonal arrays
+        self_block_diag = _block_diag(self_broadcasted)
+        other_block_diag = _block_diag(other_broadcasted)
+
+        # Use csr_matmat to perform sparse matrix multiplication
+        prod_block_diag = (self_block_diag @ other_block_diag).tocoo()
+
+        # Convert the 2-D block diagonal array back to n-D
+        return _extract_block_diag(
+            prod_block_diag,
+            shape=(*broadcast_shape, self.shape[-2], other.shape[-1]),
+        )
+
+
+    def _broadcast_to(self, new_shape, copy=False):
+        if self.shape == new_shape:
+            return self.copy() if copy else self
+
+        old_shape = self.shape
+
+        # Check if the new shape is compatible for broadcasting
+        if len(new_shape) < len(old_shape):
+            raise ValueError("New shape must have at least as many dimensions"
+                             " as the current shape")
+
+        # Add leading ones to shape to ensure same length as `new_shape`
+        shape = (1,) * (len(new_shape) - len(old_shape)) + tuple(old_shape)
+
+        # Ensure the old shape can be broadcast to the new shape
+        if any((o != 1 and o != n) for o, n in zip(shape, new_shape)):
+            raise ValueError(f"current shape {old_shape} cannot be "
+                             "broadcast to new shape {new_shape}")
+
+        # Reshape the COO array to match the new dimensions
+        self = self.reshape(shape)
+
+        idx_dtype = get_index_dtype(self.coords, maxval=max(new_shape))
+        coords = self.coords
+        new_data = self.data
+        new_coords = coords[-1:]  # Copy last coordinate to start
+        cum_repeat = 1 # Cumulative repeat factor for broadcasting
+
+        if shape[-1] != new_shape[-1]: # broadcasting the n-th (col) dimension
+            repeat_count = new_shape[-1]
+            cum_repeat *= repeat_count
+            new_data = np.tile(new_data, repeat_count)
+            new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), self.nnz)
+            new_coords = (new_dim,)
+
+        for i in range(-2, -(len(shape)+1), -1):
+            if shape[i] != new_shape[i]:
+                repeat_count = new_shape[i] # number of times to repeat data, coords
+                cum_repeat *= repeat_count # update cumulative repeat factor
+                nnz = len(new_data) # Number of non-zero elements so far
+
+                # Tile data and coordinates to match the new repeat count
+                new_data = np.tile(new_data, repeat_count)
+                new_coords = tuple(np.tile(new_coords[i+1:], repeat_count))
+
+                # Create new dimensions and stack them
+                new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), nnz)
+                new_coords = (new_dim,) + new_coords
+            else:
+                # If no broadcasting needed, tile the coordinates
+                new_dim = np.tile(coords[i], cum_repeat)
+                new_coords = (new_dim,) + new_coords
+
+        return coo_array((new_data, new_coords), new_shape)
+
+
+def _block_diag(self):
+    """
+    Converts an N-D COO array into a 2-D COO array in block diagonal form.
+
+    Parameters:
+    self (coo_array): An N-Dimensional COO sparse array.
+
+    Returns:
+    coo_array: A 2-Dimensional COO sparse array in block diagonal form.
+    """
+    if self.ndim<2:
+        raise ValueError("array must have atleast dim=2")
+    num_blocks = math.prod(self.shape[:-2])
+    n_col = self.shape[-1]
+    n_row = self.shape[-2]
+    res_arr = self.reshape((num_blocks, n_row, n_col))
+    new_coords = (
+        res_arr.coords[1] + res_arr.coords[0] * res_arr.shape[1],
+        res_arr.coords[2] + res_arr.coords[0] * res_arr.shape[2],
+    )
+
+    new_shape = (num_blocks * n_row, num_blocks * n_col)
+    return coo_array((self.data, tuple(new_coords)), shape=new_shape)
+
+
+def _extract_block_diag(self, shape):
+    n_row, n_col = shape[-2], shape[-1]
+
+    # Extract data and coordinates from the block diagonal COO array
+    data = self.data
+    row, col = self.row, self.col
+
+    # Initialize new coordinates array
+    new_coords = np.empty((len(shape), self.nnz), dtype=int)
+
+    # Calculate within-block indices
+    new_coords[-2] = row % n_row
+    new_coords[-1] = col % n_col
+
+    # Calculate coordinates for higher dimensions
+    temp_block_idx = row // n_row
+    for i in range(len(shape) - 3, -1, -1):
+        size = shape[i]
+        new_coords[i] = temp_block_idx % size
+        temp_block_idx = temp_block_idx // size
+
+    # Create the new COO array with the original n-D shape
+    return coo_array((data, tuple(new_coords)), shape=shape)
+
+
+def _process_axes(ndim_a, ndim_b, axes):
+    if isinstance(axes, int):
+        if axes < 1 or axes > min(ndim_a, ndim_b):
+            raise ValueError("axes integer is out of bounds for input arrays")
+        axes_a = list(range(ndim_a - axes, ndim_a))
+        axes_b = list(range(axes))
+    elif isinstance(axes, (tuple, list)):
+        if len(axes) != 2:
+            raise ValueError("axes must be a tuple/list of length 2")
+        axes_a, axes_b = axes
+        if len(axes_a) != len(axes_b):
+            raise ValueError("axes lists/tuples must be of the same length")
+        if any(ax >= ndim_a or ax < -ndim_a for ax in axes_a) or \
+           any(bx >= ndim_b or bx < -ndim_b for bx in axes_b):
+            raise ValueError("axes indices are out of bounds for input arrays")
+    else:
+        raise TypeError("axes must be an integer or a tuple/list of integers")
+
+    axes_a = [axis + ndim_a if axis < 0 else axis for axis in axes_a]
+    axes_b = [axis + ndim_b if axis < 0 else axis for axis in axes_b]
+    return axes_a, axes_b
+
+
+def _ravel_non_reduced_axes(coords, shape, axes):
+    ndim = len(shape)
+    non_reduced_axes = [ax for ax in range(ndim) if ax not in axes]
+
+    if not non_reduced_axes:
+        # Return an array with one row
+        return np.zeros_like(coords[0])
+
+    # Extract the shape of the non-reduced axes
+    non_reduced_shape = [shape[ax] for ax in non_reduced_axes]
+
+    # Extract the coordinates of the non-reduced axes
+    non_reduced_coords = tuple(coords[idx] for idx in non_reduced_axes)
+
+    # Ravel the coordinates into 1D
+    return np.ravel_multi_index(non_reduced_coords, non_reduced_shape)
+
+
+def _ravel_coords(coords, shape, order='C'):
+    """Like np.ravel_multi_index, but avoids some overflow issues."""
+    if len(coords) == 1:
+        return coords[0]
+    # Handle overflow as in https://github.com/scipy/scipy/pull/9132
+    if len(coords) == 2:
+        nrows, ncols = shape
+        row, col = coords
+        if order == 'C':
+            maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1))
+            idx_dtype = get_index_dtype(maxval=maxval)
+            return np.multiply(ncols, row, dtype=idx_dtype) + col
+        elif order == 'F':
+            maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1))
+            idx_dtype = get_index_dtype(maxval=maxval)
+            return np.multiply(nrows, col, dtype=idx_dtype) + row
+        else:
+            raise ValueError("'order' must be 'C' or 'F'")
+    return np.ravel_multi_index(coords, shape, order=order)
+
+
+def isspmatrix_coo(x):
+    """Is `x` of coo_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a coo matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a coo matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo
+    >>> isspmatrix_coo(coo_matrix([[5]]))
+    True
+    >>> isspmatrix_coo(coo_array([[5]]))
+    False
+    >>> isspmatrix_coo(csr_matrix([[5]]))
+    False
+    """
+    return isinstance(x, coo_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class coo_array(_coo_base, sparray):
+    """
+    A sparse array in COOrdinate format.
+
+    Also known as the 'ijv' or 'triplet' format.
+
+    This can be instantiated in several ways:
+        coo_array(D)
+            where D is an ndarray
+
+        coo_array(S)
+            with another sparse array or matrix S (equivalent to S.tocoo())
+
+        coo_array(shape, [dtype])
+            to construct an empty sparse array with shape `shape`
+            dtype is optional, defaulting to dtype='d'.
+
+        coo_array((data, coords), [shape])
+            to construct from existing data and index arrays:
+                1. data[:]       the entries of the sparse array, in any order
+                2. coords[i][:]  the axis-i coordinates of the data entries
+
+            Where ``A[coords] = data``, and coords is a tuple of index arrays.
+            When shape is not specified, it is inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the sparse array
+    shape : tuple of integers
+        Shape of the sparse array
+    ndim : int
+        Number of dimensions of the sparse array
+    nnz
+    size
+    data
+        COO format data array of the sparse array
+    coords
+        COO format tuple of index arrays
+    has_canonical_format : bool
+        Whether the matrix has sorted coordinates and no duplicates
+    format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the COO format
+        - facilitates fast conversion among sparse formats
+        - permits duplicate entries (see example)
+        - very fast conversion to and from CSR/CSC formats
+
+    Disadvantages of the COO format
+        - does not directly support:
+            + arithmetic operations
+            + slicing
+
+    Intended Usage
+        - COO is a fast format for constructing sparse arrays
+        - Once a COO array has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - By default when converting to CSR or CSC format, duplicate (i,j)
+          entries will be summed together.  This facilitates efficient
+          construction of finite element matrices and the like. (see example)
+
+    Canonical format
+        - Entries and coordinates sorted by row, then column.
+        - There are no duplicate entries (i.e. duplicate (i,j) locations)
+        - Data arrays MAY have explicit zeros.
+
+    Examples
+    --------
+
+    >>> # Constructing an empty sparse array
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_array
+    >>> coo_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> # Constructing a sparse array using ijv format
+    >>> row  = np.array([0, 3, 1, 0])
+    >>> col  = np.array([0, 3, 1, 2])
+    >>> data = np.array([4, 5, 7, 9])
+    >>> coo_array((data, (row, col)), shape=(4, 4)).toarray()
+    array([[4, 0, 9, 0],
+           [0, 7, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 5]])
+
+    >>> # Constructing a sparse array with duplicate coordinates
+    >>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
+    >>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
+    >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
+    >>> coo = coo_array((data, (row, col)), shape=(4, 4))
+    >>> # Duplicate coordinates are maintained until implicitly or explicitly summed
+    >>> np.max(coo.data)
+    1
+    >>> coo.toarray()
+    array([[3, 0, 1, 0],
+           [0, 2, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 1]])
+
+    """
+
+
+class coo_matrix(spmatrix, _coo_base):
+    """
+    A sparse matrix in COOrdinate format.
+
+    Also known as the 'ijv' or 'triplet' format.
+
+    This can be instantiated in several ways:
+        coo_matrix(D)
+            where D is a 2-D ndarray
+
+        coo_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocoo())
+
+        coo_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        coo_matrix((data, (i, j)), [shape=(M, N)])
+            to construct from three arrays:
+                1. data[:]   the entries of the matrix, in any order
+                2. i[:]      the row indices of the matrix entries
+                3. j[:]      the column indices of the matrix entries
+
+            Where ``A[i[k], j[k]] = data[k]``.  When shape is not
+            specified, it is 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
+        COO format data array of the matrix
+    row
+        COO format row index array of the matrix
+    col
+        COO format column index array of the matrix
+    has_canonical_format : bool
+        Whether the matrix has sorted indices and no duplicates
+    format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the COO format
+        - facilitates fast conversion among sparse formats
+        - permits duplicate entries (see example)
+        - very fast conversion to and from CSR/CSC formats
+
+    Disadvantages of the COO format
+        - does not directly support:
+            + arithmetic operations
+            + slicing
+
+    Intended Usage
+        - COO is a fast format for constructing sparse matrices
+        - Once a COO matrix has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - By default when converting to CSR or CSC format, duplicate (i,j)
+          entries will be summed together.  This facilitates efficient
+          construction of finite element matrices and the like. (see example)
+
+    Canonical format
+        - Entries and coordinates sorted by row, then column.
+        - There are no duplicate entries (i.e. duplicate (i,j) locations)
+        - Data arrays MAY have explicit zeros.
+
+    Examples
+    --------
+
+    >>> # Constructing an empty matrix
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_matrix
+    >>> coo_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> # Constructing a matrix using ijv format
+    >>> row  = np.array([0, 3, 1, 0])
+    >>> col  = np.array([0, 3, 1, 2])
+    >>> data = np.array([4, 5, 7, 9])
+    >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
+    array([[4, 0, 9, 0],
+           [0, 7, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 5]])
+
+    >>> # Constructing a matrix with duplicate coordinates
+    >>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
+    >>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
+    >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
+    >>> coo = coo_matrix((data, (row, col)), shape=(4, 4))
+    >>> # Duplicate coordinates are maintained until implicitly or explicitly summed
+    >>> np.max(coo.data)
+    1
+    >>> coo.toarray()
+    array([[3, 0, 1, 0],
+           [0, 2, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 1]])
+
+    """
+
+    def __setstate__(self, state):
+        if 'coords' not in state:
+            # For retro-compatibility with the previous attributes
+            # storing nnz coordinates for 2D COO matrix.
+            state['coords'] = (state.pop('row'), state.pop('col'))
+        self.__dict__.update(state)
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_csc.py b/python_embeded/Lib/site-packages/scipy/sparse/_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e651136d8269d955f067ad434610bbea6f7339b1
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_csparsetools.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/sparse/_csparsetools.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c9bc41aef8adc48ac834d80b76eb4e3d7c9c0ddf
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/sparse/_csparsetools.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_csr.py b/python_embeded/Lib/site-packages/scipy/sparse/_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..92ced1ce0c5026534c208c0dd1b141235b85c3d0
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_data.py b/python_embeded/Lib/site-packages/scipy/sparse/_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..8345414bee1a96be2b07f1db0bd747fd85a9bfdd
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_dia.py b/python_embeded/Lib/site-packages/scipy/sparse/_dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac355dcac3cf6194f32db54f8010b31038b533e3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/sparse/_dia.py
@@ -0,0 +1,590 @@
+"""Sparse DIAgonal format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dia_array', 'dia_matrix', 'isspmatrix_dia']
+
+import numpy as np
+
+from .._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._data import _data_matrix
+from ._sputils import (
+    isshape, upcast_char, getdtype, get_sum_dtype, validateaxis, check_shape
+)
+from ._sparsetools import dia_matvec
+
+
+class _dia_base(_data_matrix):
+    _format = 'dia'
+
+    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 == "dia":
+                if copy:
+                    arg1 = arg1.copy()
+                self.data = arg1.data
+                self.offsets = arg1.offsets
+                self._shape = check_shape(arg1.shape)
+            else:
+                if arg1.format == self.format and copy:
+                    A = arg1.copy()
+                else:
+                    A = arg1.todia()
+                self.data = A.data
+                self.offsets = A.offsets
+                self._shape = check_shape(A.shape)
+        elif isinstance(arg1, tuple):
+            if isshape(arg1):
+                # It's a tuple of matrix dimensions (M, N)
+                # create empty matrix
+                self._shape = check_shape(arg1)
+                self.data = np.zeros((0,0), getdtype(dtype, default=float))
+                idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+                self.offsets = np.zeros((0), dtype=idx_dtype)
+            else:
+                try:
+                    # Try interpreting it as (data, offsets)
+                    data, offsets = arg1
+                except Exception as e:
+                    message = 'unrecognized form for dia_array constructor'
+                    raise ValueError(message) from e
+                else:
+                    if shape is None:
+                        raise ValueError('expected a shape argument')
+                    if not copy:
+                        copy = copy_if_needed
+                    self.data = np.atleast_2d(np.array(arg1[0], dtype=dtype, copy=copy))
+                    offsets = np.array(arg1[1],
+                                       dtype=self._get_index_dtype(maxval=max(shape)),
+                                       copy=copy)
+                    self.offsets = np.atleast_1d(offsets)
+                    self._shape = check_shape(shape)
+        else:
+            # must be dense, convert to COO first, then to DIA
+            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"DIA arrays don't support {arg1.ndim}D input. Use 2D")
+            A = self._coo_container(arg1, dtype=dtype, shape=shape).todia()
+            self.data = A.data
+            self.offsets = A.offsets
+            self._shape = check_shape(A.shape)
+
+        if dtype is not None:
+            newdtype = getdtype(dtype)
+            self.data = self.data.astype(newdtype)
+
+        # check format
+        if self.offsets.ndim != 1:
+            raise ValueError('offsets array must have rank 1')
+
+        if self.data.ndim != 2:
+            raise ValueError('data array must have rank 2')
+
+        if self.data.shape[0] != len(self.offsets):
+            raise ValueError('number of diagonals (%d) '
+                    'does not match the number of offsets (%d)'
+                    % (self.data.shape[0], len(self.offsets)))
+
+        if len(np.unique(self.offsets)) != len(self.offsets):
+            raise ValueError('offset array contains duplicate values')
+
+    def __repr__(self):
+        _, fmt = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        d = self.data.shape[0]
+        return (
+            f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements ({d} diagonals) and shape {self.shape}>"
+        )
+
+    def _data_mask(self):
+        """Returns a mask of the same shape as self.data, where
+        mask[i,j] is True when data[i,j] corresponds to a stored element."""
+        num_rows, num_cols = self.shape
+        offset_inds = np.arange(self.data.shape[1])
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        return mask
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over an axis is not implemented for DIA format"
+            )
+        mask = self._data_mask()
+        return np.count_nonzero(self.data[mask])
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError("_getnnz over an axis is not implemented "
+                                      "for DIA format")
+        M,N = self.shape
+        nnz = 0
+        for k in self.offsets:
+            if k > 0:
+                nnz += min(M,N-k)
+            else:
+                nnz += min(M+k,N)
+        return int(nnz)
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def sum(self, axis=None, dtype=None, out=None):
+        validateaxis(axis)
+
+        if axis is not None and axis < 0:
+            axis += 2
+
+        res_dtype = get_sum_dtype(self.dtype)
+        num_rows, num_cols = self.shape
+        ret = None
+
+        if axis == 0:
+            mask = self._data_mask()
+            x = (self.data * mask).sum(axis=0)
+            if x.shape[0] == num_cols:
+                res = x
+            else:
+                res = np.zeros(num_cols, dtype=x.dtype)
+                res[:x.shape[0]] = x
+            ret = self._ascontainer(res, dtype=res_dtype)
+
+        else:
+            row_sums = np.zeros((num_rows, 1), dtype=res_dtype)
+            one = np.ones(num_cols, dtype=res_dtype)
+            dia_matvec(num_rows, num_cols, len(self.offsets),
+                       self.data.shape[1], self.offsets, self.data, one, row_sums)
+
+            row_sums = self._ascontainer(row_sums)
+
+            if axis is None:
+                return row_sums.sum(dtype=dtype, out=out)
+
+            ret = self._ascontainer(row_sums.sum(axis=axis))
+
+        return ret.sum(axis=(), dtype=dtype, out=out)
+
+    sum.__doc__ = _spbase.sum.__doc__
+
+    def _add_sparse(self, other):
+        # If other is not DIA format, let them handle us instead.
+        if not isinstance(other, _dia_base):
+            return other._add_sparse(self)
+
+        # Fast path for exact equality of the sparsity structure.
+        if np.array_equal(self.offsets, other.offsets):
+            return self._with_data(self.data + other.data)
+
+        # Find the union of the offsets (which will be sorted and unique).
+        new_offsets = np.union1d(self.offsets, other.offsets)
+        self_idx = np.searchsorted(new_offsets, self.offsets)
+        other_idx = np.searchsorted(new_offsets, other.offsets)
+
+        self_d = self.data.shape[1]
+        other_d = other.data.shape[1]
+        # Fast path for a sparsity structure where the final offsets are a
+        # permutation of the existing offsets and the diagonal lengths match.
+        if self_d == other_d and len(new_offsets) == len(self.offsets):
+            new_data = self.data[_invert_index(self_idx)]
+            new_data[other_idx, :] += other.data
+        elif self_d == other_d and len(new_offsets) == len(other.offsets):
+            new_data = other.data[_invert_index(other_idx)]
+            new_data[self_idx, :] += self.data
+        else:
+            # Maximum diagonal length of the result.
+            d = min(self.shape[0] + new_offsets[-1], self.shape[1])
+
+            # Add all diagonals to a freshly-allocated data array.
+            new_data = np.zeros(
+                (len(new_offsets), d),
+                dtype=np.result_type(self.data, other.data),
+            )
+            new_data[self_idx, :self_d] += self.data[:, :d]
+            new_data[other_idx, :other_d] += other.data[:, :d]
+        return self._dia_container((new_data, new_offsets), shape=self.shape)
+
+    def _mul_scalar(self, other):
+        return self._with_data(self.data * other)
+
+    def _matmul_vector(self, other):
+        x = other
+
+        y = np.zeros(self.shape[0], dtype=upcast_char(self.dtype.char,
+                                                       x.dtype.char))
+
+        L = self.data.shape[1]
+
+        M,N = self.shape
+
+        dia_matvec(M,N, len(self.offsets), L, self.offsets, self.data,
+                   x.ravel(), y.ravel())
+
+        return y
+
+    def _setdiag(self, values, k=0):
+        M, N = self.shape
+
+        if values.ndim == 0:
+            # broadcast
+            values_n = np.inf
+        else:
+            values_n = len(values)
+
+        if k < 0:
+            n = min(M + k, N, values_n)
+            min_index = 0
+            max_index = n
+        else:
+            n = min(M, N - k, values_n)
+            min_index = k
+            max_index = k + n
+
+        if values.ndim != 0:
+            # allow also longer sequences
+            values = values[:n]
+
+        data_rows, data_cols = self.data.shape
+        if k in self.offsets:
+            if max_index > data_cols:
+                data = np.zeros((data_rows, max_index), dtype=self.data.dtype)
+                data[:, :data_cols] = self.data
+                self.data = data
+            self.data[self.offsets == k, min_index:max_index] = values
+        else:
+            self.offsets = np.append(self.offsets, self.offsets.dtype.type(k))
+            m = max(max_index, data_cols)
+            data = np.zeros((data_rows + 1, m), dtype=self.data.dtype)
+            data[:-1, :data_cols] = self.data
+            data[-1, min_index:max_index] = values
+            self.data = data
+
+    def todia(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    todia.__doc__ = _spbase.todia.__doc__
+
+    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.")
+
+        num_rows, num_cols = self.shape
+        max_dim = max(self.shape)
+
+        # flip diagonal offsets
+        offsets = -self.offsets
+
+        # re-align the data matrix
+        r = np.arange(len(offsets), dtype=np.intc)[:, None]
+        c = np.arange(num_rows, dtype=np.intc) - (offsets % max_dim)[:, None]
+        pad_amount = max(0, max_dim-self.data.shape[1])
+        data = np.hstack((self.data, np.zeros((self.data.shape[0], pad_amount),
+                                              dtype=self.data.dtype)))
+        data = data[r, c]
+        return self._dia_container((data, offsets), shape=(
+            num_cols, num_rows), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        idx, = np.nonzero(self.offsets == k)
+        first_col = max(0, k)
+        last_col = min(rows + k, cols)
+        result_size = last_col - first_col
+        if idx.size == 0:
+            return np.zeros(result_size, dtype=self.data.dtype)
+        result = self.data[idx[0], first_col:last_col]
+        padding = result_size - len(result)
+        if padding > 0:
+            result = np.pad(result, (0, padding), mode='constant')
+        return result
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    def tocsc(self, copy=False):
+        if self.nnz == 0:
+            return self._csc_container(self.shape, dtype=self.dtype)
+
+        num_rows, num_cols = self.shape
+        num_offsets, offset_len = self.data.shape
+        offset_inds = np.arange(offset_len)
+
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        mask &= (self.data != 0)
+
+        idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+        indptr = np.zeros(num_cols + 1, dtype=idx_dtype)
+        indptr[1:offset_len+1] = np.cumsum(mask.sum(axis=0)[:num_cols])
+        if offset_len < num_cols:
+            indptr[offset_len+1:] = indptr[offset_len]
+        indices = row.T[mask.T].astype(idx_dtype, copy=False)
+        data = self.data.T[mask.T]
+        return self._csc_container((data, indices, indptr), shape=self.shape,
+                                   dtype=self.dtype)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocoo(self, copy=False):
+        num_rows, num_cols = self.shape
+        num_offsets, offset_len = self.data.shape
+        offset_inds = np.arange(offset_len)
+
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        mask &= (self.data != 0)
+        row = row[mask]
+        col = np.tile(offset_inds, num_offsets)[mask.ravel()]
+        idx_dtype = self._get_index_dtype(
+            arrays=(self.offsets,), maxval=max(self.shape)
+        )
+        row = row.astype(idx_dtype, copy=False)
+        col = col.astype(idx_dtype, copy=False)
+        data = self.data[mask]
+        # Note: this cannot set has_canonical_format=True, because despite the
+        # lack of duplicates, we do not generate sorted indices.
+        return self._coo_container(
+            (data, (row, col)), shape=self.shape, dtype=self.dtype, copy=False
+        )
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    # 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 are copied.
+        """
+        if copy:
+            return self._dia_container(
+                (data, self.offsets.copy()), shape=self.shape
+            )
+        else:
+            return self._dia_container(
+                (data, self.offsets), shape=self.shape
+            )
+
+    def resize(self, *shape):
+        shape = check_shape(shape)
+        M, N = shape
+        # we do not need to handle the case of expanding N
+        self.data = self.data[:, :N]
+
+        if (M > self.shape[0] and
+                np.any(self.offsets + self.shape[0] < self.data.shape[1])):
+            # explicitly clear values that were previously hidden
+            mask = (self.offsets[:, None] + self.shape[0] <=
+                    np.arange(self.data.shape[1]))
+            self.data[mask] = 0
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+
+def _invert_index(idx):
+    """Helper function to invert an index array."""
+    inv = np.zeros_like(idx)
+    inv[idx] = np.arange(len(idx))
+    return inv
+
+
+def isspmatrix_dia(x):
+    """Is `x` of dia_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a dia matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a dia matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import dia_array, dia_matrix, coo_matrix, isspmatrix_dia
+    >>> isspmatrix_dia(dia_matrix([[5]]))
+    True
+    >>> isspmatrix_dia(dia_array([[5]]))
+    False
+    >>> isspmatrix_dia(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, dia_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class dia_array(_dia_base, sparray):
+    """
+    Sparse array with DIAgonal storage.
+
+    This can be instantiated in several ways:
+        dia_array(D)
+            where D is a 2-D ndarray
+
+        dia_array(S)
+            with another sparse array or matrix S (equivalent to S.todia())
+
+        dia_array((M, N), [dtype])
+            to construct an empty array with shape (M, N),
+            dtype is optional, defaulting to dtype='d'.
+
+        dia_array((data, offsets), shape=(M, N))
+            where the ``data[k,:]`` stores the diagonal entries for
+            diagonal ``offsets[k]`` (See example below)
+
+    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
+        DIA format data array of the array
+    offsets
+        DIA format offset array of the array
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+    Sparse arrays with DIAgonal storage do not support slicing.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import dia_array
+    >>> dia_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+    >>> offsets = np.array([0, -1, 2])
+    >>> dia_array((data, offsets), shape=(4, 4)).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    >>> from scipy.sparse import dia_array
+    >>> n = 10
+    >>> ex = np.ones(n)
+    >>> data = np.array([ex, 2 * ex, ex])
+    >>> offsets = np.array([-1, 0, 1])
+    >>> dia_array((data, offsets), shape=(n, n)).toarray()
+    array([[2., 1., 0., ..., 0., 0., 0.],
+           [1., 2., 1., ..., 0., 0., 0.],
+           [0., 1., 2., ..., 0., 0., 0.],
+           ...,
+           [0., 0., 0., ..., 2., 1., 0.],
+           [0., 0., 0., ..., 1., 2., 1.],
+           [0., 0., 0., ..., 0., 1., 2.]])
+    """
+
+
+class dia_matrix(spmatrix, _dia_base):
+    """
+    Sparse matrix with DIAgonal storage.
+
+    This can be instantiated in several ways:
+        dia_matrix(D)
+            where D is a 2-D ndarray
+
+        dia_matrix(S)
+            with another sparse array or matrix S (equivalent to S.todia())
+
+        dia_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N),
+            dtype is optional, defaulting to dtype='d'.
+
+        dia_matrix((data, offsets), shape=(M, N))
+            where the ``data[k,:]`` stores the diagonal entries for
+            diagonal ``offsets[k]`` (See example below)
+
+    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
+        DIA format data array of the matrix
+    offsets
+        DIA format offset array of the matrix
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+    Sparse matrices with DIAgonal storage do not support slicing.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import dia_matrix
+    >>> dia_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+    >>> offsets = np.array([0, -1, 2])
+    >>> dia_matrix((data, offsets), shape=(4, 4)).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    >>> from scipy.sparse import dia_matrix
+    >>> n = 10
+    >>> ex = np.ones(n)
+    >>> data = np.array([ex, 2 * ex, ex])
+    >>> offsets = np.array([-1, 0, 1])
+    >>> dia_matrix((data, offsets), shape=(n, n)).toarray()
+    array([[2., 1., 0., ..., 0., 0., 0.],
+           [1., 2., 1., ..., 0., 0., 0.],
+           [0., 1., 2., ..., 0., 0., 0.],
+           ...,
+           [0., 0., 0., ..., 2., 1., 0.],
+           [0., 0., 0., ..., 1., 2., 1.],
+           [0., 0., 0., ..., 0., 1., 2.]])
+    """
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_dok.py b/python_embeded/Lib/site-packages/scipy/sparse/_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bf395791730e7bcc59b3e670580de18f70e6a74
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_extract.py b/python_embeded/Lib/site-packages/scipy/sparse/_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff8b4552c4ff31dcae77054e6739ed8921b53854
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/sparse/_extract.py
@@ -0,0 +1,178 @@
+"""Functions to extract parts of sparse matrices
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['find', 'tril', 'triu']
+
+
+from ._coo import coo_matrix, coo_array
+from ._base import sparray
+
+
+def find(A):
+    """Return the indices and values of the nonzero elements of a matrix
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose nonzero elements are desired.
+
+    Returns
+    -------
+    (I,J,V) : tuple of arrays
+        I,J, and V contain the row indices, column indices, and values
+        of the nonzero entries.
+
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, find
+    >>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
+    >>> find(A)
+    (array([0, 0, 1], dtype=int32),
+     array([0, 1, 2], dtype=int32),
+     array([ 7.,  8.,  9.]))
+
+    """
+
+    A = coo_array(A, copy=True)
+    A.sum_duplicates()
+    # remove explicit zeros
+    nz_mask = A.data != 0
+    return A.row[nz_mask], A.col[nz_mask], A.data[nz_mask]
+
+
+def tril(A, k=0, format=None):
+    """Return the lower triangular portion of a sparse array or matrix
+
+    Returns the elements on or below the k-th diagonal of A.
+        - k = 0 corresponds to the main diagonal
+        - k > 0 is above the main diagonal
+        - k < 0 is below the main diagonal
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose lower trianglar portion is desired.
+    k : integer : optional
+        The top-most diagonal of the lower triangle.
+    format : string
+        Sparse format of the result, e.g. format="csr", etc.
+
+    Returns
+    -------
+    L : sparse matrix
+        Lower triangular portion of A in sparse format.
+
+    See Also
+    --------
+    triu : upper triangle in sparse format
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, tril
+    >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
+    ...               dtype='int32')
+    >>> A.toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> tril(A).toarray()
+    array([[1, 0, 0, 0, 0],
+           [4, 5, 0, 0, 0],
+           [0, 0, 8, 0, 0]], dtype=int32)
+    >>> tril(A).nnz
+    4
+    >>> tril(A, k=1).toarray()
+    array([[1, 2, 0, 0, 0],
+           [4, 5, 0, 0, 0],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> tril(A, k=-1).toarray()
+    array([[0, 0, 0, 0, 0],
+           [4, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0]], dtype=int32)
+    >>> tril(A, format='csc')
+    
+
+    """
+    coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
+
+    # convert to COOrdinate format where things are easy
+    A = coo_sparse(A, copy=False)
+    mask = A.row + k >= A.col
+
+    row = A.row[mask]
+    col = A.col[mask]
+    data = A.data[mask]
+    new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
+    return new_coo.asformat(format)
+
+
+def triu(A, k=0, format=None):
+    """Return the upper triangular portion of a sparse array or matrix
+
+    Returns the elements on or above the k-th diagonal of A.
+        - k = 0 corresponds to the main diagonal
+        - k > 0 is above the main diagonal
+        - k < 0 is below the main diagonal
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose upper trianglar portion is desired.
+    k : integer : optional
+        The bottom-most diagonal of the upper triangle.
+    format : string
+        Sparse format of the result, e.g. format="csr", etc.
+
+    Returns
+    -------
+    L : sparse array or matrix
+        Upper triangular portion of A in sparse format.
+        Sparse array if A is a sparse array, otherwise matrix.
+
+    See Also
+    --------
+    tril : lower triangle in sparse format
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, triu
+    >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
+    ...                dtype='int32')
+    >>> A.toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A).toarray()
+    array([[1, 2, 0, 0, 3],
+           [0, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A).nnz
+    8
+    >>> triu(A, k=1).toarray()
+    array([[0, 2, 0, 0, 3],
+           [0, 0, 0, 6, 7],
+           [0, 0, 0, 9, 0]], dtype=int32)
+    >>> triu(A, k=-1).toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A, format='csc')
+    
+
+    """
+    coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
+
+    # convert to COOrdinate format where things are easy
+    A = coo_sparse(A, copy=False)
+    mask = A.row + k <= A.col
+
+    row = A.row[mask]
+    col = A.col[mask]
+    data = A.data[mask]
+    new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
+    return new_coo.asformat(format)
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_index.py b/python_embeded/Lib/site-packages/scipy/sparse/_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf7594f2ad8ee8189f18a383ee728489a35e94c1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/sparse/_index.py
@@ -0,0 +1,444 @@
+"""Indexing mixin for sparse array/matrix classes.
+"""
+import numpy as np
+from ._sputils import isintlike
+from ._base import sparray, issparse
+
+INT_TYPES = (int, np.integer)
+
+
+def _broadcast_arrays(a, b):
+    """
+    Same as np.broadcast_arrays(a, b) but old writeability rules.
+
+    NumPy >= 1.17.0 transitions broadcast_arrays to return
+    read-only arrays. Set writeability explicitly to avoid warnings.
+    Retain the old writeability rules, as our Cython code assumes
+    the old behavior.
+    """
+    x, y = np.broadcast_arrays(a, b)
+    x.flags.writeable = a.flags.writeable
+    y.flags.writeable = b.flags.writeable
+    return x, y
+
+
+class IndexMixin:
+    """
+    This class provides common dispatching and validation logic for indexing.
+    """
+    def __getitem__(self, key):
+        index, new_shape = self._validate_indices(key)
+
+        # 1D array
+        if len(index) == 1:
+            idx = index[0]
+            if isinstance(idx, np.ndarray):
+                if idx.shape == ():
+                    idx = idx.item()
+            if isinstance(idx, INT_TYPES):
+                res = self._get_int(idx)
+            elif isinstance(idx, slice):
+                res = self._get_slice(idx)
+            else:  # assume array idx
+                res = self._get_array(idx)
+
+            # package the result and return
+            if not isinstance(self, sparray):
+                return res
+            # handle np.newaxis in idx when result would otherwise be a scalar
+            if res.shape == () and new_shape != ():
+                if len(new_shape) == 1:
+                    return self.__class__([res], shape=new_shape, dtype=self.dtype)
+                if len(new_shape) == 2:
+                    return self.__class__([[res]], shape=new_shape, dtype=self.dtype)
+            return res.reshape(new_shape)
+
+        # 2D array
+        row, col = index
+
+        # Dispatch to specialized methods.
+        if isinstance(row, INT_TYPES):
+            if isinstance(col, INT_TYPES):
+                res = self._get_intXint(row, col)
+            elif isinstance(col, slice):
+                res = self._get_intXslice(row, col)
+            elif col.ndim == 1:
+                res = self._get_intXarray(row, col)
+            elif col.ndim == 2:
+                res = self._get_intXarray(row, col)
+            else:
+                raise IndexError('index results in >2 dimensions')
+        elif isinstance(row, slice):
+            if isinstance(col, INT_TYPES):
+                res = self._get_sliceXint(row, col)
+            elif isinstance(col, slice):
+                if row == slice(None) and row == col:
+                    res = self.copy()
+                else:
+                    res = self._get_sliceXslice(row, col)
+            elif col.ndim == 1:
+                res = self._get_sliceXarray(row, col)
+            else:
+                raise IndexError('index results in >2 dimensions')
+        else:
+            if isinstance(col, INT_TYPES):
+                res = self._get_arrayXint(row, col)
+            elif isinstance(col, slice):
+                res = self._get_arrayXslice(row, col)
+            # arrayXarray preprocess
+            elif (row.ndim == 2 and row.shape[1] == 1
+                and (col.ndim == 1 or col.shape[0] == 1)):
+                # outer indexing
+                res = self._get_columnXarray(row[:, 0], col.ravel())
+            else:
+                # inner indexing
+                row, col = _broadcast_arrays(row, col)
+                if row.shape != col.shape:
+                    raise IndexError('number of row and column indices differ')
+                if row.size == 0:
+                    res = self.__class__(np.atleast_2d(row).shape, dtype=self.dtype)
+                else:
+                    res = self._get_arrayXarray(row, col)
+
+        # handle spmatrix (must be 2d, dont let 1d new_shape start reshape)
+        if not isinstance(self, sparray):
+            if new_shape == () or (len(new_shape) == 1 and res.ndim != 0):
+                # res handles cases not inflated by None
+                return res
+            if len(new_shape) == 1:
+                # shape inflated to 1D by None in index. Make 2D
+                new_shape = (1,) + new_shape
+            # reshape if needed (when None changes shape, e.g. A[1,:,None])
+            return res if new_shape == res.shape else res.reshape(new_shape)
+
+        # package the result and return
+        if res.shape != new_shape:
+            # handle formats that support indexing but not 1D (lil for now)
+            if self.format == "lil" and len(new_shape) != 2:
+                if res.shape == ():
+                    return self._coo_container([res], shape = new_shape)
+                return res.tocoo().reshape(new_shape)
+            return res.reshape(new_shape)
+        return res
+
+    def __setitem__(self, key, x):
+        index, _ = self._validate_indices(key)
+
+        # 1D array
+        if len(index) == 1:
+            idx = index[0]
+
+            if issparse(x):
+                x = x.toarray()
+            else:
+                x = np.asarray(x, dtype=self.dtype)
+
+            if isinstance(idx, INT_TYPES):
+                if x.size != 1:
+                    raise ValueError('Trying to assign a sequence to an item')
+                self._set_int(idx, x.flat[0])
+                return
+
+            if isinstance(idx, slice):
+                # check for simple case of slice that gives 1 item
+                # Note: Python `range` does not use lots of memory
+                idx_range = range(*idx.indices(self.shape[0]))
+                N = len(idx_range)
+                if N == 1 and x.size == 1:
+                    self._set_int(idx_range[0], x.flat[0])
+                    return
+                idx = np.arange(*idx.indices(self.shape[0]))
+                idx_shape = idx.shape
+            else:
+                idx_shape = idx.squeeze().shape
+            # broadcast scalar to full 1d
+            if x.squeeze().shape != idx_shape:
+                x = np.broadcast_to(x, idx.shape)
+            if x.size != 0:
+                self._set_array(idx, x)
+            return
+
+        # 2D array
+        row, col = index
+
+        if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
+            x = np.asarray(x, dtype=self.dtype)
+            if x.size != 1:
+                raise ValueError('Trying to assign a sequence to an item')
+            self._set_intXint(row, col, x.flat[0])
+            return
+
+        if isinstance(row, slice):
+            row = np.arange(*row.indices(self.shape[0]))[:, None]
+        else:
+            row = np.atleast_1d(row)
+
+        if isinstance(col, slice):
+            col = np.arange(*col.indices(self.shape[1]))[None, :]
+            if row.ndim == 1:
+                row = row[:, None]
+        else:
+            col = np.atleast_1d(col)
+
+        i, j = _broadcast_arrays(row, col)
+        if i.shape != j.shape:
+            raise IndexError('number of row and column indices differ')
+
+        if issparse(x):
+            if 0 in x.shape:
+                return
+            if i.ndim == 1:
+                # Inner indexing, so treat them like row vectors.
+                i = i[None]
+                j = j[None]
+            x = x.tocoo(copy=False).reshape(x._shape_as_2d, copy=True)
+            broadcast_row = x.shape[0] == 1 and i.shape[0] != 1
+            broadcast_col = x.shape[1] == 1 and i.shape[1] != 1
+            if not ((broadcast_row or x.shape[0] == i.shape[0]) and
+                    (broadcast_col or x.shape[1] == i.shape[1])):
+                raise ValueError('shape mismatch in assignment')
+            x.sum_duplicates()
+            self._set_arrayXarray_sparse(i, j, x)
+        else:
+            # Make x and i into the same shape
+            x = np.asarray(x, dtype=self.dtype)
+            if x.squeeze().shape != i.squeeze().shape:
+                x = np.broadcast_to(x, i.shape)
+            if x.size == 0:
+                return
+            x = x.reshape(i.shape)
+            self._set_arrayXarray(i, j, x)
+
+    def _validate_indices(self, key):
+        """Returns two tuples: (index tuple, requested shape tuple)"""
+        # single ellipsis
+        if key is Ellipsis:
+            return (slice(None),) * self.ndim, self.shape
+
+        if not isinstance(key, tuple):
+            key = [key]
+
+        ellps_pos = None
+        index_1st = []
+        prelim_ndim = 0
+        for i, idx in enumerate(key):
+            if idx is Ellipsis:
+                if ellps_pos is not None:
+                    raise IndexError('an index can only have a single ellipsis')
+                ellps_pos = i
+            elif idx is None:
+                index_1st.append(idx)
+            elif isinstance(idx, slice) or isintlike(idx):
+                index_1st.append(idx)
+                prelim_ndim += 1
+            elif (ix := _compatible_boolean_index(idx, self.ndim)) is not None:
+                index_1st.append(ix)
+                prelim_ndim += ix.ndim
+            elif issparse(idx):
+                # TODO: make sparse matrix indexing work for sparray
+                raise IndexError(
+                    'Indexing with sparse matrices is not supported '
+                    'except boolean indexing where matrix and index '
+                    'are equal shapes.')
+            else:  # dense array
+                index_1st.append(np.asarray(idx))
+                prelim_ndim += 1
+        ellip_slices = (self.ndim - prelim_ndim) * [slice(None)]
+        if ellip_slices:
+            if ellps_pos is None:
+                index_1st.extend(ellip_slices)
+            else:
+                index_1st = index_1st[:ellps_pos] + ellip_slices + index_1st[ellps_pos:]
+
+        # second pass (have processed ellipsis and preprocessed arrays)
+        idx_shape = []
+        index_ndim = 0
+        index = []
+        array_indices = []
+        for i, idx in enumerate(index_1st):
+            if idx is None:
+                idx_shape.append(1)
+            elif isinstance(idx, slice):
+                index.append(idx)
+                Ms = self._shape[index_ndim]
+                len_slice = len(range(*idx.indices(Ms)))
+                idx_shape.append(len_slice)
+                index_ndim += 1
+            elif isintlike(idx):
+                N = self._shape[index_ndim]
+                if not (-N <= idx < N):
+                    raise IndexError(f'index ({idx}) out of range')
+                idx = int(idx + N if idx < 0 else idx)
+                index.append(idx)
+                index_ndim += 1
+            # bool array (checked in first pass)
+            elif idx.dtype.kind == 'b':
+                ix = idx
+                tmp_ndim = index_ndim + ix.ndim
+                mid_shape = self._shape[index_ndim:tmp_ndim]
+                if ix.shape != mid_shape:
+                    raise IndexError(
+                        f"bool index {i} has shape {mid_shape} instead of {ix.shape}"
+                    )
+                index.extend(ix.nonzero())
+                array_indices.extend(range(index_ndim, tmp_ndim))
+                index_ndim = tmp_ndim
+            else:  # dense array
+                N = self._shape[index_ndim]
+                idx = self._asindices(idx, N)
+                index.append(idx)
+                array_indices.append(index_ndim)
+                index_ndim += 1
+        if index_ndim > self.ndim:
+            raise IndexError(
+                f'invalid index ndim. Array is {self.ndim}D. Index needs {index_ndim}D'
+            )
+        if len(array_indices) > 1:
+            idx_arrays = _broadcast_arrays(*(index[i] for i in array_indices))
+            if any(idx_arrays[0].shape != ix.shape for ix in idx_arrays[1:]):
+                shapes = " ".join(str(ix.shape) for ix in idx_arrays)
+                msg = (f'shape mismatch: indexing arrays could not be broadcast '
+                       f'together with shapes {shapes}')
+                raise IndexError(msg)
+            # TODO: handle this for nD (adjacent arrays stay, separated move to start)
+            idx_shape = list(idx_arrays[0].shape) + idx_shape
+        elif len(array_indices) == 1:
+            arr_index = array_indices[0]
+            arr_shape = list(index[arr_index].shape)
+            idx_shape = idx_shape[:arr_index] + arr_shape + idx_shape[arr_index:]
+        if (ndim := len(idx_shape)) > 2:
+            raise IndexError(f'Only 1D or 2D arrays allowed. Index makes {ndim}D')
+        return tuple(index), tuple(idx_shape)
+
+    def _asindices(self, idx, length):
+        """Convert `idx` to a valid index for an axis with a given length.
+
+        Subclasses that need special validation can override this method.
+        """
+        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 1 or 2')
+
+        if x.size == 0:
+            return x
+
+        # Check bounds
+        max_indx = x.max()
+        if max_indx >= length:
+            raise IndexError('index (%d) out of range' % max_indx)
+
+        min_indx = x.min()
+        if min_indx < 0:
+            if min_indx < -length:
+                raise IndexError('index (%d) out of range' % min_indx)
+            if x is idx or not x.flags.owndata:
+                x = x.copy()
+            x[x < 0] += length
+        return x
+
+    def _getrow(self, i):
+        """Return a copy of row i of the matrix, as a (1 x n) row vector.
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < -M or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        if i < 0:
+            i += M
+        return self._get_intXslice(i, slice(None))
+
+    def _getcol(self, i):
+        """Return a copy of column i of the matrix, as a (m x 1) column vector.
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < -N or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        if i < 0:
+            i += N
+        return self._get_sliceXint(slice(None), i)
+
+    def _get_int(self, idx):
+        raise NotImplementedError()
+
+    def _get_slice(self, idx):
+        raise NotImplementedError()
+
+    def _get_array(self, idx):
+        raise NotImplementedError()
+
+    def _get_intXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_intXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_intXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_columnXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _set_int(self, idx, x):
+        raise NotImplementedError()
+
+    def _set_array(self, idx, x):
+        raise NotImplementedError()
+
+    def _set_intXint(self, row, col, x):
+        raise NotImplementedError()
+
+    def _set_arrayXarray(self, row, col, x):
+        raise NotImplementedError()
+
+    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 _compatible_boolean_index(idx, desired_ndim):
+    """Check for boolean array or array-like. peek before asarray for array-like"""
+    # use attribute ndim to indicate a compatible array and check dtype
+    # if not, look at 1st element as quick rejection of bool, else slower asanyarray
+    if not hasattr(idx, 'ndim'):
+        # is first element boolean?
+        try:
+            ix = next(iter(idx), None)
+            for _ in range(desired_ndim):
+                if isinstance(ix, bool):
+                    break
+                ix = next(iter(ix), None)
+            else:
+                return None
+        except TypeError:
+            return None
+        # since first is boolean, construct array and check all elements
+        idx = np.asanyarray(idx)
+
+    if idx.dtype.kind == 'b':
+        return idx
+    return None
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_lil.py b/python_embeded/Lib/site-packages/scipy/sparse/_lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..60b0c9a7ed80e32d5ff373ff504c59ce6ca08199
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_matrix.py b/python_embeded/Lib/site-packages/scipy/sparse/_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..16b8093d71a55aa70c7230f7317b96f43d0ce376
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/sparse/_matrix.py
@@ -0,0 +1,146 @@
+class spmatrix:
+    """This class provides a base class for all sparse matrix classes.
+
+    It cannot be instantiated.  Most of the work is provided by subclasses.
+    """
+    _allow_nd = (2,)
+
+    @property
+    def _bsr_container(self):
+        from ._bsr import bsr_matrix
+        return bsr_matrix
+
+    @property
+    def _coo_container(self):
+        from ._coo import coo_matrix
+        return coo_matrix
+
+    @property
+    def _csc_container(self):
+        from ._csc import csc_matrix
+        return csc_matrix
+
+    @property
+    def _csr_container(self):
+        from ._csr import csr_matrix
+        return csr_matrix
+
+    @property
+    def _dia_container(self):
+        from ._dia import dia_matrix
+        return dia_matrix
+
+    @property
+    def _dok_container(self):
+        from ._dok import dok_matrix
+        return dok_matrix
+
+    @property
+    def _lil_container(self):
+        from ._lil import lil_matrix
+        return lil_matrix
+
+    # Restore matrix multiplication
+    def __mul__(self, other):
+        return self._matmul_dispatch(other)
+
+    def __rmul__(self, other):
+        return self._rmatmul_dispatch(other)
+
+    # Restore matrix power
+    def __pow__(self, power):
+        from .linalg import matrix_power
+
+        return matrix_power(self, power)
+
+    ## Backward compatibility
+
+    def set_shape(self, shape):
+        """Set the shape of the matrix in-place"""
+        # Make sure copy is False since this is in place
+        # Make sure format is unchanged because we are doing a __dict__ swap
+        new_self = self.reshape(shape, copy=False).asformat(self.format)
+        self.__dict__ = new_self.__dict__
+
+    def get_shape(self):
+        """Get the shape of the matrix"""
+        return self._shape
+
+    shape = property(fget=get_shape, fset=set_shape,
+                     doc="Shape of the matrix")
+
+    def asfptype(self):
+        """Upcast matrix to a floating point format (if necessary)"""
+        return self._asfptype()
+
+    def getmaxprint(self):
+        """Maximum number of elements to display when printed."""
+        return self._getmaxprint()
+
+    def getformat(self):
+        """Matrix storage format"""
+        return self.format
+
+    def getnnz(self, axis=None):
+        """Number of stored values, including explicit zeros.
+
+        Parameters
+        ----------
+        axis : None, 0, or 1
+            Select between the number of values across the whole array, in
+            each column, or in each row.
+        """
+        return self._getnnz(axis=axis)
+
+    def getH(self):
+        """Return the Hermitian transpose of this matrix.
+
+        See Also
+        --------
+        numpy.matrix.getH : NumPy's implementation of `getH` for matrices
+        """
+        return self.conjugate().transpose()
+
+    def getcol(self, j):
+        """Returns a copy of column j of the matrix, as an (m x 1) sparse
+        matrix (column vector).
+        """
+        return self._getcol(j)
+
+    def getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n) sparse
+        matrix (row vector).
+        """
+        return self._getrow(i)
+
+    def todense(self, order=None, out=None):
+        """
+        Return a dense representation of this sparse matrix.
+
+        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 (or `numpy.matrix`) 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 matrix on which you are calling the
+            method.
+
+        Returns
+        -------
+        arr : numpy.matrix, 2-D
+            A NumPy matrix object with the same shape and containing
+            the same data represented by the sparse matrix, with the
+            requested memory order. If `out` was passed and was an
+            array (rather than a `numpy.matrix`), it will be filled
+            with the appropriate values and returned wrapped in a
+            `numpy.matrix` object that shares the same memory.
+        """
+        return super().todense(order, out)
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_matrix_io.py b/python_embeded/Lib/site-packages/scipy/sparse/_matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b923f3f430eea247c8e2d548d2fc92aac650e96
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_sparsetools.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/sparse/_sparsetools.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..b72b8821f6e07ce5dd3e642938e4b053dd2f21ec
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/sparse/_sparsetools.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/sparse/_spfuncs.py b/python_embeded/Lib/site-packages/scipy/sparse/_spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..86d52a51384cb01fbe64ced3c58696374b068d97
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/sparse/_sputils.py b/python_embeded/Lib/site-packages/scipy/sparse/_sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee829386aafa7ce4254805e532948c7aefcbf6f9
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/spatial/__init__.py b/python_embeded/Lib/site-packages/scipy/spatial/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d98a636f62f06d4a07d6b6ab14502935b45add6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/__init__.py
@@ -0,0 +1,129 @@
+"""
+=============================================================
+Spatial algorithms and data structures (:mod:`scipy.spatial`)
+=============================================================
+
+.. currentmodule:: scipy.spatial
+
+.. toctree::
+   :hidden:
+
+   spatial.distance
+
+Spatial transformations
+=======================
+
+These are contained in the `scipy.spatial.transform` submodule.
+
+Nearest-neighbor queries
+========================
+.. autosummary::
+   :toctree: generated/
+
+   KDTree      -- class for efficient nearest-neighbor queries
+   cKDTree     -- class for efficient nearest-neighbor queries (faster implementation)
+   Rectangle
+
+Distance metrics
+================
+
+Distance metrics are contained in the :mod:`scipy.spatial.distance` submodule.
+
+Delaunay triangulation, convex hulls, and Voronoi diagrams
+==========================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   Delaunay    -- compute Delaunay triangulation of input points
+   ConvexHull  -- compute a convex hull for input points
+   Voronoi     -- compute a Voronoi diagram hull from input points
+   SphericalVoronoi -- compute a Voronoi diagram from input points on the surface of a sphere
+   HalfspaceIntersection -- compute the intersection points of input halfspaces
+
+Plotting helpers
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   delaunay_plot_2d     -- plot 2-D triangulation
+   convex_hull_plot_2d  -- plot 2-D convex hull
+   voronoi_plot_2d      -- plot 2-D Voronoi diagram
+
+.. seealso:: :ref:`Tutorial `
+
+
+Simplex representation
+======================
+The simplices (triangles, tetrahedra, etc.) appearing in the Delaunay
+tessellation (N-D simplices), convex hull facets, and Voronoi ridges
+(N-1-D simplices) are represented in the following scheme::
+
+    tess = Delaunay(points)
+    hull = ConvexHull(points)
+    voro = Voronoi(points)
+
+    # coordinates of the jth vertex of the ith simplex
+    tess.points[tess.simplices[i, j], :]        # tessellation element
+    hull.points[hull.simplices[i, j], :]        # convex hull facet
+    voro.vertices[voro.ridge_vertices[i, j], :] # ridge between Voronoi cells
+
+For Delaunay triangulations and convex hulls, the neighborhood
+structure of the simplices satisfies the condition:
+``tess.neighbors[i,j]`` is the neighboring simplex of the ith
+simplex, opposite to the ``j``-vertex. It is -1 in case of no neighbor.
+
+Convex hull facets also define a hyperplane equation::
+
+    (hull.equations[i,:-1] * coord).sum() + hull.equations[i,-1] == 0
+
+Similar hyperplane equations for the Delaunay triangulation correspond
+to the convex hull facets on the corresponding N+1-D
+paraboloid.
+
+The Delaunay triangulation objects offer a method for locating the
+simplex containing a given point, and barycentric coordinate
+computations.
+
+Functions
+---------
+
+.. autosummary::
+   :toctree: generated/
+
+   tsearch
+   distance_matrix
+   minkowski_distance
+   minkowski_distance_p
+   procrustes
+   geometric_slerp
+
+Warnings / Errors used in :mod:`scipy.spatial`
+----------------------------------------------
+.. autosummary::
+   :toctree: generated/
+
+   QhullError
+"""  # noqa: E501
+
+from ._kdtree import *
+from ._ckdtree import *  # type: ignore[import-not-found]
+from ._qhull import *
+from ._spherical_voronoi import SphericalVoronoi
+from ._plotutils import *
+from ._procrustes import procrustes
+from ._geometric_slerp import geometric_slerp
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import ckdtree, kdtree, qhull
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from . import distance, transform
+
+__all__ += ['distance', 'transform']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_ckdtree.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_ckdtree.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..4761d01a5e05703f171e6a42011f6e3091f9445f
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_ckdtree.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_distance_pybind.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_distance_pybind.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..83385e187ca4eb4a00c0edec4f80c6bcfd8c2180
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_distance_pybind.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_distance_wrap.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_distance_wrap.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..457734740e8e907125d05335619236c3449958f6
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_distance_wrap.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_geometric_slerp.py b/python_embeded/Lib/site-packages/scipy/spatial/_geometric_slerp.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a11c07f1c7c59fa216e5901bde43c26a76117c9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_geometric_slerp.py
@@ -0,0 +1,238 @@
+__all__ = ['geometric_slerp']
+
+import warnings
+from typing import TYPE_CHECKING
+
+import numpy as np
+from scipy.spatial.distance import euclidean
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+
+def _geometric_slerp(start, end, t):
+    # create an orthogonal basis using QR decomposition
+    basis = np.vstack([start, end])
+    Q, R = np.linalg.qr(basis.T)
+    signs = 2 * (np.diag(R) >= 0) - 1
+    Q = Q.T * signs.T[:, np.newaxis]
+    R = R.T * signs.T[:, np.newaxis]
+
+    # calculate the angle between `start` and `end`
+    c = np.dot(start, end)
+    s = np.linalg.det(R)
+    omega = np.arctan2(s, c)
+
+    # interpolate
+    start, end = Q
+    s = np.sin(t * omega)
+    c = np.cos(t * omega)
+    return start * c[:, np.newaxis] + end * s[:, np.newaxis]
+
+
+def geometric_slerp(
+    start: "npt.ArrayLike",
+    end: "npt.ArrayLike",
+    t: "npt.ArrayLike",
+    tol: float = 1e-7,
+) -> np.ndarray:
+    """
+    Geometric spherical linear interpolation.
+
+    The interpolation occurs along a unit-radius
+    great circle arc in arbitrary dimensional space.
+
+    Parameters
+    ----------
+    start : (n_dimensions, ) array-like
+        Single n-dimensional input coordinate in a 1-D array-like
+        object. `n` must be greater than 1.
+    end : (n_dimensions, ) array-like
+        Single n-dimensional input coordinate in a 1-D array-like
+        object. `n` must be greater than 1.
+    t : float or (n_points,) 1D array-like
+        A float or 1D array-like of doubles representing interpolation
+        parameters, with values required in the inclusive interval
+        between 0 and 1. A common approach is to generate the array
+        with ``np.linspace(0, 1, n_pts)`` for linearly spaced points.
+        Ascending, descending, and scrambled orders are permitted.
+    tol : float
+        The absolute tolerance for determining if the start and end
+        coordinates are antipodes.
+
+    Returns
+    -------
+    result : (t.size, D)
+        An array of doubles containing the interpolated
+        spherical path and including start and
+        end when 0 and 1 t are used. The
+        interpolated values should correspond to the
+        same sort order provided in the t array. The result
+        may be 1-dimensional if ``t`` is a float.
+
+    Raises
+    ------
+    ValueError
+        If ``start`` and ``end`` are antipodes, not on the
+        unit n-sphere, or for a variety of degenerate conditions.
+
+    See Also
+    --------
+    scipy.spatial.transform.Slerp : 3-D Slerp that works with quaternions
+
+    Notes
+    -----
+    The implementation is based on the mathematical formula provided in [1]_,
+    and the first known presentation of this algorithm, derived from study of
+    4-D geometry, is credited to Glenn Davis in a footnote of the original
+    quaternion Slerp publication by Ken Shoemake [2]_.
+
+    .. versionadded:: 1.5.0
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Slerp#Geometric_Slerp
+    .. [2] Ken Shoemake (1985) Animating rotation with quaternion curves.
+           ACM SIGGRAPH Computer Graphics, 19(3): 245-254.
+
+    Examples
+    --------
+    Interpolate four linearly-spaced values on the circumference of
+    a circle spanning 90 degrees:
+
+    >>> import numpy as np
+    >>> from scipy.spatial import geometric_slerp
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> start = np.array([1, 0])
+    >>> end = np.array([0, 1])
+    >>> t_vals = np.linspace(0, 1, 4)
+    >>> result = geometric_slerp(start,
+    ...                          end,
+    ...                          t_vals)
+
+    The interpolated results should be at 30 degree intervals
+    recognizable on the unit circle:
+
+    >>> ax.scatter(result[...,0], result[...,1], c='k')
+    >>> circle = plt.Circle((0, 0), 1, color='grey')
+    >>> ax.add_artist(circle)
+    >>> ax.set_aspect('equal')
+    >>> plt.show()
+
+    Attempting to interpolate between antipodes on a circle is
+    ambiguous because there are two possible paths, and on a
+    sphere there are infinite possible paths on the geodesic surface.
+    Nonetheless, one of the ambiguous paths is returned along
+    with a warning:
+
+    >>> opposite_pole = np.array([-1, 0])
+    >>> with np.testing.suppress_warnings() as sup:
+    ...     sup.filter(UserWarning)
+    ...     geometric_slerp(start,
+    ...                     opposite_pole,
+    ...                     t_vals)
+    array([[ 1.00000000e+00,  0.00000000e+00],
+           [ 5.00000000e-01,  8.66025404e-01],
+           [-5.00000000e-01,  8.66025404e-01],
+           [-1.00000000e+00,  1.22464680e-16]])
+
+    Extend the original example to a sphere and plot interpolation
+    points in 3D:
+
+    >>> from mpl_toolkits.mplot3d import proj3d
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111, projection='3d')
+
+    Plot the unit sphere for reference (optional):
+
+    >>> u = np.linspace(0, 2 * np.pi, 100)
+    >>> v = np.linspace(0, np.pi, 100)
+    >>> x = np.outer(np.cos(u), np.sin(v))
+    >>> y = np.outer(np.sin(u), np.sin(v))
+    >>> z = np.outer(np.ones(np.size(u)), np.cos(v))
+    >>> ax.plot_surface(x, y, z, color='y', alpha=0.1)
+
+    Interpolating over a larger number of points
+    may provide the appearance of a smooth curve on
+    the surface of the sphere, which is also useful
+    for discretized integration calculations on a
+    sphere surface:
+
+    >>> start = np.array([1, 0, 0])
+    >>> end = np.array([0, 0, 1])
+    >>> t_vals = np.linspace(0, 1, 200)
+    >>> result = geometric_slerp(start,
+    ...                          end,
+    ...                          t_vals)
+    >>> ax.plot(result[...,0],
+    ...         result[...,1],
+    ...         result[...,2],
+    ...         c='k')
+    >>> plt.show()
+    """
+
+    start = np.asarray(start, dtype=np.float64)
+    end = np.asarray(end, dtype=np.float64)
+    t = np.asarray(t)
+
+    if t.ndim > 1:
+        raise ValueError("The interpolation parameter "
+                         "value must be one dimensional.")
+
+    if start.ndim != 1 or end.ndim != 1:
+        raise ValueError("Start and end coordinates "
+                         "must be one-dimensional")
+
+    if start.size != end.size:
+        raise ValueError("The dimensions of start and "
+                         "end must match (have same size)")
+
+    if start.size < 2 or end.size < 2:
+        raise ValueError("The start and end coordinates must "
+                         "both be in at least two-dimensional "
+                         "space")
+
+    if np.array_equal(start, end):
+        return np.linspace(start, start, t.size)
+
+    # for points that violate equation for n-sphere
+    for coord in [start, end]:
+        if not np.allclose(np.linalg.norm(coord), 1.0,
+                           rtol=1e-9,
+                           atol=0):
+            raise ValueError("start and end are not"
+                             " on a unit n-sphere")
+
+    if not isinstance(tol, float):
+        raise ValueError("tol must be a float")
+    else:
+        tol = np.fabs(tol)
+
+    coord_dist = euclidean(start, end)
+
+    # diameter of 2 within tolerance means antipodes, which is a problem
+    # for all unit n-spheres (even the 0-sphere would have an ambiguous path)
+    if np.allclose(coord_dist, 2.0, rtol=0, atol=tol):
+        warnings.warn("start and end are antipodes "
+                      "using the specified tolerance; "
+                      "this may cause ambiguous slerp paths",
+                      stacklevel=2)
+
+    t = np.asarray(t, dtype=np.float64)
+
+    if t.size == 0:
+        return np.empty((0, start.size))
+
+    if t.min() < 0 or t.max() > 1:
+        raise ValueError("interpolation parameter must be in [0, 1]")
+
+    if t.ndim == 0:
+        return _geometric_slerp(start,
+                                end,
+                                np.atleast_1d(t)).ravel()
+    else:
+        return _geometric_slerp(start,
+                                end,
+                                t)
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_hausdorff.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_hausdorff.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..7501d22f12883d3b844639aad459822af58f0311
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_hausdorff.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_kdtree.py b/python_embeded/Lib/site-packages/scipy/spatial/_kdtree.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a86c5c9b9bebe68b5daf17fc25f35cac8250473
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_kdtree.py
@@ -0,0 +1,920 @@
+# Copyright Anne M. Archibald 2008
+# Released under the scipy license
+import numpy as np
+from ._ckdtree import cKDTree, cKDTreeNode  # type: ignore[import-not-found]
+
+__all__ = ['minkowski_distance_p', 'minkowski_distance',
+           'distance_matrix',
+           'Rectangle', 'KDTree']
+
+
+def minkowski_distance_p(x, y, p=2):
+    """Compute the pth power of the L**p distance between two arrays.
+
+    For efficiency, this function computes the L**p distance but does
+    not extract the pth root. If `p` is 1 or infinity, this is equal to
+    the actual L**p distance.
+
+    The last dimensions of `x` and `y` must be the same length.  Any
+    other dimensions must be compatible for broadcasting.
+
+    Parameters
+    ----------
+    x : (..., K) array_like
+        Input array.
+    y : (..., K) array_like
+        Input array.
+    p : float, 1 <= p <= infinity
+        Which Minkowski p-norm to use.
+
+    Returns
+    -------
+    dist : ndarray
+        pth power of the distance between the input arrays.
+
+    Examples
+    --------
+    >>> from scipy.spatial import minkowski_distance_p
+    >>> minkowski_distance_p([[0, 0], [0, 0]], [[1, 1], [0, 1]])
+    array([2., 1.])
+
+    """
+    x = np.asarray(x)
+    y = np.asarray(y)
+
+    # Find smallest common datatype with float64 (return type of this
+    # function) - addresses #10262.
+    # Don't just cast to float64 for complex input case.
+    common_datatype = np.promote_types(np.promote_types(x.dtype, y.dtype),
+                                       'float64')
+
+    # Make sure x and y are NumPy arrays of correct datatype.
+    x = x.astype(common_datatype)
+    y = y.astype(common_datatype)
+
+    if p == np.inf:
+        return np.amax(np.abs(y-x), axis=-1)
+    elif p == 1:
+        return np.sum(np.abs(y-x), axis=-1)
+    else:
+        return np.sum(np.abs(y-x)**p, axis=-1)
+
+
+def minkowski_distance(x, y, p=2):
+    """Compute the L**p distance between two arrays.
+
+    The last dimensions of `x` and `y` must be the same length.  Any
+    other dimensions must be compatible for broadcasting.
+
+    Parameters
+    ----------
+    x : (..., K) array_like
+        Input array.
+    y : (..., K) array_like
+        Input array.
+    p : float, 1 <= p <= infinity
+        Which Minkowski p-norm to use.
+
+    Returns
+    -------
+    dist : ndarray
+        Distance between the input arrays.
+
+    Examples
+    --------
+    >>> from scipy.spatial import minkowski_distance
+    >>> minkowski_distance([[0, 0], [0, 0]], [[1, 1], [0, 1]])
+    array([ 1.41421356,  1.        ])
+
+    """
+    x = np.asarray(x)
+    y = np.asarray(y)
+    if p == np.inf or p == 1:
+        return minkowski_distance_p(x, y, p)
+    else:
+        return minkowski_distance_p(x, y, p)**(1./p)
+
+
+class Rectangle:
+    """Hyperrectangle class.
+
+    Represents a Cartesian product of intervals.
+    """
+    def __init__(self, maxes, mins):
+        """Construct a hyperrectangle."""
+        self.maxes = np.maximum(maxes,mins).astype(float)
+        self.mins = np.minimum(maxes,mins).astype(float)
+        self.m, = self.maxes.shape
+
+    def __repr__(self):
+        return f""
+
+    def volume(self):
+        """Total volume."""
+        return np.prod(self.maxes-self.mins)
+
+    def split(self, d, split):
+        """Produce two hyperrectangles by splitting.
+
+        In general, if you need to compute maximum and minimum
+        distances to the children, it can be done more efficiently
+        by updating the maximum and minimum distances to the parent.
+
+        Parameters
+        ----------
+        d : int
+            Axis to split hyperrectangle along.
+        split : float
+            Position along axis `d` to split at.
+
+        """
+        mid = np.copy(self.maxes)
+        mid[d] = split
+        less = Rectangle(self.mins, mid)
+        mid = np.copy(self.mins)
+        mid[d] = split
+        greater = Rectangle(mid, self.maxes)
+        return less, greater
+
+    def min_distance_point(self, x, p=2.):
+        """
+        Return the minimum distance between input and points in the
+        hyperrectangle.
+
+        Parameters
+        ----------
+        x : array_like
+            Input.
+        p : float, optional
+            Input.
+
+        """
+        return minkowski_distance(
+            0, np.maximum(0, np.maximum(self.mins-x, x-self.maxes)),
+            p
+        )
+
+    def max_distance_point(self, x, p=2.):
+        """
+        Return the maximum distance between input and points in the hyperrectangle.
+
+        Parameters
+        ----------
+        x : array_like
+            Input array.
+        p : float, optional
+            Input.
+
+        """
+        return minkowski_distance(0, np.maximum(self.maxes-x, x-self.mins), p)
+
+    def min_distance_rectangle(self, other, p=2.):
+        """
+        Compute the minimum distance between points in the two hyperrectangles.
+
+        Parameters
+        ----------
+        other : hyperrectangle
+            Input.
+        p : float
+            Input.
+
+        """
+        return minkowski_distance(
+            0,
+            np.maximum(0, np.maximum(self.mins-other.maxes,
+                                     other.mins-self.maxes)),
+            p
+        )
+
+    def max_distance_rectangle(self, other, p=2.):
+        """
+        Compute the maximum distance between points in the two hyperrectangles.
+
+        Parameters
+        ----------
+        other : hyperrectangle
+            Input.
+        p : float, optional
+            Input.
+
+        """
+        return minkowski_distance(
+            0, np.maximum(self.maxes-other.mins, other.maxes-self.mins), p)
+
+
+class KDTree(cKDTree):
+    """kd-tree for quick nearest-neighbor lookup.
+
+    This class provides an index into a set of k-dimensional points
+    which can be used to rapidly look up the nearest neighbors of any
+    point.
+
+    Parameters
+    ----------
+    data : array_like, shape (n,m)
+        The n data points of dimension m to be indexed. This array is
+        not copied unless this is necessary to produce a contiguous
+        array of doubles, and so modifying this data will result in
+        bogus results. The data are also copied if the kd-tree is built
+        with copy_data=True.
+    leafsize : positive int, optional
+        The number of points at which the algorithm switches over to
+        brute-force.  Default: 10.
+    compact_nodes : bool, optional
+        If True, the kd-tree is built to shrink the hyperrectangles to
+        the actual data range. This usually gives a more compact tree that
+        is robust against degenerated input data and gives faster queries
+        at the expense of longer build time. Default: True.
+    copy_data : bool, optional
+        If True the data is always copied to protect the kd-tree against
+        data corruption. Default: False.
+    balanced_tree : bool, optional
+        If True, the median is used to split the hyperrectangles instead of
+        the midpoint. This usually gives a more compact tree and
+        faster queries at the expense of longer build time. Default: True.
+    boxsize : array_like or scalar, optional
+        Apply a m-d toroidal topology to the KDTree.. The topology is generated
+        by :math:`x_i + n_i L_i` where :math:`n_i` are integers and :math:`L_i`
+        is the boxsize along i-th dimension. The input data shall be wrapped
+        into :math:`[0, L_i)`. A ValueError is raised if any of the data is
+        outside of this bound.
+
+    Notes
+    -----
+    The algorithm used is described in Maneewongvatana and Mount 1999.
+    The general idea is that the kd-tree is a binary tree, each of whose
+    nodes represents an axis-aligned hyperrectangle. Each node specifies
+    an axis and splits the set of points based on whether their coordinate
+    along that axis is greater than or less than a particular value.
+
+    During construction, the axis and splitting point are chosen by the
+    "sliding midpoint" rule, which ensures that the cells do not all
+    become long and thin.
+
+    The tree can be queried for the r closest neighbors of any given point
+    (optionally returning only those within some maximum distance of the
+    point). It can also be queried, with a substantial gain in efficiency,
+    for the r approximate closest neighbors.
+
+    For large dimensions (20 is already large) do not expect this to run
+    significantly faster than brute force. High-dimensional nearest-neighbor
+    queries are a substantial open problem in computer science.
+
+    Attributes
+    ----------
+    data : ndarray, shape (n,m)
+        The n data points of dimension m to be indexed. This array is
+        not copied unless this is necessary to produce a contiguous
+        array of doubles. The data are also copied if the kd-tree is built
+        with ``copy_data=True``.
+    leafsize : positive int
+        The number of points at which the algorithm switches over to
+        brute-force.
+    m : int
+        The dimension of a single data-point.
+    n : int
+        The number of data points.
+    maxes : ndarray, shape (m,)
+        The maximum value in each dimension of the n data points.
+    mins : ndarray, shape (m,)
+        The minimum value in each dimension of the n data points.
+    size : int
+        The number of nodes in the tree.
+
+    """
+
+    class node:
+        @staticmethod
+        def _create(ckdtree_node=None):
+            """Create either an inner or leaf node, wrapping a cKDTreeNode instance"""
+            if ckdtree_node is None:
+                return KDTree.node(ckdtree_node)
+            elif ckdtree_node.split_dim == -1:
+                return KDTree.leafnode(ckdtree_node)
+            else:
+                return KDTree.innernode(ckdtree_node)
+
+        def __init__(self, ckdtree_node=None):
+            if ckdtree_node is None:
+                ckdtree_node = cKDTreeNode()
+            self._node = ckdtree_node
+
+        def __lt__(self, other):
+            return id(self) < id(other)
+
+        def __gt__(self, other):
+            return id(self) > id(other)
+
+        def __le__(self, other):
+            return id(self) <= id(other)
+
+        def __ge__(self, other):
+            return id(self) >= id(other)
+
+        def __eq__(self, other):
+            return id(self) == id(other)
+
+    class leafnode(node):
+        @property
+        def idx(self):
+            return self._node.indices
+
+        @property
+        def children(self):
+            return self._node.children
+
+    class innernode(node):
+        def __init__(self, ckdtreenode):
+            assert isinstance(ckdtreenode, cKDTreeNode)
+            super().__init__(ckdtreenode)
+            self.less = KDTree.node._create(ckdtreenode.lesser)
+            self.greater = KDTree.node._create(ckdtreenode.greater)
+
+        @property
+        def split_dim(self):
+            return self._node.split_dim
+
+        @property
+        def split(self):
+            return self._node.split
+
+        @property
+        def children(self):
+            return self._node.children
+
+    @property
+    def tree(self):
+        if not hasattr(self, "_tree"):
+            self._tree = KDTree.node._create(super().tree)
+
+        return self._tree
+
+    def __init__(self, data, leafsize=10, compact_nodes=True, copy_data=False,
+                 balanced_tree=True, boxsize=None):
+        data = np.asarray(data)
+        if data.dtype.kind == 'c':
+            raise TypeError("KDTree does not work with complex data")
+
+        # Note KDTree has different default leafsize from cKDTree
+        super().__init__(data, leafsize, compact_nodes, copy_data,
+                         balanced_tree, boxsize)
+
+    def query(
+            self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf, workers=1):
+        r"""Query the kd-tree for nearest neighbors.
+
+        Parameters
+        ----------
+        x : array_like, last dimension self.m
+            An array of points to query.
+        k : int or Sequence[int], optional
+            Either the number of nearest neighbors to return, or a list of the
+            k-th nearest neighbors to return, starting from 1.
+        eps : nonnegative float, optional
+            Return approximate nearest neighbors; the kth returned value
+            is guaranteed to be no further than (1+eps) times the
+            distance to the real kth nearest neighbor.
+        p : float, 1<=p<=infinity, optional
+            Which Minkowski p-norm to use.
+            1 is the sum-of-absolute-values distance ("Manhattan" distance).
+            2 is the usual Euclidean distance.
+            infinity is the maximum-coordinate-difference distance.
+            A large, finite p may cause a ValueError if overflow can occur.
+        distance_upper_bound : nonnegative float, optional
+            Return only neighbors within this distance. This is used to prune
+            tree searches, so if you are doing a series of nearest-neighbor
+            queries, it may help to supply the distance to the nearest neighbor
+            of the most recent point.
+        workers : int, optional
+            Number of workers to use for parallel processing. If -1 is given
+            all CPU threads are used. Default: 1.
+
+            .. versionadded:: 1.6.0
+
+        Returns
+        -------
+        d : float or array of floats
+            The distances to the nearest neighbors.
+            If ``x`` has shape ``tuple+(self.m,)``, then ``d`` has shape
+            ``tuple+(k,)``.
+            When k == 1, the last dimension of the output is squeezed.
+            Missing neighbors are indicated with infinite distances.
+            Hits are sorted by distance (nearest first).
+
+            .. versionchanged:: 1.9.0
+               Previously if ``k=None``, then `d` was an object array of
+               shape ``tuple``, containing lists of distances. This behavior
+               has been removed, use `query_ball_point` instead.
+
+        i : integer or array of integers
+            The index of each neighbor in ``self.data``.
+            ``i`` is the same shape as d.
+            Missing neighbors are indicated with ``self.n``.
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> from scipy.spatial import KDTree
+        >>> x, y = np.mgrid[0:5, 2:8]
+        >>> tree = KDTree(np.c_[x.ravel(), y.ravel()])
+
+        To query the nearest neighbours and return squeezed result, use
+
+        >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=1)
+        >>> print(dd, ii, sep='\n')
+        [2.         0.2236068]
+        [ 0 13]
+
+        To query the nearest neighbours and return unsqueezed result, use
+
+        >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1])
+        >>> print(dd, ii, sep='\n')
+        [[2.        ]
+         [0.2236068]]
+        [[ 0]
+         [13]]
+
+        To query the second nearest neighbours and return unsqueezed result,
+        use
+
+        >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[2])
+        >>> print(dd, ii, sep='\n')
+        [[2.23606798]
+         [0.80622577]]
+        [[ 6]
+         [19]]
+
+        To query the first and second nearest neighbours, use
+
+        >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=2)
+        >>> print(dd, ii, sep='\n')
+        [[2.         2.23606798]
+         [0.2236068  0.80622577]]
+        [[ 0  6]
+         [13 19]]
+
+        or, be more specific
+
+        >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1, 2])
+        >>> print(dd, ii, sep='\n')
+        [[2.         2.23606798]
+         [0.2236068  0.80622577]]
+        [[ 0  6]
+         [13 19]]
+
+        """
+        x = np.asarray(x)
+        if x.dtype.kind == 'c':
+            raise TypeError("KDTree does not work with complex data")
+
+        if k is None:
+            raise ValueError("k must be an integer or a sequence of integers")
+
+        d, i = super().query(x, k, eps, p, distance_upper_bound, workers)
+        if isinstance(i, int):
+            i = np.intp(i)
+        return d, i
+
+    def query_ball_point(self, x, r, p=2., eps=0, workers=1,
+                         return_sorted=None, return_length=False):
+        """Find all points within distance r of point(s) x.
+
+        Parameters
+        ----------
+        x : array_like, shape tuple + (self.m,)
+            The point or points to search for neighbors of.
+        r : array_like, float
+            The radius of points to return, must broadcast to the length of x.
+        p : float, optional
+            Which Minkowski p-norm to use.  Should be in the range [1, inf].
+            A finite large p may cause a ValueError if overflow can occur.
+        eps : nonnegative float, optional
+            Approximate search. Branches of the tree are not explored if their
+            nearest points are further than ``r / (1 + eps)``, and branches are
+            added in bulk if their furthest points are nearer than
+            ``r * (1 + eps)``.
+        workers : int, optional
+            Number of jobs to schedule for parallel processing. If -1 is given
+            all processors are used. Default: 1.
+
+            .. versionadded:: 1.6.0
+        return_sorted : bool, optional
+            Sorts returned indices if True and does not sort them if False. If
+            None, does not sort single point queries, but does sort
+            multi-point queries which was the behavior before this option
+            was added.
+
+            .. versionadded:: 1.6.0
+        return_length : bool, optional
+            Return the number of points inside the radius instead of a list
+            of the indices.
+
+            .. versionadded:: 1.6.0
+
+        Returns
+        -------
+        results : list or array of lists
+            If `x` is a single point, returns a list of the indices of the
+            neighbors of `x`. If `x` is an array of points, returns an object
+            array of shape tuple containing lists of neighbors.
+
+        Notes
+        -----
+        If you have many points whose neighbors you want to find, you may save
+        substantial amounts of time by putting them in a KDTree and using
+        query_ball_tree.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import spatial
+        >>> x, y = np.mgrid[0:5, 0:5]
+        >>> points = np.c_[x.ravel(), y.ravel()]
+        >>> tree = spatial.KDTree(points)
+        >>> sorted(tree.query_ball_point([2, 0], 1))
+        [5, 10, 11, 15]
+
+        Query multiple points and plot the results:
+
+        >>> import matplotlib.pyplot as plt
+        >>> points = np.asarray(points)
+        >>> plt.plot(points[:,0], points[:,1], '.')
+        >>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1):
+        ...     nearby_points = points[results]
+        ...     plt.plot(nearby_points[:,0], nearby_points[:,1], 'o')
+        >>> plt.margins(0.1, 0.1)
+        >>> plt.show()
+
+        """
+        x = np.asarray(x)
+        if x.dtype.kind == 'c':
+            raise TypeError("KDTree does not work with complex data")
+        return super().query_ball_point(
+            x, r, p, eps, workers, return_sorted, return_length)
+
+    def query_ball_tree(self, other, r, p=2., eps=0):
+        """
+        Find all pairs of points between `self` and `other` whose distance is
+        at most r.
+
+        Parameters
+        ----------
+        other : KDTree instance
+            The tree containing points to search against.
+        r : float
+            The maximum distance, has to be positive.
+        p : float, optional
+            Which Minkowski norm to use.  `p` has to meet the condition
+            ``1 <= p <= infinity``.
+        eps : float, optional
+            Approximate search.  Branches of the tree are not explored
+            if their nearest points are further than ``r/(1+eps)``, and
+            branches are added in bulk if their furthest points are nearer
+            than ``r * (1+eps)``.  `eps` has to be non-negative.
+
+        Returns
+        -------
+        results : list of lists
+            For each element ``self.data[i]`` of this tree, ``results[i]`` is a
+            list of the indices of its neighbors in ``other.data``.
+
+        Examples
+        --------
+        You can search all pairs of points between two kd-trees within a distance:
+
+        >>> import matplotlib.pyplot as plt
+        >>> import numpy as np
+        >>> from scipy.spatial import KDTree
+        >>> rng = np.random.default_rng()
+        >>> points1 = rng.random((15, 2))
+        >>> points2 = rng.random((15, 2))
+        >>> plt.figure(figsize=(6, 6))
+        >>> plt.plot(points1[:, 0], points1[:, 1], "xk", markersize=14)
+        >>> plt.plot(points2[:, 0], points2[:, 1], "og", markersize=14)
+        >>> kd_tree1 = KDTree(points1)
+        >>> kd_tree2 = KDTree(points2)
+        >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2)
+        >>> for i in range(len(indexes)):
+        ...     for j in indexes[i]:
+        ...         plt.plot([points1[i, 0], points2[j, 0]],
+        ...             [points1[i, 1], points2[j, 1]], "-r")
+        >>> plt.show()
+
+        """
+        return super().query_ball_tree(other, r, p, eps)
+
+    def query_pairs(self, r, p=2., eps=0, output_type='set'):
+        """Find all pairs of points in `self` whose distance is at most r.
+
+        Parameters
+        ----------
+        r : positive float
+            The maximum distance.
+        p : float, optional
+            Which Minkowski norm to use.  `p` has to meet the condition
+            ``1 <= p <= infinity``.
+        eps : float, optional
+            Approximate search.  Branches of the tree are not explored
+            if their nearest points are further than ``r/(1+eps)``, and
+            branches are added in bulk if their furthest points are nearer
+            than ``r * (1+eps)``.  `eps` has to be non-negative.
+        output_type : string, optional
+            Choose the output container, 'set' or 'ndarray'. Default: 'set'
+
+            .. versionadded:: 1.6.0
+
+        Returns
+        -------
+        results : set or ndarray
+            Set of pairs ``(i,j)``, with ``i < j``, for which the corresponding
+            positions are close. If output_type is 'ndarray', an ndarry is
+            returned instead of a set.
+
+        Examples
+        --------
+        You can search all pairs of points in a kd-tree within a distance:
+
+        >>> import matplotlib.pyplot as plt
+        >>> import numpy as np
+        >>> from scipy.spatial import KDTree
+        >>> rng = np.random.default_rng()
+        >>> points = rng.random((20, 2))
+        >>> plt.figure(figsize=(6, 6))
+        >>> plt.plot(points[:, 0], points[:, 1], "xk", markersize=14)
+        >>> kd_tree = KDTree(points)
+        >>> pairs = kd_tree.query_pairs(r=0.2)
+        >>> for (i, j) in pairs:
+        ...     plt.plot([points[i, 0], points[j, 0]],
+        ...             [points[i, 1], points[j, 1]], "-r")
+        >>> plt.show()
+
+        """
+        return super().query_pairs(r, p, eps, output_type)
+
+    def count_neighbors(self, other, r, p=2., weights=None, cumulative=True):
+        """Count how many nearby pairs can be formed.
+
+        Count the number of pairs ``(x1,x2)`` can be formed, with ``x1`` drawn
+        from ``self`` and ``x2`` drawn from ``other``, and where
+        ``distance(x1, x2, p) <= r``.
+
+        Data points on ``self`` and ``other`` are optionally weighted by the
+        ``weights`` argument. (See below)
+
+        This is adapted from the "two-point correlation" algorithm described by
+        Gray and Moore [1]_.  See notes for further discussion.
+
+        Parameters
+        ----------
+        other : KDTree
+            The other tree to draw points from, can be the same tree as self.
+        r : float or one-dimensional array of floats
+            The radius to produce a count for. Multiple radii are searched with
+            a single tree traversal.
+            If the count is non-cumulative(``cumulative=False``), ``r`` defines
+            the edges of the bins, and must be non-decreasing.
+        p : float, optional
+            1<=p<=infinity.
+            Which Minkowski p-norm to use.
+            Default 2.0.
+            A finite large p may cause a ValueError if overflow can occur.
+        weights : tuple, array_like, or None, optional
+            If None, the pair-counting is unweighted.
+            If given as a tuple, weights[0] is the weights of points in
+            ``self``, and weights[1] is the weights of points in ``other``;
+            either can be None to indicate the points are unweighted.
+            If given as an array_like, weights is the weights of points in
+            ``self`` and ``other``. For this to make sense, ``self`` and
+            ``other`` must be the same tree. If ``self`` and ``other`` are two
+            different trees, a ``ValueError`` is raised.
+            Default: None
+
+            .. versionadded:: 1.6.0
+        cumulative : bool, optional
+            Whether the returned counts are cumulative. When cumulative is set
+            to ``False`` the algorithm is optimized to work with a large number
+            of bins (>10) specified by ``r``. When ``cumulative`` is set to
+            True, the algorithm is optimized to work with a small number of
+            ``r``. Default: True
+
+            .. versionadded:: 1.6.0
+
+        Returns
+        -------
+        result : scalar or 1-D array
+            The number of pairs. For unweighted counts, the result is integer.
+            For weighted counts, the result is float.
+            If cumulative is False, ``result[i]`` contains the counts with
+            ``(-inf if i == 0 else r[i-1]) < R <= r[i]``
+
+        Notes
+        -----
+        Pair-counting is the basic operation used to calculate the two point
+        correlation functions from a data set composed of position of objects.
+
+        Two point correlation function measures the clustering of objects and
+        is widely used in cosmology to quantify the large scale structure
+        in our Universe, but it may be useful for data analysis in other fields
+        where self-similar assembly of objects also occur.
+
+        The Landy-Szalay estimator for the two point correlation function of
+        ``D`` measures the clustering signal in ``D``. [2]_
+
+        For example, given the position of two sets of objects,
+
+        - objects ``D`` (data) contains the clustering signal, and
+
+        - objects ``R`` (random) that contains no signal,
+
+        .. math::
+
+             \\xi(r) = \\frac{ - 2 f  + f^2}{f^2},
+
+        where the brackets represents counting pairs between two data sets
+        in a finite bin around ``r`` (distance), corresponding to setting
+        `cumulative=False`, and ``f = float(len(D)) / float(len(R))`` is the
+        ratio between number of objects from data and random.
+
+        The algorithm implemented here is loosely based on the dual-tree
+        algorithm described in [1]_. We switch between two different
+        pair-cumulation scheme depending on the setting of ``cumulative``.
+        The computing time of the method we use when for
+        ``cumulative == False`` does not scale with the total number of bins.
+        The algorithm for ``cumulative == True`` scales linearly with the
+        number of bins, though it is slightly faster when only
+        1 or 2 bins are used. [5]_.
+
+        As an extension to the naive pair-counting,
+        weighted pair-counting counts the product of weights instead
+        of number of pairs.
+        Weighted pair-counting is used to estimate marked correlation functions
+        ([3]_, section 2.2),
+        or to properly calculate the average of data per distance bin
+        (e.g. [4]_, section 2.1 on redshift).
+
+        .. [1] Gray and Moore,
+               "N-body problems in statistical learning",
+               Mining the sky, 2000,
+               https://arxiv.org/abs/astro-ph/0012333
+
+        .. [2] Landy and Szalay,
+               "Bias and variance of angular correlation functions",
+               The Astrophysical Journal, 1993,
+               http://adsabs.harvard.edu/abs/1993ApJ...412...64L
+
+        .. [3] Sheth, Connolly and Skibba,
+               "Marked correlations in galaxy formation models",
+               Arxiv e-print, 2005,
+               https://arxiv.org/abs/astro-ph/0511773
+
+        .. [4] Hawkins, et al.,
+               "The 2dF Galaxy Redshift Survey: correlation functions,
+               peculiar velocities and the matter density of the Universe",
+               Monthly Notices of the Royal Astronomical Society, 2002,
+               http://adsabs.harvard.edu/abs/2003MNRAS.346...78H
+
+        .. [5] https://github.com/scipy/scipy/pull/5647#issuecomment-168474926
+
+        Examples
+        --------
+        You can count neighbors number between two kd-trees within a distance:
+
+        >>> import numpy as np
+        >>> from scipy.spatial import KDTree
+        >>> rng = np.random.default_rng()
+        >>> points1 = rng.random((5, 2))
+        >>> points2 = rng.random((5, 2))
+        >>> kd_tree1 = KDTree(points1)
+        >>> kd_tree2 = KDTree(points2)
+        >>> kd_tree1.count_neighbors(kd_tree2, 0.2)
+        1
+
+        This number is same as the total pair number calculated by
+        `query_ball_tree`:
+
+        >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2)
+        >>> sum([len(i) for i in indexes])
+        1
+
+        """
+        return super().count_neighbors(other, r, p, weights, cumulative)
+
+    def sparse_distance_matrix(
+            self, other, max_distance, p=2., output_type='dok_matrix'):
+        """Compute a sparse distance matrix.
+
+        Computes a distance matrix between two KDTrees, leaving as zero
+        any distance greater than max_distance.
+
+        Parameters
+        ----------
+        other : KDTree
+
+        max_distance : positive float
+
+        p : float, 1<=p<=infinity
+            Which Minkowski p-norm to use.
+            A finite large p may cause a ValueError if overflow can occur.
+
+        output_type : string, optional
+            Which container to use for output data. Options: 'dok_matrix',
+            'coo_matrix', 'dict', or 'ndarray'. Default: 'dok_matrix'.
+
+            .. versionadded:: 1.6.0
+
+        Returns
+        -------
+        result : dok_matrix, coo_matrix, dict or ndarray
+            Sparse matrix representing the results in "dictionary of keys"
+            format. If a dict is returned the keys are (i,j) tuples of indices.
+            If output_type is 'ndarray' a record array with fields 'i', 'j',
+            and 'v' is returned,
+
+        Examples
+        --------
+        You can compute a sparse distance matrix between two kd-trees:
+
+        >>> import numpy as np
+        >>> from scipy.spatial import KDTree
+        >>> rng = np.random.default_rng()
+        >>> points1 = rng.random((5, 2))
+        >>> points2 = rng.random((5, 2))
+        >>> kd_tree1 = KDTree(points1)
+        >>> kd_tree2 = KDTree(points2)
+        >>> sdm = kd_tree1.sparse_distance_matrix(kd_tree2, 0.3)
+        >>> sdm.toarray()
+        array([[0.        , 0.        , 0.12295571, 0.        , 0.        ],
+           [0.        , 0.        , 0.        , 0.        , 0.        ],
+           [0.28942611, 0.        , 0.        , 0.2333084 , 0.        ],
+           [0.        , 0.        , 0.        , 0.        , 0.        ],
+           [0.24617575, 0.29571802, 0.26836782, 0.        , 0.        ]])
+
+        You can check distances above the `max_distance` are zeros:
+
+        >>> from scipy.spatial import distance_matrix
+        >>> distance_matrix(points1, points2)
+        array([[0.56906522, 0.39923701, 0.12295571, 0.8658745 , 0.79428925],
+           [0.37327919, 0.7225693 , 0.87665969, 0.32580855, 0.75679479],
+           [0.28942611, 0.30088013, 0.6395831 , 0.2333084 , 0.33630734],
+           [0.31994999, 0.72658602, 0.71124834, 0.55396483, 0.90785663],
+           [0.24617575, 0.29571802, 0.26836782, 0.57714465, 0.6473269 ]])
+
+        """
+        return super().sparse_distance_matrix(
+            other, max_distance, p, output_type)
+
+
+def distance_matrix(x, y, p=2, threshold=1000000):
+    """Compute the distance matrix.
+
+    Returns the matrix of all pair-wise distances.
+
+    Parameters
+    ----------
+    x : (M, K) array_like
+        Matrix of M vectors in K dimensions.
+    y : (N, K) array_like
+        Matrix of N vectors in K dimensions.
+    p : float, 1 <= p <= infinity
+        Which Minkowski p-norm to use.
+    threshold : positive int
+        If ``M * N * K`` > `threshold`, algorithm uses a Python loop instead
+        of large temporary arrays.
+
+    Returns
+    -------
+    result : (M, N) ndarray
+        Matrix containing the distance from every vector in `x` to every vector
+        in `y`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance_matrix
+    >>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]])
+    array([[ 1.        ,  1.41421356],
+           [ 1.41421356,  1.        ]])
+
+    """
+
+    x = np.asarray(x)
+    m, k = x.shape
+    y = np.asarray(y)
+    n, kk = y.shape
+
+    if k != kk:
+        raise ValueError(f"x contains {k}-dimensional vectors but y contains "
+                         f"{kk}-dimensional vectors")
+
+    if m*n*k <= threshold:
+        return minkowski_distance(x[:,np.newaxis,:],y[np.newaxis,:,:],p)
+    else:
+        result = np.empty((m,n),dtype=float)  # FIXME: figure out the best dtype
+        if m < n:
+            for i in range(m):
+                result[i,:] = minkowski_distance(x[i],y,p)
+        else:
+            for j in range(n):
+                result[:,j] = minkowski_distance(x,y[j],p)
+        return result
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_plotutils.py b/python_embeded/Lib/site-packages/scipy/spatial/_plotutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf99c849925cc6c75928cb4ea48c96aade58c312
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_plotutils.py
@@ -0,0 +1,274 @@
+import numpy as np
+from scipy._lib.decorator import decorator as _decorator
+
+__all__ = ['delaunay_plot_2d', 'convex_hull_plot_2d', 'voronoi_plot_2d']
+
+
+@_decorator
+def _held_figure(func, obj, ax=None, **kw):
+    import matplotlib.pyplot as plt
+
+    if ax is None:
+        fig = plt.figure()
+        ax = fig.gca()
+        return func(obj, ax=ax, **kw)
+
+    # As of matplotlib 2.0, the "hold" mechanism is deprecated.
+    # When matplotlib 1.x is no longer supported, this check can be removed.
+    was_held = getattr(ax, 'ishold', lambda: True)()
+    if was_held:
+        return func(obj, ax=ax, **kw)
+    try:
+        ax.hold(True)
+        return func(obj, ax=ax, **kw)
+    finally:
+        ax.hold(was_held)
+
+
+def _adjust_bounds(ax, points):
+    margin = 0.1 * np.ptp(points, axis=0)
+    xy_min = points.min(axis=0) - margin
+    xy_max = points.max(axis=0) + margin
+    ax.set_xlim(xy_min[0], xy_max[0])
+    ax.set_ylim(xy_min[1], xy_max[1])
+
+
+@_held_figure
+def delaunay_plot_2d(tri, ax=None):
+    """
+    Plot the given Delaunay triangulation in 2-D
+
+    Parameters
+    ----------
+    tri : scipy.spatial.Delaunay instance
+        Triangulation to plot
+    ax : matplotlib.axes.Axes instance, optional
+        Axes to plot on
+
+    Returns
+    -------
+    fig : matplotlib.figure.Figure instance
+        Figure for the plot
+
+    See Also
+    --------
+    Delaunay
+    matplotlib.pyplot.triplot
+
+    Notes
+    -----
+    Requires Matplotlib.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.spatial import Delaunay, delaunay_plot_2d
+
+    The Delaunay triangulation of a set of random points:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((30, 2))
+    >>> tri = Delaunay(points)
+
+    Plot it:
+
+    >>> _ = delaunay_plot_2d(tri)
+    >>> plt.show()
+
+    """
+    if tri.points.shape[1] != 2:
+        raise ValueError("Delaunay triangulation is not 2-D")
+
+    x, y = tri.points.T
+    ax.plot(x, y, 'o')
+    ax.triplot(x, y, tri.simplices.copy())
+
+    _adjust_bounds(ax, tri.points)
+
+    return ax.figure
+
+
+@_held_figure
+def convex_hull_plot_2d(hull, ax=None):
+    """
+    Plot the given convex hull diagram in 2-D
+
+    Parameters
+    ----------
+    hull : scipy.spatial.ConvexHull instance
+        Convex hull to plot
+    ax : matplotlib.axes.Axes instance, optional
+        Axes to plot on
+
+    Returns
+    -------
+    fig : matplotlib.figure.Figure instance
+        Figure for the plot
+
+    See Also
+    --------
+    ConvexHull
+
+    Notes
+    -----
+    Requires Matplotlib.
+
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.spatial import ConvexHull, convex_hull_plot_2d
+
+    The convex hull of a random set of points:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((30, 2))
+    >>> hull = ConvexHull(points)
+
+    Plot it:
+
+    >>> _ = convex_hull_plot_2d(hull)
+    >>> plt.show()
+
+    """
+    from matplotlib.collections import LineCollection
+
+    if hull.points.shape[1] != 2:
+        raise ValueError("Convex hull is not 2-D")
+
+    ax.plot(hull.points[:, 0], hull.points[:, 1], 'o')
+    line_segments = [hull.points[simplex] for simplex in hull.simplices]
+    ax.add_collection(LineCollection(line_segments,
+                                     colors='k',
+                                     linestyle='solid'))
+    _adjust_bounds(ax, hull.points)
+
+    return ax.figure
+
+
+@_held_figure
+def voronoi_plot_2d(vor, ax=None, **kw):
+    """
+    Plot the given Voronoi diagram in 2-D
+
+    Parameters
+    ----------
+    vor : scipy.spatial.Voronoi instance
+        Diagram to plot
+    ax : matplotlib.axes.Axes instance, optional
+        Axes to plot on
+    show_points : bool, optional
+        Add the Voronoi points to the plot.
+    show_vertices : bool, optional
+        Add the Voronoi vertices to the plot.
+    line_colors : string, optional
+        Specifies the line color for polygon boundaries
+    line_width : float, optional
+        Specifies the line width for polygon boundaries
+    line_alpha : float, optional
+        Specifies the line alpha for polygon boundaries
+    point_size : float, optional
+        Specifies the size of points
+
+    Returns
+    -------
+    fig : matplotlib.figure.Figure instance
+        Figure for the plot
+
+    See Also
+    --------
+    Voronoi
+
+    Notes
+    -----
+    Requires Matplotlib. For degenerate input, including collinearity and
+    other violations of general position, it may be preferable to
+    calculate the Voronoi diagram with Qhull options ``QJ`` for random
+    joggling, or ``Qt`` to enforce triangulated output. Otherwise, some
+    Voronoi regions may not be visible.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.spatial import Voronoi, voronoi_plot_2d
+
+    Create a set of points for the example:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((10,2))
+
+    Generate the Voronoi diagram for the points:
+
+    >>> vor = Voronoi(points)
+
+    Use `voronoi_plot_2d` to plot the diagram:
+
+    >>> fig = voronoi_plot_2d(vor)
+
+    Use `voronoi_plot_2d` to plot the diagram again, with some settings
+    customized:
+
+    >>> fig = voronoi_plot_2d(vor, show_vertices=False, line_colors='orange',
+    ...                       line_width=2, line_alpha=0.6, point_size=2)
+    >>> plt.show()
+
+    """
+    from matplotlib.collections import LineCollection
+
+    if vor.points.shape[1] != 2:
+        raise ValueError("Voronoi diagram is not 2-D")
+
+    if kw.get('show_points', True):
+        point_size = kw.get('point_size', None)
+        ax.plot(vor.points[:, 0], vor.points[:, 1], '.', markersize=point_size)
+    if kw.get('show_vertices', True):
+        ax.plot(vor.vertices[:, 0], vor.vertices[:, 1], 'o')
+
+    line_colors = kw.get('line_colors', 'k')
+    line_width = kw.get('line_width', 1.0)
+    line_alpha = kw.get('line_alpha', 1.0)
+
+    center = vor.points.mean(axis=0)
+    ptp_bound = np.ptp(vor.points, axis=0)
+
+    finite_segments = []
+    infinite_segments = []
+    for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
+        simplex = np.asarray(simplex)
+        if np.all(simplex >= 0):
+            finite_segments.append(vor.vertices[simplex])
+        else:
+            i = simplex[simplex >= 0][0]  # finite end Voronoi vertex
+
+            t = vor.points[pointidx[1]] - vor.points[pointidx[0]]  # tangent
+            t /= np.linalg.norm(t)
+            n = np.array([-t[1], t[0]])  # normal
+
+            midpoint = vor.points[pointidx].mean(axis=0)
+            direction = np.sign(np.dot(midpoint - center, n)) * n
+            if (vor.furthest_site):
+                direction = -direction
+            aspect_factor = abs(ptp_bound.max() / ptp_bound.min())
+            far_point = vor.vertices[i] + direction * ptp_bound.max() * aspect_factor
+
+            infinite_segments.append([vor.vertices[i], far_point])
+
+    ax.add_collection(LineCollection(finite_segments,
+                                     colors=line_colors,
+                                     lw=line_width,
+                                     alpha=line_alpha,
+                                     linestyle='solid'))
+    ax.add_collection(LineCollection(infinite_segments,
+                                     colors=line_colors,
+                                     lw=line_width,
+                                     alpha=line_alpha,
+                                     linestyle='dashed'))
+
+    _adjust_bounds(ax, vor.points)
+
+    return ax.figure
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_procrustes.py b/python_embeded/Lib/site-packages/scipy/spatial/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..c51f59604ffc3ae06e3d08797c9dc347fa5abdd4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_procrustes.py
@@ -0,0 +1,132 @@
+"""
+This module provides functions to perform full Procrustes analysis.
+
+This code was originally written by Justin Kucynski and ported over from
+scikit-bio by Yoshiki Vazquez-Baeza.
+"""
+
+import numpy as np
+from scipy.linalg import orthogonal_procrustes
+
+
+__all__ = ['procrustes']
+
+
+def procrustes(data1, data2):
+    r"""Procrustes analysis, a similarity test for two data sets.
+
+    Each input matrix is a set of points or vectors (the rows of the matrix).
+    The dimension of the space is the number of columns of each matrix. Given
+    two identically sized matrices, procrustes standardizes both such that:
+
+    - :math:`tr(AA^{T}) = 1`.
+
+    - Both sets of points are centered around the origin.
+
+    Procrustes ([1]_, [2]_) then applies the optimal transform to the second
+    matrix (including scaling/dilation, rotations, and reflections) to minimize
+    :math:`M^{2}=\sum(data1-data2)^{2}`, or the sum of the squares of the
+    pointwise differences between the two input datasets.
+
+    This function was not designed to handle datasets with different numbers of
+    datapoints (rows).  If two data sets have different dimensionality
+    (different number of columns), simply add columns of zeros to the smaller
+    of the two.
+
+    Parameters
+    ----------
+    data1 : array_like
+        Matrix, n rows represent points in k (columns) space `data1` is the
+        reference data, after it is standardised, the data from `data2` will be
+        transformed to fit the pattern in `data1` (must have >1 unique points).
+    data2 : array_like
+        n rows of data in k space to be fit to `data1`.  Must be the  same
+        shape ``(numrows, numcols)`` as data1 (must have >1 unique points).
+
+    Returns
+    -------
+    mtx1 : array_like
+        A standardized version of `data1`.
+    mtx2 : array_like
+        The orientation of `data2` that best fits `data1`. Centered, but not
+        necessarily :math:`tr(AA^{T}) = 1`.
+    disparity : float
+        :math:`M^{2}` as defined above.
+
+    Raises
+    ------
+    ValueError
+        If the input arrays are not two-dimensional.
+        If the shape of the input arrays is different.
+        If the input arrays have zero columns or zero rows.
+
+    See Also
+    --------
+    scipy.linalg.orthogonal_procrustes
+    scipy.spatial.distance.directed_hausdorff : Another similarity test
+      for two data sets
+
+    Notes
+    -----
+    - The disparity should not depend on the order of the input matrices, but
+      the output matrices will, as only the first output matrix is guaranteed
+      to be scaled such that :math:`tr(AA^{T}) = 1`.
+
+    - Duplicate data points are generally ok, duplicating a data point will
+      increase its effect on the procrustes fit.
+
+    - The disparity scales as the number of points per input matrix.
+
+    References
+    ----------
+    .. [1] Krzanowski, W. J. (2000). "Principles of Multivariate analysis".
+    .. [2] Gower, J. C. (1975). "Generalized procrustes analysis".
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial import procrustes
+
+    The matrix ``b`` is a rotated, shifted, scaled and mirrored version of
+    ``a`` here:
+
+    >>> a = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], 'd')
+    >>> b = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], 'd')
+    >>> mtx1, mtx2, disparity = procrustes(a, b)
+    >>> round(disparity)
+    0
+
+    """
+    mtx1 = np.array(data1, dtype=np.float64, copy=True)
+    mtx2 = np.array(data2, dtype=np.float64, copy=True)
+
+    if mtx1.ndim != 2 or mtx2.ndim != 2:
+        raise ValueError("Input matrices must be two-dimensional")
+    if mtx1.shape != mtx2.shape:
+        raise ValueError("Input matrices must be of same shape")
+    if mtx1.size == 0:
+        raise ValueError("Input matrices must be >0 rows and >0 cols")
+
+    # translate all the data to the origin
+    mtx1 -= np.mean(mtx1, 0)
+    mtx2 -= np.mean(mtx2, 0)
+
+    norm1 = np.linalg.norm(mtx1)
+    norm2 = np.linalg.norm(mtx2)
+
+    if norm1 == 0 or norm2 == 0:
+        raise ValueError("Input matrices must contain >1 unique points")
+
+    # change scaling of data (in rows) such that trace(mtx*mtx') = 1
+    mtx1 /= norm1
+    mtx2 /= norm2
+
+    # transform mtx2 to minimize disparity
+    R, s = orthogonal_procrustes(mtx1, mtx2)
+    mtx2 = np.dot(mtx2, R.T) * s
+
+    # measure the dissimilarity between the two datasets
+    disparity = np.sum(np.square(mtx1 - mtx2))
+
+    return mtx1, mtx2, disparity
+
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_qhull.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_qhull.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..3285e49cdcab0f25b4438bab3a53bb1923064cd4
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_qhull.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_qhull.pyi b/python_embeded/Lib/site-packages/scipy/spatial/_qhull.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..633cd4812057b9d088456d9900fd208260ccd1a2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_qhull.pyi
@@ -0,0 +1,213 @@
+'''
+Static type checking stub file for scipy/spatial/qhull.pyx
+'''
+
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+from typing_extensions import final
+
+class QhullError(RuntimeError):
+    ...
+    
+@final
+class _Qhull:
+    # Read-only cython attribute that behaves, more or less, like a property
+    @property
+    def ndim(self) -> int: ...
+    mode_option: bytes
+    options: bytes
+    furthest_site: bool
+
+    def __init__(
+        self,
+        mode_option: bytes,
+        points: NDArray[np.float64],
+        options: None | bytes = ...,
+        required_options: None | bytes = ...,
+        furthest_site: bool = ...,
+        incremental: bool = ...,
+        interior_point: None | NDArray[np.float64] = ...,
+    ) -> None: ...
+    def check_active(self) -> None: ...
+    def close(self) -> None: ...
+    def get_points(self) -> NDArray[np.float64]: ...
+    def add_points(
+        self,
+        points: ArrayLike,
+        interior_point: ArrayLike = ...
+    ) -> None: ...
+    def get_paraboloid_shift_scale(self) -> tuple[float, float]: ...
+    def volume_area(self) -> tuple[float, float]: ...
+    def triangulate(self) -> None: ...
+    def get_simplex_facet_array(self) -> tuple[
+        NDArray[np.intc],
+        NDArray[np.intc],
+        NDArray[np.float64],
+        NDArray[np.intc],
+        NDArray[np.intc],
+    ]: ...
+    def get_hull_points(self) -> NDArray[np.float64]: ...
+    def get_hull_facets(self) -> tuple[
+        list[list[int]],
+        NDArray[np.float64],
+    ]: ...
+    def get_voronoi_diagram(self) -> tuple[
+        NDArray[np.float64],
+        NDArray[np.intc],
+        list[list[int]],
+        list[list[int]],
+        NDArray[np.intp],
+    ]: ...
+    def get_extremes_2d(self) -> NDArray[np.intc]: ...
+
+def _get_barycentric_transforms(
+    points: NDArray[np.float64],
+    simplices: NDArray[np.intc],
+    eps: float
+) -> NDArray[np.float64]: ...
+
+class _QhullUser:
+    ndim: int
+    npoints: int
+    min_bound: NDArray[np.float64]
+    max_bound: NDArray[np.float64]
+
+    def __init__(self, qhull: _Qhull, incremental: bool = ...) -> None: ...
+    def close(self) -> None: ...
+    def _update(self, qhull: _Qhull) -> None: ...
+    def _add_points(
+        self,
+        points: ArrayLike,
+        restart: bool = ...,
+        interior_point: ArrayLike = ...
+    ) -> None: ...
+
+class Delaunay(_QhullUser):
+    furthest_site: bool
+    paraboloid_scale: float
+    paraboloid_shift: float
+    simplices: NDArray[np.intc]
+    neighbors: NDArray[np.intc]
+    equations: NDArray[np.float64]
+    coplanar: NDArray[np.intc]
+    good: NDArray[np.intc]
+    nsimplex: int
+    vertices: NDArray[np.intc]
+
+    def __init__(
+        self,
+        points: ArrayLike,
+        furthest_site: bool = ...,
+        incremental: bool = ...,
+        qhull_options: None | str = ...
+    ) -> None: ...
+    def _update(self, qhull: _Qhull) -> None: ...
+    def add_points(
+        self,
+        points: ArrayLike,
+        restart: bool = ...
+    ) -> None: ...
+    @property
+    def points(self) -> NDArray[np.float64]: ...
+    @property
+    def transform(self) -> NDArray[np.float64]: ...
+    @property
+    def vertex_to_simplex(self) -> NDArray[np.intc]: ...
+    @property
+    def vertex_neighbor_vertices(self) -> tuple[
+        NDArray[np.intc],
+        NDArray[np.intc],
+    ]: ...
+    @property
+    def convex_hull(self) -> NDArray[np.intc]: ...
+    def find_simplex(
+        self,
+        xi: ArrayLike,
+        bruteforce: bool = ...,
+        tol: float = ...
+    ) -> NDArray[np.intc]: ...
+    def plane_distance(self, xi: ArrayLike) -> NDArray[np.float64]: ...
+    def lift_points(self, x: ArrayLike) -> NDArray[np.float64]: ...
+
+def tsearch(tri: Delaunay, xi: ArrayLike) -> NDArray[np.intc]: ...
+def _copy_docstr(dst: object, src: object) -> None: ...
+
+class ConvexHull(_QhullUser):
+    simplices: NDArray[np.intc]
+    neighbors: NDArray[np.intc]
+    equations: NDArray[np.float64]
+    coplanar: NDArray[np.intc]
+    good: None | NDArray[np.bool_]
+    volume: float
+    area: float
+    nsimplex: int
+
+    def __init__(
+        self,
+        points: ArrayLike,
+        incremental: bool = ...,
+        qhull_options: None | str = ...
+    ) -> None: ...
+    def _update(self, qhull: _Qhull) -> None: ...
+    def add_points(self, points: ArrayLike,
+                   restart: bool = ...) -> None: ...
+    @property
+    def points(self) -> NDArray[np.float64]: ...
+    @property
+    def vertices(self) -> NDArray[np.intc]: ...
+
+class Voronoi(_QhullUser):
+    vertices: NDArray[np.float64]
+    ridge_points: NDArray[np.intc]
+    ridge_vertices: list[list[int]]
+    regions: list[list[int]]
+    point_region: NDArray[np.intp]
+    furthest_site: bool
+
+    def __init__(
+        self,
+        points: ArrayLike,
+        furthest_site: bool = ...,
+        incremental: bool = ...,
+        qhull_options: None | str = ...
+    ) -> None: ...
+    def _update(self, qhull: _Qhull) -> None: ...
+    def add_points(
+        self,
+        points: ArrayLike,
+        restart: bool = ...
+    ) -> None: ...
+    @property
+    def points(self) -> NDArray[np.float64]: ...
+    @property
+    def ridge_dict(self) -> dict[tuple[int, int], list[int]]: ...
+
+class HalfspaceIntersection(_QhullUser):
+    interior_point: NDArray[np.float64]
+    dual_facets: list[list[int]]
+    dual_equations: NDArray[np.float64]
+    dual_points: NDArray[np.float64]
+    dual_volume: float
+    dual_area: float
+    intersections: NDArray[np.float64]
+    ndim: int
+    nineq: int
+
+    def __init__(
+        self,
+        halfspaces: ArrayLike,
+        interior_point: ArrayLike,
+        incremental: bool = ...,
+        qhull_options: None | str = ...
+    ) -> None: ...
+    def _update(self, qhull: _Qhull) -> None: ...
+    def add_halfspaces(
+        self,
+        halfspaces: ArrayLike,
+        restart: bool = ...
+    ) -> None: ...
+    @property
+    def halfspaces(self) -> NDArray[np.float64]: ...
+    @property
+    def dual_vertices(self) -> NDArray[np.integer]: ...
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_spherical_voronoi.py b/python_embeded/Lib/site-packages/scipy/spatial/_spherical_voronoi.py
new file mode 100644
index 0000000000000000000000000000000000000000..239360966b7f9e3cc9489942ad9eb3dc5acc9b63
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_spherical_voronoi.py
@@ -0,0 +1,341 @@
+"""
+Spherical Voronoi Code
+
+.. versionadded:: 0.18.0
+
+"""
+#
+# Copyright (C)  Tyler Reddy, Ross Hemsley, Edd Edmondson,
+#                Nikolai Nowaczyk, Joe Pitt-Francis, 2015.
+#
+# Distributed under the same BSD license as SciPy.
+#
+
+import numpy as np
+import scipy
+from . import _voronoi
+from scipy.spatial import cKDTree  # type: ignore[attr-defined]
+
+__all__ = ['SphericalVoronoi']
+
+
+def calculate_solid_angles(R):
+    """Calculates the solid angles of plane triangles. Implements the method of
+    Van Oosterom and Strackee [VanOosterom]_ with some modifications. Assumes
+    that input points have unit norm."""
+    # Original method uses a triple product `R1 . (R2 x R3)` for the numerator.
+    # This is equal to the determinant of the matrix [R1 R2 R3], which can be
+    # computed with better stability.
+    numerator = np.linalg.det(R)
+    denominator = 1 + (np.einsum('ij,ij->i', R[:, 0], R[:, 1]) +
+                       np.einsum('ij,ij->i', R[:, 1], R[:, 2]) +
+                       np.einsum('ij,ij->i', R[:, 2], R[:, 0]))
+    return np.abs(2 * np.arctan2(numerator, denominator))
+
+
+class SphericalVoronoi:
+    """ Voronoi diagrams on the surface of a sphere.
+
+    .. versionadded:: 0.18.0
+
+    Parameters
+    ----------
+    points : ndarray of floats, shape (npoints, ndim)
+        Coordinates of points from which to construct a spherical
+        Voronoi diagram.
+    radius : float, optional
+        Radius of the sphere (Default: 1)
+    center : ndarray of floats, shape (ndim,)
+        Center of sphere (Default: origin)
+    threshold : float
+        Threshold for detecting duplicate points and
+        mismatches between points and sphere parameters.
+        (Default: 1e-06)
+
+    Attributes
+    ----------
+    points : double array of shape (npoints, ndim)
+        the points in `ndim` dimensions to generate the Voronoi diagram from
+    radius : double
+        radius of the sphere
+    center : double array of shape (ndim,)
+        center of the sphere
+    vertices : double array of shape (nvertices, ndim)
+        Voronoi vertices corresponding to points
+    regions : list of list of integers of shape (npoints, _ )
+        the n-th entry is a list consisting of the indices
+        of the vertices belonging to the n-th point in points
+
+    Methods
+    -------
+    calculate_areas
+        Calculates the areas of the Voronoi regions. For 2D point sets, the
+        regions are circular arcs. The sum of the areas is ``2 * pi * radius``.
+        For 3D point sets, the regions are spherical polygons. The sum of the
+        areas is ``4 * pi * radius**2``.
+
+    Raises
+    ------
+    ValueError
+        If there are duplicates in `points`.
+        If the provided `radius` is not consistent with `points`.
+
+    Notes
+    -----
+    The spherical Voronoi diagram algorithm proceeds as follows. The Convex
+    Hull of the input points (generators) is calculated, and is equivalent to
+    their Delaunay triangulation on the surface of the sphere [Caroli]_.
+    The Convex Hull neighbour information is then used to
+    order the Voronoi region vertices around each generator. The latter
+    approach is substantially less sensitive to floating point issues than
+    angle-based methods of Voronoi region vertex sorting.
+
+    Empirical assessment of spherical Voronoi algorithm performance suggests
+    quadratic time complexity (loglinear is optimal, but algorithms are more
+    challenging to implement).
+
+    References
+    ----------
+    .. [Caroli] Caroli et al. Robust and Efficient Delaunay triangulations of
+                points on or close to a sphere. Research Report RR-7004, 2009.
+
+    .. [VanOosterom] Van Oosterom and Strackee. The solid angle of a plane
+                     triangle. IEEE Transactions on Biomedical Engineering,
+                     2, 1983, pp 125--126.
+
+    See Also
+    --------
+    Voronoi : Conventional Voronoi diagrams in N dimensions.
+
+    Examples
+    --------
+    Do some imports and take some points on a cube:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.spatial import SphericalVoronoi, geometric_slerp
+    >>> from mpl_toolkits.mplot3d import proj3d
+    >>> # set input data
+    >>> points = np.array([[0, 0, 1], [0, 0, -1], [1, 0, 0],
+    ...                    [0, 1, 0], [0, -1, 0], [-1, 0, 0], ])
+
+    Calculate the spherical Voronoi diagram:
+
+    >>> radius = 1
+    >>> center = np.array([0, 0, 0])
+    >>> sv = SphericalVoronoi(points, radius, center)
+
+    Generate plot:
+
+    >>> # sort vertices (optional, helpful for plotting)
+    >>> sv.sort_vertices_of_regions()
+    >>> t_vals = np.linspace(0, 1, 2000)
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111, projection='3d')
+    >>> # plot the unit sphere for reference (optional)
+    >>> u = np.linspace(0, 2 * np.pi, 100)
+    >>> v = np.linspace(0, np.pi, 100)
+    >>> x = np.outer(np.cos(u), np.sin(v))
+    >>> y = np.outer(np.sin(u), np.sin(v))
+    >>> z = np.outer(np.ones(np.size(u)), np.cos(v))
+    >>> ax.plot_surface(x, y, z, color='y', alpha=0.1)
+    >>> # plot generator points
+    >>> ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b')
+    >>> # plot Voronoi vertices
+    >>> ax.scatter(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2],
+    ...                    c='g')
+    >>> # indicate Voronoi regions (as Euclidean polygons)
+    >>> for region in sv.regions:
+    ...    n = len(region)
+    ...    for i in range(n):
+    ...        start = sv.vertices[region][i]
+    ...        end = sv.vertices[region][(i + 1) % n]
+    ...        result = geometric_slerp(start, end, t_vals)
+    ...        ax.plot(result[..., 0],
+    ...                result[..., 1],
+    ...                result[..., 2],
+    ...                c='k')
+    >>> ax.azim = 10
+    >>> ax.elev = 40
+    >>> _ = ax.set_xticks([])
+    >>> _ = ax.set_yticks([])
+    >>> _ = ax.set_zticks([])
+    >>> fig.set_size_inches(4, 4)
+    >>> plt.show()
+
+    """
+    def __init__(self, points, radius=1, center=None, threshold=1e-06):
+
+        if radius is None:
+            raise ValueError('`radius` is `None`. '
+                             'Please provide a floating point number '
+                             '(i.e. `radius=1`).')
+
+        self.radius = float(radius)
+        self.points = np.array(points).astype(np.float64)
+        self._dim = self.points.shape[1]
+        if center is None:
+            self.center = np.zeros(self._dim)
+        else:
+            self.center = np.array(center, dtype=float)
+
+        # test degenerate input
+        self._rank = np.linalg.matrix_rank(self.points - self.points[0],
+                                           tol=threshold * self.radius)
+        if self._rank < self._dim:
+            raise ValueError(f"Rank of input points must be at least {self._dim}")
+
+        if cKDTree(self.points).query_pairs(threshold * self.radius):
+            raise ValueError("Duplicate generators present.")
+
+        radii = np.linalg.norm(self.points - self.center, axis=1)
+        max_discrepancy = np.abs(radii - self.radius).max()
+        if max_discrepancy >= threshold * self.radius:
+            raise ValueError("Radius inconsistent with generators.")
+
+        self._calc_vertices_regions()
+
+    def _calc_vertices_regions(self):
+        """
+        Calculates the Voronoi vertices and regions of the generators stored
+        in self.points. The vertices will be stored in self.vertices and the
+        regions in self.regions.
+
+        This algorithm was discussed at PyData London 2015 by
+        Tyler Reddy, Ross Hemsley and Nikolai Nowaczyk
+        """
+        # get Convex Hull
+        conv = scipy.spatial.ConvexHull(self.points)
+        # get circumcenters of Convex Hull triangles from facet equations
+        # for 3D input circumcenters will have shape: (2N-4, 3)
+        self.vertices = self.radius * conv.equations[:, :-1] + self.center
+        self._simplices = conv.simplices
+        # calculate regions from triangulation
+        # for 3D input simplex_indices will have shape: (2N-4,)
+        simplex_indices = np.arange(len(self._simplices))
+        # for 3D input tri_indices will have shape: (6N-12,)
+        tri_indices = np.column_stack([simplex_indices] * self._dim).ravel()
+        # for 3D input point_indices will have shape: (6N-12,)
+        point_indices = self._simplices.ravel()
+        # for 3D input indices will have shape: (6N-12,)
+        indices = np.argsort(point_indices, kind='mergesort')
+        # for 3D input flattened_groups will have shape: (6N-12,)
+        flattened_groups = tri_indices[indices].astype(np.intp)
+        # intervals will have shape: (N+1,)
+        intervals = np.cumsum(np.bincount(point_indices + 1))
+        # split flattened groups to get nested list of unsorted regions
+        groups = [list(flattened_groups[intervals[i]:intervals[i + 1]])
+                  for i in range(len(intervals) - 1)]
+        self.regions = groups
+
+    def sort_vertices_of_regions(self):
+        """Sort indices of the vertices to be (counter-)clockwise ordered.
+
+        Raises
+        ------
+        TypeError
+            If the points are not three-dimensional.
+
+        Notes
+        -----
+        For each region in regions, it sorts the indices of the Voronoi
+        vertices such that the resulting points are in a clockwise or
+        counterclockwise order around the generator point.
+
+        This is done as follows: Recall that the n-th region in regions
+        surrounds the n-th generator in points and that the k-th
+        Voronoi vertex in vertices is the circumcenter of the k-th triangle
+        in self._simplices.  For each region n, we choose the first triangle
+        (=Voronoi vertex) in self._simplices and a vertex of that triangle
+        not equal to the center n. These determine a unique neighbor of that
+        triangle, which is then chosen as the second triangle. The second
+        triangle will have a unique vertex not equal to the current vertex or
+        the center. This determines a unique neighbor of the second triangle,
+        which is then chosen as the third triangle and so forth. We proceed
+        through all the triangles (=Voronoi vertices) belonging to the
+        generator in points and obtain a sorted version of the vertices
+        of its surrounding region.
+        """
+        if self._dim != 3:
+            raise TypeError("Only supported for three-dimensional point sets")
+        _voronoi.sort_vertices_of_regions(self._simplices, self.regions)
+
+    def _calculate_areas_3d(self):
+        self.sort_vertices_of_regions()
+        sizes = [len(region) for region in self.regions]
+        csizes = np.cumsum(sizes)
+        num_regions = csizes[-1]
+
+        # We create a set of triangles consisting of one point and two Voronoi
+        # vertices. The vertices of each triangle are adjacent in the sorted
+        # regions list.
+        point_indices = [i for i, size in enumerate(sizes)
+                         for j in range(size)]
+
+        nbrs1 = np.array([r for region in self.regions for r in region])
+
+        # The calculation of nbrs2 is a vectorized version of:
+        # np.array([r for region in self.regions for r in np.roll(region, 1)])
+        nbrs2 = np.roll(nbrs1, 1)
+        indices = np.roll(csizes, 1)
+        indices[0] = 0
+        nbrs2[indices] = nbrs1[csizes - 1]
+
+        # Normalize points and vertices.
+        pnormalized = (self.points - self.center) / self.radius
+        vnormalized = (self.vertices - self.center) / self.radius
+
+        # Create the complete set of triangles and calculate their solid angles
+        triangles = np.hstack([pnormalized[point_indices],
+                               vnormalized[nbrs1],
+                               vnormalized[nbrs2]
+                               ]).reshape((num_regions, 3, 3))
+        triangle_solid_angles = calculate_solid_angles(triangles)
+
+        # Sum the solid angles of the triangles in each region
+        solid_angles = np.cumsum(triangle_solid_angles)[csizes - 1]
+        solid_angles[1:] -= solid_angles[:-1]
+
+        # Get polygon areas using A = omega * r**2
+        return solid_angles * self.radius**2
+
+    def _calculate_areas_2d(self):
+        # Find start and end points of arcs
+        arcs = self.points[self._simplices] - self.center
+
+        # Calculate the angle subtended by arcs
+        d = np.sum((arcs[:, 1] - arcs[:, 0]) ** 2, axis=1)
+        theta = np.arccos(1 - (d / (2 * (self.radius ** 2))))
+
+        # Get areas using A = r * theta
+        areas = self.radius * theta
+
+        # Correct arcs which go the wrong way (single-hemisphere inputs)
+        signs = np.sign(np.einsum('ij,ij->i', arcs[:, 0],
+                                              self.vertices - self.center))
+        indices = np.where(signs < 0)
+        areas[indices] = 2 * np.pi * self.radius - areas[indices]
+        return areas
+
+    def calculate_areas(self):
+        """Calculates the areas of the Voronoi regions.
+
+        For 2D point sets, the regions are circular arcs. The sum of the areas
+        is ``2 * pi * radius``.
+
+        For 3D point sets, the regions are spherical polygons. The sum of the
+        areas is ``4 * pi * radius**2``.
+
+        .. versionadded:: 1.5.0
+
+        Returns
+        -------
+        areas : double array of shape (npoints,)
+            The areas of the Voronoi regions.
+        """
+        if self._dim == 2:
+            return self._calculate_areas_2d()
+        elif self._dim == 3:
+            return self._calculate_areas_3d()
+        else:
+            raise TypeError("Only supported for 2D and 3D point sets")
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c2af99751fc55a5c3e026f755c813f5daf649562
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.pyi b/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..eb35bb4bfe0f806e1cda984d513563fd84aebda3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/_voronoi.pyi
@@ -0,0 +1,4 @@
+
+import numpy as np
+
+def sort_vertices_of_regions(simplices: np.ndarray, regions: list[list[int]]) -> None: ...  # noqa: E501
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/ckdtree.py b/python_embeded/Lib/site-packages/scipy/spatial/ckdtree.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cc496cbf10e71a5aa2e7c422c1f3b181075e5cb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/ckdtree.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.spatial` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["cKDTree"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="spatial", module="ckdtree",
+                                   private_modules=["_ckdtree"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/distance.py b/python_embeded/Lib/site-packages/scipy/spatial/distance.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f1fd87fec3ef32c14491e6cad3c9ada21faaf36
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/distance.py
@@ -0,0 +1,3140 @@
+"""
+Distance computations (:mod:`scipy.spatial.distance`)
+=====================================================
+
+.. sectionauthor:: Damian Eads
+
+Function reference
+------------------
+
+Distance matrix computation from a collection of raw observation vectors
+stored in a rectangular array.
+
+.. autosummary::
+   :toctree: generated/
+
+   pdist   -- pairwise distances between observation vectors.
+   cdist   -- distances between two collections of observation vectors
+   squareform -- convert distance matrix to a condensed one and vice versa
+   directed_hausdorff -- directed Hausdorff distance between arrays
+
+Predicates for checking the validity of distance matrices, both
+condensed and redundant. Also contained in this module are functions
+for computing the number of observations in a distance matrix.
+
+.. autosummary::
+   :toctree: generated/
+
+   is_valid_dm -- checks for a valid distance matrix
+   is_valid_y  -- checks for a valid condensed distance matrix
+   num_obs_dm  -- # of observations in a distance matrix
+   num_obs_y   -- # of observations in a condensed distance matrix
+
+Distance functions between two numeric vectors ``u`` and ``v``. Computing
+distances over a large collection of vectors is inefficient for these
+functions. Use ``pdist`` for this purpose.
+
+.. autosummary::
+   :toctree: generated/
+
+   braycurtis       -- the Bray-Curtis distance.
+   canberra         -- the Canberra distance.
+   chebyshev        -- the Chebyshev distance.
+   cityblock        -- the Manhattan distance.
+   correlation      -- the Correlation distance.
+   cosine           -- the Cosine distance.
+   euclidean        -- the Euclidean distance.
+   jensenshannon    -- the Jensen-Shannon distance.
+   mahalanobis      -- the Mahalanobis distance.
+   minkowski        -- the Minkowski distance.
+   seuclidean       -- the normalized Euclidean distance.
+   sqeuclidean      -- the squared Euclidean distance.
+
+Distance functions between two boolean vectors (representing sets) ``u`` and
+``v``.  As in the case of numerical vectors, ``pdist`` is more efficient for
+computing the distances between all pairs.
+
+.. autosummary::
+   :toctree: generated/
+
+   dice             -- the Dice dissimilarity.
+   hamming          -- the Hamming distance.
+   jaccard          -- the Jaccard distance.
+   kulczynski1      -- the Kulczynski 1 distance.
+   rogerstanimoto   -- the Rogers-Tanimoto dissimilarity.
+   russellrao       -- the Russell-Rao dissimilarity.
+   sokalmichener    -- the Sokal-Michener dissimilarity.
+   sokalsneath      -- the Sokal-Sneath dissimilarity.
+   yule             -- the Yule dissimilarity.
+
+:func:`hamming` also operates over discrete numerical vectors.
+"""
+
+# Copyright (C) Damian Eads, 2007-2008. New BSD License.
+
+__all__ = [
+    'braycurtis',
+    'canberra',
+    'cdist',
+    'chebyshev',
+    'cityblock',
+    'correlation',
+    'cosine',
+    'dice',
+    'directed_hausdorff',
+    'euclidean',
+    'hamming',
+    'is_valid_dm',
+    'is_valid_y',
+    'jaccard',
+    'jensenshannon',
+    'kulczynski1',
+    'mahalanobis',
+    'minkowski',
+    'num_obs_dm',
+    'num_obs_y',
+    'pdist',
+    'rogerstanimoto',
+    'russellrao',
+    'seuclidean',
+    'sokalmichener',
+    'sokalsneath',
+    'sqeuclidean',
+    'squareform',
+    'yule'
+]
+
+
+import math
+import warnings
+import numpy as np
+import dataclasses
+
+from collections.abc import Callable
+from functools import partial
+from scipy._lib._util import _asarray_validated, _transition_to_rng
+from scipy._lib.deprecation import _deprecated
+
+from . import _distance_wrap
+from . import _hausdorff
+from ..linalg import norm
+from ..special import rel_entr
+
+from . import _distance_pybind
+
+
+def _copy_array_if_base_present(a):
+    """Copy the array if its base points to a parent array."""
+    if a.base is not None:
+        return a.copy()
+    return a
+
+
+def _correlation_cdist_wrap(XA, XB, dm, **kwargs):
+    XA = XA - XA.mean(axis=1, keepdims=True)
+    XB = XB - XB.mean(axis=1, keepdims=True)
+    _distance_wrap.cdist_cosine_double_wrap(XA, XB, dm, **kwargs)
+
+
+def _correlation_pdist_wrap(X, dm, **kwargs):
+    X2 = X - X.mean(axis=1, keepdims=True)
+    _distance_wrap.pdist_cosine_double_wrap(X2, dm, **kwargs)
+
+
+def _convert_to_type(X, out_type):
+    return np.ascontiguousarray(X, dtype=out_type)
+
+
+def _nbool_correspond_all(u, v, w=None):
+    if u.dtype == v.dtype == bool and w is None:
+        not_u = ~u
+        not_v = ~v
+        nff = (not_u & not_v).sum()
+        nft = (not_u & v).sum()
+        ntf = (u & not_v).sum()
+        ntt = (u & v).sum()
+    else:
+        dtype = np.result_type(int, u.dtype, v.dtype)
+        u = u.astype(dtype)
+        v = v.astype(dtype)
+        not_u = 1.0 - u
+        not_v = 1.0 - v
+        if w is not None:
+            not_u = w * not_u
+            u = w * u
+        nff = (not_u * not_v).sum()
+        nft = (not_u * v).sum()
+        ntf = (u * not_v).sum()
+        ntt = (u * v).sum()
+    return (nff, nft, ntf, ntt)
+
+
+def _nbool_correspond_ft_tf(u, v, w=None):
+    if u.dtype == v.dtype == bool and w is None:
+        not_u = ~u
+        not_v = ~v
+        nft = (not_u & v).sum()
+        ntf = (u & not_v).sum()
+    else:
+        dtype = np.result_type(int, u.dtype, v.dtype)
+        u = u.astype(dtype)
+        v = v.astype(dtype)
+        not_u = 1.0 - u
+        not_v = 1.0 - v
+        if w is not None:
+            not_u = w * not_u
+            u = w * u
+        nft = (not_u * v).sum()
+        ntf = (u * not_v).sum()
+    return (nft, ntf)
+
+
+def _validate_cdist_input(XA, XB, mA, mB, n, metric_info, **kwargs):
+    # get supported types
+    types = metric_info.types
+    # choose best type
+    typ = types[types.index(XA.dtype)] if XA.dtype in types else types[0]
+    # validate data
+    XA = _convert_to_type(XA, out_type=typ)
+    XB = _convert_to_type(XB, out_type=typ)
+
+    # validate kwargs
+    _validate_kwargs = metric_info.validator
+    if _validate_kwargs:
+        kwargs = _validate_kwargs((XA, XB), mA + mB, n, **kwargs)
+    return XA, XB, typ, kwargs
+
+
+def _validate_weight_with_size(X, m, n, **kwargs):
+    w = kwargs.pop('w', None)
+    if w is None:
+        return kwargs
+
+    if w.ndim != 1 or w.shape[0] != n:
+        raise ValueError("Weights must have same size as input vector. "
+                         f"{w.shape[0]} vs. {n}")
+
+    kwargs['w'] = _validate_weights(w)
+    return kwargs
+
+
+def _validate_hamming_kwargs(X, m, n, **kwargs):
+    w = kwargs.get('w', np.ones((n,), dtype='double'))
+
+    if w.ndim != 1 or w.shape[0] != n:
+        raise ValueError(
+            "Weights must have same size as input vector. %d vs. %d" % (w.shape[0], n)
+        )
+
+    kwargs['w'] = _validate_weights(w)
+    return kwargs
+
+
+def _validate_mahalanobis_kwargs(X, m, n, **kwargs):
+    VI = kwargs.pop('VI', None)
+    if VI is None:
+        if m <= n:
+            # There are fewer observations than the dimension of
+            # the observations.
+            raise ValueError("The number of observations (%d) is too "
+                             "small; the covariance matrix is "
+                             "singular. For observations with %d "
+                             "dimensions, at least %d observations "
+                             "are required." % (m, n, n + 1))
+        if isinstance(X, tuple):
+            X = np.vstack(X)
+        CV = np.atleast_2d(np.cov(X.astype(np.float64, copy=False).T))
+        VI = np.linalg.inv(CV).T.copy()
+    kwargs["VI"] = _convert_to_double(VI)
+    return kwargs
+
+
+def _validate_minkowski_kwargs(X, m, n, **kwargs):
+    kwargs = _validate_weight_with_size(X, m, n, **kwargs)
+    if 'p' not in kwargs:
+        kwargs['p'] = 2.
+    else:
+        if kwargs['p'] <= 0:
+            raise ValueError("p must be greater than 0")
+
+    return kwargs
+
+
+def _validate_pdist_input(X, m, n, metric_info, **kwargs):
+    # get supported types
+    types = metric_info.types
+    # choose best type
+    typ = types[types.index(X.dtype)] if X.dtype in types else types[0]
+    # validate data
+    X = _convert_to_type(X, out_type=typ)
+
+    # validate kwargs
+    _validate_kwargs = metric_info.validator
+    if _validate_kwargs:
+        kwargs = _validate_kwargs(X, m, n, **kwargs)
+    return X, typ, kwargs
+
+
+def _validate_seuclidean_kwargs(X, m, n, **kwargs):
+    V = kwargs.pop('V', None)
+    if V is None:
+        if isinstance(X, tuple):
+            X = np.vstack(X)
+        V = np.var(X.astype(np.float64, copy=False), axis=0, ddof=1)
+    else:
+        V = np.asarray(V, order='c')
+        if len(V.shape) != 1:
+            raise ValueError('Variance vector V must '
+                             'be one-dimensional.')
+        if V.shape[0] != n:
+            raise ValueError('Variance vector V must be of the same '
+                             'dimension as the vectors on which the distances '
+                             'are computed.')
+    kwargs['V'] = _convert_to_double(V)
+    return kwargs
+
+
+def _validate_vector(u, dtype=None):
+    # XXX Is order='c' really necessary?
+    u = np.asarray(u, dtype=dtype, order='c')
+    if u.ndim == 1:
+        return u
+    raise ValueError("Input vector should be 1-D.")
+
+
+def _validate_weights(w, dtype=np.float64):
+    w = _validate_vector(w, dtype=dtype)
+    if np.any(w < 0):
+        raise ValueError("Input weights should be all non-negative")
+    return w
+
+
+@_transition_to_rng('seed', position_num=2, replace_doc=False)
+def directed_hausdorff(u, v, rng=0):
+    """
+    Compute the directed Hausdorff distance between two 2-D arrays.
+
+    Distances between pairs are calculated using a Euclidean metric.
+
+    Parameters
+    ----------
+    u : (M,N) array_like
+        Input array with M points in N dimensions.
+    v : (O,N) array_like
+        Input array with O points in N dimensions.
+    rng : int or `numpy.random.Generator` or None, optional
+        Pseudorandom number generator state. Default is 0 so the
+        shuffling of `u` and `v` is reproducible.
+
+        If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used.
+
+        If this argument is passed by position or `seed` is passed by keyword,
+        legacy behavior for the argument `seed` applies:
+
+        - If `seed` is None, a new ``RandomState`` instance is used. The state is
+          initialized using data from ``/dev/urandom`` (or the Windows analogue)
+          if available or from the system clock otherwise.
+        - 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.
+
+        .. versionchanged:: 1.15.0
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to `rng`.
+            For an interim period, both keywords will continue to work, although only
+            one may be specified at a time. After the interim period, function calls
+            using the `seed` keyword will emit warnings. The behavior of both `seed`
+            and `rng` are outlined above, but only the `rng` keyword should be used in
+            new code.
+
+    Returns
+    -------
+    d : double
+        The directed Hausdorff distance between arrays `u` and `v`,
+
+    index_1 : int
+        index of point contributing to Hausdorff pair in `u`
+
+    index_2 : int
+        index of point contributing to Hausdorff pair in `v`
+
+    Raises
+    ------
+    ValueError
+        An exception is thrown if `u` and `v` do not have
+        the same number of columns.
+
+    See Also
+    --------
+    scipy.spatial.procrustes : Another similarity test for two data sets
+
+    Notes
+    -----
+    Uses the early break technique and the random sampling approach
+    described by [1]_. Although worst-case performance is ``O(m * o)``
+    (as with the brute force algorithm), this is unlikely in practice
+    as the input data would have to require the algorithm to explore
+    every single point interaction, and after the algorithm shuffles
+    the input points at that. The best case performance is O(m), which
+    is satisfied by selecting an inner loop distance that is less than
+    cmax and leads to an early break as often as possible. The authors
+    have formally shown that the average runtime is closer to O(m).
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] A. A. Taha and A. Hanbury, "An efficient algorithm for
+           calculating the exact Hausdorff distance." IEEE Transactions On
+           Pattern Analysis And Machine Intelligence, vol. 37 pp. 2153-63,
+           2015.
+
+    Examples
+    --------
+    Find the directed Hausdorff distance between two 2-D arrays of
+    coordinates:
+
+    >>> from scipy.spatial.distance import directed_hausdorff
+    >>> import numpy as np
+    >>> u = np.array([(1.0, 0.0),
+    ...               (0.0, 1.0),
+    ...               (-1.0, 0.0),
+    ...               (0.0, -1.0)])
+    >>> v = np.array([(2.0, 0.0),
+    ...               (0.0, 2.0),
+    ...               (-2.0, 0.0),
+    ...               (0.0, -4.0)])
+
+    >>> directed_hausdorff(u, v)[0]
+    2.23606797749979
+    >>> directed_hausdorff(v, u)[0]
+    3.0
+
+    Find the general (symmetric) Hausdorff distance between two 2-D
+    arrays of coordinates:
+
+    >>> max(directed_hausdorff(u, v)[0], directed_hausdorff(v, u)[0])
+    3.0
+
+    Find the indices of the points that generate the Hausdorff distance
+    (the Hausdorff pair):
+
+    >>> directed_hausdorff(v, u)[1:]
+    (3, 3)
+
+    """
+    u = np.asarray(u, dtype=np.float64, order='c')
+    v = np.asarray(v, dtype=np.float64, order='c')
+    if u.shape[1] != v.shape[1]:
+        raise ValueError('u and v need to have the same '
+                         'number of columns')
+    result = _hausdorff.directed_hausdorff(u, v, rng)
+    return result
+
+
+def minkowski(u, v, p=2, w=None):
+    """
+    Compute the Minkowski distance between two 1-D arrays.
+
+    The Minkowski distance between 1-D arrays `u` and `v`,
+    is defined as
+
+    .. math::
+
+       {\\|u-v\\|}_p = (\\sum{|u_i - v_i|^p})^{1/p}.
+
+
+       \\left(\\sum{w_i(|(u_i - v_i)|^p)}\\right)^{1/p}.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    p : scalar
+        The order of the norm of the difference :math:`{\\|u-v\\|}_p`. Note
+        that for :math:`0 < p < 1`, the triangle inequality only holds with
+        an additional multiplicative factor, i.e. it is only a quasi-metric.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    minkowski : double
+        The Minkowski distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.minkowski([1, 0, 0], [0, 1, 0], 1)
+    2.0
+    >>> distance.minkowski([1, 0, 0], [0, 1, 0], 2)
+    1.4142135623730951
+    >>> distance.minkowski([1, 0, 0], [0, 1, 0], 3)
+    1.2599210498948732
+    >>> distance.minkowski([1, 1, 0], [0, 1, 0], 1)
+    1.0
+    >>> distance.minkowski([1, 1, 0], [0, 1, 0], 2)
+    1.0
+    >>> distance.minkowski([1, 1, 0], [0, 1, 0], 3)
+    1.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if p <= 0:
+        raise ValueError("p must be greater than 0")
+    u_v = u - v
+    if w is not None:
+        w = _validate_weights(w)
+        if p == 1:
+            root_w = w
+        elif p == 2:
+            # better precision and speed
+            root_w = np.sqrt(w)
+        elif p == np.inf:
+            root_w = (w != 0)
+        else:
+            root_w = np.power(w, 1/p)
+        u_v = root_w * u_v
+    dist = norm(u_v, ord=p)
+    return dist
+
+
+def euclidean(u, v, w=None):
+    """
+    Computes the Euclidean distance between two 1-D arrays.
+
+    The Euclidean distance between 1-D arrays `u` and `v`, is defined as
+
+    .. math::
+
+       {\\|u-v\\|}_2
+
+       \\left(\\sum{(w_i |(u_i - v_i)|^2)}\\right)^{1/2}
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    euclidean : double
+        The Euclidean distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.euclidean([1, 0, 0], [0, 1, 0])
+    1.4142135623730951
+    >>> distance.euclidean([1, 1, 0], [0, 1, 0])
+    1.0
+
+    """
+    return minkowski(u, v, p=2, w=w)
+
+
+def sqeuclidean(u, v, w=None):
+    """
+    Compute the squared Euclidean distance between two 1-D arrays.
+
+    The squared Euclidean distance between `u` and `v` is defined as
+
+    .. math::
+
+       \\sum_i{w_i |u_i - v_i|^2}
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    sqeuclidean : double
+        The squared Euclidean distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.sqeuclidean([1, 0, 0], [0, 1, 0])
+    2.0
+    >>> distance.sqeuclidean([1, 1, 0], [0, 1, 0])
+    1.0
+
+    """
+    # Preserve float dtypes, but convert everything else to np.float64
+    # for stability.
+    utype, vtype = None, None
+    if not (hasattr(u, "dtype") and np.issubdtype(u.dtype, np.inexact)):
+        utype = np.float64
+    if not (hasattr(v, "dtype") and np.issubdtype(v.dtype, np.inexact)):
+        vtype = np.float64
+
+    u = _validate_vector(u, dtype=utype)
+    v = _validate_vector(v, dtype=vtype)
+    u_v = u - v
+    u_v_w = u_v  # only want weights applied once
+    if w is not None:
+        w = _validate_weights(w)
+        u_v_w = w * u_v
+    return np.dot(u_v, u_v_w)
+
+
+def correlation(u, v, w=None, centered=True):
+    """
+    Compute the correlation distance between two 1-D arrays.
+
+    The correlation distance between `u` and `v`, is
+    defined as
+
+    .. math::
+
+        1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})}
+                  {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2}
+
+    where :math:`\\bar{u}` is the mean of the elements of `u`
+    and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`.
+
+    Parameters
+    ----------
+    u : (N,) array_like of floats
+        Input array.
+
+        .. deprecated:: 1.15.0
+           Complex `u` is deprecated and will raise an error in SciPy 1.17.0
+    v : (N,) array_like of floats
+        Input array.
+
+        .. deprecated:: 1.15.0
+           Complex `v` is deprecated and will raise an error in SciPy 1.17.0
+    w : (N,) array_like of floats, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+    centered : bool, optional
+        If True, `u` and `v` will be centered. Default is True.
+
+    Returns
+    -------
+    correlation : double
+        The correlation distance between 1-D array `u` and `v`.
+
+    Examples
+    --------
+    Find the correlation between two arrays.
+
+    >>> from scipy.spatial.distance import correlation
+    >>> correlation([1, 0, 1], [1, 1, 0])
+    1.5
+
+    Using a weighting array, the correlation can be calculated as:
+
+    >>> correlation([1, 0, 1], [1, 1, 0], w=[0.9, 0.1, 0.1])
+    1.1
+
+    If centering is not needed, the correlation can be calculated as:
+
+    >>> correlation([1, 0, 1], [1, 1, 0], centered=False)
+    0.5
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if np.iscomplexobj(u) or np.iscomplexobj(v):
+        message = (
+            "Complex `u` and `v` are deprecated and will raise an error in "
+            "SciPy 1.17.0.")
+        warnings.warn(message, DeprecationWarning, stacklevel=2)
+    if w is not None:
+        w = _validate_weights(w)
+        w = w / w.sum()
+    if centered:
+        if w is not None:
+            umu = np.dot(u, w)
+            vmu = np.dot(v, w)
+        else:
+            umu = np.mean(u)
+            vmu = np.mean(v)
+        u = u - umu
+        v = v - vmu
+    if w is not None:
+        vw = v * w
+        uw = u * w
+    else:
+        vw, uw = v, u
+    uv = np.dot(u, vw)
+    uu = np.dot(u, uw)
+    vv = np.dot(v, vw)
+    dist = 1.0 - uv / math.sqrt(uu * vv)
+    # Clip the result to avoid rounding error
+    return np.clip(dist, 0.0, 2.0)
+
+
+def cosine(u, v, w=None):
+    """
+    Compute the Cosine distance between 1-D arrays.
+
+    The Cosine distance between `u` and `v`, is defined as
+
+    .. math::
+
+        1 - \\frac{u \\cdot v}
+                  {\\|u\\|_2 \\|v\\|_2}.
+
+    where :math:`u \\cdot v` is the dot product of :math:`u` and
+    :math:`v`.
+
+    Parameters
+    ----------
+    u : (N,) array_like of floats
+        Input array.
+
+        .. deprecated:: 1.15.0
+           Complex `u` is deprecated and will raise an error in SciPy 1.17.0
+    v : (N,) array_like of floats
+        Input array.
+
+        .. deprecated:: 1.15.0
+           Complex `v` is deprecated and will raise an error in SciPy 1.17.0
+    w : (N,) array_like of floats, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    cosine : double
+        The Cosine distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.cosine([1, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.cosine([100, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.cosine([1, 1, 0], [0, 1, 0])
+    0.29289321881345254
+
+    """
+    # cosine distance is also referred to as 'uncentered correlation',
+    #   or 'reflective correlation'
+    return correlation(u, v, w=w, centered=False)
+
+
+def hamming(u, v, w=None):
+    """
+    Compute the Hamming distance between two 1-D arrays.
+
+    The Hamming distance between 1-D arrays `u` and `v`, is simply the
+    proportion of disagreeing components in `u` and `v`. If `u` and `v` are
+    boolean vectors, the Hamming distance is
+
+    .. math::
+
+       \\frac{c_{01} + c_{10}}{n}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n`.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    hamming : double
+        The Hamming distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.hamming([1, 0, 0], [0, 1, 0])
+    0.66666666666666663
+    >>> distance.hamming([1, 0, 0], [1, 1, 0])
+    0.33333333333333331
+    >>> distance.hamming([1, 0, 0], [2, 0, 0])
+    0.33333333333333331
+    >>> distance.hamming([1, 0, 0], [3, 0, 0])
+    0.33333333333333331
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if u.shape != v.shape:
+        raise ValueError('The 1d arrays must have equal lengths.')
+    u_ne_v = u != v
+    if w is not None:
+        w = _validate_weights(w)
+        if w.shape != u.shape:
+            raise ValueError("'w' should have the same length as 'u' and 'v'.")
+        w = w / w.sum()
+        return np.dot(u_ne_v, w)
+    return np.mean(u_ne_v)
+
+
+def jaccard(u, v, w=None):
+    r"""
+    Compute the Jaccard dissimilarity between two boolean vectors.
+
+    Given boolean vectors :math:`u \equiv (u_1, \cdots, u_n)`
+    and :math:`v \equiv (v_1, \cdots, v_n)` that are not both zero,
+    their *Jaccard dissimilarity* is defined as ([1]_, p. 26)
+
+    .. math::
+
+       d_\textrm{jaccard}(u, v) := \frac{c_{10} + c_{01}}
+                                        {c_{11} + c_{10} + c_{01}}
+
+    where
+
+    .. math::
+
+       c_{ij} := \sum_{1 \le k \le n, u_k=i, v_k=j} 1
+
+    for :math:`i, j \in \{ 0, 1\}`.  If :math:`u` and :math:`v` are both zero,
+    their Jaccard dissimilarity is defined to be zero. [2]_
+
+    If a (non-negative) weight vector :math:`w \equiv (w_1, \cdots, w_n)`
+    is supplied, the *weighted Jaccard dissimilarity* is defined similarly
+    but with :math:`c_{ij}` replaced by
+
+    .. math::
+
+       \tilde{c}_{ij} := \sum_{1 \le k \le n, u_k=i, v_k=j} w_k
+
+    Parameters
+    ----------
+    u : (N,) array_like of bools
+        Input vector.
+    v : (N,) array_like of bools
+        Input vector.
+    w : (N,) array_like of floats, optional
+        Weights for each pair of :math:`(u_k, v_k)`.  Default is ``None``,
+        which gives each pair a weight of ``1.0``.
+
+    Returns
+    -------
+    jaccard : float
+        The Jaccard dissimilarity between vectors `u` and `v`, optionally
+        weighted by `w` if supplied.
+
+    Notes
+    -----
+    The Jaccard dissimilarity satisfies the triangle inequality and is
+    qualified as a metric. [2]_
+
+    The *Jaccard index*, or *Jaccard similarity coefficient*, is equal to
+    one minus the Jaccard dissimilarity. [3]_
+
+    The dissimilarity between general (finite) sets may be computed by
+    encoding them as boolean vectors and computing the dissimilarity
+    between the encoded vectors.
+    For example, subsets :math:`A,B` of :math:`\{ 1, 2, ..., n \}` may be
+    encoded into boolean vectors :math:`u, v` by setting
+    :math:`u_k := 1_{k \in A}`, :math:`v_k := 1_{k \in B}`
+    for :math:`k = 1,2,\cdots,n`.
+
+    .. versionchanged:: 1.2.0
+       Previously, if all (positively weighted) elements in `u` and `v` are
+       zero, the function would return ``nan``.  This was changed to return
+       ``0`` instead.
+
+    .. versionchanged:: 1.15.0
+       Non-0/1 numeric input used to produce an ad hoc result.  Since 1.15.0,
+       numeric input is converted to Boolean before computation.
+
+    References
+    ----------
+    .. [1] Kaufman, L. and Rousseeuw, P. J.  (1990).  "Finding Groups in Data:
+           An Introduction to Cluster Analysis."  John Wiley & Sons, Inc.
+    .. [2] Kosub, S.  (2019).  "A note on the triangle inequality for the
+           Jaccard distance."  *Pattern Recognition Letters*, 120:36-38.
+    .. [3] https://en.wikipedia.org/wiki/Jaccard_index
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+
+    Non-zero vectors with no matching 1s have dissimilarity of 1.0:
+
+    >>> distance.jaccard([1, 0, 0], [0, 1, 0])
+    1.0
+
+    Vectors with some matching 1s have dissimilarity less than 1.0:
+
+    >>> distance.jaccard([1, 0, 0, 0], [1, 1, 1, 0])
+    0.6666666666666666
+
+    Identical vectors, including zero vectors, have dissimilarity of 0.0:
+
+    >>> distance.jaccard([1, 0, 0], [1, 0, 0])
+    0.0
+    >>> distance.jaccard([0, 0, 0], [0, 0, 0])
+    0.0
+
+    The following example computes the dissimilarity from a confusion matrix
+    directly by setting the weight vector to the frequency of True Positive,
+    False Negative, False Positive, and True Negative:
+
+    >>> distance.jaccard([1, 1, 0, 0], [1, 0, 1, 0], [31, 41, 59, 26])
+    0.7633587786259542  # (41+59)/(31+41+59)
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+
+    unequal = np.bitwise_xor(u != 0, v != 0)
+    nonzero = np.bitwise_or(u != 0, v != 0)
+    if w is not None:
+        w = _validate_weights(w)
+        unequal = w * unequal
+        nonzero = w * nonzero
+    a = np.float64(unequal.sum())
+    b = np.float64(nonzero.sum())
+    return (a / b) if b != 0 else np.float64(0)
+
+
+_deprecated_kulczynski1 = _deprecated(
+    "The kulczynski1 metric is deprecated since SciPy 1.15.0 and will be "
+    "removed in SciPy 1.17.0.  Replace usage of 'kulczynski1(u, v)' with "
+    "'1/jaccard(u, v) - 1'."
+)
+
+
+@_deprecated_kulczynski1
+def kulczynski1(u, v, *, w=None):
+    """
+    Compute the Kulczynski 1 dissimilarity between two boolean 1-D arrays.
+
+    .. deprecated:: 1.15.0
+       This function is deprecated and will be removed in SciPy 1.17.0.
+       Replace usage of ``kulczynski1(u, v)`` with ``1/jaccard(u, v) - 1``.
+
+    The Kulczynski 1 dissimilarity between two boolean 1-D arrays `u` and `v`
+    of length ``n``, is defined as
+
+    .. math::
+
+         \\frac{c_{11}}
+              {c_{01} + c_{10}}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k \\in {0, 1, ..., n-1}`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    kulczynski1 : float
+        The Kulczynski 1 distance between vectors `u` and `v`.
+
+    Notes
+    -----
+    This measure has a minimum value of 0 and no upper limit.
+    It is un-defined when there are no non-matches.
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] Kulczynski S. et al. Bulletin
+           International de l'Academie Polonaise des Sciences
+           et des Lettres, Classe des Sciences Mathematiques
+           et Naturelles, Serie B (Sciences Naturelles). 1927;
+           Supplement II: 57-203.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.kulczynski1([1, 0, 0], [0, 1, 0])
+    0.0
+    >>> distance.kulczynski1([True, False, False], [True, True, False])
+    1.0
+    >>> distance.kulczynski1([True, False, False], [True])
+    0.5
+    >>> distance.kulczynski1([1, 0, 0], [3, 1, 0])
+    -3.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+    (_, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w)
+
+    return ntt / (ntf + nft)
+
+
+def seuclidean(u, v, V):
+    """
+    Return the standardized Euclidean distance between two 1-D arrays.
+
+    The standardized Euclidean distance between two n-vectors `u` and `v` is
+
+    .. math::
+
+       \\sqrt{\\sum\\limits_i \\frac{1}{V_i} \\left(u_i-v_i \\right)^2}
+
+    ``V`` is the variance vector; ``V[I]`` is the variance computed over all the i-th
+    components of the points. If not passed, it is automatically computed.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    V : (N,) array_like
+        `V` is an 1-D array of component variances. It is usually computed
+        among a larger collection of vectors.
+
+    Returns
+    -------
+    seuclidean : double
+        The standardized Euclidean distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [0.1, 0.1, 0.1])
+    4.4721359549995796
+    >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [1, 0.1, 0.1])
+    3.3166247903553998
+    >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [10, 0.1, 0.1])
+    3.1780497164141406
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    V = _validate_vector(V, dtype=np.float64)
+    if V.shape[0] != u.shape[0] or u.shape[0] != v.shape[0]:
+        raise TypeError('V must be a 1-D array of the same dimension '
+                        'as u and v.')
+    return euclidean(u, v, w=1/V)
+
+
+def cityblock(u, v, w=None):
+    """
+    Compute the City Block (Manhattan) distance.
+
+    Computes the Manhattan distance between two 1-D arrays `u` and `v`,
+    which is defined as
+
+    .. math::
+
+       \\sum_i {\\left| u_i - v_i \\right|}.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    cityblock : double
+        The City Block (Manhattan) distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.cityblock([1, 0, 0], [0, 1, 0])
+    2
+    >>> distance.cityblock([1, 0, 0], [0, 2, 0])
+    3
+    >>> distance.cityblock([1, 0, 0], [1, 1, 0])
+    1
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    l1_diff = abs(u - v)
+    if w is not None:
+        w = _validate_weights(w)
+        l1_diff = w * l1_diff
+    return l1_diff.sum()
+
+
+def mahalanobis(u, v, VI):
+    """
+    Compute the Mahalanobis distance between two 1-D arrays.
+
+    The Mahalanobis distance between 1-D arrays `u` and `v`, is defined as
+
+    .. math::
+
+       \\sqrt{ (u-v) V^{-1} (u-v)^T }
+
+    where ``V`` is the covariance matrix.  Note that the argument `VI`
+    is the inverse of ``V``.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    VI : array_like
+        The inverse of the covariance matrix.
+
+    Returns
+    -------
+    mahalanobis : double
+        The Mahalanobis distance between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
+    >>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
+    1.0
+    >>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv)
+    1.0
+    >>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv)
+    1.7320508075688772
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    VI = np.atleast_2d(VI)
+    delta = u - v
+    m = np.dot(np.dot(delta, VI), delta)
+    return np.sqrt(m)
+
+
+def chebyshev(u, v, w=None):
+    r"""
+    Compute the Chebyshev distance.
+
+    The *Chebyshev distance* between real vectors
+    :math:`u \equiv (u_1, \cdots, u_n)` and
+    :math:`v \equiv (v_1, \cdots, v_n)` is defined as [1]_
+
+    .. math::
+
+       d_\textrm{chebyshev}(u,v) := \max_{1 \le i \le n} |u_i-v_i|
+
+    If a (non-negative) weight vector :math:`w \equiv (w_1, \cdots, w_n)`
+    is supplied, the *weighted Chebyshev distance* is defined to be the
+    weighted Minkowski distance of infinite order; that is,
+
+    .. math::
+
+       \begin{align}
+       d_\textrm{chebyshev}(u,v;w) &:= \lim_{p\rightarrow \infty}
+          \left( \sum_{i=1}^n w_i | u_i-v_i |^p \right)^\frac{1}{p} \\
+        &= \max_{1 \le i \le n} 1_{w_i > 0} | u_i - v_i |
+       \end{align}
+
+    Parameters
+    ----------
+    u : (N,) array_like of floats
+        Input vector.
+    v : (N,) array_like of floats
+        Input vector.
+    w : (N,) array_like of floats, optional
+        Weight vector.  Default is ``None``, which gives all pairs
+        :math:`(u_i, v_i)` the same weight ``1.0``.
+
+    Returns
+    -------
+    chebyshev : float
+        The Chebyshev distance between vectors `u` and `v`, optionally weighted
+        by `w`.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Chebyshev_distance
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.chebyshev([1, 0, 0], [0, 1, 0])
+    1
+    >>> distance.chebyshev([1, 1, 0], [0, 1, 0])
+    1
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+        return max((w > 0) * abs(u - v))
+    return max(abs(u - v))
+
+
+def braycurtis(u, v, w=None):
+    """
+    Compute the Bray-Curtis distance between two 1-D arrays.
+
+    Bray-Curtis distance is defined as
+
+    .. math::
+
+       \\sum{|u_i-v_i|} / \\sum{|u_i+v_i|}
+
+    The Bray-Curtis distance is in the range [0, 1] if all coordinates are
+    positive, and is undefined if the inputs are of length zero.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    braycurtis : double
+        The Bray-Curtis distance between 1-D arrays `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.braycurtis([1, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.braycurtis([1, 1, 0], [0, 1, 0])
+    0.33333333333333331
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v, dtype=np.float64)
+    l1_diff = abs(u - v)
+    l1_sum = abs(u + v)
+    if w is not None:
+        w = _validate_weights(w)
+        l1_diff = w * l1_diff
+        l1_sum = w * l1_sum
+    return l1_diff.sum() / l1_sum.sum()
+
+
+def canberra(u, v, w=None):
+    """
+    Compute the Canberra distance between two 1-D arrays.
+
+    The Canberra distance is defined as
+
+    .. math::
+
+         d(u,v) = \\sum_i \\frac{|u_i-v_i|}
+                              {|u_i|+|v_i|}.
+
+    Parameters
+    ----------
+    u : (N,) array_like
+        Input array.
+    v : (N,) array_like
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    canberra : double
+        The Canberra distance between vectors `u` and `v`.
+
+    Notes
+    -----
+    When ``u[i]`` and ``v[i]`` are 0 for given i, then the fraction 0/0 = 0 is
+    used in the calculation.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.canberra([1, 0, 0], [0, 1, 0])
+    2.0
+    >>> distance.canberra([1, 1, 0], [0, 1, 0])
+    1.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v, dtype=np.float64)
+    if w is not None:
+        w = _validate_weights(w)
+    with np.errstate(invalid='ignore'):
+        abs_uv = abs(u - v)
+        abs_u = abs(u)
+        abs_v = abs(v)
+        d = abs_uv / (abs_u + abs_v)
+        if w is not None:
+            d = w * d
+        d = np.nansum(d)
+    return d
+
+
+def jensenshannon(p, q, base=None, *, axis=0, keepdims=False):
+    """
+    Compute the Jensen-Shannon distance (metric) between
+    two probability arrays. This is the square root
+    of the Jensen-Shannon divergence.
+
+    The Jensen-Shannon distance between two probability
+    vectors `p` and `q` is defined as,
+
+    .. math::
+
+       \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}}
+
+    where :math:`m` is the pointwise mean of :math:`p` and :math:`q`
+    and :math:`D` is the Kullback-Leibler divergence.
+
+    This routine will normalize `p` and `q` if they don't sum to 1.0.
+
+    Parameters
+    ----------
+    p : (N,) array_like
+        left probability vector
+    q : (N,) array_like
+        right probability vector
+    base : double, optional
+        the base of the logarithm used to compute the output
+        if not given, then the routine uses the default base of
+        scipy.stats.entropy.
+    axis : int, optional
+        Axis along which the Jensen-Shannon distances are computed. The default
+        is 0.
+
+        .. versionadded:: 1.7.0
+    keepdims : bool, optional
+        If this is set to `True`, the reduced axes are left in the
+        result as dimensions with size one. With this option,
+        the result will broadcast correctly against the input array.
+        Default is False.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    js : double or ndarray
+        The Jensen-Shannon distances between `p` and `q` along the `axis`.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> import numpy as np
+    >>> distance.jensenshannon([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], 2.0)
+    1.0
+    >>> distance.jensenshannon([1.0, 0.0], [0.5, 0.5])
+    0.46450140402245893
+    >>> distance.jensenshannon([1.0, 0.0, 0.0], [1.0, 0.0, 0.0])
+    0.0
+    >>> a = np.array([[1, 2, 3, 4],
+    ...               [5, 6, 7, 8],
+    ...               [9, 10, 11, 12]])
+    >>> b = np.array([[13, 14, 15, 16],
+    ...               [17, 18, 19, 20],
+    ...               [21, 22, 23, 24]])
+    >>> distance.jensenshannon(a, b, axis=0)
+    array([0.1954288, 0.1447697, 0.1138377, 0.0927636])
+    >>> distance.jensenshannon(a, b, axis=1)
+    array([0.1402339, 0.0399106, 0.0201815])
+
+    """
+    p = np.asarray(p)
+    q = np.asarray(q)
+    p = p / np.sum(p, axis=axis, keepdims=True)
+    q = q / np.sum(q, axis=axis, keepdims=True)
+    m = (p + q) / 2.0
+    left = rel_entr(p, m)
+    right = rel_entr(q, m)
+    left_sum = np.sum(left, axis=axis, keepdims=keepdims)
+    right_sum = np.sum(right, axis=axis, keepdims=keepdims)
+    js = left_sum + right_sum
+    if base is not None:
+        js /= np.log(base)
+    return np.sqrt(js / 2.0)
+
+
+def yule(u, v, w=None):
+    """
+    Compute the Yule dissimilarity between two boolean 1-D arrays.
+
+    The Yule dissimilarity is defined as
+
+    .. math::
+
+         \\frac{R}{c_{TT} * c_{FF} + \\frac{R}{2}}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n` and :math:`R = 2.0 * c_{TF} * c_{FT}`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    yule : double
+        The Yule dissimilarity between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.yule([1, 0, 0], [0, 1, 0])
+    2.0
+    >>> distance.yule([1, 1, 0], [0, 1, 0])
+    0.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+    (nff, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w)
+    half_R = ntf * nft
+    if half_R == 0:
+        return 0.0
+    else:
+        return float(2.0 * half_R / (ntt * nff + half_R))
+
+
+def dice(u, v, w=None):
+    """
+    Compute the Dice dissimilarity between two boolean 1-D arrays.
+
+    The Dice dissimilarity between `u` and `v`, is
+
+    .. math::
+
+         \\frac{c_{TF} + c_{FT}}
+              {2c_{TT} + c_{FT} + c_{TF}}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input 1-D array.
+    v : (N,) array_like, bool
+        Input 1-D array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    dice : double
+        The Dice dissimilarity between 1-D arrays `u` and `v`.
+
+    Notes
+    -----
+    This function computes the Dice dissimilarity index. To compute the
+    Dice similarity index, convert one to the other with similarity =
+    1 - dissimilarity.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.dice([1, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.dice([1, 0, 0], [1, 1, 0])
+    0.3333333333333333
+    >>> distance.dice([1, 0, 0], [2, 0, 0])
+    -0.3333333333333333
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+    if u.dtype == v.dtype == bool and w is None:
+        ntt = (u & v).sum()
+    else:
+        dtype = np.result_type(int, u.dtype, v.dtype)
+        u = u.astype(dtype)
+        v = v.astype(dtype)
+        if w is None:
+            ntt = (u * v).sum()
+        else:
+            ntt = (u * v * w).sum()
+    (nft, ntf) = _nbool_correspond_ft_tf(u, v, w=w)
+    return float((ntf + nft) / np.array(2.0 * ntt + ntf + nft))
+
+
+def rogerstanimoto(u, v, w=None):
+    """
+    Compute the Rogers-Tanimoto dissimilarity between two boolean 1-D arrays.
+
+    The Rogers-Tanimoto dissimilarity between two boolean 1-D arrays
+    `u` and `v`, is defined as
+
+    .. math::
+       \\frac{R}
+            {c_{TT} + c_{FF} + R}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    rogerstanimoto : double
+        The Rogers-Tanimoto dissimilarity between vectors
+        `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.rogerstanimoto([1, 0, 0], [0, 1, 0])
+    0.8
+    >>> distance.rogerstanimoto([1, 0, 0], [1, 1, 0])
+    0.5
+    >>> distance.rogerstanimoto([1, 0, 0], [2, 0, 0])
+    -1.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+    (nff, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w)
+    return float(2.0 * (ntf + nft)) / float(ntt + nff + (2.0 * (ntf + nft)))
+
+
+def russellrao(u, v, w=None):
+    """
+    Compute the Russell-Rao dissimilarity between two boolean 1-D arrays.
+
+    The Russell-Rao dissimilarity between two boolean 1-D arrays, `u` and
+    `v`, is defined as
+
+    .. math::
+
+      \\frac{n - c_{TT}}
+           {n}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    russellrao : double
+        The Russell-Rao dissimilarity between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.russellrao([1, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.russellrao([1, 0, 0], [1, 1, 0])
+    0.6666666666666666
+    >>> distance.russellrao([1, 0, 0], [2, 0, 0])
+    0.3333333333333333
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if u.dtype == v.dtype == bool and w is None:
+        ntt = (u & v).sum()
+        n = float(len(u))
+    elif w is None:
+        ntt = (u * v).sum()
+        n = float(len(u))
+    else:
+        w = _validate_weights(w)
+        ntt = (u * v * w).sum()
+        n = w.sum()
+    return float(n - ntt) / n
+
+
+_deprecated_sokalmichener = _deprecated(
+    "The sokalmichener metric is deprecated since SciPy 1.15.0 and will be "
+    "removed in SciPy 1.17.0.  Replace usage of 'sokalmichener(u, v)' with "
+    "'rogerstanimoto(u, v)'."
+)
+
+
+@_deprecated_sokalmichener
+def sokalmichener(u, v, w=None):
+    """
+    Compute the Sokal-Michener dissimilarity between two boolean 1-D arrays.
+
+    .. deprecated:: 1.15.0
+       This function is deprecated and will be removed in SciPy 1.17.0.
+       Replace usage of ``sokalmichener(u, v)`` with ``rogerstanimoto(u, v)``.
+
+    The Sokal-Michener dissimilarity between boolean 1-D arrays `u` and `v`,
+    is defined as
+
+    .. math::
+
+       \\frac{R}
+            {S + R}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n`, :math:`R = 2 * (c_{TF} + c_{FT})` and
+    :math:`S = c_{FF} + c_{TT}`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    sokalmichener : double
+        The Sokal-Michener dissimilarity between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.sokalmichener([1, 0, 0], [0, 1, 0])
+    0.8
+    >>> distance.sokalmichener([1, 0, 0], [1, 1, 0])
+    0.5
+    >>> distance.sokalmichener([1, 0, 0], [2, 0, 0])
+    -1.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if w is not None:
+        w = _validate_weights(w)
+    nff, nft, ntf, ntt = _nbool_correspond_all(u, v, w=w)
+    return float(2.0 * (ntf + nft)) / float(ntt + nff + 2.0 * (ntf + nft))
+
+
+def sokalsneath(u, v, w=None):
+    """
+    Compute the Sokal-Sneath dissimilarity between two boolean 1-D arrays.
+
+    The Sokal-Sneath dissimilarity between `u` and `v`,
+
+    .. math::
+
+       \\frac{R}
+            {c_{TT} + R}
+
+    where :math:`c_{ij}` is the number of occurrences of
+    :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
+    :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.
+
+    Parameters
+    ----------
+    u : (N,) array_like, bool
+        Input array.
+    v : (N,) array_like, bool
+        Input array.
+    w : (N,) array_like, optional
+        The weights for each value in `u` and `v`. Default is None,
+        which gives each value a weight of 1.0
+
+    Returns
+    -------
+    sokalsneath : double
+        The Sokal-Sneath dissimilarity between vectors `u` and `v`.
+
+    Examples
+    --------
+    >>> from scipy.spatial import distance
+    >>> distance.sokalsneath([1, 0, 0], [0, 1, 0])
+    1.0
+    >>> distance.sokalsneath([1, 0, 0], [1, 1, 0])
+    0.66666666666666663
+    >>> distance.sokalsneath([1, 0, 0], [2, 1, 0])
+    0.0
+    >>> distance.sokalsneath([1, 0, 0], [3, 1, 0])
+    -2.0
+
+    """
+    u = _validate_vector(u)
+    v = _validate_vector(v)
+    if u.dtype == v.dtype == bool and w is None:
+        ntt = (u & v).sum()
+    elif w is None:
+        ntt = (u * v).sum()
+    else:
+        w = _validate_weights(w)
+        ntt = (u * v * w).sum()
+    (nft, ntf) = _nbool_correspond_ft_tf(u, v, w=w)
+    denom = np.array(ntt + 2.0 * (ntf + nft))
+    if not denom.any():
+        raise ValueError('Sokal-Sneath dissimilarity is not defined for '
+                         'vectors that are entirely false.')
+    return float(2.0 * (ntf + nft)) / denom
+
+
+_convert_to_double = partial(_convert_to_type, out_type=np.float64)
+_convert_to_bool = partial(_convert_to_type, out_type=bool)
+
+# adding python-only wrappers to _distance_wrap module
+_distance_wrap.pdist_correlation_double_wrap = _correlation_pdist_wrap
+_distance_wrap.cdist_correlation_double_wrap = _correlation_cdist_wrap
+
+
+@dataclasses.dataclass(frozen=True)
+class CDistMetricWrapper:
+    metric_name: str
+
+    def __call__(self, XA, XB, *, out=None, **kwargs):
+        XA = np.ascontiguousarray(XA)
+        XB = np.ascontiguousarray(XB)
+        mA, n = XA.shape
+        mB, _ = XB.shape
+        metric_name = self.metric_name
+        metric_info = _METRICS[metric_name]
+        XA, XB, typ, kwargs = _validate_cdist_input(
+            XA, XB, mA, mB, n, metric_info, **kwargs)
+
+        w = kwargs.pop('w', None)
+        if w is not None:
+            metric = metric_info.dist_func
+            return _cdist_callable(
+                XA, XB, metric=metric, out=out, w=w, **kwargs)
+
+        dm = _prepare_out_argument(out, np.float64, (mA, mB))
+        # get cdist wrapper
+        cdist_fn = getattr(_distance_wrap, f'cdist_{metric_name}_{typ}_wrap')
+        cdist_fn(XA, XB, dm, **kwargs)
+        return dm
+
+
+@dataclasses.dataclass(frozen=True)
+class PDistMetricWrapper:
+    metric_name: str
+
+    def __call__(self, X, *, out=None, **kwargs):
+        X = np.ascontiguousarray(X)
+        m, n = X.shape
+        metric_name = self.metric_name
+        metric_info = _METRICS[metric_name]
+        X, typ, kwargs = _validate_pdist_input(
+            X, m, n, metric_info, **kwargs)
+        out_size = (m * (m - 1)) // 2
+        w = kwargs.pop('w', None)
+        if w is not None:
+            metric = metric_info.dist_func
+            return _pdist_callable(
+                X, metric=metric, out=out, w=w, **kwargs)
+
+        dm = _prepare_out_argument(out, np.float64, (out_size,))
+        # get pdist wrapper
+        pdist_fn = getattr(_distance_wrap, f'pdist_{metric_name}_{typ}_wrap')
+        pdist_fn(X, dm, **kwargs)
+        return dm
+
+
+@dataclasses.dataclass(frozen=True)
+class MetricInfo:
+    # Name of python distance function
+    canonical_name: str
+    # All aliases, including canonical_name
+    aka: set[str]
+    # unvectorized distance function
+    dist_func: Callable
+    # Optimized cdist function
+    cdist_func: Callable
+    # Optimized pdist function
+    pdist_func: Callable
+    # function that checks kwargs and computes default values:
+    # f(X, m, n, **kwargs)
+    validator: Callable | None = None
+    # list of supported types:
+    # X (pdist) and XA (cdist) are used to choose the type. if there is no
+    # match the first type is used. Default double
+    types: list[str] = dataclasses.field(default_factory=lambda: ['double'])
+    # true if out array must be C-contiguous
+    requires_contiguous_out: bool = True
+
+
+# Registry of implemented metrics:
+_METRIC_INFOS = [
+    MetricInfo(
+        canonical_name='braycurtis',
+        aka={'braycurtis'},
+        dist_func=braycurtis,
+        cdist_func=_distance_pybind.cdist_braycurtis,
+        pdist_func=_distance_pybind.pdist_braycurtis,
+    ),
+    MetricInfo(
+        canonical_name='canberra',
+        aka={'canberra'},
+        dist_func=canberra,
+        cdist_func=_distance_pybind.cdist_canberra,
+        pdist_func=_distance_pybind.pdist_canberra,
+    ),
+    MetricInfo(
+        canonical_name='chebyshev',
+        aka={'chebychev', 'chebyshev', 'cheby', 'cheb', 'ch'},
+        dist_func=chebyshev,
+        cdist_func=_distance_pybind.cdist_chebyshev,
+        pdist_func=_distance_pybind.pdist_chebyshev,
+    ),
+    MetricInfo(
+        canonical_name='cityblock',
+        aka={'cityblock', 'cblock', 'cb', 'c'},
+        dist_func=cityblock,
+        cdist_func=_distance_pybind.cdist_cityblock,
+        pdist_func=_distance_pybind.pdist_cityblock,
+    ),
+    MetricInfo(
+        canonical_name='correlation',
+        aka={'correlation', 'co'},
+        dist_func=correlation,
+        cdist_func=CDistMetricWrapper('correlation'),
+        pdist_func=PDistMetricWrapper('correlation'),
+    ),
+    MetricInfo(
+        canonical_name='cosine',
+        aka={'cosine', 'cos'},
+        dist_func=cosine,
+        cdist_func=CDistMetricWrapper('cosine'),
+        pdist_func=PDistMetricWrapper('cosine'),
+    ),
+    MetricInfo(
+        canonical_name='dice',
+        aka={'dice'},
+        types=['bool'],
+        dist_func=dice,
+        cdist_func=_distance_pybind.cdist_dice,
+        pdist_func=_distance_pybind.pdist_dice,
+    ),
+    MetricInfo(
+        canonical_name='euclidean',
+        aka={'euclidean', 'euclid', 'eu', 'e'},
+        dist_func=euclidean,
+        cdist_func=_distance_pybind.cdist_euclidean,
+        pdist_func=_distance_pybind.pdist_euclidean,
+    ),
+    MetricInfo(
+        canonical_name='hamming',
+        aka={'matching', 'hamming', 'hamm', 'ha', 'h'},
+        types=['double', 'bool'],
+        validator=_validate_hamming_kwargs,
+        dist_func=hamming,
+        cdist_func=_distance_pybind.cdist_hamming,
+        pdist_func=_distance_pybind.pdist_hamming,
+    ),
+    MetricInfo(
+        canonical_name='jaccard',
+        aka={'jaccard', 'jacc', 'ja', 'j'},
+        types=['double', 'bool'],
+        dist_func=jaccard,
+        cdist_func=_distance_pybind.cdist_jaccard,
+        pdist_func=_distance_pybind.pdist_jaccard,
+    ),
+    MetricInfo(
+        canonical_name='jensenshannon',
+        aka={'jensenshannon', 'js'},
+        dist_func=jensenshannon,
+        cdist_func=CDistMetricWrapper('jensenshannon'),
+        pdist_func=PDistMetricWrapper('jensenshannon'),
+    ),
+    MetricInfo(
+        canonical_name='kulczynski1',
+        aka={'kulczynski1'},
+        types=['bool'],
+        dist_func=kulczynski1,
+        cdist_func=_deprecated_kulczynski1(_distance_pybind.cdist_kulczynski1),
+        pdist_func=_deprecated_kulczynski1(_distance_pybind.pdist_kulczynski1),
+    ),
+    MetricInfo(
+        canonical_name='mahalanobis',
+        aka={'mahalanobis', 'mahal', 'mah'},
+        validator=_validate_mahalanobis_kwargs,
+        dist_func=mahalanobis,
+        cdist_func=CDistMetricWrapper('mahalanobis'),
+        pdist_func=PDistMetricWrapper('mahalanobis'),
+    ),
+    MetricInfo(
+        canonical_name='minkowski',
+        aka={'minkowski', 'mi', 'm', 'pnorm'},
+        validator=_validate_minkowski_kwargs,
+        dist_func=minkowski,
+        cdist_func=_distance_pybind.cdist_minkowski,
+        pdist_func=_distance_pybind.pdist_minkowski,
+    ),
+    MetricInfo(
+        canonical_name='rogerstanimoto',
+        aka={'rogerstanimoto'},
+        types=['bool'],
+        dist_func=rogerstanimoto,
+        cdist_func=_distance_pybind.cdist_rogerstanimoto,
+        pdist_func=_distance_pybind.pdist_rogerstanimoto,
+    ),
+    MetricInfo(
+        canonical_name='russellrao',
+        aka={'russellrao'},
+        types=['bool'],
+        dist_func=russellrao,
+        cdist_func=_distance_pybind.cdist_russellrao,
+        pdist_func=_distance_pybind.pdist_russellrao,
+    ),
+    MetricInfo(
+        canonical_name='seuclidean',
+        aka={'seuclidean', 'se', 's'},
+        validator=_validate_seuclidean_kwargs,
+        dist_func=seuclidean,
+        cdist_func=CDistMetricWrapper('seuclidean'),
+        pdist_func=PDistMetricWrapper('seuclidean'),
+    ),
+    MetricInfo(
+        canonical_name='sokalmichener',
+        aka={'sokalmichener'},
+        types=['bool'],
+        dist_func=sokalmichener,
+        cdist_func=_deprecated_sokalmichener(_distance_pybind.cdist_sokalmichener),
+        pdist_func=_deprecated_sokalmichener(_distance_pybind.pdist_sokalmichener),
+    ),
+    MetricInfo(
+        canonical_name='sokalsneath',
+        aka={'sokalsneath'},
+        types=['bool'],
+        dist_func=sokalsneath,
+        cdist_func=_distance_pybind.cdist_sokalsneath,
+        pdist_func=_distance_pybind.pdist_sokalsneath,
+    ),
+    MetricInfo(
+        canonical_name='sqeuclidean',
+        aka={'sqeuclidean', 'sqe', 'sqeuclid'},
+        dist_func=sqeuclidean,
+        cdist_func=_distance_pybind.cdist_sqeuclidean,
+        pdist_func=_distance_pybind.pdist_sqeuclidean,
+    ),
+    MetricInfo(
+        canonical_name='yule',
+        aka={'yule'},
+        types=['bool'],
+        dist_func=yule,
+        cdist_func=_distance_pybind.cdist_yule,
+        pdist_func=_distance_pybind.pdist_yule,
+    ),
+]
+
+_METRICS = {info.canonical_name: info for info in _METRIC_INFOS}
+_METRIC_ALIAS = {alias: info
+                     for info in _METRIC_INFOS
+                     for alias in info.aka}
+
+_METRICS_NAMES = list(_METRICS.keys())
+
+_TEST_METRICS = {'test_' + info.canonical_name: info for info in _METRIC_INFOS}
+
+
+def pdist(X, metric='euclidean', *, out=None, **kwargs):
+    """
+    Pairwise distances between observations in n-dimensional space.
+
+    See Notes for common calling conventions.
+
+    Parameters
+    ----------
+    X : array_like
+        An m by n array of m original observations in an
+        n-dimensional space.
+    metric : str or function, optional
+        The distance metric to use. The distance function can
+        be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
+        'correlation', 'cosine', 'dice', 'euclidean', 'hamming',
+        'jaccard', 'jensenshannon', 'kulczynski1',
+        'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
+        'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
+        'sqeuclidean', 'yule'.
+    out : ndarray, optional
+        The output array.
+        If not None, condensed distance matrix Y is stored in this array.
+    **kwargs : dict, optional
+        Extra arguments to `metric`: refer to each metric documentation for a
+        list of all possible arguments.
+
+        Some possible arguments:
+
+        p : scalar
+        The p-norm to apply for Minkowski, weighted and unweighted.
+        Default: 2.
+
+        w : ndarray
+        The weight vector for metrics that support weights (e.g., Minkowski).
+
+        V : ndarray
+        The variance vector for standardized Euclidean.
+        Default: var(X, axis=0, ddof=1)
+
+        VI : ndarray
+        The inverse of the covariance matrix for Mahalanobis.
+        Default: inv(cov(X.T)).T
+
+    Returns
+    -------
+    Y : ndarray
+        Returns a condensed distance matrix Y. For each :math:`i` and :math:`j`
+        (where :math:`i 0` (note
+       that this is only a quasi-metric if :math:`0 < p < 1`).
+
+    3. ``Y = pdist(X, 'cityblock')``
+
+       Computes the city block or Manhattan distance between the
+       points.
+
+    4. ``Y = pdist(X, 'seuclidean', V=None)``
+
+       Computes the standardized Euclidean distance. The standardized
+       Euclidean distance between two n-vectors ``u`` and ``v`` is
+
+       .. math::
+
+          \\sqrt{\\sum {(u_i-v_i)^2 / V[x_i]}}
+
+
+       V is the variance vector; V[i] is the variance computed over all
+       the i'th components of the points.  If not passed, it is
+       automatically computed.
+
+    5. ``Y = pdist(X, 'sqeuclidean')``
+
+       Computes the squared Euclidean distance :math:`\\|u-v\\|_2^2` between
+       the vectors.
+
+    6. ``Y = pdist(X, 'cosine')``
+
+       Computes the cosine distance between vectors u and v,
+
+       .. math::
+
+          1 - \\frac{u \\cdot v}
+                   {{\\|u\\|}_2 {\\|v\\|}_2}
+
+       where :math:`\\|*\\|_2` is the 2-norm of its argument ``*``, and
+       :math:`u \\cdot v` is the dot product of ``u`` and ``v``.
+
+    7. ``Y = pdist(X, 'correlation')``
+
+       Computes the correlation distance between vectors u and v. This is
+
+       .. math::
+
+          1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})}
+                   {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2}
+
+       where :math:`\\bar{v}` is the mean of the elements of vector v,
+       and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`.
+
+    8. ``Y = pdist(X, 'hamming')``
+
+       Computes the normalized Hamming distance, or the proportion of
+       those vector elements between two n-vectors ``u`` and ``v``
+       which disagree. To save memory, the matrix ``X`` can be of type
+       boolean.
+
+    9. ``Y = pdist(X, 'jaccard')``
+
+       Computes the Jaccard distance between the points. Given two
+       vectors, ``u`` and ``v``, the Jaccard distance is the
+       proportion of those elements ``u[i]`` and ``v[i]`` that
+       disagree.
+
+    10. ``Y = pdist(X, 'jensenshannon')``
+
+        Computes the Jensen-Shannon distance between two probability arrays.
+        Given two probability vectors, :math:`p` and :math:`q`, the
+        Jensen-Shannon distance is
+
+        .. math::
+
+           \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}}
+
+        where :math:`m` is the pointwise mean of :math:`p` and :math:`q`
+        and :math:`D` is the Kullback-Leibler divergence.
+
+    11. ``Y = pdist(X, 'chebyshev')``
+
+        Computes the Chebyshev distance between the points. The
+        Chebyshev distance between two n-vectors ``u`` and ``v`` is the
+        maximum norm-1 distance between their respective elements. More
+        precisely, the distance is given by
+
+        .. math::
+
+           d(u,v) = \\max_i {|u_i-v_i|}
+
+    12. ``Y = pdist(X, 'canberra')``
+
+        Computes the Canberra distance between the points. The
+        Canberra distance between two points ``u`` and ``v`` is
+
+        .. math::
+
+          d(u,v) = \\sum_i \\frac{|u_i-v_i|}
+                               {|u_i|+|v_i|}
+
+
+    13. ``Y = pdist(X, 'braycurtis')``
+
+        Computes the Bray-Curtis distance between the points. The
+        Bray-Curtis distance between two points ``u`` and ``v`` is
+
+
+        .. math::
+
+             d(u,v) = \\frac{\\sum_i {|u_i-v_i|}}
+                            {\\sum_i {|u_i+v_i|}}
+
+    14. ``Y = pdist(X, 'mahalanobis', VI=None)``
+
+        Computes the Mahalanobis distance between the points. The
+        Mahalanobis distance between two points ``u`` and ``v`` is
+        :math:`\\sqrt{(u-v)(1/V)(u-v)^T}` where :math:`(1/V)` (the ``VI``
+        variable) is the inverse covariance. If ``VI`` is not None,
+        ``VI`` will be used as the inverse covariance matrix.
+
+    15. ``Y = pdist(X, 'yule')``
+
+        Computes the Yule distance between each pair of boolean
+        vectors. (see yule function documentation)
+
+    16. ``Y = pdist(X, 'matching')``
+
+        Synonym for 'hamming'.
+
+    17. ``Y = pdist(X, 'dice')``
+
+        Computes the Dice distance between each pair of boolean
+        vectors. (see dice function documentation)
+
+    18. ``Y = pdist(X, 'kulczynski1')``
+
+        Computes the kulczynski1 distance between each pair of
+        boolean vectors. (see kulczynski1 function documentation)
+
+        .. deprecated:: 1.15.0
+           This metric is deprecated and will be removed in SciPy 1.17.0.
+           Replace usage of ``pdist(X, 'kulczynski1')`` with
+           ``1 / pdist(X, 'jaccard') - 1``.
+
+    19. ``Y = pdist(X, 'rogerstanimoto')``
+
+        Computes the Rogers-Tanimoto distance between each pair of
+        boolean vectors. (see rogerstanimoto function documentation)
+
+    20. ``Y = pdist(X, 'russellrao')``
+
+        Computes the Russell-Rao distance between each pair of
+        boolean vectors. (see russellrao function documentation)
+
+    21. ``Y = pdist(X, 'sokalmichener')``
+
+        Computes the Sokal-Michener distance between each pair of
+        boolean vectors. (see sokalmichener function documentation)
+
+        .. deprecated:: 1.15.0
+           This metric is deprecated and will be removed in SciPy 1.17.0.
+           Replace usage of ``pdist(X, 'sokalmichener')`` with
+           ``pdist(X, 'rogerstanimoto')``.
+
+    22. ``Y = pdist(X, 'sokalsneath')``
+
+        Computes the Sokal-Sneath distance between each pair of
+        boolean vectors. (see sokalsneath function documentation)
+
+    23. ``Y = pdist(X, 'kulczynski1')``
+
+        Computes the Kulczynski 1 distance between each pair of
+        boolean vectors. (see kulczynski1 function documentation)
+
+    24. ``Y = pdist(X, f)``
+
+        Computes the distance between all pairs of vectors in X
+        using the user supplied 2-arity function f. For example,
+        Euclidean distance between the vectors could be computed
+        as follows::
+
+          dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))
+
+        Note that you should avoid passing a reference to one of
+        the distance functions defined in this library. For example,::
+
+          dm = pdist(X, sokalsneath)
+
+        would calculate the pair-wise distances between the vectors in
+        X using the Python function sokalsneath. This would result in
+        sokalsneath being called :math:`{n \\choose 2}` times, which
+        is inefficient. Instead, the optimized C version is more
+        efficient, and we call it using the following syntax.::
+
+          dm = pdist(X, 'sokalsneath')
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial.distance import pdist
+
+    ``x`` is an array of five points in three-dimensional space.
+
+    >>> x = np.array([[2, 0, 2], [2, 2, 3], [-2, 4, 5], [0, 1, 9], [2, 2, 4]])
+
+    ``pdist(x)`` with no additional arguments computes the 10 pairwise
+    Euclidean distances:
+
+    >>> pdist(x)
+    array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949,
+           6.40312424, 1.        , 5.38516481, 4.58257569, 5.47722558])
+
+    The following computes the pairwise Minkowski distances with ``p = 3.5``:
+
+    >>> pdist(x, metric='minkowski', p=3.5)
+    array([2.04898923, 5.1154929 , 7.02700737, 2.43802731, 4.19042714,
+           6.03956994, 1.        , 4.45128103, 4.10636143, 5.0619695 ])
+
+    The pairwise city block or Manhattan distances:
+
+    >>> pdist(x, metric='cityblock')
+    array([ 3., 11., 10.,  4.,  8.,  9.,  1.,  9.,  7.,  8.])
+
+    """
+    # You can also call this as:
+    #     Y = pdist(X, 'test_abc')
+    # where 'abc' is the metric being tested.  This computes the distance
+    # between all pairs of vectors in X using the distance metric 'abc' but
+    # with a more succinct, verifiable, but less efficient implementation.
+
+    X = _asarray_validated(X, sparse_ok=False, objects_ok=True, mask_ok=True,
+                           check_finite=False)
+
+    s = X.shape
+    if len(s) != 2:
+        raise ValueError('A 2-dimensional array must be passed.')
+
+    m, n = s
+
+    if callable(metric):
+        mstr = getattr(metric, '__name__', 'UnknownCustomMetric')
+        metric_info = _METRIC_ALIAS.get(mstr, None)
+
+        if metric_info is not None:
+            X, typ, kwargs = _validate_pdist_input(
+                X, m, n, metric_info, **kwargs)
+
+        return _pdist_callable(X, metric=metric, out=out, **kwargs)
+    elif isinstance(metric, str):
+        mstr = metric.lower()
+        metric_info = _METRIC_ALIAS.get(mstr, None)
+
+        if metric_info is not None:
+            pdist_fn = metric_info.pdist_func
+            return pdist_fn(X, out=out, **kwargs)
+        elif mstr.startswith("test_"):
+            metric_info = _TEST_METRICS.get(mstr, None)
+            if metric_info is None:
+                raise ValueError(f'Unknown "Test" Distance Metric: {mstr[5:]}')
+            X, typ, kwargs = _validate_pdist_input(
+                X, m, n, metric_info, **kwargs)
+            return _pdist_callable(
+                X, metric=metric_info.dist_func, out=out, **kwargs)
+        else:
+            raise ValueError(f'Unknown Distance Metric: {mstr}')
+    else:
+        raise TypeError('2nd argument metric must be a string identifier '
+                        'or a function.')
+
+
+def squareform(X, force="no", checks=True):
+    """
+    Convert a vector-form distance vector to a square-form distance
+    matrix, and vice-versa.
+
+    Parameters
+    ----------
+    X : array_like
+        Either a condensed or redundant distance matrix.
+    force : str, optional
+        As with MATLAB(TM), if force is equal to ``'tovector'`` or
+        ``'tomatrix'``, the input will be treated as a distance matrix or
+        distance vector respectively.
+    checks : bool, optional
+        If set to False, no checks will be made for matrix
+        symmetry nor zero diagonals. This is useful if it is known that
+        ``X - X.T1`` is small and ``diag(X)`` is close to zero.
+        These values are ignored any way so they do not disrupt the
+        squareform transformation.
+
+    Returns
+    -------
+    Y : ndarray
+        If a condensed distance matrix is passed, a redundant one is
+        returned, or if a redundant one is passed, a condensed distance
+        matrix is returned.
+
+    Notes
+    -----
+    1. ``v = squareform(X)``
+
+       Given a square n-by-n symmetric distance matrix ``X``,
+       ``v = squareform(X)`` returns a ``n * (n-1) / 2``
+       (i.e. binomial coefficient n choose 2) sized vector `v`
+       where :math:`v[{n \\choose 2} - {n-i \\choose 2} + (j-i-1)]`
+       is the distance between distinct points ``i`` and ``j``.
+       If ``X`` is non-square or asymmetric, an error is raised.
+
+    2. ``X = squareform(v)``
+
+       Given a ``n * (n-1) / 2`` sized vector ``v``
+       for some integer ``n >= 1`` encoding distances as described,
+       ``X = squareform(v)`` returns a n-by-n distance matrix ``X``.
+       The ``X[i, j]`` and ``X[j, i]`` values are set to
+       :math:`v[{n \\choose 2} - {n-i \\choose 2} + (j-i-1)]`
+       and all diagonal elements are zero.
+
+    In SciPy 0.19.0, ``squareform`` stopped casting all input types to
+    float64, and started returning arrays of the same dtype as the input.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial.distance import pdist, squareform
+
+    ``x`` is an array of five points in three-dimensional space.
+
+    >>> x = np.array([[2, 0, 2], [2, 2, 3], [-2, 4, 5], [0, 1, 9], [2, 2, 4]])
+
+    ``pdist(x)`` computes the Euclidean distances between each pair of
+    points in ``x``.  The distances are returned in a one-dimensional
+    array with length ``5*(5 - 1)/2 = 10``.
+
+    >>> distvec = pdist(x)
+    >>> distvec
+    array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949,
+           6.40312424, 1.        , 5.38516481, 4.58257569, 5.47722558])
+
+    ``squareform(distvec)`` returns the 5x5 distance matrix.
+
+    >>> m = squareform(distvec)
+    >>> m
+    array([[0.        , 2.23606798, 6.40312424, 7.34846923, 2.82842712],
+           [2.23606798, 0.        , 4.89897949, 6.40312424, 1.        ],
+           [6.40312424, 4.89897949, 0.        , 5.38516481, 4.58257569],
+           [7.34846923, 6.40312424, 5.38516481, 0.        , 5.47722558],
+           [2.82842712, 1.        , 4.58257569, 5.47722558, 0.        ]])
+
+    When given a square distance matrix ``m``, ``squareform(m)`` returns
+    the one-dimensional condensed distance vector associated with the
+    matrix.  In this case, we recover ``distvec``.
+
+    >>> squareform(m)
+    array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949,
+           6.40312424, 1.        , 5.38516481, 4.58257569, 5.47722558])
+    """
+    X = np.ascontiguousarray(X)
+
+    s = X.shape
+
+    if force.lower() == 'tomatrix':
+        if len(s) != 1:
+            raise ValueError("Forcing 'tomatrix' but input X is not a "
+                             "distance vector.")
+    elif force.lower() == 'tovector':
+        if len(s) != 2:
+            raise ValueError("Forcing 'tovector' but input X is not a "
+                             "distance matrix.")
+
+    # X = squareform(v)
+    if len(s) == 1:
+        if s[0] == 0:
+            return np.zeros((1, 1), dtype=X.dtype)
+
+        # Grab the closest value to the square root of the number
+        # of elements times 2 to see if the number of elements
+        # is indeed a binomial coefficient.
+        d = int(np.ceil(np.sqrt(s[0] * 2)))
+
+        # Check that v is of valid dimensions.
+        if d * (d - 1) != s[0] * 2:
+            raise ValueError('Incompatible vector size. It must be a binomial '
+                             'coefficient n choose 2 for some integer n >= 2.')
+
+        # Allocate memory for the distance matrix.
+        M = np.zeros((d, d), dtype=X.dtype)
+
+        # Since the C code does not support striding using strides.
+        # The dimensions are used instead.
+        X = _copy_array_if_base_present(X)
+
+        # Fill in the values of the distance matrix.
+        _distance_wrap.to_squareform_from_vector_wrap(M, X)
+
+        # Return the distance matrix.
+        return M
+    elif len(s) == 2:
+        if s[0] != s[1]:
+            raise ValueError('The matrix argument must be square.')
+        if checks:
+            is_valid_dm(X, throw=True, name='X')
+
+        # One-side of the dimensions is set here.
+        d = s[0]
+
+        if d <= 1:
+            return np.array([], dtype=X.dtype)
+
+        # Create a vector.
+        v = np.zeros((d * (d - 1)) // 2, dtype=X.dtype)
+
+        # Since the C code does not support striding using strides.
+        # The dimensions are used instead.
+        X = _copy_array_if_base_present(X)
+
+        # Convert the vector to squareform.
+        _distance_wrap.to_vector_from_squareform_wrap(X, v)
+        return v
+    else:
+        raise ValueError("The first argument must be one or two dimensional "
+                         f"array. A {len(s)}-dimensional array is not permitted")
+
+
+def is_valid_dm(D, tol=0.0, throw=False, name="D", warning=False):
+    """
+    Return True if input array is a valid distance matrix.
+
+    Distance matrices must be 2-dimensional numpy arrays.
+    They must have a zero-diagonal, and they must be symmetric.
+
+    Parameters
+    ----------
+    D : array_like
+        The candidate object to test for validity.
+    tol : float, optional
+        The distance matrix should be symmetric. `tol` is the maximum
+        difference between entries ``ij`` and ``ji`` for the distance
+        metric to be considered symmetric.
+    throw : bool, optional
+        An exception is thrown if the distance matrix passed is not valid.
+    name : str, optional
+        The name of the variable to checked. This is useful if
+        throw is set to True so the offending variable can be identified
+        in the exception message when an exception is thrown.
+    warning : bool, optional
+        Instead of throwing an exception, a warning message is
+        raised.
+
+    Returns
+    -------
+    valid : bool
+        True if the variable `D` passed is a valid distance matrix.
+
+    Notes
+    -----
+    Small numerical differences in `D` and `D.T` and non-zeroness of
+    the diagonal are ignored if they are within the tolerance specified
+    by `tol`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial.distance import is_valid_dm
+
+    This matrix is a valid distance matrix.
+
+    >>> d = np.array([[0.0, 1.1, 1.2, 1.3],
+    ...               [1.1, 0.0, 1.0, 1.4],
+    ...               [1.2, 1.0, 0.0, 1.5],
+    ...               [1.3, 1.4, 1.5, 0.0]])
+    >>> is_valid_dm(d)
+    True
+
+    In the following examples, the input is not a valid distance matrix.
+
+    Not square:
+
+    >>> is_valid_dm([[0, 2, 2], [2, 0, 2]])
+    False
+
+    Nonzero diagonal element:
+
+    >>> is_valid_dm([[0, 1, 1], [1, 2, 3], [1, 3, 0]])
+    False
+
+    Not symmetric:
+
+    >>> is_valid_dm([[0, 1, 3], [2, 0, 1], [3, 1, 0]])
+    False
+
+    """
+    D = np.asarray(D, order='c')
+    valid = True
+    try:
+        s = D.shape
+        if len(D.shape) != 2:
+            if name:
+                raise ValueError(f"Distance matrix '{name}' must have shape=2 "
+                                 "(i.e. be two-dimensional).")
+            else:
+                raise ValueError('Distance matrix must have shape=2 (i.e. '
+                                 'be two-dimensional).')
+        if tol == 0.0:
+            if not (D == D.T).all():
+                if name:
+                    raise ValueError(f"Distance matrix '{name}' must be symmetric.")
+                else:
+                    raise ValueError('Distance matrix must be symmetric.')
+            if not (D[range(0, s[0]), range(0, s[0])] == 0).all():
+                if name:
+                    raise ValueError(f"Distance matrix '{name}' diagonal must be zero.")
+                else:
+                    raise ValueError('Distance matrix diagonal must be zero.')
+        else:
+            if not (D - D.T <= tol).all():
+                if name:
+                    raise ValueError(f'Distance matrix \'{name}\' must be '
+                                     f'symmetric within tolerance {tol:5.5f}.')
+                else:
+                    raise ValueError('Distance matrix must be symmetric within '
+                                     f'tolerance {tol:5.5f}.')
+            if not (D[range(0, s[0]), range(0, s[0])] <= tol).all():
+                if name:
+                    raise ValueError(f'Distance matrix \'{name}\' diagonal must be '
+                                     f'close to zero within tolerance {tol:5.5f}.')
+                else:
+                    raise ValueError(('Distance matrix \'{}\' diagonal must be close '
+                                      'to zero within tolerance {:5.5f}.').format(*tol))
+    except Exception as e:
+        if throw:
+            raise
+        if warning:
+            warnings.warn(str(e), stacklevel=2)
+        valid = False
+    return valid
+
+
+def is_valid_y(y, warning=False, throw=False, name=None):
+    """
+    Return True if the input array is a valid condensed distance matrix.
+
+    Condensed distance matrices must be 1-dimensional numpy arrays.
+    Their length must be a binomial coefficient :math:`{n \\choose 2}`
+    for some positive integer n.
+
+    Parameters
+    ----------
+    y : array_like
+        The condensed distance matrix.
+    warning : bool, optional
+        Invokes a warning if the variable passed is not a valid
+        condensed distance matrix. The warning message explains why
+        the distance matrix is not valid.  `name` is used when
+        referencing the offending variable.
+    throw : bool, optional
+        Throws an exception if the variable passed is not a valid
+        condensed distance matrix.
+    name : bool, optional
+        Used when referencing the offending variable in the
+        warning or exception message.
+
+    Returns
+    -------
+    bool
+        True if the input array is a valid condensed distance matrix,
+        False otherwise.
+
+    Examples
+    --------
+    >>> from scipy.spatial.distance import is_valid_y
+
+    This vector is a valid condensed distance matrix.  The length is 6,
+    which corresponds to ``n = 4``, since ``4*(4 - 1)/2`` is 6.
+
+    >>> v = [1.0, 1.2, 1.0, 0.5, 1.3, 0.9]
+    >>> is_valid_y(v)
+    True
+
+    An input vector with length, say, 7, is not a valid condensed distance
+    matrix.
+
+    >>> is_valid_y([1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7])
+    False
+
+    """
+    y = np.asarray(y, order='c')
+    valid = True
+    try:
+        if len(y.shape) != 1:
+            if name:
+                raise ValueError(f"Condensed distance matrix '{name}' must "
+                                 "have shape=1 (i.e. be one-dimensional).")
+            else:
+                raise ValueError('Condensed distance matrix must have shape=1 '
+                                 '(i.e. be one-dimensional).')
+        n = y.shape[0]
+        d = int(np.ceil(np.sqrt(n * 2)))
+        if (d * (d - 1) / 2) != n:
+            if name:
+                raise ValueError(f"Length n of condensed distance matrix '{name}' "
+                                 "must be a binomial coefficient, i.e."
+                                 "there must be a k such that (k \\choose 2)=n)!")
+            else:
+                raise ValueError('Length n of condensed distance matrix must '
+                                 'be a binomial coefficient, i.e. there must '
+                                 'be a k such that (k \\choose 2)=n)!')
+    except Exception as e:
+        if throw:
+            raise
+        if warning:
+            warnings.warn(str(e), stacklevel=2)
+        valid = False
+    return valid
+
+
+def num_obs_dm(d):
+    """
+    Return the number of original observations that correspond to a
+    square, redundant distance matrix.
+
+    Parameters
+    ----------
+    d : array_like
+        The target distance matrix.
+
+    Returns
+    -------
+    num_obs_dm : int
+        The number of observations in the redundant distance matrix.
+
+    Examples
+    --------
+    Find the number of original observations corresponding
+    to a square redundant distance matrix d.
+    
+    >>> from scipy.spatial.distance import num_obs_dm
+    >>> d = [[0, 100, 200], [100, 0, 150], [200, 150, 0]]
+    >>> num_obs_dm(d)
+    3
+    """
+    d = np.asarray(d, order='c')
+    is_valid_dm(d, tol=np.inf, throw=True, name='d')
+    return d.shape[0]
+
+
+def num_obs_y(Y):
+    """
+    Return the number of original observations that correspond to a
+    condensed distance matrix.
+
+    Parameters
+    ----------
+    Y : array_like
+        Condensed distance matrix.
+
+    Returns
+    -------
+    n : int
+        The number of observations in the condensed distance matrix `Y`.
+
+    Examples
+    --------
+    Find the number of original observations corresponding to a
+    condensed distance matrix Y.
+    
+    >>> from scipy.spatial.distance import num_obs_y
+    >>> Y = [1, 2, 3.5, 7, 10, 4]
+    >>> num_obs_y(Y)
+    4
+    """
+    Y = np.asarray(Y, order='c')
+    is_valid_y(Y, throw=True, name='Y')
+    k = Y.shape[0]
+    if k == 0:
+        raise ValueError("The number of observations cannot be determined on "
+                         "an empty distance matrix.")
+    d = int(np.ceil(np.sqrt(k * 2)))
+    if (d * (d - 1) / 2) != k:
+        raise ValueError("Invalid condensed distance matrix passed. Must be "
+                         "some k where k=(n choose 2) for some n >= 2.")
+    return d
+
+
+def _prepare_out_argument(out, dtype, expected_shape):
+    if out is None:
+        return np.empty(expected_shape, dtype=dtype)
+
+    if out.shape != expected_shape:
+        raise ValueError("Output array has incorrect shape.")
+    if not out.flags.c_contiguous:
+        raise ValueError("Output array must be C-contiguous.")
+    if out.dtype != np.float64:
+        raise ValueError("Output array must be double type.")
+    return out
+
+
+def _pdist_callable(X, *, out, metric, **kwargs):
+    n = X.shape[0]
+    out_size = (n * (n - 1)) // 2
+    dm = _prepare_out_argument(out, np.float64, (out_size,))
+    k = 0
+    for i in range(X.shape[0] - 1):
+        for j in range(i + 1, X.shape[0]):
+            dm[k] = metric(X[i], X[j], **kwargs)
+            k += 1
+    return dm
+
+
+def _cdist_callable(XA, XB, *, out, metric, **kwargs):
+    mA = XA.shape[0]
+    mB = XB.shape[0]
+    dm = _prepare_out_argument(out, np.float64, (mA, mB))
+    for i in range(mA):
+        for j in range(mB):
+            dm[i, j] = metric(XA[i], XB[j], **kwargs)
+    return dm
+
+
+def cdist(XA, XB, metric='euclidean', *, out=None, **kwargs):
+    """
+    Compute distance between each pair of the two collections of inputs.
+
+    See Notes for common calling conventions.
+
+    Parameters
+    ----------
+    XA : array_like
+        An :math:`m_A` by :math:`n` array of :math:`m_A`
+        original observations in an :math:`n`-dimensional space.
+        Inputs are converted to float type.
+    XB : array_like
+        An :math:`m_B` by :math:`n` array of :math:`m_B`
+        original observations in an :math:`n`-dimensional space.
+        Inputs are converted to float type.
+    metric : str or callable, optional
+        The distance metric to use. If a string, the distance function can be
+        'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation',
+        'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'jensenshannon',
+        'kulczynski1', 'mahalanobis', 'matching', 'minkowski',
+        'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener',
+        'sokalsneath', 'sqeuclidean', 'yule'.
+    **kwargs : dict, optional
+        Extra arguments to `metric`: refer to each metric documentation for a
+        list of all possible arguments.
+
+        Some possible arguments:
+
+        p : scalar
+        The p-norm to apply for Minkowski, weighted and unweighted.
+        Default: 2.
+
+        w : array_like
+        The weight vector for metrics that support weights (e.g., Minkowski).
+
+        V : array_like
+        The variance vector for standardized Euclidean.
+        Default: var(vstack([XA, XB]), axis=0, ddof=1)
+
+        VI : array_like
+        The inverse of the covariance matrix for Mahalanobis.
+        Default: inv(cov(vstack([XA, XB].T))).T
+
+        out : ndarray
+        The output array
+        If not None, the distance matrix Y is stored in this array.
+
+    Returns
+    -------
+    Y : ndarray
+        A :math:`m_A` by :math:`m_B` distance matrix is returned.
+        For each :math:`i` and :math:`j`, the metric
+        ``dist(u=XA[i], v=XB[j])`` is computed and stored in the
+        :math:`ij` th entry.
+
+    Raises
+    ------
+    ValueError
+        An exception is thrown if `XA` and `XB` do not have
+        the same number of columns.
+
+    Notes
+    -----
+    The following are common calling conventions:
+
+    1. ``Y = cdist(XA, XB, 'euclidean')``
+
+       Computes the distance between :math:`m` points using
+       Euclidean distance (2-norm) as the distance metric between the
+       points. The points are arranged as :math:`m`
+       :math:`n`-dimensional row vectors in the matrix X.
+
+    2. ``Y = cdist(XA, XB, 'minkowski', p=2.)``
+
+       Computes the distances using the Minkowski distance
+       :math:`\\|u-v\\|_p` (:math:`p`-norm) where :math:`p > 0` (note
+       that this is only a quasi-metric if :math:`0 < p < 1`).
+
+    3. ``Y = cdist(XA, XB, 'cityblock')``
+
+       Computes the city block or Manhattan distance between the
+       points.
+
+    4. ``Y = cdist(XA, XB, 'seuclidean', V=None)``
+
+       Computes the standardized Euclidean distance. The standardized
+       Euclidean distance between two n-vectors ``u`` and ``v`` is
+
+       .. math::
+
+          \\sqrt{\\sum {(u_i-v_i)^2 / V[x_i]}}.
+
+       V is the variance vector; V[i] is the variance computed over all
+       the i'th components of the points. If not passed, it is
+       automatically computed.
+
+    5. ``Y = cdist(XA, XB, 'sqeuclidean')``
+
+       Computes the squared Euclidean distance :math:`\\|u-v\\|_2^2` between
+       the vectors.
+
+    6. ``Y = cdist(XA, XB, 'cosine')``
+
+       Computes the cosine distance between vectors u and v,
+
+       .. math::
+
+          1 - \\frac{u \\cdot v}
+                   {{\\|u\\|}_2 {\\|v\\|}_2}
+
+       where :math:`\\|*\\|_2` is the 2-norm of its argument ``*``, and
+       :math:`u \\cdot v` is the dot product of :math:`u` and :math:`v`.
+
+    7. ``Y = cdist(XA, XB, 'correlation')``
+
+       Computes the correlation distance between vectors u and v. This is
+
+       .. math::
+
+          1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})}
+                   {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2}
+
+       where :math:`\\bar{v}` is the mean of the elements of vector v,
+       and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`.
+
+
+    8. ``Y = cdist(XA, XB, 'hamming')``
+
+       Computes the normalized Hamming distance, or the proportion of
+       those vector elements between two n-vectors ``u`` and ``v``
+       which disagree. To save memory, the matrix ``X`` can be of type
+       boolean.
+
+    9. ``Y = cdist(XA, XB, 'jaccard')``
+
+       Computes the Jaccard distance between the points. Given two
+       vectors, ``u`` and ``v``, the Jaccard distance is the
+       proportion of those elements ``u[i]`` and ``v[i]`` that
+       disagree where at least one of them is non-zero.
+
+    10. ``Y = cdist(XA, XB, 'jensenshannon')``
+
+        Computes the Jensen-Shannon distance between two probability arrays.
+        Given two probability vectors, :math:`p` and :math:`q`, the
+        Jensen-Shannon distance is
+
+        .. math::
+
+           \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}}
+
+        where :math:`m` is the pointwise mean of :math:`p` and :math:`q`
+        and :math:`D` is the Kullback-Leibler divergence.
+
+    11. ``Y = cdist(XA, XB, 'chebyshev')``
+
+        Computes the Chebyshev distance between the points. The
+        Chebyshev distance between two n-vectors ``u`` and ``v`` is the
+        maximum norm-1 distance between their respective elements. More
+        precisely, the distance is given by
+
+        .. math::
+
+           d(u,v) = \\max_i {|u_i-v_i|}.
+
+    12. ``Y = cdist(XA, XB, 'canberra')``
+
+        Computes the Canberra distance between the points. The
+        Canberra distance between two points ``u`` and ``v`` is
+
+        .. math::
+
+          d(u,v) = \\sum_i \\frac{|u_i-v_i|}
+                               {|u_i|+|v_i|}.
+
+    13. ``Y = cdist(XA, XB, 'braycurtis')``
+
+        Computes the Bray-Curtis distance between the points. The
+        Bray-Curtis distance between two points ``u`` and ``v`` is
+
+
+        .. math::
+
+             d(u,v) = \\frac{\\sum_i (|u_i-v_i|)}
+                           {\\sum_i (|u_i+v_i|)}
+
+    14. ``Y = cdist(XA, XB, 'mahalanobis', VI=None)``
+
+        Computes the Mahalanobis distance between the points. The
+        Mahalanobis distance between two points ``u`` and ``v`` is
+        :math:`\\sqrt{(u-v)(1/V)(u-v)^T}` where :math:`(1/V)` (the ``VI``
+        variable) is the inverse covariance. If ``VI`` is not None,
+        ``VI`` will be used as the inverse covariance matrix.
+
+    15. ``Y = cdist(XA, XB, 'yule')``
+
+        Computes the Yule distance between the boolean
+        vectors. (see `yule` function documentation)
+
+    16. ``Y = cdist(XA, XB, 'matching')``
+
+        Synonym for 'hamming'.
+
+    17. ``Y = cdist(XA, XB, 'dice')``
+
+        Computes the Dice distance between the boolean vectors. (see
+        `dice` function documentation)
+
+    18. ``Y = cdist(XA, XB, 'kulczynski1')``
+
+        Computes the kulczynski distance between the boolean
+        vectors. (see `kulczynski1` function documentation)
+
+        .. deprecated:: 1.15.0
+           This metric is deprecated and will be removed in SciPy 1.17.0.
+           Replace usage of ``cdist(XA, XB, 'kulczynski1')`` with
+           ``1 / cdist(XA, XB, 'jaccard') - 1``.
+
+    19. ``Y = cdist(XA, XB, 'rogerstanimoto')``
+
+        Computes the Rogers-Tanimoto distance between the boolean
+        vectors. (see `rogerstanimoto` function documentation)
+
+    20. ``Y = cdist(XA, XB, 'russellrao')``
+
+        Computes the Russell-Rao distance between the boolean
+        vectors. (see `russellrao` function documentation)
+
+    21. ``Y = cdist(XA, XB, 'sokalmichener')``
+
+        Computes the Sokal-Michener distance between the boolean
+        vectors. (see `sokalmichener` function documentation)
+
+        .. deprecated:: 1.15.0
+           This metric is deprecated and will be removed in SciPy 1.17.0.
+           Replace usage of ``cdist(XA, XB, 'sokalmichener')`` with
+           ``cdist(XA, XB, 'rogerstanimoto')``.
+
+    22. ``Y = cdist(XA, XB, 'sokalsneath')``
+
+        Computes the Sokal-Sneath distance between the vectors. (see
+        `sokalsneath` function documentation)
+
+    23. ``Y = cdist(XA, XB, f)``
+
+        Computes the distance between all pairs of vectors in X
+        using the user supplied 2-arity function f. For example,
+        Euclidean distance between the vectors could be computed
+        as follows::
+
+          dm = cdist(XA, XB, lambda u, v: np.sqrt(((u-v)**2).sum()))
+
+        Note that you should avoid passing a reference to one of
+        the distance functions defined in this library. For example,::
+
+          dm = cdist(XA, XB, sokalsneath)
+
+        would calculate the pair-wise distances between the vectors in
+        X using the Python function `sokalsneath`. This would result in
+        sokalsneath being called :math:`{n \\choose 2}` times, which
+        is inefficient. Instead, the optimized C version is more
+        efficient, and we call it using the following syntax::
+
+          dm = cdist(XA, XB, 'sokalsneath')
+
+    Examples
+    --------
+    Find the Euclidean distances between four 2-D coordinates:
+
+    >>> from scipy.spatial import distance
+    >>> import numpy as np
+    >>> coords = [(35.0456, -85.2672),
+    ...           (35.1174, -89.9711),
+    ...           (35.9728, -83.9422),
+    ...           (36.1667, -86.7833)]
+    >>> distance.cdist(coords, coords, 'euclidean')
+    array([[ 0.    ,  4.7044,  1.6172,  1.8856],
+           [ 4.7044,  0.    ,  6.0893,  3.3561],
+           [ 1.6172,  6.0893,  0.    ,  2.8477],
+           [ 1.8856,  3.3561,  2.8477,  0.    ]])
+
+
+    Find the Manhattan distance from a 3-D point to the corners of the unit
+    cube:
+
+    >>> a = np.array([[0, 0, 0],
+    ...               [0, 0, 1],
+    ...               [0, 1, 0],
+    ...               [0, 1, 1],
+    ...               [1, 0, 0],
+    ...               [1, 0, 1],
+    ...               [1, 1, 0],
+    ...               [1, 1, 1]])
+    >>> b = np.array([[ 0.1,  0.2,  0.4]])
+    >>> distance.cdist(a, b, 'cityblock')
+    array([[ 0.7],
+           [ 0.9],
+           [ 1.3],
+           [ 1.5],
+           [ 1.5],
+           [ 1.7],
+           [ 2.1],
+           [ 2.3]])
+
+    """
+    # You can also call this as:
+    #     Y = cdist(XA, XB, 'test_abc')
+    # where 'abc' is the metric being tested.  This computes the distance
+    # between all pairs of vectors in XA and XB using the distance metric 'abc'
+    # but with a more succinct, verifiable, but less efficient implementation.
+
+    XA = np.asarray(XA)
+    XB = np.asarray(XB)
+
+    s = XA.shape
+    sB = XB.shape
+
+    if len(s) != 2:
+        raise ValueError('XA must be a 2-dimensional array.')
+    if len(sB) != 2:
+        raise ValueError('XB must be a 2-dimensional array.')
+    if s[1] != sB[1]:
+        raise ValueError('XA and XB must have the same number of columns '
+                         '(i.e. feature dimension.)')
+
+    mA = s[0]
+    mB = sB[0]
+    n = s[1]
+
+    if callable(metric):
+        mstr = getattr(metric, '__name__', 'Unknown')
+        metric_info = _METRIC_ALIAS.get(mstr, None)
+        if metric_info is not None:
+            XA, XB, typ, kwargs = _validate_cdist_input(
+                XA, XB, mA, mB, n, metric_info, **kwargs)
+        return _cdist_callable(XA, XB, metric=metric, out=out, **kwargs)
+    elif isinstance(metric, str):
+        mstr = metric.lower()
+        metric_info = _METRIC_ALIAS.get(mstr, None)
+        if metric_info is not None:
+            cdist_fn = metric_info.cdist_func
+            return cdist_fn(XA, XB, out=out, **kwargs)
+        elif mstr.startswith("test_"):
+            metric_info = _TEST_METRICS.get(mstr, None)
+            if metric_info is None:
+                raise ValueError(f'Unknown "Test" Distance Metric: {mstr[5:]}')
+            XA, XB, typ, kwargs = _validate_cdist_input(
+                XA, XB, mA, mB, n, metric_info, **kwargs)
+            return _cdist_callable(
+                XA, XB, metric=metric_info.dist_func, out=out, **kwargs)
+        else:
+            raise ValueError(f'Unknown Distance Metric: {mstr}')
+    else:
+        raise TypeError('2nd argument metric must be a string identifier '
+                        'or a function.')
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/distance.pyi b/python_embeded/Lib/site-packages/scipy/spatial/distance.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..9ea0cc775151da1459cc25d08616157a4179a2fa
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/distance.pyi
@@ -0,0 +1,210 @@
+from typing import (overload, Any, SupportsFloat, Literal, Protocol, SupportsIndex)
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+
+# Anything that can be parsed by `np.float64.__init__` and is thus
+# compatible with `ndarray.__setitem__` (for a float64 array)
+_FloatValue = None | str | bytes | SupportsFloat | SupportsIndex
+
+class _MetricCallback1(Protocol):
+    def __call__(
+        self, __XA: NDArray[Any], __XB: NDArray[Any]
+    ) -> _FloatValue: ...
+
+class _MetricCallback2(Protocol):
+    def __call__(
+        self, __XA: NDArray[Any], __XB: NDArray[Any], **kwargs: Any
+    ) -> _FloatValue: ...
+
+# TODO: Use a single protocol with a parameter specification variable
+# once available (PEP 612)
+_MetricCallback = _MetricCallback1 | _MetricCallback2
+
+_MetricKind = Literal[
+    'braycurtis',
+    'canberra',
+    'chebychev', 'chebyshev', 'cheby', 'cheb', 'ch',
+    'cityblock', 'cblock', 'cb', 'c',
+    'correlation', 'co',
+    'cosine', 'cos',
+    'dice',
+    'euclidean', 'euclid', 'eu', 'e',
+    'hamming', 'hamm', 'ha', 'h',
+    'minkowski', 'mi', 'm', 'pnorm',
+    'jaccard', 'jacc', 'ja', 'j',
+    'jensenshannon', 'js',
+    'kulczynski1',
+    'mahalanobis', 'mahal', 'mah',
+    'rogerstanimoto',
+    'russellrao',
+    'seuclidean', 'se', 's',
+    'sokalmichener',
+    'sokalsneath',
+    'sqeuclidean', 'sqe', 'sqeuclid',
+    'yule',
+]
+
+# Function annotations
+
+def braycurtis(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def canberra(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+# TODO: Add `metric`-specific overloads
+# Returns a float64 or float128 array, depending on the input dtype
+@overload
+def cdist(
+    XA: ArrayLike,
+    XB: ArrayLike,
+    metric: _MetricKind = ...,
+    *,
+    out: None | NDArray[np.floating[Any]] = ...,
+    p: float = ...,
+    w: ArrayLike | None = ...,
+    V: ArrayLike | None = ...,
+    VI: ArrayLike | None = ...,
+) -> NDArray[np.floating[Any]]: ...
+@overload
+def cdist(
+    XA: ArrayLike,
+    XB: ArrayLike,
+    metric: _MetricCallback,
+    *,
+    out: None | NDArray[np.floating[Any]] = ...,
+    **kwargs: Any,
+) -> NDArray[np.floating[Any]]: ...
+
+# TODO: Wait for dtype support; the return type is
+# dependent on the input arrays dtype
+def chebyshev(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> Any: ...
+
+# TODO: Wait for dtype support; the return type is
+# dependent on the input arrays dtype
+def cityblock(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> Any: ...
+
+def correlation(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ..., centered: bool = ...
+) -> np.float64: ...
+
+def cosine(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def dice(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
+
+def directed_hausdorff(
+    u: ArrayLike, v: ArrayLike, seed: int | None = ...
+) -> tuple[float, int, int]: ...
+
+def euclidean(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
+
+def hamming(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def is_valid_dm(
+    D: ArrayLike,
+    tol: float = ...,
+    throw: bool = ...,
+    name: str | None = ...,
+    warning: bool = ...,
+) -> bool: ...
+
+def is_valid_y(
+    y: ArrayLike,
+    warning: bool = ...,
+    throw: bool = ...,
+    name: str | None = ...,
+) -> bool: ...
+
+def jaccard(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def jensenshannon(
+    p: ArrayLike, q: ArrayLike, base: float | None = ...
+) -> np.float64: ...
+
+def kulczynski1(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def mahalanobis(
+    u: ArrayLike, v: ArrayLike, VI: ArrayLike
+) -> np.float64: ...
+
+def minkowski(
+    u: ArrayLike, v: ArrayLike, p: float = ..., w: ArrayLike | None = ...
+) -> float: ...
+
+def num_obs_dm(d: ArrayLike) -> int: ...
+
+def num_obs_y(Y: ArrayLike) -> int: ...
+
+# TODO: Add `metric`-specific overloads
+@overload
+def pdist(
+    X: ArrayLike,
+    metric: _MetricKind = ...,
+    *,
+    out: None | NDArray[np.floating[Any]] = ...,
+    p: float = ...,
+    w: ArrayLike | None = ...,
+    V: ArrayLike | None = ...,
+    VI: ArrayLike | None = ...,
+) -> NDArray[np.floating[Any]]: ...
+@overload
+def pdist(
+    X: ArrayLike,
+    metric: _MetricCallback,
+    *,
+    out: None | NDArray[np.floating[Any]] = ...,
+    **kwargs: Any,
+) -> NDArray[np.floating[Any]]: ...
+
+def seuclidean(
+    u: ArrayLike, v: ArrayLike, V: ArrayLike
+) -> float: ...
+
+def sokalmichener(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
+
+def sokalsneath(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def sqeuclidean(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> np.float64: ...
+
+def squareform(
+    X: ArrayLike,
+    force: Literal["no", "tomatrix", "tovector"] = ...,
+    checks: bool = ...,
+) -> NDArray[Any]: ...
+
+def rogerstanimoto(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
+
+def russellrao(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
+
+def yule(
+    u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ...
+) -> float: ...
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/kdtree.py b/python_embeded/Lib/site-packages/scipy/spatial/kdtree.py
new file mode 100644
index 0000000000000000000000000000000000000000..932feb1da0eab25e5311d77032183f713e5a841a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/kdtree.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.spatial` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'KDTree',
+    'Rectangle',
+    'cKDTree',
+    'distance_matrix',
+    'minkowski_distance',
+    'minkowski_distance_p',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="spatial", module="kdtree",
+                                   private_modules=["_kdtree"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/spatial/qhull.py b/python_embeded/Lib/site-packages/scipy/spatial/qhull.py
new file mode 100644
index 0000000000000000000000000000000000000000..0389b5e9f4f232aa83acde8abbc47b4d12de17fe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/spatial/qhull.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.spatial` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'ConvexHull',
+    'Delaunay',
+    'HalfspaceIntersection',
+    'QhullError',
+    'Voronoi',
+    'tsearch',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="spatial", module="qhull",
+                                   private_modules=["_qhull"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/special/__init__.pxd b/python_embeded/Lib/site-packages/scipy/special/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..66607001dd89782f2aa400a95ad8d420d566fb8d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/special/__init__.pxd
@@ -0,0 +1 @@
+from scipy.special cimport cython_special
diff --git a/python_embeded/Lib/site-packages/scipy/special/__init__.py b/python_embeded/Lib/site-packages/scipy/special/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5587f94defa2c35a66d0fa171a7db1a997d04e89
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_add_newdocs.py b/python_embeded/Lib/site-packages/scipy/special/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..2030b50c370e9bfc7e03101abbd29f49748a2faf
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_basic.py b/python_embeded/Lib/site-packages/scipy/special/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac715aff224385e48055eb9185a6eb24d1f93755
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_comb.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_comb.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..62733e481a13a2d4cc42442361022a641943d4bb
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_comb.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_ellip_harm.py b/python_embeded/Lib/site-packages/scipy/special/_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..683e810c22cfe35470b60c7238728ae35950f223
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ellip_harm_2.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_ellip_harm_2.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..286a23b959e9c7778f2816ee5bb369ffc83c40c8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_ellip_harm_2.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_gufuncs.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_gufuncs.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..4f7c8bd48178ff03679d927994b8e5af62083473
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_gufuncs.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_input_validation.py b/python_embeded/Lib/site-packages/scipy/special/_input_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1eeaed161e2cfecd30fb9a0655bd26861751a46
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_lambertw.py b/python_embeded/Lib/site-packages/scipy/special/_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7fe4d1e399e883cf21de179715ff4986585d695
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_logsumexp.py b/python_embeded/Lib/site-packages/scipy/special/_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..48b25a0ba314f4b0c37a466b96e54d18575b3c4f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_mptestutils.py b/python_embeded/Lib/site-packages/scipy/special/_mptestutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5031c1097a0be444d60796358571466a0a6108f7
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_multiufuncs.py b/python_embeded/Lib/site-packages/scipy/special/_multiufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8e536906f162bdf3c27cd12e0cff5f6b4ed3aa2
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_orthogonal.py b/python_embeded/Lib/site-packages/scipy/special/_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..47c0ba6df228f25417906b9ef0d42044285b1727
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_orthogonal.pyi b/python_embeded/Lib/site-packages/scipy/special/_orthogonal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..bd6ec6ada05c648031c86719a7f4448f8da715ab
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_sf_error.py b/python_embeded/Lib/site-packages/scipy/special/_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa5e1fa7dedd8974f51083b929bf8e2e779e0679
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_specfun.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_specfun.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..97d8175a4a0ea76c63c2b8a892e1012e1e7763fb
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_specfun.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_special_ufuncs.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_special_ufuncs.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..a530c656f29c757ec31a02550bbeb7f92c2979d8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_special_ufuncs.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_spfun_stats.py b/python_embeded/Lib/site-packages/scipy/special/_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..666ab904f66502203f0a9e2141e8f7cf80d77f7b
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_spherical_bessel.py b/python_embeded/Lib/site-packages/scipy/special/_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e585080cdb6527e819d5b07af06f356099c29bd
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_support_alternative_backends.py b/python_embeded/Lib/site-packages/scipy/special/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0b119abd683cc99f0ffd0bb3ffc815df1804d73
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_test_internal.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_test_internal.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..a8cbd11d5f9946f674989942a49109d6144fa6f8
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_test_internal.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_test_internal.pyi b/python_embeded/Lib/site-packages/scipy/special/_test_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..63f5aa17bab4cc7e29d8dbe151cf075b828b89c3
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_testutils.py b/python_embeded/Lib/site-packages/scipy/special/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..78c9922765ab38606760e9873d1df1b74b356bfc
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_ufuncs.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..c56ec6a0537cc4a7351d634ff3c145f6eee96333
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_ufuncs.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_ufuncs.pyi b/python_embeded/Lib/site-packages/scipy/special/_ufuncs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8424b41858f1e46446c417fc4ee18328d8943850
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs.pyx b/python_embeded/Lib/site-packages/scipy/special/_ufuncs.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..c20130991997f68cf73026e75a43183d6c3b79f5
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..35d7841e7b6ec204b04aedba126308433a0c1312
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.pxd b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..8fb7ac8d774561b2e4001b5b542a5d7b9d829480
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.pyx b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..f943c88ade76df1a6e1791d4f4393fc56bcf297f
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx_defs.h b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_cxx_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..2189316433d9c44ef72fe4b837d45b24947275aa
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/_ufuncs_defs.h b/python_embeded/Lib/site-packages/scipy/special/_ufuncs_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..d2893fa37208624e30ffaedaf3e92ba28585d562
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/add_newdocs.py b/python_embeded/Lib/site-packages/scipy/special/add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c2de826bdc0fa7697c222dae6e5f5f6925aecb7
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/basic.py b/python_embeded/Lib/site-packages/scipy/special/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dea0a87fafcd82db5e3bfd58744d556eee68e49
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/cython_special.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/special/cython_special.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..8b918f2732301a57ec57485ecf80e0bd531707e3
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/cython_special.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/cython_special.pxd b/python_embeded/Lib/site-packages/scipy/special/cython_special.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..1f1b19d3608568649fe778dbd9f9310998256894
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/cython_special.pyi b/python_embeded/Lib/site-packages/scipy/special/cython_special.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..535e8b808f8b8d0131513da140643f5048a8246d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/special/cython_special.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name) -> Any: ...
diff --git a/python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll.a b/python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..18401302d52e0926855b0b5b5611b14473494f05
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/special/orthogonal.py b/python_embeded/Lib/site-packages/scipy/special/orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..c817f8093b0a51c5dabf90c5ae82f7ca3c622ad8
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/sf_error.py b/python_embeded/Lib/site-packages/scipy/special/sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dfa720626371915bd359693cda3b649a6867d21
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/specfun.py b/python_embeded/Lib/site-packages/scipy/special/specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4e58cc2ec2b1cab2151910b5432b11709dd62ca
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/special/spfun_stats.py b/python_embeded/Lib/site-packages/scipy/special/spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..2013535c2c523ed7596275238853c4feb1653feb
--- /dev/null
+++ b/python_embeded/Lib/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/python_embeded/Lib/site-packages/scipy/stats/__init__.py b/python_embeded/Lib/site-packages/scipy/stats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..810118f5631b2765d8e2253ec9f7372536e58ab8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/__init__.py
@@ -0,0 +1,667 @@
+"""
+.. _statsrefmanual:
+
+==========================================
+Statistical functions (:mod:`scipy.stats`)
+==========================================
+
+.. currentmodule:: scipy.stats
+
+This module contains a large number of probability distributions,
+summary and frequency statistics, correlation functions and statistical
+tests, masked statistics, kernel density estimation, quasi-Monte Carlo
+functionality, and more.
+
+Statistics is a very large area, and there are topics that are out of scope
+for SciPy and are covered by other packages. Some of the most important ones
+are:
+
+- `statsmodels `__:
+  regression, linear models, time series analysis, extensions to topics
+  also covered by ``scipy.stats``.
+- `Pandas `__: tabular data, time series
+  functionality, interfaces to other statistical languages.
+- `PyMC `__: Bayesian statistical
+  modeling, probabilistic machine learning.
+- `scikit-learn `__: classification, regression,
+  model selection.
+- `Seaborn `__: statistical data visualization.
+- `rpy2 `__: Python to R bridge.
+
+
+Probability distributions
+=========================
+
+Each univariate distribution is an instance of a subclass of `rv_continuous`
+(`rv_discrete` for discrete distributions):
+
+.. autosummary::
+   :toctree: generated/
+
+   rv_continuous
+   rv_discrete
+   rv_histogram
+
+Continuous distributions
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   alpha             -- Alpha
+   anglit            -- Anglit
+   arcsine           -- Arcsine
+   argus             -- Argus
+   beta              -- Beta
+   betaprime         -- Beta Prime
+   bradford          -- Bradford
+   burr              -- Burr (Type III)
+   burr12            -- Burr (Type XII)
+   cauchy            -- Cauchy
+   chi               -- Chi
+   chi2              -- Chi-squared
+   cosine            -- Cosine
+   crystalball       -- Crystalball
+   dgamma            -- Double Gamma
+   dpareto_lognorm   -- Double Pareto Lognormal
+   dweibull          -- Double Weibull
+   erlang            -- Erlang
+   expon             -- Exponential
+   exponnorm         -- Exponentially Modified Normal
+   exponweib         -- Exponentiated Weibull
+   exponpow          -- Exponential Power
+   f                 -- F (Snecdor F)
+   fatiguelife       -- Fatigue Life (Birnbaum-Saunders)
+   fisk              -- Fisk
+   foldcauchy        -- Folded Cauchy
+   foldnorm          -- Folded Normal
+   genlogistic       -- Generalized Logistic
+   gennorm           -- Generalized normal
+   genpareto         -- Generalized Pareto
+   genexpon          -- Generalized Exponential
+   genextreme        -- Generalized Extreme Value
+   gausshyper        -- Gauss Hypergeometric
+   gamma             -- Gamma
+   gengamma          -- Generalized gamma
+   genhalflogistic   -- Generalized Half Logistic
+   genhyperbolic     -- Generalized Hyperbolic
+   geninvgauss       -- Generalized Inverse Gaussian
+   gibrat            -- Gibrat
+   gompertz          -- Gompertz (Truncated Gumbel)
+   gumbel_r          -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I
+   gumbel_l          -- Left Sided Gumbel, etc.
+   halfcauchy        -- Half Cauchy
+   halflogistic      -- Half Logistic
+   halfnorm          -- Half Normal
+   halfgennorm       -- Generalized Half Normal
+   hypsecant         -- Hyperbolic Secant
+   invgamma          -- Inverse Gamma
+   invgauss          -- Inverse Gaussian
+   invweibull        -- Inverse Weibull
+   irwinhall         -- Irwin-Hall
+   jf_skew_t         -- Jones and Faddy Skew-T
+   johnsonsb         -- Johnson SB
+   johnsonsu         -- Johnson SU
+   kappa4            -- Kappa 4 parameter
+   kappa3            -- Kappa 3 parameter
+   ksone             -- Distribution of Kolmogorov-Smirnov one-sided test statistic
+   kstwo             -- Distribution of Kolmogorov-Smirnov two-sided test statistic
+   kstwobign         -- Limiting Distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
+   landau            -- Landau
+   laplace           -- Laplace
+   laplace_asymmetric    -- Asymmetric Laplace
+   levy              -- Levy
+   levy_l
+   levy_stable
+   logistic          -- Logistic
+   loggamma          -- Log-Gamma
+   loglaplace        -- Log-Laplace (Log Double Exponential)
+   lognorm           -- Log-Normal
+   loguniform        -- Log-Uniform
+   lomax             -- Lomax (Pareto of the second kind)
+   maxwell           -- Maxwell
+   mielke            -- Mielke's Beta-Kappa
+   moyal             -- Moyal
+   nakagami          -- Nakagami
+   ncx2              -- Non-central chi-squared
+   ncf               -- Non-central F
+   nct               -- Non-central Student's T
+   norm              -- Normal (Gaussian)
+   norminvgauss      -- Normal Inverse Gaussian
+   pareto            -- Pareto
+   pearson3          -- Pearson type III
+   powerlaw          -- Power-function
+   powerlognorm      -- Power log normal
+   powernorm         -- Power normal
+   rdist             -- R-distribution
+   rayleigh          -- Rayleigh
+   rel_breitwigner   -- Relativistic Breit-Wigner
+   rice              -- Rice
+   recipinvgauss     -- Reciprocal Inverse Gaussian
+   semicircular      -- Semicircular
+   skewcauchy        -- Skew Cauchy
+   skewnorm          -- Skew normal
+   studentized_range    -- Studentized Range
+   t                 -- Student's T
+   trapezoid         -- Trapezoidal
+   triang            -- Triangular
+   truncexpon        -- Truncated Exponential
+   truncnorm         -- Truncated Normal
+   truncpareto       -- Truncated Pareto
+   truncweibull_min  -- Truncated minimum Weibull distribution
+   tukeylambda       -- Tukey-Lambda
+   uniform           -- Uniform
+   vonmises          -- Von-Mises (Circular)
+   vonmises_line     -- Von-Mises (Line)
+   wald              -- Wald
+   weibull_min       -- Minimum Weibull (see Frechet)
+   weibull_max       -- Maximum Weibull (see Frechet)
+   wrapcauchy        -- Wrapped Cauchy
+
+The ``fit`` method of the univariate continuous distributions uses
+maximum likelihood estimation to fit the distribution to a data set.
+The ``fit`` method can accept regular data or *censored data*.
+Censored data is represented with instances of the `CensoredData`
+class.
+
+.. autosummary::
+   :toctree: generated/
+
+   CensoredData
+
+
+Multivariate distributions
+--------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   multivariate_normal    -- Multivariate normal distribution
+   matrix_normal          -- Matrix normal distribution
+   dirichlet              -- Dirichlet
+   dirichlet_multinomial  -- Dirichlet multinomial distribution
+   wishart                -- Wishart
+   invwishart             -- Inverse Wishart
+   multinomial            -- Multinomial distribution
+   special_ortho_group    -- SO(N) group
+   ortho_group            -- O(N) group
+   unitary_group          -- U(N) group
+   random_correlation     -- random correlation matrices
+   multivariate_t         -- Multivariate t-distribution
+   multivariate_hypergeom -- Multivariate hypergeometric distribution
+   normal_inverse_gamma   -- Normal-inverse-gamma distribution
+   random_table           -- Distribution of random tables with given marginals
+   uniform_direction      -- Uniform distribution on S(N-1)
+   vonmises_fisher        -- Von Mises-Fisher distribution
+
+`scipy.stats.multivariate_normal` methods accept instances
+of the following class to represent the covariance.
+
+.. autosummary::
+   :toctree: generated/
+
+   Covariance             -- Representation of a covariance matrix
+
+
+Discrete distributions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   bernoulli                -- Bernoulli
+   betabinom                -- Beta-Binomial
+   betanbinom               -- Beta-Negative Binomial
+   binom                    -- Binomial
+   boltzmann                -- Boltzmann (Truncated Discrete Exponential)
+   dlaplace                 -- Discrete Laplacian
+   geom                     -- Geometric
+   hypergeom                -- Hypergeometric
+   logser                   -- Logarithmic (Log-Series, Series)
+   nbinom                   -- Negative Binomial
+   nchypergeom_fisher       -- Fisher's Noncentral Hypergeometric
+   nchypergeom_wallenius    -- Wallenius's Noncentral Hypergeometric
+   nhypergeom               -- Negative Hypergeometric
+   planck                   -- Planck (Discrete Exponential)
+   poisson                  -- Poisson
+   poisson_binom            -- Poisson Binomial
+   randint                  -- Discrete Uniform
+   skellam                  -- Skellam
+   yulesimon                -- Yule-Simon
+   zipf                     -- Zipf (Zeta)
+   zipfian                  -- Zipfian
+
+
+An overview of statistical functions is given below.  Many of these functions
+have a similar version in `scipy.stats.mstats` which work for masked arrays.
+
+Summary statistics
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   describe          -- Descriptive statistics
+   gmean             -- Geometric mean
+   hmean             -- Harmonic mean
+   pmean             -- Power mean
+   kurtosis          -- Fisher or Pearson kurtosis
+   mode              -- Modal value
+   moment            -- Central moment
+   lmoment
+   expectile         -- Expectile
+   skew              -- Skewness
+   kstat             --
+   kstatvar          --
+   tmean             -- Truncated arithmetic mean
+   tvar              -- Truncated variance
+   tmin              --
+   tmax              --
+   tstd              --
+   tsem              --
+   variation         -- Coefficient of variation
+   find_repeats
+   rankdata
+   tiecorrect
+   trim_mean
+   gstd              -- Geometric Standard Deviation
+   iqr
+   sem
+   bayes_mvs
+   mvsdist
+   entropy
+   differential_entropy
+   median_abs_deviation
+
+Frequency statistics
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   cumfreq
+   percentileofscore
+   scoreatpercentile
+   relfreq
+
+.. autosummary::
+   :toctree: generated/
+
+   binned_statistic     -- Compute a binned statistic for a set of data.
+   binned_statistic_2d  -- Compute a 2-D binned statistic for a set of data.
+   binned_statistic_dd  -- Compute a d-D binned statistic for a set of data.
+
+.. _hypotests:
+
+Hypothesis Tests and related functions
+======================================
+SciPy has many functions for performing hypothesis tests that return a
+test statistic and a p-value, and several of them return confidence intervals
+and/or other related information.
+
+The headings below are based on common uses of the functions within, but due to
+the wide variety of statistical procedures, any attempt at coarse-grained
+categorization will be imperfect. Also, note that tests within the same heading
+are not interchangeable in general (e.g. many have different distributional
+assumptions).
+
+One Sample Tests / Paired Sample Tests
+--------------------------------------
+One sample tests are typically used to assess whether a single sample was
+drawn from a specified distribution or a distribution with specified properties
+(e.g. zero mean).
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_1samp
+   binomtest
+   quantile_test
+   skewtest
+   kurtosistest
+   normaltest
+   jarque_bera
+   shapiro
+   anderson
+   cramervonmises
+   ks_1samp
+   goodness_of_fit
+   chisquare
+   power_divergence
+
+Paired sample tests are often used to assess whether two samples were drawn
+from the same distribution; they differ from the independent sample tests below
+in that each observation in one sample is treated as paired with a
+closely-related observation in the other sample (e.g. when environmental
+factors are controlled between observations within a pair but not among pairs).
+They can also be interpreted or used as one-sample tests (e.g. tests on the
+mean or median of *differences* between paired observations).
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_rel
+   wilcoxon
+
+Association/Correlation Tests
+-----------------------------
+
+These tests are often used to assess whether there is a relationship (e.g.
+linear) between paired observations in multiple samples or among the
+coordinates of multivariate observations.
+
+.. autosummary::
+   :toctree: generated/
+
+   linregress
+   pearsonr
+   spearmanr
+   pointbiserialr
+   kendalltau
+   chatterjeexi
+   weightedtau
+   somersd
+   siegelslopes
+   theilslopes
+   page_trend_test
+   multiscale_graphcorr
+
+These association tests and are to work with samples in the form of contingency
+tables. Supporting functions are available in `scipy.stats.contingency`.
+
+.. autosummary::
+   :toctree: generated/
+
+   chi2_contingency
+   fisher_exact
+   barnard_exact
+   boschloo_exact
+
+Independent Sample Tests
+------------------------
+Independent sample tests are typically used to assess whether multiple samples
+were independently drawn from the same distribution or different distributions
+with a shared property (e.g. equal means).
+
+Some tests are specifically for comparing two samples.
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_ind_from_stats
+   poisson_means_test
+   ttest_ind
+   mannwhitneyu
+   bws_test
+   ranksums
+   brunnermunzel
+   mood
+   ansari
+   cramervonmises_2samp
+   epps_singleton_2samp
+   ks_2samp
+   kstest
+
+Others are generalized to multiple samples.
+
+.. autosummary::
+   :toctree: generated/
+
+   f_oneway
+   tukey_hsd
+   dunnett
+   kruskal
+   alexandergovern
+   fligner
+   levene
+   bartlett
+   median_test
+   friedmanchisquare
+   anderson_ksamp
+
+Resampling and Monte Carlo Methods
+----------------------------------
+The following functions can reproduce the p-value and confidence interval
+results of most of the functions above, and often produce accurate results in a
+wider variety of conditions. They can also be used to perform hypothesis tests
+and generate confidence intervals for custom statistics. This flexibility comes
+at the cost of greater computational requirements and stochastic results.
+
+.. autosummary::
+   :toctree: generated/
+
+   monte_carlo_test
+   permutation_test
+   bootstrap
+   power
+
+Instances of the following object can be passed into some hypothesis test
+functions to perform a resampling or Monte Carlo version of the hypothesis
+test.
+
+.. autosummary::
+   :toctree: generated/
+
+   MonteCarloMethod
+   PermutationMethod
+   BootstrapMethod
+
+Multiple Hypothesis Testing and Meta-Analysis
+---------------------------------------------
+These functions are for assessing the results of individual tests as a whole.
+Functions for performing specific multiple hypothesis tests (e.g. post hoc
+tests) are listed above.
+
+.. autosummary::
+   :toctree: generated/
+
+   combine_pvalues
+   false_discovery_control
+
+
+The following functions are related to the tests above but do not belong in the
+above categories.
+
+Random Variables
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   make_distribution
+   Normal
+   Uniform
+   Mixture
+   order_statistic
+   truncate
+   abs
+   exp
+   log
+
+Quasi-Monte Carlo
+=================
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.qmc
+
+Contingency Tables
+==================
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.contingency
+
+Masked statistics functions
+===========================
+
+.. toctree::
+
+   stats.mstats
+
+
+Other statistical functionality
+===============================
+
+Transformations
+---------------
+
+.. autosummary::
+   :toctree: generated/
+
+   boxcox
+   boxcox_normmax
+   boxcox_llf
+   yeojohnson
+   yeojohnson_normmax
+   yeojohnson_llf
+   obrientransform
+   sigmaclip
+   trimboth
+   trim1
+   zmap
+   zscore
+   gzscore
+
+Statistical distances
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   wasserstein_distance
+   wasserstein_distance_nd
+   energy_distance
+
+Sampling
+--------
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.sampling
+
+Fitting / Survival Analysis
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   fit
+   ecdf
+   logrank
+
+Directional statistical functions
+---------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   directional_stats
+   circmean
+   circvar
+   circstd
+
+Sensitivity Analysis
+--------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sobol_indices
+
+Plot-tests
+----------
+
+.. autosummary::
+   :toctree: generated/
+
+   ppcc_max
+   ppcc_plot
+   probplot
+   boxcox_normplot
+   yeojohnson_normplot
+
+Univariate and multivariate kernel density estimation
+-----------------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   gaussian_kde
+
+Warnings / Errors used in :mod:`scipy.stats`
+--------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   DegenerateDataWarning
+   ConstantInputWarning
+   NearConstantInputWarning
+   FitError
+
+Result classes used in :mod:`scipy.stats`
+-----------------------------------------
+
+.. warning::
+
+    These classes are private, but they are included here because instances
+    of them are returned by other statistical functions. User import and
+    instantiation is not supported.
+
+.. toctree::
+   :maxdepth: 2
+
+   stats._result_classes
+
+"""  # noqa: E501
+
+from ._warnings_errors import (ConstantInputWarning, NearConstantInputWarning,
+                               DegenerateDataWarning, FitError)
+from ._stats_py import *
+from ._variation import variation
+from .distributions import *
+from ._morestats import *
+from ._multicomp import *
+from ._binomtest import binomtest
+from ._binned_statistic import *
+from ._kde import gaussian_kde
+from . import mstats
+from . import qmc
+from ._multivariate import *
+from . import contingency
+from .contingency import chi2_contingency
+from ._censored_data import CensoredData
+from ._resampling import (bootstrap, monte_carlo_test, permutation_test, power,
+                          MonteCarloMethod, PermutationMethod, BootstrapMethod)
+from ._entropy import *
+from ._hypotests import *
+from ._page_trend_test import page_trend_test
+from ._mannwhitneyu import mannwhitneyu
+from ._bws_test import bws_test
+from ._fit import fit, goodness_of_fit
+from ._covariance import Covariance
+from ._sensitivity_analysis import *
+from ._survival import *
+from ._distribution_infrastructure import (
+    make_distribution, Mixture, order_statistic, truncate, exp, log, abs
+)
+from ._new_distributions import Normal, Uniform
+from ._mgc import multiscale_graphcorr
+from ._correlation import chatterjeexi
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    biasedurn, kde, morestats, mstats_basic, mstats_extras, mvn, stats
+)
+
+
+__all__ = [s for s in dir() if not s.startswith("_")]  # Remove dunders.
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_ansari_swilk_statistics.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_ansari_swilk_statistics.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..61016562f791d92b364c30317dd8a4db35aff5e7
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_ansari_swilk_statistics.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_axis_nan_policy.py b/python_embeded/Lib/site-packages/scipy/stats/_axis_nan_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..42f545b234bc943df6d8dbbb38028ee4f8975651
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_axis_nan_policy.py
@@ -0,0 +1,699 @@
+# Many scipy.stats functions support `axis` and `nan_policy` parameters.
+# When the two are combined, it can be tricky to get all the behavior just
+# right. This file contains utility functions useful for scipy.stats functions
+# that support `axis` and `nan_policy`, including a decorator that
+# automatically adds `axis` and `nan_policy` arguments to a function.
+
+import warnings
+import numpy as np
+from functools import wraps
+from scipy._lib._docscrape import FunctionDoc, Parameter
+from scipy._lib._util import _contains_nan, AxisError, _get_nan
+from scipy._lib._array_api import array_namespace, is_numpy
+
+import inspect
+
+too_small_1d_not_omit = (
+    "One or more sample arguments is too small; all "
+    "returned values will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_1d_omit = (
+    "After omitting NaNs, one or more sample arguments "
+    "is too small; all returned values will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_nd_not_omit = (
+    "All axis-slices of one or more sample arguments are "
+    "too small; all elements of returned arrays will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_nd_omit = (
+    "After omitting NaNs, one or more axis-slices of one "
+    "or more sample arguments is too small; corresponding "
+    "elements of returned arrays will be NaN. "
+    "See documentation for sample size requirements.")
+
+class SmallSampleWarning(RuntimeWarning):
+    pass
+
+
+def _broadcast_arrays(arrays, axis=None, xp=None):
+    """
+    Broadcast shapes of arrays, ignoring incompatibility of specified axes
+    """
+    if not arrays:
+        return arrays
+    xp = array_namespace(*arrays) if xp is None else xp
+    arrays = [xp.asarray(arr) for arr in arrays]
+    shapes = [arr.shape for arr in arrays]
+    new_shapes = _broadcast_shapes(shapes, axis)
+    if axis is None:
+        new_shapes = [new_shapes]*len(arrays)
+    return [xp.broadcast_to(array, new_shape)
+            for array, new_shape in zip(arrays, new_shapes)]
+
+
+def _broadcast_shapes(shapes, axis=None):
+    """
+    Broadcast shapes, ignoring incompatibility of specified axes
+    """
+    if not shapes:
+        return shapes
+
+    # input validation
+    if axis is not None:
+        axis = np.atleast_1d(axis)
+        message = '`axis` must be an integer, a tuple of integers, or `None`.'
+        try:
+            with np.errstate(invalid='ignore'):
+                axis_int = axis.astype(int)
+        except ValueError as e:
+            raise AxisError(message) from e
+        if not np.array_equal(axis_int, axis):
+            raise AxisError(message)
+        axis = axis_int
+
+    # First, ensure all shapes have same number of dimensions by prepending 1s.
+    n_dims = max([len(shape) for shape in shapes])
+    new_shapes = np.ones((len(shapes), n_dims), dtype=int)
+    for row, shape in zip(new_shapes, shapes):
+        row[len(row)-len(shape):] = shape  # can't use negative indices (-0:)
+
+    # Remove the shape elements of the axes to be ignored, but remember them.
+    if axis is not None:
+        axis[axis < 0] = n_dims + axis[axis < 0]
+        axis = np.sort(axis)
+        if axis[-1] >= n_dims or axis[0] < 0:
+            message = (f"`axis` is out of bounds "
+                       f"for array of dimension {n_dims}")
+            raise AxisError(message)
+
+        if len(np.unique(axis)) != len(axis):
+            raise AxisError("`axis` must contain only distinct elements")
+
+        removed_shapes = new_shapes[:, axis]
+        new_shapes = np.delete(new_shapes, axis, axis=1)
+
+    # If arrays are broadcastable, shape elements that are 1 may be replaced
+    # with a corresponding non-1 shape element. Assuming arrays are
+    # broadcastable, that final shape element can be found with:
+    new_shape = np.max(new_shapes, axis=0)
+    # except in case of an empty array:
+    new_shape *= new_shapes.all(axis=0)
+
+    # Among all arrays, there can only be one unique non-1 shape element.
+    # Therefore, if any non-1 shape element does not match what we found
+    # above, the arrays must not be broadcastable after all.
+    if np.any(~((new_shapes == 1) | (new_shapes == new_shape))):
+        raise ValueError("Array shapes are incompatible for broadcasting.")
+
+    if axis is not None:
+        # Add back the shape elements that were ignored
+        new_axis = axis - np.arange(len(axis))
+        new_shapes = [tuple(np.insert(new_shape, new_axis, removed_shape))
+                      for removed_shape in removed_shapes]
+        return new_shapes
+    else:
+        return tuple(new_shape)
+
+
+def _broadcast_array_shapes_remove_axis(arrays, axis=None):
+    """
+    Broadcast shapes of arrays, dropping specified axes
+
+    Given a sequence of arrays `arrays` and an integer or tuple `axis`, find
+    the shape of the broadcast result after consuming/dropping `axis`.
+    In other words, return output shape of a typical hypothesis test on
+    `arrays` vectorized along `axis`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._axis_nan_policy import _broadcast_array_shapes_remove_axis
+    >>> a = np.zeros((5, 2, 1))
+    >>> b = np.zeros((9, 3))
+    >>> _broadcast_array_shapes_remove_axis((a, b), 1)
+    (5, 3)
+    """
+    # Note that here, `axis=None` means do not consume/drop any axes - _not_
+    # ravel arrays before broadcasting.
+    shapes = [arr.shape for arr in arrays]
+    return _broadcast_shapes_remove_axis(shapes, axis)
+
+
+def _broadcast_shapes_remove_axis(shapes, axis=None):
+    """
+    Broadcast shapes, dropping specified axes
+
+    Same as _broadcast_array_shapes_remove_axis, but given a sequence
+    of array shapes `shapes` instead of the arrays themselves.
+    """
+    shapes = _broadcast_shapes(shapes, axis)
+    shape = shapes[0]
+    if axis is not None:
+        shape = np.delete(shape, axis)
+    return tuple(shape)
+
+
+def _broadcast_concatenate(arrays, axis, paired=False):
+    """Concatenate arrays along an axis with broadcasting."""
+    arrays = _broadcast_arrays(arrays, axis if not paired else None)
+    res = np.concatenate(arrays, axis=axis)
+    return res
+
+
+# TODO: add support for `axis` tuples
+def _remove_nans(samples, paired):
+    "Remove nans from paired or unpaired 1D samples"
+    # potential optimization: don't copy arrays that don't contain nans
+    if not paired:
+        return [sample[~np.isnan(sample)] for sample in samples]
+
+    # for paired samples, we need to remove the whole pair when any part
+    # has a nan
+    nans = np.isnan(samples[0])
+    for sample in samples[1:]:
+        nans = nans | np.isnan(sample)
+    not_nans = ~nans
+    return [sample[not_nans] for sample in samples]
+
+
+def _remove_sentinel(samples, paired, sentinel):
+    "Remove sentinel values from paired or unpaired 1D samples"
+    # could consolidate with `_remove_nans`, but it's not quite as simple as
+    # passing `sentinel=np.nan` because `(np.nan == np.nan) is False`
+
+    # potential optimization: don't copy arrays that don't contain sentinel
+    if not paired:
+        return [sample[sample != sentinel] for sample in samples]
+
+    # for paired samples, we need to remove the whole pair when any part
+    # has a nan
+    sentinels = (samples[0] == sentinel)
+    for sample in samples[1:]:
+        sentinels = sentinels | (sample == sentinel)
+    not_sentinels = ~sentinels
+    return [sample[not_sentinels] for sample in samples]
+
+
+def _masked_arrays_2_sentinel_arrays(samples):
+    # masked arrays in `samples` are converted to regular arrays, and values
+    # corresponding with masked elements are replaced with a sentinel value
+
+    # return without modifying arrays if none have a mask
+    has_mask = False
+    for sample in samples:
+        mask = getattr(sample, 'mask', False)
+        has_mask = has_mask or np.any(mask)
+    if not has_mask:
+        return samples, None  # None means there is no sentinel value
+
+    # Choose a sentinel value. We can't use `np.nan`, because sentinel (masked)
+    # values are always omitted, but there are different nan policies.
+    dtype = np.result_type(*samples)
+    dtype = dtype if np.issubdtype(dtype, np.number) else np.float64
+    for i in range(len(samples)):
+        # Things get more complicated if the arrays are of different types.
+        # We could have different sentinel values for each array, but
+        # the purpose of this code is convenience, not efficiency.
+        samples[i] = samples[i].astype(dtype, copy=False)
+
+    inexact = np.issubdtype(dtype, np.inexact)
+    info = np.finfo if inexact else np.iinfo
+    max_possible, min_possible = info(dtype).max, info(dtype).min
+    nextafter = np.nextafter if inexact else (lambda x, _: x - 1)
+
+    sentinel = max_possible
+    # For simplicity, min_possible/np.infs are not candidate sentinel values
+    while sentinel > min_possible:
+        for sample in samples:
+            if np.any(sample == sentinel):  # choose a new sentinel value
+                sentinel = nextafter(sentinel, -np.inf)
+                break
+        else:  # when sentinel value is OK, break the while loop
+            break
+    else:
+        message = ("This function replaces masked elements with sentinel "
+                   "values, but the data contains all distinct values of this "
+                   "data type. Consider promoting the dtype to `np.float64`.")
+        raise ValueError(message)
+
+    # replace masked elements with sentinel value
+    out_samples = []
+    for sample in samples:
+        mask = getattr(sample, 'mask', None)
+        if mask is not None:  # turn all masked arrays into sentinel arrays
+            mask = np.broadcast_to(mask, sample.shape)
+            sample = sample.data.copy() if np.any(mask) else sample.data
+            sample = np.asarray(sample)  # `sample.data` could be a memoryview?
+            sample[mask] = sentinel
+        out_samples.append(sample)
+
+    return out_samples, sentinel
+
+
+def _check_empty_inputs(samples, axis):
+    """
+    Check for empty sample; return appropriate output for a vectorized hypotest
+    """
+    # if none of the samples are empty, we need to perform the test
+    if not any(sample.size == 0 for sample in samples):
+        return None
+    # otherwise, the statistic and p-value will be either empty arrays or
+    # arrays with NaNs. Produce the appropriate array and return it.
+    output_shape = _broadcast_array_shapes_remove_axis(samples, axis)
+    output = np.ones(output_shape) * _get_nan(*samples)
+    return output
+
+
+def _add_reduced_axes(res, reduced_axes, keepdims):
+    """
+    Add reduced axes back to all the arrays in the result object
+    if keepdims = True.
+    """
+    return ([np.expand_dims(output, reduced_axes) 
+             if not isinstance(output, int) else output for output in res]
+            if keepdims else res)
+
+
+# Standard docstring / signature entries for `axis`, `nan_policy`, `keepdims`
+_name = 'axis'
+_desc = (
+    """If an int, the axis of the input along which to compute the statistic.
+The statistic of each axis-slice (e.g. row) of the input will appear in a
+corresponding element of the output.
+If ``None``, the input will be raveled before computing the statistic."""
+    .split('\n'))
+
+
+def _get_axis_params(default_axis=0, _name=_name, _desc=_desc):  # bind NOW
+    _type = f"int or None, default: {default_axis}"
+    _axis_parameter_doc = Parameter(_name, _type, _desc)
+    _axis_parameter = inspect.Parameter(_name,
+                                        inspect.Parameter.KEYWORD_ONLY,
+                                        default=default_axis)
+    return _axis_parameter_doc, _axis_parameter
+
+
+_name = 'nan_policy'
+_type = "{'propagate', 'omit', 'raise'}"
+_desc = (
+    """Defines how to handle input NaNs.
+
+- ``propagate``: if a NaN is present in the axis slice (e.g. row) along
+  which the  statistic is computed, the corresponding entry of the output
+  will be NaN.
+- ``omit``: NaNs will be omitted when performing the calculation.
+  If insufficient data remains in the axis slice along which the
+  statistic is computed, the corresponding entry of the output will be
+  NaN.
+- ``raise``: if a NaN is present, a ``ValueError`` will be raised."""
+    .split('\n'))
+_nan_policy_parameter_doc = Parameter(_name, _type, _desc)
+_nan_policy_parameter = inspect.Parameter(_name,
+                                          inspect.Parameter.KEYWORD_ONLY,
+                                          default='propagate')
+
+_name = 'keepdims'
+_type = "bool, default: False"
+_desc = (
+    """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 input array."""
+    .split('\n'))
+_keepdims_parameter_doc = Parameter(_name, _type, _desc)
+_keepdims_parameter = inspect.Parameter(_name,
+                                        inspect.Parameter.KEYWORD_ONLY,
+                                        default=False)
+
+_standard_note_addition = (
+    """\nBeginning in SciPy 1.9, ``np.matrix`` inputs (not recommended for new
+code) are converted to ``np.ndarray`` before the calculation is performed. In
+this case, the output will be a scalar or ``np.ndarray`` of appropriate shape
+rather than a 2D ``np.matrix``. Similarly, while masked elements of masked
+arrays are ignored, the output will be a scalar or ``np.ndarray`` rather than a
+masked array with ``mask=False``.""").split('\n')
+
+
+def _axis_nan_policy_factory(tuple_to_result, default_axis=0,
+                             n_samples=1, paired=False,
+                             result_to_tuple=None, too_small=0,
+                             n_outputs=2, kwd_samples=(), override=None):
+    """Factory for a wrapper that adds axis/nan_policy params to a function.
+
+    Parameters
+    ----------
+    tuple_to_result : callable
+        Callable that returns an object of the type returned by the function
+        being wrapped (e.g. the namedtuple or dataclass returned by a
+        statistical test) provided the separate components (e.g. statistic,
+        pvalue).
+    default_axis : int, default: 0
+        The default value of the axis argument. Standard is 0 except when
+        backwards compatibility demands otherwise (e.g. `None`).
+    n_samples : int or callable, default: 1
+        The number of data samples accepted by the function
+        (e.g. `mannwhitneyu`), a callable that accepts a dictionary of
+        parameters passed into the function and returns the number of data
+        samples (e.g. `wilcoxon`), or `None` to indicate an arbitrary number
+        of samples (e.g. `kruskal`).
+    paired : {False, True}
+        Whether the function being wrapped treats the samples as paired (i.e.
+        corresponding elements of each sample should be considered as different
+        components of the same sample.)
+    result_to_tuple : callable, optional
+        Function that unpacks the results of the function being wrapped into
+        a tuple. This is essentially the inverse of `tuple_to_result`. Default
+        is `None`, which is appropriate for statistical tests that return a
+        statistic, pvalue tuple (rather than, e.g., a non-iterable datalass).
+    too_small : int or callable, default: 0
+        The largest unnacceptably small sample for the function being wrapped.
+        For example, some functions require samples of size two or more or they
+        raise an error. This argument prevents the error from being raised when
+        input is not 1D and instead places a NaN in the corresponding element
+        of the result. If callable, it must accept a list of samples, axis,
+        and a dictionary of keyword arguments passed to the wrapper function as
+        arguments and return a bool indicating weather the samples passed are
+        too small.
+    n_outputs : int or callable, default: 2
+        The number of outputs produced by the function given 1d sample(s). For
+        example, hypothesis tests that return a namedtuple or result object
+        with attributes ``statistic`` and ``pvalue`` use the default
+        ``n_outputs=2``; summary statistics with scalar output use
+        ``n_outputs=1``. Alternatively, may be a callable that accepts a
+        dictionary of arguments passed into the wrapped function and returns
+        the number of outputs corresponding with those arguments.
+    kwd_samples : sequence, default: ()
+        The names of keyword parameters that should be treated as samples. For
+        example, `gmean` accepts as its first argument a sample `a` but
+        also `weights` as a fourth, optional keyword argument. In this case, we
+        use `n_samples=1` and kwd_samples=['weights'].
+    override : dict, default: {'vectorization': False, 'nan_propagation': True}
+        Pass a dictionary with ``'vectorization': True`` to ensure that the
+        decorator overrides the function's behavior for multimensional input.
+        Use ``'nan_propagation': False`` to ensure that the decorator does not
+        override the function's behavior for ``nan_policy='propagate'``.
+    """
+    # Specify which existing behaviors the decorator must override
+    temp = override or {}
+    override = {'vectorization': False,
+                'nan_propagation': True}
+    override.update(temp)
+
+    if result_to_tuple is None:
+        def result_to_tuple(res):
+            return res
+
+    # The only `result_to_tuple` that needs the second argument (number of
+    # outputs) is the one for `moment`, and this was realized very late.
+    # Rather than changing all `result_to_tuple` definitions, we wrap them
+    # here to accept a second argument if they don't already.
+    if len(inspect.signature(result_to_tuple).parameters) == 1:
+        def result_to_tuple(res, _, f=result_to_tuple):
+            return f(res)
+
+    if not callable(too_small):
+        def is_too_small(samples, *ts_args, axis=-1, **ts_kwargs):
+            for sample in samples:
+                if sample.shape[axis] <= too_small:
+                    return True
+            return False
+    else:
+        is_too_small = too_small
+
+    def axis_nan_policy_decorator(hypotest_fun_in):
+        @wraps(hypotest_fun_in)
+        def axis_nan_policy_wrapper(*args, _no_deco=False, **kwds):
+
+            if _no_deco:  # for testing, decorator does nothing
+                return hypotest_fun_in(*args, **kwds)
+
+            # For now, skip the decorator entirely if using array API. In the future,
+            # we'll probably want to use it for `keepdims`, `axis` tuples, etc.
+            if len(args) == 0:  # extract sample from `kwds` if there are no `args`
+                used_kwd_samples = list(set(kwds).intersection(set(kwd_samples)))
+                temp = used_kwd_samples[:1]
+            else:
+                temp = args[0]
+
+            if not is_numpy(array_namespace(temp)):
+                msg = ("Use of `nan_policy` and `keepdims` "
+                       "is incompatible with non-NumPy arrays.")
+                if 'nan_policy' in kwds or 'keepdims' in kwds:
+                    raise NotImplementedError(msg)
+                return hypotest_fun_in(*args, **kwds)
+
+            # We need to be flexible about whether position or keyword
+            # arguments are used, but we need to make sure users don't pass
+            # both for the same parameter. To complicate matters, some
+            # functions accept samples with *args, and some functions already
+            # accept `axis` and `nan_policy` as positional arguments.
+            # The strategy is to make sure that there is no duplication
+            # between `args` and `kwds`, combine the two into `kwds`, then
+            # the samples, `nan_policy`, and `axis` from `kwds`, as they are
+            # dealt with separately.
+
+            # Check for intersection between positional and keyword args
+            params = list(inspect.signature(hypotest_fun_in).parameters)
+            if n_samples is None:
+                # Give unique names to each positional sample argument
+                # Note that *args can't be provided as a keyword argument
+                params = [f"arg{i}" for i in range(len(args))] + params[1:]
+
+            # raise if there are too many positional args
+            maxarg = (np.inf if inspect.getfullargspec(hypotest_fun_in).varargs
+                      else len(inspect.getfullargspec(hypotest_fun_in).args))
+            if len(args) > maxarg:  # let the function raise the right error
+                hypotest_fun_in(*args, **kwds)
+
+            # raise if multiple values passed for same parameter
+            d_args = dict(zip(params, args))
+            intersection = set(d_args) & set(kwds)
+            if intersection:  # let the function raise the right error
+                hypotest_fun_in(*args, **kwds)
+
+            # Consolidate other positional and keyword args into `kwds`
+            kwds.update(d_args)
+
+            # rename avoids UnboundLocalError
+            if callable(n_samples):
+                # Future refactoring idea: no need for callable n_samples.
+                # Just replace `n_samples` and `kwd_samples` with a single
+                # list of the names of all samples, and treat all of them
+                # as `kwd_samples` are treated below.
+                n_samp = n_samples(kwds)
+            else:
+                n_samp = n_samples or len(args)
+
+            # get the number of outputs
+            n_out = n_outputs  # rename to avoid UnboundLocalError
+            if callable(n_out):
+                n_out = n_out(kwds)
+
+            # If necessary, rearrange function signature: accept other samples
+            # as positional args right after the first n_samp args
+            kwd_samp = [name for name in kwd_samples
+                        if kwds.get(name, None) is not None]
+            n_kwd_samp = len(kwd_samp)
+            if not kwd_samp:
+                hypotest_fun_out = hypotest_fun_in
+            else:
+                def hypotest_fun_out(*samples, **kwds):
+                    new_kwds = dict(zip(kwd_samp, samples[n_samp:]))
+                    kwds.update(new_kwds)
+                    return hypotest_fun_in(*samples[:n_samp], **kwds)
+
+            # Extract the things we need here
+            try:  # if something is missing
+                samples = [np.atleast_1d(kwds.pop(param))
+                           for param in (params[:n_samp] + kwd_samp)]
+            except KeyError:  # let the function raise the right error
+                # might need to revisit this if required arg is not a "sample"
+                hypotest_fun_in(*args, **kwds)
+            vectorized = True if 'axis' in params else False
+            vectorized = vectorized and not override['vectorization']
+            axis = kwds.pop('axis', default_axis)
+            nan_policy = kwds.pop('nan_policy', 'propagate')
+            keepdims = kwds.pop("keepdims", False)
+            del args  # avoid the possibility of passing both `args` and `kwds`
+
+            # convert masked arrays to regular arrays with sentinel values
+            samples, sentinel = _masked_arrays_2_sentinel_arrays(samples)
+
+            # standardize to always work along last axis
+            reduced_axes = axis
+            if axis is None:
+                if samples:
+                    # when axis=None, take the maximum of all dimensions since
+                    # all the dimensions are reduced.
+                    n_dims = np.max([sample.ndim for sample in samples])
+                    reduced_axes = tuple(range(n_dims))
+                samples = [np.asarray(sample.ravel()) for sample in samples]
+            else:
+                # don't ignore any axes when broadcasting if paired
+                samples = _broadcast_arrays(samples, axis=axis if not paired else None)
+                axis = np.atleast_1d(axis)
+                n_axes = len(axis)
+                # move all axes in `axis` to the end to be raveled
+                samples = [np.moveaxis(sample, axis, range(-len(axis), 0))
+                           for sample in samples]
+                shapes = [sample.shape for sample in samples]
+                # New shape is unchanged for all axes _not_ in `axis`
+                # At the end, we append the product of the shapes of the axes
+                # in `axis`. Appending -1 doesn't work for zero-size arrays!
+                new_shapes = [shape[:-n_axes] + (np.prod(shape[-n_axes:]),)
+                              for shape in shapes]
+                samples = [sample.reshape(new_shape)
+                           for sample, new_shape in zip(samples, new_shapes)]
+            axis = -1  # work over the last axis
+            NaN = _get_nan(*samples) if samples else np.nan
+
+            # if axis is not needed, just handle nan_policy and return
+            ndims = np.array([sample.ndim for sample in samples])
+            if np.all(ndims <= 1):
+                # Addresses nan_policy == "raise"
+                if nan_policy != 'propagate' or override['nan_propagation']:
+                    contains_nan = [_contains_nan(sample, nan_policy)[0]
+                                    for sample in samples]
+                else:
+                    # Behave as though there are no NaNs (even if there are)
+                    contains_nan = [False]*len(samples)
+
+                # Addresses nan_policy == "propagate"
+                if any(contains_nan) and (nan_policy == 'propagate'
+                                          and override['nan_propagation']):
+                    res = np.full(n_out, NaN)
+                    res = _add_reduced_axes(res, reduced_axes, keepdims)
+                    return tuple_to_result(*res)
+
+                # Addresses nan_policy == "omit"
+                too_small_msg = too_small_1d_not_omit
+                if any(contains_nan) and nan_policy == 'omit':
+                    # consider passing in contains_nan
+                    samples = _remove_nans(samples, paired)
+                    too_small_msg = too_small_1d_omit
+
+                if sentinel:
+                    samples = _remove_sentinel(samples, paired, sentinel)
+
+                if is_too_small(samples, kwds):
+                    warnings.warn(too_small_msg, SmallSampleWarning, stacklevel=2)
+                    res = np.full(n_out, NaN)
+                    res = _add_reduced_axes(res, reduced_axes, keepdims)
+                    return tuple_to_result(*res)
+
+                res = hypotest_fun_out(*samples, **kwds)
+                res = result_to_tuple(res, n_out)
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # check for empty input
+            empty_output = _check_empty_inputs(samples, axis)
+            # only return empty output if zero sized input is too small.
+            if (
+                empty_output is not None
+                and (is_too_small(samples, kwds) or empty_output.size == 0)
+            ):
+                if is_too_small(samples, kwds) and empty_output.size != 0:
+                    warnings.warn(too_small_nd_not_omit, SmallSampleWarning,
+                                  stacklevel=2)
+                res = [empty_output.copy() for i in range(n_out)]
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # otherwise, concatenate all samples along axis, remembering where
+            # each separate sample begins
+            lengths = np.array([sample.shape[axis] for sample in samples])
+            split_indices = np.cumsum(lengths)
+            x = _broadcast_concatenate(samples, axis, paired=paired)
+
+            # Addresses nan_policy == "raise"
+            if nan_policy != 'propagate' or override['nan_propagation']:
+                contains_nan, _ = _contains_nan(x, nan_policy)
+            else:
+                contains_nan = False  # behave like there are no NaNs
+
+            if vectorized and not contains_nan and not sentinel:
+                res = hypotest_fun_out(*samples, axis=axis, **kwds)
+                res = result_to_tuple(res, n_out)
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # Addresses nan_policy == "omit"
+            if contains_nan and nan_policy == 'omit':
+                def hypotest_fun(x):
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    samples = _remove_nans(samples, paired)
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        warnings.warn(too_small_nd_omit, SmallSampleWarning,
+                                      stacklevel=4)
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            # Addresses nan_policy == "propagate"
+            elif (contains_nan and nan_policy == 'propagate'
+                  and override['nan_propagation']):
+                def hypotest_fun(x):
+                    if np.isnan(x).any():
+                        return np.full(n_out, NaN)
+
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            else:
+                def hypotest_fun(x):
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            x = np.moveaxis(x, axis, 0)
+            res = np.apply_along_axis(hypotest_fun, axis=0, arr=x)
+            res = _add_reduced_axes(res, reduced_axes, keepdims)
+            return tuple_to_result(*res)
+
+        _axis_parameter_doc, _axis_parameter = _get_axis_params(default_axis)
+        doc = FunctionDoc(axis_nan_policy_wrapper)
+        parameter_names = [param.name for param in doc['Parameters']]
+        if 'axis' in parameter_names:
+            doc['Parameters'][parameter_names.index('axis')] = (
+                _axis_parameter_doc)
+        else:
+            doc['Parameters'].append(_axis_parameter_doc)
+        if 'nan_policy' in parameter_names:
+            doc['Parameters'][parameter_names.index('nan_policy')] = (
+                _nan_policy_parameter_doc)
+        else:
+            doc['Parameters'].append(_nan_policy_parameter_doc)
+        if 'keepdims' in parameter_names:
+            doc['Parameters'][parameter_names.index('keepdims')] = (
+                _keepdims_parameter_doc)
+        else:
+            doc['Parameters'].append(_keepdims_parameter_doc)
+        doc['Notes'] += _standard_note_addition
+        doc = str(doc).split("\n", 1)[1]  # remove signature
+        axis_nan_policy_wrapper.__doc__ = str(doc)
+
+        sig = inspect.signature(axis_nan_policy_wrapper)
+        parameters = sig.parameters
+        parameter_list = list(parameters.values())
+        if 'axis' not in parameters:
+            parameter_list.append(_axis_parameter)
+        if 'nan_policy' not in parameters:
+            parameter_list.append(_nan_policy_parameter)
+        if 'keepdims' not in parameters:
+            parameter_list.append(_keepdims_parameter)
+        sig = sig.replace(parameters=parameter_list)
+        axis_nan_policy_wrapper.__signature__ = sig
+
+        return axis_nan_policy_wrapper
+    return axis_nan_policy_decorator
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dc973956606951f1b4e3fd82732ba006329d4ff2
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.pxd b/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..a0d0b0d0fbd0fb2f1ddadffc0e3b91a7eab9eba9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_biasedurn.pxd
@@ -0,0 +1,27 @@
+# Declare the class with cdef
+cdef extern from "biasedurn/stocc.h" nogil:
+    cdef cppclass CFishersNCHypergeometric:
+        CFishersNCHypergeometric(int, int, int, double, double) except +
+        int mode()
+        double mean()
+        double variance()
+        double probability(int x)
+        double moments(double * mean, double * var)
+
+    cdef cppclass CWalleniusNCHypergeometric:
+        CWalleniusNCHypergeometric() except +
+        CWalleniusNCHypergeometric(int, int, int, double, double) except +
+        int mode()
+        double mean()
+        double variance()
+        double probability(int x)
+        double moments(double * mean, double * var)
+
+    cdef cppclass StochasticLib3:
+        StochasticLib3(int seed) except +
+        double Random() except +
+        void SetAccuracy(double accur)
+        int FishersNCHyp (int n, int m, int N, double odds) except +
+        int WalleniusNCHyp (int n, int m, int N, double odds) except +
+        double(*next_double)()
+        double(*next_normal)(const double m, const double s)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_binned_statistic.py b/python_embeded/Lib/site-packages/scipy/stats/_binned_statistic.py
new file mode 100644
index 0000000000000000000000000000000000000000..58ce75eef73e95186335ee19496303bb525bf82e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_binned_statistic.py
@@ -0,0 +1,795 @@
+import builtins
+from warnings import catch_warnings, simplefilter
+import numpy as np
+from operator import index
+from collections import namedtuple
+
+__all__ = ['binned_statistic',
+           'binned_statistic_2d',
+           'binned_statistic_dd']
+
+
+BinnedStatisticResult = namedtuple('BinnedStatisticResult',
+                                   ('statistic', 'bin_edges', 'binnumber'))
+
+
+def binned_statistic(x, values, statistic='mean',
+                     bins=10, range=None):
+    """
+    Compute a binned statistic for one or more sets of data.
+
+    This is a generalization of a histogram function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values (or set of values) within each bin.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        A sequence of values to be binned.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `x`, or a set of sequences - each the same shape as
+        `x`.  If `values` is a set of sequences, the statistic will be computed
+        on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : int or sequence of scalars, optional
+        If `bins` is an int, it defines the number of equal-width bins in the
+        given range (10 by default).  If `bins` is a sequence, it defines the
+        bin edges, including the rightmost edge, allowing for non-uniform bin
+        widths.  Values in `x` that are smaller than lowest bin edge are
+        assigned to bin number 0, values beyond the highest bin are assigned to
+        ``bins[-1]``.  If the bin edges are specified, the number of bins will
+        be, (nx = len(bins)-1).
+    range : (float, float) or [(float, float)], optional
+        The lower and upper range of the bins.  If not provided, range
+        is simply ``(x.min(), x.max())``.  Values outside the range are
+        ignored.
+
+    Returns
+    -------
+    statistic : array
+        The values of the selected statistic in each bin.
+    bin_edges : array of dtype float
+        Return the bin edges ``(length(statistic)+1)``.
+    binnumber: 1-D ndarray of ints
+        Indices of the bins (corresponding to `bin_edges`) in which each value
+        of `x` belongs.  Same length as `values`.  A binnumber of `i` means the
+        corresponding value is between (bin_edges[i-1], bin_edges[i]).
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd
+
+    Notes
+    -----
+    All but the last (righthand-most) bin is half-open.  In other words, if
+    `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
+    but excluding 2) and the second ``[2, 3)``.  The last bin, however, is
+    ``[3, 4]``, which *includes* 4.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    First some basic examples:
+
+    Create two evenly spaced bins in the range of the given sample, and sum the
+    corresponding values in each of those bins:
+
+    >>> values = [1.0, 1.0, 2.0, 1.5, 3.0]
+    >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
+    BinnedStatisticResult(statistic=array([4. , 4.5]),
+            bin_edges=array([1., 4., 7.]), binnumber=array([1, 1, 1, 2, 2]))
+
+    Multiple arrays of values can also be passed.  The statistic is calculated
+    on each set independently:
+
+    >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]]
+    >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
+    BinnedStatisticResult(statistic=array([[4. , 4.5],
+           [8. , 9. ]]), bin_edges=array([1., 4., 7.]),
+           binnumber=array([1, 1, 1, 2, 2]))
+
+    >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean',
+    ...                        bins=3)
+    BinnedStatisticResult(statistic=array([1., 2., 4.]),
+            bin_edges=array([1., 2., 3., 4.]),
+            binnumber=array([1, 2, 1, 2, 3]))
+
+    As a second example, we now generate some random data of sailing boat speed
+    as a function of wind speed, and then determine how fast our boat is for
+    certain wind speeds:
+
+    >>> rng = np.random.default_rng()
+    >>> windspeed = 8 * rng.random(500)
+    >>> boatspeed = .3 * windspeed**.5 + .2 * rng.random(500)
+    >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
+    ...                 boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
+    >>> plt.figure()
+    >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data')
+    >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
+    ...            label='binned statistic of data')
+    >>> plt.legend()
+
+    Now we can use ``binnumber`` to select all datapoints with a windspeed
+    below 1:
+
+    >>> low_boatspeed = boatspeed[binnumber == 0]
+
+    As a final example, we will use ``bin_edges`` and ``binnumber`` to make a
+    plot of a distribution that shows the mean and distribution around that
+    mean per bin, on top of a regular histogram and the probability
+    distribution function:
+
+    >>> x = np.linspace(0, 5, num=500)
+    >>> x_pdf = stats.maxwell.pdf(x)
+    >>> samples = stats.maxwell.rvs(size=10000)
+
+    >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf,
+    ...         statistic='mean', bins=25)
+    >>> bin_width = (bin_edges[1] - bin_edges[0])
+    >>> bin_centers = bin_edges[1:] - bin_width/2
+
+    >>> plt.figure()
+    >>> plt.hist(samples, bins=50, density=True, histtype='stepfilled',
+    ...          alpha=0.2, label='histogram of data')
+    >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf')
+    >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2,
+    ...            label='binned statistic of data')
+    >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5)
+    >>> plt.legend(fontsize=10)
+    >>> plt.show()
+
+    """
+    try:
+        N = len(bins)
+    except TypeError:
+        N = 1
+
+    if N != 1:
+        bins = [np.asarray(bins, float)]
+
+    if range is not None:
+        if len(range) == 2:
+            range = [range]
+
+    medians, edges, binnumbers = binned_statistic_dd(
+        [x], values, statistic, bins, range)
+
+    return BinnedStatisticResult(medians, edges[0], binnumbers)
+
+
+BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult',
+                                     ('statistic', 'x_edge', 'y_edge',
+                                      'binnumber'))
+
+
+def binned_statistic_2d(x, y, values, statistic='mean',
+                        bins=10, range=None, expand_binnumbers=False):
+    """
+    Compute a bidimensional binned statistic for one or more sets of data.
+
+    This is a generalization of a histogram2d function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values (or set of values) within each bin.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        A sequence of values to be binned along the first dimension.
+    y : (N,) array_like
+        A sequence of values to be binned along the second dimension.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `x`, or a list of sequences - each with the same
+        shape as `x`.  If `values` is such a list, the statistic will be
+        computed on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : int or [int, int] or array_like or [array, array], optional
+        The bin specification:
+
+          * the number of bins for the two dimensions (nx = ny = bins),
+          * the number of bins in each dimension (nx, ny = bins),
+          * the bin edges for the two dimensions (x_edge = y_edge = bins),
+          * the bin edges in each dimension (x_edge, y_edge = bins).
+
+        If the bin edges are specified, the number of bins will be,
+        (nx = len(x_edge)-1, ny = len(y_edge)-1).
+
+    range : (2,2) array_like, optional
+        The leftmost and rightmost edges of the bins along each dimension
+        (if not specified explicitly in the `bins` parameters):
+        [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be
+        considered outliers and not tallied in the histogram.
+    expand_binnumbers : bool, optional
+        'False' (default): the returned `binnumber` is a shape (N,) array of
+        linearized bin indices.
+        'True': the returned `binnumber` is 'unraveled' into a shape (2,N)
+        ndarray, where each row gives the bin numbers in the corresponding
+        dimension.
+        See the `binnumber` returned value, and the `Examples` section.
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    statistic : (nx, ny) ndarray
+        The values of the selected statistic in each two-dimensional bin.
+    x_edge : (nx + 1) ndarray
+        The bin edges along the first dimension.
+    y_edge : (ny + 1) ndarray
+        The bin edges along the second dimension.
+    binnumber : (N,) array of ints or (2,N) ndarray of ints
+        This assigns to each element of `sample` an integer that represents the
+        bin in which this observation falls.  The representation depends on the
+        `expand_binnumbers` argument.  See `Notes` for details.
+
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd
+
+    Notes
+    -----
+    Binedges:
+    All but the last (righthand-most) bin is half-open.  In other words, if
+    `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
+    but excluding 2) and the second ``[2, 3)``.  The last bin, however, is
+    ``[3, 4]``, which *includes* 4.
+
+    `binnumber`:
+    This returned argument assigns to each element of `sample` an integer that
+    represents the bin in which it belongs.  The representation depends on the
+    `expand_binnumbers` argument. If 'False' (default): The returned
+    `binnumber` is a shape (N,) array of linearized indices mapping each
+    element of `sample` to its corresponding bin (using row-major ordering).
+    Note that the returned linearized bin indices are used for an array with
+    extra bins on the outer binedges to capture values outside of the defined
+    bin bounds.
+    If 'True': The returned `binnumber` is a shape (2,N) ndarray where
+    each row indicates bin placements for each dimension respectively.  In each
+    dimension, a binnumber of `i` means the corresponding value is between
+    (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> from scipy import stats
+
+    Calculate the counts with explicit bin-edges:
+
+    >>> x = [0.1, 0.1, 0.1, 0.6]
+    >>> y = [2.1, 2.6, 2.1, 2.1]
+    >>> binx = [0.0, 0.5, 1.0]
+    >>> biny = [2.0, 2.5, 3.0]
+    >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny])
+    >>> ret.statistic
+    array([[2., 1.],
+           [1., 0.]])
+
+    The bin in which each sample is placed is given by the `binnumber`
+    returned parameter.  By default, these are the linearized bin indices:
+
+    >>> ret.binnumber
+    array([5, 6, 5, 9])
+
+    The bin indices can also be expanded into separate entries for each
+    dimension using the `expand_binnumbers` parameter:
+
+    >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny],
+    ...                                 expand_binnumbers=True)
+    >>> ret.binnumber
+    array([[1, 1, 1, 2],
+           [1, 2, 1, 1]])
+
+    Which shows that the first three elements belong in the xbin 1, and the
+    fourth into xbin 2; and so on for y.
+
+    """
+
+    # This code is based on np.histogram2d
+    try:
+        N = len(bins)
+    except TypeError:
+        N = 1
+
+    if N != 1 and N != 2:
+        xedges = yedges = np.asarray(bins, float)
+        bins = [xedges, yedges]
+
+    medians, edges, binnumbers = binned_statistic_dd(
+        [x, y], values, statistic, bins, range,
+        expand_binnumbers=expand_binnumbers)
+
+    return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers)
+
+
+BinnedStatisticddResult = namedtuple('BinnedStatisticddResult',
+                                     ('statistic', 'bin_edges',
+                                      'binnumber'))
+
+
+def _bincount(x, weights):
+    if np.iscomplexobj(weights):
+        a = np.bincount(x, np.real(weights))
+        b = np.bincount(x, np.imag(weights))
+        z = a + b*1j
+
+    else:
+        z = np.bincount(x, weights)
+    return z
+
+
+def binned_statistic_dd(sample, values, statistic='mean',
+                        bins=10, range=None, expand_binnumbers=False,
+                        binned_statistic_result=None):
+    """
+    Compute a multidimensional binned statistic for a set of data.
+
+    This is a generalization of a histogramdd function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values within each bin.
+
+    Parameters
+    ----------
+    sample : array_like
+        Data to histogram passed as a sequence of N arrays of length D, or
+        as an (N,D) array.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `sample`, or a list of sequences - each with the
+        same shape as `sample`.  If `values` is such a list, the statistic
+        will be computed on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0. If the number of values
+            within a given bin is 0 or 1, the computed standard deviation value
+            will be 0 for the bin.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : sequence or positive int, optional
+        The bin specification must be in one of the following forms:
+
+          * A sequence of arrays describing the bin edges along each dimension.
+          * The number of bins for each dimension (nx, ny, ... = bins).
+          * The number of bins for all dimensions (nx = ny = ... = bins).
+    range : sequence, optional
+        A sequence of lower and upper bin edges to be used if the edges are
+        not given explicitly in `bins`. Defaults to the minimum and maximum
+        values along each dimension.
+    expand_binnumbers : bool, optional
+        'False' (default): the returned `binnumber` is a shape (N,) array of
+        linearized bin indices.
+        'True': the returned `binnumber` is 'unraveled' into a shape (D,N)
+        ndarray, where each row gives the bin numbers in the corresponding
+        dimension.
+        See the `binnumber` returned value, and the `Examples` section of
+        `binned_statistic_2d`.
+    binned_statistic_result : binnedStatisticddResult
+        Result of a previous call to the function in order to reuse bin edges
+        and bin numbers with new values and/or a different statistic.
+        To reuse bin numbers, `expand_binnumbers` must have been set to False
+        (the default)
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    statistic : ndarray, shape(nx1, nx2, nx3,...)
+        The values of the selected statistic in each two-dimensional bin.
+    bin_edges : list of ndarrays
+        A list of D arrays describing the (nxi + 1) bin edges for each
+        dimension.
+    binnumber : (N,) array of ints or (D,N) ndarray of ints
+        This assigns to each element of `sample` an integer that represents the
+        bin in which this observation falls.  The representation depends on the
+        `expand_binnumbers` argument.  See `Notes` for details.
+
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d
+
+    Notes
+    -----
+    Binedges:
+    All but the last (righthand-most) bin is half-open in each dimension.  In
+    other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is
+    ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``.  The
+    last bin, however, is ``[3, 4]``, which *includes* 4.
+
+    `binnumber`:
+    This returned argument assigns to each element of `sample` an integer that
+    represents the bin in which it belongs.  The representation depends on the
+    `expand_binnumbers` argument. If 'False' (default): The returned
+    `binnumber` is a shape (N,) array of linearized indices mapping each
+    element of `sample` to its corresponding bin (using row-major ordering).
+    If 'True': The returned `binnumber` is a shape (D,N) ndarray where
+    each row indicates bin placements for each dimension respectively.  In each
+    dimension, a binnumber of `i` means the corresponding value is between
+    (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.mplot3d import Axes3D
+
+    Take an array of 600 (x, y) coordinates as an example.
+    `binned_statistic_dd` can handle arrays of higher dimension `D`. But a plot
+    of dimension `D+1` is required.
+
+    >>> mu = np.array([0., 1.])
+    >>> sigma = np.array([[1., -0.5],[-0.5, 1.5]])
+    >>> multinormal = stats.multivariate_normal(mu, sigma)
+    >>> data = multinormal.rvs(size=600, random_state=235412)
+    >>> data.shape
+    (600, 2)
+
+    Create bins and count how many arrays fall in each bin:
+
+    >>> N = 60
+    >>> x = np.linspace(-3, 3, N)
+    >>> y = np.linspace(-3, 4, N)
+    >>> ret = stats.binned_statistic_dd(data, np.arange(600), bins=[x, y],
+    ...                                 statistic='count')
+    >>> bincounts = ret.statistic
+
+    Set the volume and the location of bars:
+
+    >>> dx = x[1] - x[0]
+    >>> dy = y[1] - y[0]
+    >>> x, y = np.meshgrid(x[:-1]+dx/2, y[:-1]+dy/2)
+    >>> z = 0
+
+    >>> bincounts = bincounts.ravel()
+    >>> x = x.ravel()
+    >>> y = y.ravel()
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111, projection='3d')
+    >>> with np.errstate(divide='ignore'):   # silence random axes3d warning
+    ...     ax.bar3d(x, y, z, dx, dy, bincounts)
+
+    Reuse bin numbers and bin edges with new values:
+
+    >>> ret2 = stats.binned_statistic_dd(data, -np.arange(600),
+    ...                                  binned_statistic_result=ret,
+    ...                                  statistic='mean')
+    """
+    known_stats = ['mean', 'median', 'count', 'sum', 'std', 'min', 'max']
+    if not callable(statistic) and statistic not in known_stats:
+        raise ValueError(f'invalid statistic {statistic!r}')
+
+    try:
+        bins = index(bins)
+    except TypeError:
+        # bins is not an integer
+        pass
+    # If bins was an integer-like object, now it is an actual Python int.
+
+    # NOTE: for _bin_edges(), see e.g. gh-11365
+    if isinstance(bins, int) and not np.isfinite(sample).all():
+        raise ValueError(f'{sample!r} contains non-finite values.')
+
+    # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`)
+    # `Dlen` is the length of elements along each dimension.
+    # This code is based on np.histogramdd
+    try:
+        # `sample` is an ND-array.
+        Dlen, Ndim = sample.shape
+    except (AttributeError, ValueError):
+        # `sample` is a sequence of 1D arrays.
+        sample = np.atleast_2d(sample).T
+        Dlen, Ndim = sample.shape
+
+    # Store initial shape of `values` to preserve it in the output
+    values = np.asarray(values)
+    input_shape = list(values.shape)
+    # Make sure that `values` is 2D to iterate over rows
+    values = np.atleast_2d(values)
+    Vdim, Vlen = values.shape
+
+    # Make sure `values` match `sample`
+    if statistic != 'count' and Vlen != Dlen:
+        raise AttributeError('The number of `values` elements must match the '
+                             'length of each `sample` dimension.')
+
+    try:
+        M = len(bins)
+        if M != Ndim:
+            raise AttributeError('The dimension of bins must be equal '
+                                 'to the dimension of the sample x.')
+    except TypeError:
+        bins = Ndim * [bins]
+
+    if binned_statistic_result is None:
+        nbin, edges, dedges = _bin_edges(sample, bins, range)
+        binnumbers = _bin_numbers(sample, nbin, edges, dedges)
+    else:
+        edges = binned_statistic_result.bin_edges
+        nbin = np.array([len(edges[i]) + 1 for i in builtins.range(Ndim)])
+        # +1 for outlier bins
+        dedges = [np.diff(edges[i]) for i in builtins.range(Ndim)]
+        binnumbers = binned_statistic_result.binnumber
+
+    # Avoid overflow with double precision. Complex `values` -> `complex128`.
+    result_type = np.result_type(values, np.float64)
+    result = np.empty([Vdim, nbin.prod()], dtype=result_type)
+
+    if statistic in {'mean', np.mean}:
+        result.fill(np.nan)
+        flatcount = _bincount(binnumbers, None)
+        a = flatcount.nonzero()
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            result[vv, a] = flatsum[a] / flatcount[a]
+    elif statistic in {'std', np.std}:
+        result.fill(np.nan)
+        flatcount = _bincount(binnumbers, None)
+        a = flatcount.nonzero()
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            delta = values[vv] - flatsum[binnumbers] / flatcount[binnumbers]
+            std = np.sqrt(
+                _bincount(binnumbers, delta*np.conj(delta))[a] / flatcount[a]
+            )
+            result[vv, a] = std
+        result = np.real(result)
+    elif statistic == 'count':
+        result = np.empty([Vdim, nbin.prod()], dtype=np.float64)
+        result.fill(0)
+        flatcount = _bincount(binnumbers, None)
+        a = np.arange(len(flatcount))
+        result[:, a] = flatcount[np.newaxis, :]
+    elif statistic in {'sum', np.sum}:
+        result.fill(0)
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            a = np.arange(len(flatsum))
+            result[vv, a] = flatsum
+    elif statistic in {'median', np.median}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.lexsort((values[vv], binnumbers))
+            _, j, counts = np.unique(binnumbers[i],
+                                     return_index=True, return_counts=True)
+            mid = j + (counts - 1) / 2
+            mid_a = values[vv, i][np.floor(mid).astype(int)]
+            mid_b = values[vv, i][np.ceil(mid).astype(int)]
+            medians = (mid_a + mid_b) / 2
+            result[vv, binnumbers[i][j]] = medians
+    elif statistic in {'min', np.min}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.argsort(values[vv])[::-1]  # Reversed so the min is last
+            result[vv, binnumbers[i]] = values[vv, i]
+    elif statistic in {'max', np.max}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.argsort(values[vv])
+            result[vv, binnumbers[i]] = values[vv, i]
+    elif callable(statistic):
+        with np.errstate(invalid='ignore'), catch_warnings():
+            simplefilter("ignore", RuntimeWarning)
+            try:
+                null = statistic([])
+            except Exception:
+                null = np.nan
+        if np.iscomplexobj(null):
+            result = result.astype(np.complex128)
+        result.fill(null)
+        try:
+            _calc_binned_statistic(
+                Vdim, binnumbers, result, values, statistic
+            )
+        except ValueError:
+            result = result.astype(np.complex128)
+            _calc_binned_statistic(
+                Vdim, binnumbers, result, values, statistic
+            )
+
+    # Shape into a proper matrix
+    result = result.reshape(np.append(Vdim, nbin))
+
+    # Remove outliers (indices 0 and -1 for each bin-dimension).
+    core = tuple([slice(None)] + Ndim * [slice(1, -1)])
+    result = result[core]
+
+    # Unravel binnumbers into an ndarray, each row the bins for each dimension
+    if expand_binnumbers and Ndim > 1:
+        binnumbers = np.asarray(np.unravel_index(binnumbers, nbin))
+
+    if np.any(result.shape[1:] != nbin - 2):
+        raise RuntimeError('Internal Shape Error')
+
+    # Reshape to have output (`result`) match input (`values`) shape
+    result = result.reshape(input_shape[:-1] + list(nbin-2))
+
+    return BinnedStatisticddResult(result, edges, binnumbers)
+
+
+def _calc_binned_statistic(Vdim, bin_numbers, result, values, stat_func):
+    unique_bin_numbers = np.unique(bin_numbers)
+    for vv in builtins.range(Vdim):
+        bin_map = _create_binned_data(bin_numbers, unique_bin_numbers,
+                                      values, vv)
+        for i in unique_bin_numbers:
+            stat = stat_func(np.array(bin_map[i]))
+            if np.iscomplexobj(stat) and not np.iscomplexobj(result):
+                raise ValueError("The statistic function returns complex ")
+            result[vv, i] = stat
+
+
+def _create_binned_data(bin_numbers, unique_bin_numbers, values, vv):
+    """ Create hashmap of bin ids to values in bins
+    key: bin number
+    value: list of binned data
+    """
+    bin_map = dict()
+    for i in unique_bin_numbers:
+        bin_map[i] = []
+    for i in builtins.range(len(bin_numbers)):
+        bin_map[bin_numbers[i]].append(values[vv, i])
+    return bin_map
+
+
+def _bin_edges(sample, bins=None, range=None):
+    """ Create edge arrays
+    """
+    Dlen, Ndim = sample.shape
+
+    nbin = np.empty(Ndim, int)    # Number of bins in each dimension
+    edges = Ndim * [None]         # Bin edges for each dim (will be 2D array)
+    dedges = Ndim * [None]        # Spacing between edges (will be 2D array)
+
+    # Select range for each dimension
+    # Used only if number of bins is given.
+    if range is None:
+        smin = np.atleast_1d(np.array(sample.min(axis=0), float))
+        smax = np.atleast_1d(np.array(sample.max(axis=0), float))
+    else:
+        if len(range) != Ndim:
+            raise ValueError(
+                f"range given for {len(range)} dimensions; {Ndim} required")
+        smin = np.empty(Ndim)
+        smax = np.empty(Ndim)
+        for i in builtins.range(Ndim):
+            if range[i][1] < range[i][0]:
+                raise ValueError(
+                    f"In {f'dimension {i + 1} of ' if Ndim > 1 else ''}range,"
+                    " start must be <= stop")
+            smin[i], smax[i] = range[i]
+
+    # Make sure the bins have a finite width.
+    for i in builtins.range(len(smin)):
+        if smin[i] == smax[i]:
+            smin[i] = smin[i] - .5
+            smax[i] = smax[i] + .5
+
+    # Preserve sample floating point precision in bin edges
+    edges_dtype = (sample.dtype if np.issubdtype(sample.dtype, np.floating)
+                   else float)
+
+    # Create edge arrays
+    for i in builtins.range(Ndim):
+        if np.isscalar(bins[i]):
+            nbin[i] = bins[i] + 2  # +2 for outlier bins
+            edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1,
+                                   dtype=edges_dtype)
+        else:
+            edges[i] = np.asarray(bins[i], edges_dtype)
+            nbin[i] = len(edges[i]) + 1  # +1 for outlier bins
+        dedges[i] = np.diff(edges[i])
+
+    nbin = np.asarray(nbin)
+
+    return nbin, edges, dedges
+
+
+def _bin_numbers(sample, nbin, edges, dedges):
+    """Compute the bin number each sample falls into, in each dimension
+    """
+    Dlen, Ndim = sample.shape
+
+    sampBin = [
+        np.digitize(sample[:, i], edges[i])
+        for i in range(Ndim)
+    ]
+
+    # Using `digitize`, values that fall on an edge are put in the right bin.
+    # For the rightmost bin, we want values equal to the right
+    # edge to be counted in the last bin, and not as an outlier.
+    for i in range(Ndim):
+        # Find the rounding precision
+        dedges_min = dedges[i].min()
+        if dedges_min == 0:
+            raise ValueError('The smallest edge difference is numerically 0.')
+        decimal = int(-np.log10(dedges_min)) + 6
+        # Find which points are on the rightmost edge.
+        on_edge = np.where((sample[:, i] >= edges[i][-1]) &
+                           (np.around(sample[:, i], decimal) ==
+                            np.around(edges[i][-1], decimal)))[0]
+        # Shift these points one bin to the left.
+        sampBin[i][on_edge] -= 1
+
+    # Compute the sample indices in the flattened statistic matrix.
+    binnumbers = np.ravel_multi_index(sampBin, nbin)
+
+    return binnumbers
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_binomtest.py b/python_embeded/Lib/site-packages/scipy/stats/_binomtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..89f9445e513704777ff7a1ad5f0119b05a82fce0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_binomtest.py
@@ -0,0 +1,375 @@
+from math import sqrt
+import numpy as np
+from scipy._lib._util import _validate_int
+from scipy.optimize import brentq
+from scipy.special import ndtri
+from ._discrete_distns import binom
+from ._common import ConfidenceInterval
+
+
+class BinomTestResult:
+    """
+    Result of `scipy.stats.binomtest`.
+
+    Attributes
+    ----------
+    k : int
+        The number of successes (copied from `binomtest` input).
+    n : int
+        The number of trials (copied from `binomtest` input).
+    alternative : str
+        Indicates the alternative hypothesis specified in the input
+        to `binomtest`.  It will be one of ``'two-sided'``, ``'greater'``,
+        or ``'less'``.
+    statistic: float
+        The estimate of the proportion of successes.
+    pvalue : float
+        The p-value of the hypothesis test.
+
+    """
+    def __init__(self, k, n, alternative, statistic, pvalue):
+        self.k = k
+        self.n = n
+        self.alternative = alternative
+        self.statistic = statistic
+        self.pvalue = pvalue
+
+        # add alias for backward compatibility
+        self.proportion_estimate = statistic
+
+    def __repr__(self):
+        s = ("BinomTestResult("
+             f"k={self.k}, "
+             f"n={self.n}, "
+             f"alternative={self.alternative!r}, "
+             f"statistic={self.statistic}, "
+             f"pvalue={self.pvalue})")
+        return s
+
+    def proportion_ci(self, confidence_level=0.95, method='exact'):
+        """
+        Compute the confidence interval for ``statistic``.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval
+            of the estimated proportion. Default is 0.95.
+        method : {'exact', 'wilson', 'wilsoncc'}, optional
+            Selects the method used to compute the confidence interval
+            for the estimate of the proportion:
+
+            'exact' :
+                Use the Clopper-Pearson exact method [1]_.
+            'wilson' :
+                Wilson's method, without continuity correction ([2]_, [3]_).
+            'wilsoncc' :
+                Wilson's method, with continuity correction ([2]_, [3]_).
+
+            Default is ``'exact'``.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence interval.
+
+        References
+        ----------
+        .. [1] C. J. Clopper and E. S. Pearson, The use of confidence or
+               fiducial limits illustrated in the case of the binomial,
+               Biometrika, Vol. 26, No. 4, pp 404-413 (Dec. 1934).
+        .. [2] E. B. Wilson, Probable inference, the law of succession, and
+               statistical inference, J. Amer. Stat. Assoc., 22, pp 209-212
+               (1927).
+        .. [3] Robert G. Newcombe, Two-sided confidence intervals for the
+               single proportion: comparison of seven methods, Statistics
+               in Medicine, 17, pp 857-872 (1998).
+
+        Examples
+        --------
+        >>> from scipy.stats import binomtest
+        >>> result = binomtest(k=7, n=50, p=0.1)
+        >>> result.statistic
+        0.14
+        >>> result.proportion_ci()
+        ConfidenceInterval(low=0.05819170033997342, high=0.26739600249700846)
+        """
+        if method not in ('exact', 'wilson', 'wilsoncc'):
+            raise ValueError(f"method ('{method}') must be one of 'exact', "
+                             "'wilson' or 'wilsoncc'.")
+        if not (0 <= confidence_level <= 1):
+            raise ValueError(f'confidence_level ({confidence_level}) must be in '
+                             'the interval [0, 1].')
+        if method == 'exact':
+            low, high = _binom_exact_conf_int(self.k, self.n,
+                                              confidence_level,
+                                              self.alternative)
+        else:
+            # method is 'wilson' or 'wilsoncc'
+            low, high = _binom_wilson_conf_int(self.k, self.n,
+                                               confidence_level,
+                                               self.alternative,
+                                               correction=method == 'wilsoncc')
+        return ConfidenceInterval(low=low, high=high)
+
+
+def _findp(func):
+    try:
+        p = brentq(func, 0, 1)
+    except RuntimeError:
+        raise RuntimeError('numerical solver failed to converge when '
+                           'computing the confidence limits') from None
+    except ValueError as exc:
+        raise ValueError('brentq raised a ValueError; report this to the '
+                         'SciPy developers') from exc
+    return p
+
+
+def _binom_exact_conf_int(k, n, confidence_level, alternative):
+    """
+    Compute the estimate and confidence interval for the binomial test.
+
+    Returns proportion, prop_low, prop_high
+    """
+    if alternative == 'two-sided':
+        alpha = (1 - confidence_level) / 2
+        if k == 0:
+            plow = 0.0
+        else:
+            plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
+        if k == n:
+            phigh = 1.0
+        else:
+            phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
+    elif alternative == 'less':
+        alpha = 1 - confidence_level
+        plow = 0.0
+        if k == n:
+            phigh = 1.0
+        else:
+            phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
+    elif alternative == 'greater':
+        alpha = 1 - confidence_level
+        if k == 0:
+            plow = 0.0
+        else:
+            plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
+        phigh = 1.0
+    return plow, phigh
+
+
+def _binom_wilson_conf_int(k, n, confidence_level, alternative, correction):
+    # This function assumes that the arguments have already been validated.
+    # In particular, `alternative` must be one of 'two-sided', 'less' or
+    # 'greater'.
+    p = k / n
+    if alternative == 'two-sided':
+        z = ndtri(0.5 + 0.5*confidence_level)
+    else:
+        z = ndtri(confidence_level)
+
+    # For reference, the formulas implemented here are from
+    # Newcombe (1998) (ref. [3] in the proportion_ci docstring).
+    denom = 2*(n + z**2)
+    center = (2*n*p + z**2)/denom
+    q = 1 - p
+    if correction:
+        if alternative == 'less' or k == 0:
+            lo = 0.0
+        else:
+            dlo = (1 + z*sqrt(z**2 - 2 - 1/n + 4*p*(n*q + 1))) / denom
+            lo = center - dlo
+        if alternative == 'greater' or k == n:
+            hi = 1.0
+        else:
+            dhi = (1 + z*sqrt(z**2 + 2 - 1/n + 4*p*(n*q - 1))) / denom
+            hi = center + dhi
+    else:
+        delta = z/denom * sqrt(4*n*p*q + z**2)
+        if alternative == 'less' or k == 0:
+            lo = 0.0
+        else:
+            lo = center - delta
+        if alternative == 'greater' or k == n:
+            hi = 1.0
+        else:
+            hi = center + delta
+
+    return lo, hi
+
+
+def binomtest(k, n, p=0.5, alternative='two-sided'):
+    """
+    Perform a test that the probability of success is p.
+
+    The binomial test [1]_ is a test of the null hypothesis that the
+    probability of success in a Bernoulli experiment is `p`.
+
+    Details of the test can be found in many texts on statistics, such
+    as section 24.5 of [2]_.
+
+    Parameters
+    ----------
+    k : int
+        The number of successes.
+    n : int
+        The number of trials.
+    p : float, optional
+        The hypothesized probability of success, i.e. the expected
+        proportion of successes.  The value must be in the interval
+        ``0 <= p <= 1``. The default value is ``p = 0.5``.
+    alternative : {'two-sided', 'greater', 'less'}, optional
+        Indicates the alternative hypothesis. The default value is
+        'two-sided'.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.BinomTestResult` instance
+        The return value is an object with the following attributes:
+
+        k : int
+            The number of successes (copied from `binomtest` input).
+        n : int
+            The number of trials (copied from `binomtest` input).
+        alternative : str
+            Indicates the alternative hypothesis specified in the input
+            to `binomtest`.  It will be one of ``'two-sided'``, ``'greater'``,
+            or ``'less'``.
+        statistic : float
+            The estimate of the proportion of successes.
+        pvalue : float
+            The p-value of the hypothesis test.
+
+        The object has the following methods:
+
+        proportion_ci(confidence_level=0.95, method='exact') :
+            Compute the confidence interval for ``statistic``.
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] Binomial test, https://en.wikipedia.org/wiki/Binomial_test
+    .. [2] Jerrold H. Zar, Biostatistical Analysis (fifth edition),
+           Prentice Hall, Upper Saddle River, New Jersey USA (2010)
+
+    Examples
+    --------
+    >>> from scipy.stats import binomtest
+
+    A car manufacturer claims that no more than 10% of their cars are unsafe.
+    15 cars are inspected for safety, 3 were found to be unsafe. Test the
+    manufacturer's claim:
+
+    >>> result = binomtest(3, n=15, p=0.1, alternative='greater')
+    >>> result.pvalue
+    0.18406106910639114
+
+    The null hypothesis cannot be rejected at the 5% level of significance
+    because the returned p-value is greater than the critical value of 5%.
+
+    The test statistic is equal to the estimated proportion, which is simply
+    ``3/15``:
+
+    >>> result.statistic
+    0.2
+
+    We can use the `proportion_ci()` method of the result to compute the
+    confidence interval of the estimate:
+
+    >>> result.proportion_ci(confidence_level=0.95)
+    ConfidenceInterval(low=0.05684686759024681, high=1.0)
+
+    """
+    k = _validate_int(k, 'k', minimum=0)
+    n = _validate_int(n, 'n', minimum=1)
+    if k > n:
+        raise ValueError(f'k ({k}) must not be greater than n ({n}).')
+
+    if not (0 <= p <= 1):
+        raise ValueError(f"p ({p}) must be in range [0,1]")
+
+    if alternative not in ('two-sided', 'less', 'greater'):
+        raise ValueError(f"alternative ('{alternative}') not recognized; \n"
+                         "must be 'two-sided', 'less' or 'greater'")
+    if alternative == 'less':
+        pval = binom.cdf(k, n, p)
+    elif alternative == 'greater':
+        pval = binom.sf(k-1, n, p)
+    else:
+        # alternative is 'two-sided'
+        d = binom.pmf(k, n, p)
+        rerr = 1 + 1e-7
+        if k == p * n:
+            # special case as shortcut, would also be handled by `else` below
+            pval = 1.
+        elif k < p * n:
+            ix = _binary_search_for_binom_tst(lambda x1: -binom.pmf(x1, n, p),
+                                              -d*rerr, np.ceil(p * n), n)
+            # y is the number of terms between mode and n that are <= d*rerr.
+            # ix gave us the first term where a(ix) <= d*rerr < a(ix-1)
+            # if the first equality doesn't hold, y=n-ix. Otherwise, we
+            # need to include ix as well as the equality holds. Note that
+            # the equality will hold in very very rare situations due to rerr.
+            y = n - ix + int(d*rerr == binom.pmf(ix, n, p))
+            pval = binom.cdf(k, n, p) + binom.sf(n - y, n, p)
+        else:
+            ix = _binary_search_for_binom_tst(lambda x1: binom.pmf(x1, n, p),
+                                              d*rerr, 0, np.floor(p * n))
+            # y is the number of terms between 0 and mode that are <= d*rerr.
+            # we need to add a 1 to account for the 0 index.
+            # For comparing this with old behavior, see
+            # tst_binary_srch_for_binom_tst method in test_morestats.
+            y = ix + 1
+            pval = binom.cdf(y-1, n, p) + binom.sf(k-1, n, p)
+
+        pval = min(1.0, pval)
+
+    result = BinomTestResult(k=k, n=n, alternative=alternative,
+                             statistic=k/n, pvalue=pval)
+    return result
+
+
+def _binary_search_for_binom_tst(a, d, lo, hi):
+    """
+    Conducts an implicit binary search on a function specified by `a`.
+
+    Meant to be used on the binomial PMF for the case of two-sided tests
+    to obtain the value on the other side of the mode where the tail
+    probability should be computed. The values on either side of
+    the mode are always in order, meaning binary search is applicable.
+
+    Parameters
+    ----------
+    a : callable
+      The function over which to perform binary search. Its values
+      for inputs lo and hi should be in ascending order.
+    d : float
+      The value to search.
+    lo : int
+      The lower end of range to search.
+    hi : int
+      The higher end of the range to search.
+
+    Returns
+    -------
+    int
+      The index, i between lo and hi
+      such that a(i)<=d d:
+            hi = mid-1
+        else:
+            return mid
+    if a(lo) <= d:
+        return lo
+    else:
+        return lo-1
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_bws_test.py b/python_embeded/Lib/site-packages/scipy/stats/_bws_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..def9b9eaf88d98f0fc72e1678da724106795c5db
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_bws_test.py
@@ -0,0 +1,177 @@
+import numpy as np
+from functools import partial
+from scipy import stats
+
+
+def _bws_input_validation(x, y, alternative, method):
+    ''' Input validation and standardization for bws test'''
+    x, y = np.atleast_1d(x, y)
+    if x.ndim > 1 or y.ndim > 1:
+        raise ValueError('`x` and `y` must be exactly one-dimensional.')
+    if np.isnan(x).any() or np.isnan(y).any():
+        raise ValueError('`x` and `y` must not contain NaNs.')
+    if np.size(x) == 0 or np.size(y) == 0:
+        raise ValueError('`x` and `y` must be of nonzero size.')
+
+    z = stats.rankdata(np.concatenate((x, y)))
+    x, y = z[:len(x)], z[len(x):]
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f'`alternative` must be one of {alternatives}.')
+
+    method = stats.PermutationMethod() if method is None else method
+    if not isinstance(method, stats.PermutationMethod):
+        raise ValueError('`method` must be an instance of '
+                         '`scipy.stats.PermutationMethod`')
+
+    return x, y, alternative, method
+
+
+def _bws_statistic(x, y, alternative, axis):
+    '''Compute the BWS test statistic for two independent samples'''
+    # Public function currently does not accept `axis`, but `permutation_test`
+    # uses `axis` to make vectorized call.
+
+    Ri, Hj = np.sort(x, axis=axis), np.sort(y, axis=axis)
+    n, m = Ri.shape[axis], Hj.shape[axis]
+    i, j = np.arange(1, n+1), np.arange(1, m+1)
+
+    Bx_num = Ri - (m + n)/n * i
+    By_num = Hj - (m + n)/m * j
+
+    if alternative == 'two-sided':
+        Bx_num *= Bx_num
+        By_num *= By_num
+    else:
+        Bx_num *= np.abs(Bx_num)
+        By_num *= np.abs(By_num)
+
+    Bx_den = i/(n+1) * (1 - i/(n+1)) * m*(m+n)/n
+    By_den = j/(m+1) * (1 - j/(m+1)) * n*(m+n)/m
+
+    Bx = 1/n * np.sum(Bx_num/Bx_den, axis=axis)
+    By = 1/m * np.sum(By_num/By_den, axis=axis)
+
+    B = (Bx + By) / 2 if alternative == 'two-sided' else (Bx - By) / 2
+
+    return B
+
+
+def bws_test(x, y, *, alternative="two-sided", method=None):
+    r'''Perform the Baumgartner-Weiss-Schindler test on two independent samples.
+
+    The Baumgartner-Weiss-Schindler (BWS) test is a nonparametric test of 
+    the null hypothesis that the distribution underlying sample `x` 
+    is the same as the distribution underlying sample `y`. Unlike 
+    the Kolmogorov-Smirnov, Wilcoxon, and Cramer-Von Mises tests, 
+    the BWS test weights the integral by the variance of the difference
+    in cumulative distribution functions (CDFs), emphasizing the tails of the
+    distributions, which increases the power of the test in many applications.
+
+    Parameters
+    ----------
+    x, y : array-like
+        1-d arrays of samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        Let *F(u)* and *G(u)* be the cumulative distribution functions of the
+        distributions underlying `x` and `y`, respectively. Then the following
+        alternative hypotheses are available:
+
+        * 'two-sided': the distributions are not equal, i.e. *F(u) ≠ G(u)* for
+          at least one *u*.
+        * 'less': the distribution underlying `x` is stochastically less than
+          the distribution underlying `y`, i.e. *F(u) >= G(u)* for all *u*.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`, i.e. *F(u) <= G(u)* for all
+          *u*.
+
+        Under a more restrictive set of assumptions, the alternative hypotheses
+        can be expressed in terms of the locations of the distributions;
+        see [2] section 5.1.
+    method : PermutationMethod, optional
+        Configures the method used to compute the p-value. The default is
+        the default `PermutationMethod` object.
+
+    Returns
+    -------
+    res : PermutationTestResult
+    An object with attributes:
+
+    statistic : float
+        The observed test statistic of the data.
+    pvalue : float
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null hypothesis.
+
+    See also
+    --------
+    scipy.stats.wilcoxon, scipy.stats.mannwhitneyu, scipy.stats.ttest_ind
+
+    Notes
+    -----
+    When ``alternative=='two-sided'``, the statistic is defined by the
+    equations given in [1]_ Section 2. This statistic is not appropriate for
+    one-sided alternatives; in that case, the statistic is the *negative* of
+    that given by the equations in [1]_ Section 2. Consequently, when the
+    distribution of the first sample is stochastically greater than that of the
+    second sample, the statistic will tend to be positive.
+
+    References
+    ----------
+    .. [1] Neuhäuser, M. (2005). Exact Tests Based on the
+           Baumgartner-Weiss-Schindler Statistic: A Survey. Statistical Papers,
+           46(1), 1-29.
+    .. [2] Fay, M. P., & Proschan, M. A. (2010). Wilcoxon-Mann-Whitney or t-test?
+           On assumptions for hypothesis tests and multiple interpretations of 
+           decision rules. Statistics surveys, 4, 1.
+
+    Examples
+    --------
+    We follow the example of table 3 in [1]_: Fourteen children were divided
+    randomly into two groups. Their ranks at performing a specific tests are
+    as follows.
+
+    >>> import numpy as np
+    >>> x = [1, 2, 3, 4, 6, 7, 8]
+    >>> y = [5, 9, 10, 11, 12, 13, 14]
+
+    We use the BWS test to assess whether there is a statistically significant
+    difference between the two groups.
+    The null hypothesis is that there is no difference in the distributions of
+    performance between the two groups. We decide that a significance level of
+    1% is required to reject the null hypothesis in favor of the alternative
+    that the distributions are different.
+    Since the number of samples is very small, we can compare the observed test
+    statistic against the *exact* distribution of the test statistic under the
+    null hypothesis.
+
+    >>> from scipy.stats import bws_test
+    >>> res = bws_test(x, y)
+    >>> print(res.statistic)
+    5.132167152575315
+
+    This agrees with :math:`B = 5.132` reported in [1]_. The *p*-value produced
+    by `bws_test` also agrees with :math:`p = 0.0029` reported in [1]_.
+
+    >>> print(res.pvalue)
+    0.002913752913752914
+
+    Because the p-value is below our threshold of 1%, we take this as evidence
+    against the null hypothesis in favor of the alternative that there is a
+    difference in performance between the two groups.
+    '''
+
+    x, y, alternative, method = _bws_input_validation(x, y, alternative,
+                                                      method)
+    bws_statistic = partial(_bws_statistic, alternative=alternative)
+
+    permutation_alternative = 'less' if alternative == 'less' else 'greater'
+    res = stats.permutation_test((x, y), bws_statistic,
+                                 alternative=permutation_alternative,
+                                 **method._asdict())
+
+    return res
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_censored_data.py b/python_embeded/Lib/site-packages/scipy/stats/_censored_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..68b16d72970948422ee894505fdd8d7009a9a561
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_censored_data.py
@@ -0,0 +1,459 @@
+import numpy as np
+
+
+def _validate_1d(a, name, allow_inf=False):
+    if np.ndim(a) != 1:
+        raise ValueError(f'`{name}` must be a one-dimensional sequence.')
+    if np.isnan(a).any():
+        raise ValueError(f'`{name}` must not contain nan.')
+    if not allow_inf and np.isinf(a).any():
+        raise ValueError(f'`{name}` must contain only finite values.')
+
+
+def _validate_interval(interval):
+    interval = np.asarray(interval)
+    if interval.shape == (0,):
+        # The input was a sequence with length 0.
+        interval = interval.reshape((0, 2))
+    if interval.ndim != 2 or interval.shape[-1] != 2:
+        raise ValueError('`interval` must be a two-dimensional array with '
+                         'shape (m, 2), where m is the number of '
+                         'interval-censored values, but got shape '
+                         f'{interval.shape}')
+
+    if np.isnan(interval).any():
+        raise ValueError('`interval` must not contain nan.')
+    if np.isinf(interval).all(axis=1).any():
+        raise ValueError('In each row in `interval`, both values must not'
+                         ' be infinite.')
+    if (interval[:, 0] > interval[:, 1]).any():
+        raise ValueError('In each row of `interval`, the left value must not'
+                         ' exceed the right value.')
+
+    uncensored_mask = interval[:, 0] == interval[:, 1]
+    left_mask = np.isinf(interval[:, 0])
+    right_mask = np.isinf(interval[:, 1])
+    interval_mask = np.isfinite(interval).all(axis=1) & ~uncensored_mask
+
+    uncensored2 = interval[uncensored_mask, 0]
+    left2 = interval[left_mask, 1]
+    right2 = interval[right_mask, 0]
+    interval2 = interval[interval_mask]
+
+    return uncensored2, left2, right2, interval2
+
+
+def _validate_x_censored(x, censored):
+    x = np.asarray(x)
+    if x.ndim != 1:
+        raise ValueError('`x` must be one-dimensional.')
+    censored = np.asarray(censored)
+    if censored.ndim != 1:
+        raise ValueError('`censored` must be one-dimensional.')
+    if (~np.isfinite(x)).any():
+        raise ValueError('`x` must not contain nan or inf.')
+    if censored.size != x.size:
+        raise ValueError('`x` and `censored` must have the same length.')
+    return x, censored.astype(bool)
+
+
+class CensoredData:
+    """
+    Instances of this class represent censored data.
+
+    Instances may be passed to the ``fit`` method of continuous
+    univariate SciPy distributions for maximum likelihood estimation.
+    The *only* method of the univariate continuous distributions that
+    understands `CensoredData` is the ``fit`` method.  An instance of
+    `CensoredData` can not be passed to methods such as ``pdf`` and
+    ``cdf``.
+
+    An observation is said to be *censored* when the precise value is unknown,
+    but it has a known upper and/or lower bound.  The conventional terminology
+    is:
+
+    * left-censored: an observation is below a certain value but it is
+      unknown by how much.
+    * right-censored: an observation is above a certain value but it is
+      unknown by how much.
+    * interval-censored: an observation lies somewhere on an interval between
+      two values.
+
+    Left-, right-, and interval-censored data can be represented by
+    `CensoredData`.
+
+    For convenience, the class methods ``left_censored`` and
+    ``right_censored`` are provided to create a `CensoredData`
+    instance from a single one-dimensional array of measurements
+    and a corresponding boolean array to indicate which measurements
+    are censored.  The class method ``interval_censored`` accepts two
+    one-dimensional arrays that hold the lower and upper bounds of the
+    intervals.
+
+    Parameters
+    ----------
+    uncensored : array_like, 1D
+        Uncensored observations.
+    left : array_like, 1D
+        Left-censored observations.
+    right : array_like, 1D
+        Right-censored observations.
+    interval : array_like, 2D, with shape (m, 2)
+        Interval-censored observations.  Each row ``interval[k, :]``
+        represents the interval for the kth interval-censored observation.
+
+    Notes
+    -----
+    In the input array `interval`, the lower bound of the interval may
+    be ``-inf``, and the upper bound may be ``inf``, but at least one must be
+    finite. When the lower bound is ``-inf``, the row represents a left-
+    censored observation, and when the upper bound is ``inf``, the row
+    represents a right-censored observation.  If the length of an interval
+    is 0 (i.e. ``interval[k, 0] == interval[k, 1]``, the observation is
+    treated as uncensored.  So one can represent all the types of censored
+    and uncensored data in ``interval``, but it is generally more convenient
+    to use `uncensored`, `left` and `right` for uncensored, left-censored and
+    right-censored observations, respectively.
+
+    Examples
+    --------
+    In the most general case, a censored data set may contain values that
+    are left-censored, right-censored, interval-censored, and uncensored.
+    For example, here we create a data set with five observations.  Two
+    are uncensored (values 1 and 1.5), one is a left-censored observation
+    of 0, one is a right-censored observation of 10 and one is
+    interval-censored in the interval [2, 3].
+
+    >>> import numpy as np
+    >>> from scipy.stats import CensoredData
+    >>> data = CensoredData(uncensored=[1, 1.5], left=[0], right=[10],
+    ...                     interval=[[2, 3]])
+    >>> print(data)
+    CensoredData(5 values: 2 not censored, 1 left-censored,
+    1 right-censored, 1 interval-censored)
+
+    Equivalently,
+
+    >>> data = CensoredData(interval=[[1, 1],
+    ...                               [1.5, 1.5],
+    ...                               [-np.inf, 0],
+    ...                               [10, np.inf],
+    ...                               [2, 3]])
+    >>> print(data)
+    CensoredData(5 values: 2 not censored, 1 left-censored,
+    1 right-censored, 1 interval-censored)
+
+    A common case is to have a mix of uncensored observations and censored
+    observations that are all right-censored (or all left-censored). For
+    example, consider an experiment in which six devices are started at
+    various times and left running until they fail.  Assume that time is
+    measured in hours, and the experiment is stopped after 30 hours, even
+    if all the devices have not failed by that time.  We might end up with
+    data such as this::
+
+        Device  Start-time  Fail-time  Time-to-failure
+           1         0         13           13
+           2         2         24           22
+           3         5         22           17
+           4         8         23           15
+           5        10        ***          >20
+           6        12        ***          >18
+
+    Two of the devices had not failed when the experiment was stopped;
+    the observations of the time-to-failure for these two devices are
+    right-censored.  We can represent this data with
+
+    >>> data = CensoredData(uncensored=[13, 22, 17, 15], right=[20, 18])
+    >>> print(data)
+    CensoredData(6 values: 4 not censored, 2 right-censored)
+
+    Alternatively, we can use the method `CensoredData.right_censored` to
+    create a representation of this data.  The time-to-failure observations
+    are put the list ``ttf``.  The ``censored`` list indicates which values
+    in ``ttf`` are censored.
+
+    >>> ttf = [13, 22, 17, 15, 20, 18]
+    >>> censored = [False, False, False, False, True, True]
+
+    Pass these lists to `CensoredData.right_censored` to create an
+    instance of `CensoredData`.
+
+    >>> data = CensoredData.right_censored(ttf, censored)
+    >>> print(data)
+    CensoredData(6 values: 4 not censored, 2 right-censored)
+
+    If the input data is interval censored and already stored in two
+    arrays, one holding the low end of the intervals and another
+    holding the high ends, the class method ``interval_censored`` can
+    be used to create the `CensoredData` instance.
+
+    This example creates an instance with four interval-censored values.
+    The intervals are [10, 11], [0.5, 1], [2, 3], and [12.5, 13.5].
+
+    >>> a = [10, 0.5, 2, 12.5]  # Low ends of the intervals
+    >>> b = [11, 1.0, 3, 13.5]  # High ends of the intervals
+    >>> data = CensoredData.interval_censored(low=a, high=b)
+    >>> print(data)
+    CensoredData(4 values: 0 not censored, 4 interval-censored)
+
+    Finally, we create and censor some data from the `weibull_min`
+    distribution, and then fit `weibull_min` to that data. We'll assume
+    that the location parameter is known to be 0.
+
+    >>> from scipy.stats import weibull_min
+    >>> rng = np.random.default_rng()
+
+    Create the random data set.
+
+    >>> x = weibull_min.rvs(2.5, loc=0, scale=30, size=250, random_state=rng)
+    >>> x[x > 40] = 40  # Right-censor values greater or equal to 40.
+
+    Create the `CensoredData` instance with the `right_censored` method.
+    The censored values are those where the value is 40.
+
+    >>> data = CensoredData.right_censored(x, x == 40)
+    >>> print(data)
+    CensoredData(250 values: 215 not censored, 35 right-censored)
+
+    35 values have been right-censored.
+
+    Fit `weibull_min` to the censored data.  We expect to shape and scale
+    to be approximately 2.5 and 30, respectively.
+
+    >>> weibull_min.fit(data, floc=0)
+    (2.3575922823897315, 0, 30.40650074451254)
+
+    """
+
+    def __init__(self, uncensored=None, *, left=None, right=None,
+                 interval=None):
+        if uncensored is None:
+            uncensored = []
+        if left is None:
+            left = []
+        if right is None:
+            right = []
+        if interval is None:
+            interval = np.empty((0, 2))
+
+        _validate_1d(uncensored, 'uncensored')
+        _validate_1d(left, 'left')
+        _validate_1d(right, 'right')
+        uncensored2, left2, right2, interval2 = _validate_interval(interval)
+
+        self._uncensored = np.concatenate((uncensored, uncensored2))
+        self._left = np.concatenate((left, left2))
+        self._right = np.concatenate((right, right2))
+        # Note that by construction, the private attribute _interval
+        # will be a 2D array that contains only finite values representing
+        # intervals with nonzero but finite length.
+        self._interval = interval2
+
+    def __repr__(self):
+        uncensored_str = " ".join(np.array_repr(self._uncensored).split())
+        left_str = " ".join(np.array_repr(self._left).split())
+        right_str = " ".join(np.array_repr(self._right).split())
+        interval_str = " ".join(np.array_repr(self._interval).split())
+        return (f"CensoredData(uncensored={uncensored_str}, left={left_str}, "
+                f"right={right_str}, interval={interval_str})")
+
+    def __str__(self):
+        num_nc = len(self._uncensored)
+        num_lc = len(self._left)
+        num_rc = len(self._right)
+        num_ic = len(self._interval)
+        n = num_nc + num_lc + num_rc + num_ic
+        parts = [f'{num_nc} not censored']
+        if num_lc > 0:
+            parts.append(f'{num_lc} left-censored')
+        if num_rc > 0:
+            parts.append(f'{num_rc} right-censored')
+        if num_ic > 0:
+            parts.append(f'{num_ic} interval-censored')
+        return f'CensoredData({n} values: ' + ', '.join(parts) + ')'
+
+    # This is not a complete implementation of the arithmetic operators.
+    # All we need is subtracting a scalar and dividing by a scalar.
+
+    def __sub__(self, other):
+        return CensoredData(uncensored=self._uncensored - other,
+                            left=self._left - other,
+                            right=self._right - other,
+                            interval=self._interval - other)
+
+    def __truediv__(self, other):
+        return CensoredData(uncensored=self._uncensored / other,
+                            left=self._left / other,
+                            right=self._right / other,
+                            interval=self._interval / other)
+
+    def __len__(self):
+        """
+        The number of values (censored and not censored).
+        """
+        return (len(self._uncensored) + len(self._left) + len(self._right)
+                + len(self._interval))
+
+    def num_censored(self):
+        """
+        Number of censored values.
+        """
+        return len(self._left) + len(self._right) + len(self._interval)
+
+    @classmethod
+    def right_censored(cls, x, censored):
+        """
+        Create a `CensoredData` instance of right-censored data.
+
+        Parameters
+        ----------
+        x : array_like
+            `x` is the array of observed data or measurements.
+            `x` must be a one-dimensional sequence of finite numbers.
+        censored : array_like of bool
+            `censored` must be a one-dimensional sequence of boolean
+            values.  If ``censored[k]`` is True, the corresponding value
+            in `x` is right-censored.  That is, the value ``x[k]``
+            is the lower bound of the true (but unknown) value.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of uncensored and right-censored values.
+
+        Examples
+        --------
+        >>> from scipy.stats import CensoredData
+
+        Two uncensored values (4 and 10) and two right-censored values
+        (24 and 25).
+
+        >>> data = CensoredData.right_censored([4, 10, 24, 25],
+        ...                                    [False, False, True, True])
+        >>> data
+        CensoredData(uncensored=array([ 4., 10.]),
+        left=array([], dtype=float64), right=array([24., 25.]),
+        interval=array([], shape=(0, 2), dtype=float64))
+        >>> print(data)
+        CensoredData(4 values: 2 not censored, 2 right-censored)
+        """
+        x, censored = _validate_x_censored(x, censored)
+        return cls(uncensored=x[~censored], right=x[censored])
+
+    @classmethod
+    def left_censored(cls, x, censored):
+        """
+        Create a `CensoredData` instance of left-censored data.
+
+        Parameters
+        ----------
+        x : array_like
+            `x` is the array of observed data or measurements.
+            `x` must be a one-dimensional sequence of finite numbers.
+        censored : array_like of bool
+            `censored` must be a one-dimensional sequence of boolean
+            values.  If ``censored[k]`` is True, the corresponding value
+            in `x` is left-censored.  That is, the value ``x[k]``
+            is the upper bound of the true (but unknown) value.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of uncensored and left-censored values.
+
+        Examples
+        --------
+        >>> from scipy.stats import CensoredData
+
+        Two uncensored values (0.12 and 0.033) and two left-censored values
+        (both 1e-3).
+
+        >>> data = CensoredData.left_censored([0.12, 0.033, 1e-3, 1e-3],
+        ...                                   [False, False, True, True])
+        >>> data
+        CensoredData(uncensored=array([0.12 , 0.033]),
+        left=array([0.001, 0.001]), right=array([], dtype=float64),
+        interval=array([], shape=(0, 2), dtype=float64))
+        >>> print(data)
+        CensoredData(4 values: 2 not censored, 2 left-censored)
+        """
+        x, censored = _validate_x_censored(x, censored)
+        return cls(uncensored=x[~censored], left=x[censored])
+
+    @classmethod
+    def interval_censored(cls, low, high):
+        """
+        Create a `CensoredData` instance of interval-censored data.
+
+        This method is useful when all the data is interval-censored, and
+        the low and high ends of the intervals are already stored in
+        separate one-dimensional arrays.
+
+        Parameters
+        ----------
+        low : array_like
+            The one-dimensional array containing the low ends of the
+            intervals.
+        high : array_like
+            The one-dimensional array containing the high ends of the
+            intervals.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of censored values.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import CensoredData
+
+        ``a`` and ``b`` are the low and high ends of a collection of
+        interval-censored values.
+
+        >>> a = [0.5, 2.0, 3.0, 5.5]
+        >>> b = [1.0, 2.5, 3.5, 7.0]
+        >>> data = CensoredData.interval_censored(low=a, high=b)
+        >>> print(data)
+        CensoredData(4 values: 0 not censored, 4 interval-censored)
+        """
+        _validate_1d(low, 'low', allow_inf=True)
+        _validate_1d(high, 'high', allow_inf=True)
+        if len(low) != len(high):
+            raise ValueError('`low` and `high` must have the same length.')
+        interval = np.column_stack((low, high))
+        uncensored, left, right, interval = _validate_interval(interval)
+        return cls(uncensored=uncensored, left=left, right=right,
+                   interval=interval)
+
+    def _uncensor(self):
+        """
+        This function is used when a non-censored version of the data
+        is needed to create a rough estimate of the parameters of a
+        distribution via the method of moments or some similar method.
+        The data is "uncensored" by taking the given endpoints as the
+        data for the left- or right-censored data, and the mean for the
+        interval-censored data.
+        """
+        data = np.concatenate((self._uncensored, self._left, self._right,
+                               self._interval.mean(axis=1)))
+        return data
+
+    def _supported(self, a, b):
+        """
+        Return a subset of self containing the values that are in
+        (or overlap with) the interval (a, b).
+        """
+        uncensored = self._uncensored
+        uncensored = uncensored[(a < uncensored) & (uncensored < b)]
+        left = self._left
+        left = left[a < left]
+        right = self._right
+        right = right[right < b]
+        interval = self._interval
+        interval = interval[(a < interval[:, 1]) & (interval[:, 0] < b)]
+        return CensoredData(uncensored, left=left, right=right,
+                            interval=interval)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_common.py b/python_embeded/Lib/site-packages/scipy/stats/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e45cab38dc41432cadc0cb2b29d46ab20defb04
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_common.py
@@ -0,0 +1,5 @@
+from collections import namedtuple
+
+
+ConfidenceInterval = namedtuple("ConfidenceInterval", ["low", "high"])
+ConfidenceInterval. __doc__ = "Class for confidence intervals."
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_constants.py b/python_embeded/Lib/site-packages/scipy/stats/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b1555506b14791763b1ef6c3ab4be5420f5dadb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_constants.py
@@ -0,0 +1,42 @@
+"""
+Statistics-related constants.
+
+"""
+import numpy as np
+
+
+# The smallest representable positive number such that 1.0 + _EPS != 1.0.
+_EPS = np.finfo(float).eps
+
+# The largest [in magnitude] usable floating value.
+_XMAX = np.finfo(float).max
+
+# The log of the largest usable floating value; useful for knowing
+# when exp(something) will overflow
+_LOGXMAX = np.log(_XMAX)
+
+# The smallest [in magnitude] usable (i.e. not subnormal) double precision
+# floating value.
+_XMIN = np.finfo(float).tiny
+
+# The log of the smallest [in magnitude] usable (i.e not subnormal)
+# double precision floating value.
+_LOGXMIN = np.log(_XMIN)
+
+# -special.psi(1)
+_EULER = 0.577215664901532860606512090082402431042
+
+# special.zeta(3, 1)  Apery's constant
+_ZETA3 = 1.202056903159594285399738161511449990765
+
+# sqrt(pi)
+_SQRT_PI = 1.772453850905516027298167483341145182798
+
+# sqrt(2/pi)
+_SQRT_2_OVER_PI = 0.7978845608028654
+
+# log(pi)
+_LOG_PI = 1.1447298858494002
+
+# log(sqrt(2/pi))
+_LOG_SQRT_2_OVER_PI = -0.22579135264472744
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_continuous_distns.py b/python_embeded/Lib/site-packages/scipy/stats/_continuous_distns.py
new file mode 100644
index 0000000000000000000000000000000000000000..14b915d11aeba99a931e77467f0129cb99063a8e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_continuous_distns.py
@@ -0,0 +1,12516 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+import warnings
+from collections.abc import Iterable
+from functools import wraps, cached_property
+import ctypes
+
+import numpy as np
+from numpy.polynomial import Polynomial
+from scipy.interpolate import BSpline
+from scipy._lib.doccer import (extend_notes_in_docstring,
+                               replace_notes_in_docstring,
+                               inherit_docstring_from)
+from scipy._lib._ccallback import LowLevelCallable
+from scipy import optimize
+from scipy import integrate
+import scipy.special as sc
+
+import scipy.special._ufuncs as scu
+from scipy._lib._util import _lazyselect, _lazywhere
+
+from . import _stats
+from ._tukeylambda_stats import (tukeylambda_variance as _tlvar,
+                                 tukeylambda_kurtosis as _tlkurt)
+from ._distn_infrastructure import (_vectorize_rvs_over_shapes,
+    get_distribution_names, _kurtosis, _isintegral,
+    rv_continuous, _skew, _get_fixed_fit_value, _check_shape, _ShapeInfo)
+from scipy.stats._distribution_infrastructure import _log1mexp
+from ._ksstats import kolmogn, kolmognp, kolmogni
+from ._constants import (_XMIN, _LOGXMIN, _EULER, _ZETA3, _SQRT_PI,
+                         _SQRT_2_OVER_PI, _LOG_PI, _LOG_SQRT_2_OVER_PI)
+from ._censored_data import CensoredData
+from scipy.optimize import root_scalar
+from scipy.stats._warnings_errors import FitError
+import scipy.stats as stats
+
+def _remove_optimizer_parameters(kwds):
+    """
+    Remove the optimizer-related keyword arguments 'loc', 'scale' and
+    'optimizer' from `kwds`.  Then check that `kwds` is empty, and
+    raise `TypeError("Unknown arguments: %s." % kwds)` if it is not.
+
+    This function is used in the fit method of distributions that override
+    the default method and do not use the default optimization code.
+
+    `kwds` is modified in-place.
+    """
+    kwds.pop('loc', None)
+    kwds.pop('scale', None)
+    kwds.pop('optimizer', None)
+    kwds.pop('method', None)
+    if kwds:
+        raise TypeError(f"Unknown arguments: {kwds}.")
+
+
+def _call_super_mom(fun):
+    # If fit method is overridden only for MLE and doesn't specify what to do
+    # if method == 'mm' or with censored data, this decorator calls the generic
+    # implementation.
+    @wraps(fun)
+    def wrapper(self, data, *args, **kwds):
+        method = kwds.get('method', 'mle').lower()
+        censored = isinstance(data, CensoredData)
+        if method == 'mm' or (censored and data.num_censored() > 0):
+            return super(type(self), self).fit(data, *args, **kwds)
+        else:
+            if censored:
+                # data is an instance of CensoredData, but actually holds
+                # no censored values, so replace it with the array of
+                # uncensored values.
+                data = data._uncensored
+            return fun(self, data, *args, **kwds)
+
+    return wrapper
+
+
+def _get_left_bracket(fun, rbrack, lbrack=None):
+    # find left bracket for `root_scalar`. A guess for lbrack may be provided.
+    lbrack = lbrack or rbrack - 1
+    diff = rbrack - lbrack
+
+    # if there is no sign change in `fun` between the brackets, expand
+    # rbrack - lbrack until a sign change occurs
+    def interval_contains_root(lbrack, rbrack):
+        # return true if the signs disagree.
+        return np.sign(fun(lbrack)) != np.sign(fun(rbrack))
+
+    while not interval_contains_root(lbrack, rbrack):
+        diff *= 2
+        lbrack = rbrack - diff
+
+        msg = ("The solver could not find a bracket containing a "
+               "root to an MLE first order condition.")
+        if np.isinf(lbrack):
+            raise FitSolverError(msg)
+
+    return lbrack
+
+
+class ksone_gen(rv_continuous):
+    r"""Kolmogorov-Smirnov one-sided test statistic distribution.
+
+    This is the distribution of the one-sided Kolmogorov-Smirnov (KS)
+    statistics :math:`D_n^+` and :math:`D_n^-`
+    for a finite sample size ``n >= 1`` (the shape parameter).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    kstwobign, kstwo, kstest
+
+    Notes
+    -----
+    :math:`D_n^+` and :math:`D_n^-` are given by
+
+    .. math::
+
+        D_n^+ &= \text{sup}_x (F_n(x) - F(x)),\\
+        D_n^- &= \text{sup}_x (F(x) - F_n(x)),\\
+
+    where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF.
+    `ksone` describes the distribution under the null hypothesis of the KS test
+    that the empirical CDF corresponds to :math:`n` i.i.d. random variates
+    with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Birnbaum, Z. W. and Tingey, F.H. "One-sided confidence contours
+       for probability distribution functions", The Annals of Mathematical
+       Statistics, 22(4), pp 592-596 (1951).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ksone
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> n = 1e+03
+    >>> x = np.linspace(ksone.ppf(0.01, n),
+    ...                 ksone.ppf(0.99, n), 100)
+    >>> ax.plot(x, ksone.pdf(x, n),
+    ...         'r-', lw=5, alpha=0.6, label='ksone pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = ksone(n)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = ksone.ppf([0.001, 0.5, 0.999], n)
+    >>> np.allclose([0.001, 0.5, 0.999], ksone.cdf(vals, n))
+    True
+
+    """
+    def _argcheck(self, n):
+        return (n >= 1) & (n == np.round(n))
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _pdf(self, x, n):
+        return -scu._smirnovp(n, x)
+
+    def _cdf(self, x, n):
+        return scu._smirnovc(n, x)
+
+    def _sf(self, x, n):
+        return sc.smirnov(n, x)
+
+    def _ppf(self, q, n):
+        return scu._smirnovci(n, q)
+
+    def _isf(self, q, n):
+        return sc.smirnovi(n, q)
+
+
+ksone = ksone_gen(a=0.0, b=1.0, name='ksone')
+
+
+class kstwo_gen(rv_continuous):
+    r"""Kolmogorov-Smirnov two-sided test statistic distribution.
+
+    This is the distribution of the two-sided Kolmogorov-Smirnov (KS)
+    statistic :math:`D_n` for a finite sample size ``n >= 1``
+    (the shape parameter).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    kstwobign, ksone, kstest
+
+    Notes
+    -----
+    :math:`D_n` is given by
+
+    .. math::
+
+        D_n = \text{sup}_x |F_n(x) - F(x)|
+
+    where :math:`F` is a (continuous) CDF and :math:`F_n` is an empirical CDF.
+    `kstwo` describes the distribution under the null hypothesis of the KS test
+    that the empirical CDF corresponds to :math:`n` i.i.d. random variates
+    with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Simard, R., L'Ecuyer, P. "Computing the Two-Sided
+       Kolmogorov-Smirnov Distribution",  Journal of Statistical Software,
+       Vol 39, 11, 1-18 (2011).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import kstwo
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> n = 10
+    >>> x = np.linspace(kstwo.ppf(0.01, n),
+    ...                 kstwo.ppf(0.99, n), 100)
+    >>> ax.plot(x, kstwo.pdf(x, n),
+    ...         'r-', lw=5, alpha=0.6, label='kstwo pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = kstwo(n)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = kstwo.ppf([0.001, 0.5, 0.999], n)
+    >>> np.allclose([0.001, 0.5, 0.999], kstwo.cdf(vals, n))
+    True
+
+    """
+    def _argcheck(self, n):
+        return (n >= 1) & (n == np.round(n))
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _get_support(self, n):
+        return (0.5/(n if not isinstance(n, Iterable) else np.asanyarray(n)),
+                1.0)
+
+    def _pdf(self, x, n):
+        return kolmognp(n, x)
+
+    def _cdf(self, x, n):
+        return kolmogn(n, x)
+
+    def _sf(self, x, n):
+        return kolmogn(n, x, cdf=False)
+
+    def _ppf(self, q, n):
+        return kolmogni(n, q, cdf=True)
+
+    def _isf(self, q, n):
+        return kolmogni(n, q, cdf=False)
+
+
+# Use the pdf, (not the ppf) to compute moments
+kstwo = kstwo_gen(momtype=0, a=0.0, b=1.0, name='kstwo')
+
+
+class kstwobign_gen(rv_continuous):
+    r"""Limiting distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
+
+    This is the asymptotic distribution of the two-sided Kolmogorov-Smirnov
+    statistic :math:`\sqrt{n} D_n` that measures the maximum absolute
+    distance of the theoretical (continuous) CDF from the empirical CDF.
+    (see `kstest`).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ksone, kstwo, kstest
+
+    Notes
+    -----
+    :math:`\sqrt{n} D_n` is given by
+
+    .. math::
+
+        D_n = \text{sup}_x |F_n(x) - F(x)|
+
+    where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF.
+    `kstwobign`  describes the asymptotic distribution (i.e. the limit of
+    :math:`\sqrt{n} D_n`) under the null hypothesis of the KS test that the
+    empirical CDF corresponds to i.i.d. random variates with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Feller, W. "On the Kolmogorov-Smirnov Limit Theorems for Empirical
+       Distributions",  Ann. Math. Statist. Vol 19, 177-189 (1948).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        return -scu._kolmogp(x)
+
+    def _cdf(self, x):
+        return scu._kolmogc(x)
+
+    def _sf(self, x):
+        return sc.kolmogorov(x)
+
+    def _ppf(self, q):
+        return scu._kolmogci(q)
+
+    def _isf(self, q):
+        return sc.kolmogi(q)
+
+
+kstwobign = kstwobign_gen(a=0.0, name='kstwobign')
+
+
+## Normal distribution
+
+# loc = mu, scale = std
+# Keep these implementations out of the class definition so they can be reused
+# by other distributions.
+_norm_pdf_C = np.sqrt(2*np.pi)
+_norm_pdf_logC = np.log(_norm_pdf_C)
+
+
+def _norm_pdf(x):
+    return np.exp(-x**2/2.0) / _norm_pdf_C
+
+
+def _norm_logpdf(x):
+    return -x**2 / 2.0 - _norm_pdf_logC
+
+
+def _norm_cdf(x):
+    return sc.ndtr(x)
+
+
+def _norm_logcdf(x):
+    return sc.log_ndtr(x)
+
+
+def _norm_ppf(q):
+    return sc.ndtri(q)
+
+
+def _norm_sf(x):
+    return _norm_cdf(-x)
+
+
+def _norm_logsf(x):
+    return _norm_logcdf(-x)
+
+
+def _norm_isf(q):
+    return -_norm_ppf(q)
+
+
+class norm_gen(rv_continuous):
+    r"""A normal continuous random variable.
+
+    The location (``loc``) keyword specifies the mean.
+    The scale (``scale``) keyword specifies the standard deviation.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `norm` is:
+
+    .. math::
+
+        f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}}
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.standard_normal(size)
+
+    def _pdf(self, x):
+        # norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi)
+        return _norm_pdf(x)
+
+    def _logpdf(self, x):
+        return _norm_logpdf(x)
+
+    def _cdf(self, x):
+        return _norm_cdf(x)
+
+    def _logcdf(self, x):
+        return _norm_logcdf(x)
+
+    def _sf(self, x):
+        return _norm_sf(x)
+
+    def _logsf(self, x):
+        return _norm_logsf(x)
+
+    def _ppf(self, q):
+        return _norm_ppf(q)
+
+    def _isf(self, q):
+        return _norm_isf(q)
+
+    def _stats(self):
+        return 0.0, 1.0, 0.0, 0.0
+
+    def _entropy(self):
+        return 0.5*(np.log(2*np.pi)+1)
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        For the normal distribution, method of moments and maximum likelihood
+        estimation give identical fits, and explicit formulas for the estimates
+        are available.
+        This function uses these explicit formulas for the maximum likelihood
+        estimation of the normal distribution parameters, so the
+        `optimizer` and `method` arguments are ignored.\n\n""")
+    def fit(self, data, **kwds):
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            # Without this check, this function would just return the
+            # parameters that were given.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        if floc is None:
+            loc = data.mean()
+        else:
+            loc = floc
+
+        if fscale is None:
+            scale = np.sqrt(((data - loc)**2).mean())
+        else:
+            scale = fscale
+
+        return loc, scale
+
+    def _munp(self, n):
+        """
+        @returns Moments of standard normal distribution for integer n >= 0
+
+        See eq. 16 of https://arxiv.org/abs/1209.4340v2
+        """
+        if n == 0:
+            return 1.
+        if n % 2 == 0:
+            return sc.factorial2(int(n) - 1)
+        else:
+            return 0.
+
+
+norm = norm_gen(name='norm')
+
+
+class alpha_gen(rv_continuous):
+    r"""An alpha continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `alpha` ([1]_, [2]_) is:
+
+    .. math::
+
+        f(x, a) = \frac{1}{x^2 \Phi(a) \sqrt{2\pi}} *
+                  \exp(-\frac{1}{2} (a-1/x)^2)
+
+    where :math:`\Phi` is the normal CDF, :math:`x > 0`, and :math:`a > 0`.
+
+    `alpha` takes ``a`` as a shape parameter.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate
+           Distributions, Volume 1", Second Edition, John Wiley and Sons,
+           p. 173 (1994).
+    .. [2] Anthony A. Salvia, "Reliability applications of the Alpha
+           Distribution", IEEE Transactions on Reliability, Vol. R-34,
+           No. 3, pp. 251-252 (1985).
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # alpha.pdf(x, a) = 1/(x**2*Phi(a)*sqrt(2*pi)) * exp(-1/2 * (a-1/x)**2)
+        return 1.0/(x**2)/_norm_cdf(a)*_norm_pdf(a-1.0/x)
+
+    def _logpdf(self, x, a):
+        return -2*np.log(x) + _norm_logpdf(a-1.0/x) - np.log(_norm_cdf(a))
+
+    def _cdf(self, x, a):
+        return _norm_cdf(a-1.0/x) / _norm_cdf(a)
+
+    def _ppf(self, q, a):
+        return 1.0/np.asarray(a - _norm_ppf(q*_norm_cdf(a)))
+
+    def _stats(self, a):
+        return [np.inf]*2 + [np.nan]*2
+
+
+alpha = alpha_gen(a=0.0, name='alpha')
+
+
+class anglit_gen(rv_continuous):
+    r"""An anglit continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `anglit` is:
+
+    .. math::
+
+        f(x) = \sin(2x + \pi/2) = \cos(2x)
+
+    for :math:`-\pi/4 \le x \le \pi/4`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # anglit.pdf(x) = sin(2*x + \pi/2) = cos(2*x)
+        return np.cos(2*x)
+
+    def _cdf(self, x):
+        return np.sin(x+np.pi/4)**2.0
+
+    def _sf(self, x):
+        return np.cos(x + np.pi / 4) ** 2.0
+
+    def _ppf(self, q):
+        return np.arcsin(np.sqrt(q))-np.pi/4
+
+    def _stats(self):
+        return 0.0, np.pi*np.pi/16-0.5, 0.0, -2*(np.pi**4 - 96)/(np.pi*np.pi-8)**2
+
+    def _entropy(self):
+        return 1-np.log(2)
+
+
+anglit = anglit_gen(a=-np.pi/4, b=np.pi/4, name='anglit')
+
+
+class arcsine_gen(rv_continuous):
+    r"""An arcsine continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `arcsine` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi \sqrt{x (1-x)}}
+
+    for :math:`0 < x < 1`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # arcsine.pdf(x) = 1/(pi*sqrt(x*(1-x)))
+        with np.errstate(divide='ignore'):
+            return 1.0/np.pi/np.sqrt(x*(1-x))
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arcsin(np.sqrt(x))
+
+    def _ppf(self, q):
+        return np.sin(np.pi/2.0*q)**2.0
+
+    def _stats(self):
+        mu = 0.5
+        mu2 = 1.0/8
+        g1 = 0
+        g2 = -3.0/2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self):
+        return -0.24156447527049044468
+
+
+arcsine = arcsine_gen(a=0.0, b=1.0, name='arcsine')
+
+
+class FitDataError(ValueError):
+    """Raised when input data is inconsistent with fixed parameters."""
+    # This exception is raised by, for example, beta_gen.fit when both floc
+    # and fscale are fixed and there are values in the data not in the open
+    # interval (floc, floc+fscale).
+    def __init__(self, distr, lower, upper):
+        self.args = (
+            "Invalid values in `data`.  Maximum likelihood "
+            f"estimation with {distr!r} requires that {lower!r} < "
+            f"(x - loc)/scale  < {upper!r} for each x in `data`.",
+        )
+
+
+class FitSolverError(FitError):
+    """
+    Raised when a solver fails to converge while fitting a distribution.
+    """
+    # This exception is raised by, for example, beta_gen.fit when
+    # optimize.fsolve returns with ier != 1.
+    def __init__(self, mesg):
+        emsg = "Solver for the MLE equations failed to converge: "
+        emsg += mesg.replace('\n', '')
+        self.args = (emsg,)
+
+
+def _beta_mle_a(a, b, n, s1):
+    # The zeros of this function give the MLE for `a`, with
+    # `b`, `n` and `s1` given.  `s1` is the sum of the logs of
+    # the data. `n` is the number of data points.
+    psiab = sc.psi(a + b)
+    func = s1 - n * (-psiab + sc.psi(a))
+    return func
+
+
+def _beta_mle_ab(theta, n, s1, s2):
+    # Zeros of this function are critical points of
+    # the maximum likelihood function.  Solving this system
+    # for theta (which contains a and b) gives the MLE for a and b
+    # given `n`, `s1` and `s2`.  `s1` is the sum of the logs of the data,
+    # and `s2` is the sum of the logs of 1 - data.  `n` is the number
+    # of data points.
+    a, b = theta
+    psiab = sc.psi(a + b)
+    func = [s1 - n * (-psiab + sc.psi(a)),
+            s2 - n * (-psiab + sc.psi(b))]
+    return func
+
+
+class beta_gen(rv_continuous):
+    r"""A beta continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `beta` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{\Gamma(a+b) x^{a-1} (1-x)^{b-1}}
+                          {\Gamma(a) \Gamma(b)}
+
+    for :math:`0 <= x <= 1`, :math:`a > 0`, :math:`b > 0`, where
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `beta` takes :math:`a` and :math:`b` as shape parameters.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        return random_state.beta(a, b, size)
+
+    def _pdf(self, x, a, b):
+        #                     gamma(a+b) * x**(a-1) * (1-x)**(b-1)
+        # beta.pdf(x, a, b) = ------------------------------------
+        #                              gamma(a)*gamma(b)
+        with np.errstate(over='ignore'):
+            return scu._beta_pdf(x, a, b)
+
+    def _logpdf(self, x, a, b):
+        lPx = sc.xlog1py(b - 1.0, -x) + sc.xlogy(a - 1.0, x)
+        lPx -= sc.betaln(a, b)
+        return lPx
+
+    def _cdf(self, x, a, b):
+        return sc.betainc(a, b, x)
+
+    def _sf(self, x, a, b):
+        return sc.betaincc(a, b, x)
+
+    def _isf(self, x, a, b):
+        return sc.betainccinv(a, b, x)
+
+    def _ppf(self, q, a, b):
+        return scu._beta_ppf(q, a, b)
+
+    def _stats(self, a, b):
+        a_plus_b = a + b
+        _beta_mean = a/a_plus_b
+        _beta_variance = a*b / (a_plus_b**2 * (a_plus_b + 1))
+        _beta_skewness = ((2 * (b - a) * np.sqrt(a_plus_b + 1)) /
+                          ((a_plus_b + 2) * np.sqrt(a * b)))
+        _beta_kurtosis_excess_n = 6 * ((a - b)**2 * (a_plus_b + 1) -
+                                       a * b * (a_plus_b + 2))
+        _beta_kurtosis_excess_d = a * b * (a_plus_b + 2) * (a_plus_b + 3)
+        _beta_kurtosis_excess = _beta_kurtosis_excess_n / _beta_kurtosis_excess_d
+        return (
+            _beta_mean,
+            _beta_variance,
+            _beta_skewness,
+            _beta_kurtosis_excess)
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+
+        g1 = _skew(data)
+        g2 = _kurtosis(data)
+
+        def func(x):
+            a, b = x
+            sk = 2*(b-a)*np.sqrt(a + b + 1) / (a + b + 2) / np.sqrt(a*b)
+            ku = a**3 - a**2*(2*b-1) + b**2*(b+1) - 2*a*b*(b+2)
+            ku /= a*b*(a+b+2)*(a+b+3)
+            ku *= 6
+            return [sk-g1, ku-g2]
+        a, b = optimize.fsolve(func, (1.0, 1.0))
+        return super()._fitstart(data, args=(a, b))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        In the special case where `method="MLE"` and
+        both `floc` and `fscale` are given, a
+        `ValueError` is raised if any value `x` in `data` does not satisfy
+        `floc < x < floc + fscale`.\n\n""")
+    def fit(self, data, *args, **kwds):
+        # Override rv_continuous.fit, so we can more efficiently handle the
+        # case where floc and fscale are given.
+
+        floc = kwds.get('floc', None)
+        fscale = kwds.get('fscale', None)
+
+        if floc is None or fscale is None:
+            # do general fit
+            return super().fit(data, *args, **kwds)
+
+        # We already got these from kwds, so just pop them.
+        kwds.pop('floc', None)
+        kwds.pop('fscale', None)
+
+        f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a'])
+        f1 = _get_fixed_fit_value(kwds, ['f1', 'fb', 'fix_b'])
+
+        _remove_optimizer_parameters(kwds)
+
+        if f0 is not None and f1 is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        # Special case: loc and scale are constrained, so we are fitting
+        # just the shape parameters.  This can be done much more efficiently
+        # than the method used in `rv_continuous.fit`.  (See the subsection
+        # "Two unknown parameters" in the section "Maximum likelihood" of
+        # the Wikipedia article on the Beta distribution for the formulas.)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # Normalize the data to the interval [0, 1].
+        data = (np.ravel(data) - floc) / fscale
+        if np.any(data <= 0) or np.any(data >= 1):
+            raise FitDataError("beta", lower=floc, upper=floc + fscale)
+
+        xbar = data.mean()
+
+        if f0 is not None or f1 is not None:
+            # One of the shape parameters is fixed.
+
+            if f0 is not None:
+                # The shape parameter a is fixed, so swap the parameters
+                # and flip the data.  We always solve for `a`.  The result
+                # will be swapped back before returning.
+                b = f0
+                data = 1 - data
+                xbar = 1 - xbar
+            else:
+                b = f1
+
+            # Initial guess for a.  Use the formula for the mean of the beta
+            # distribution, E[x] = a / (a + b), to generate a reasonable
+            # starting point based on the mean of the data and the given
+            # value of b.
+            a = b * xbar / (1 - xbar)
+
+            # Compute the MLE for `a` by solving _beta_mle_a.
+            theta, info, ier, mesg = optimize.fsolve(
+                _beta_mle_a, a,
+                args=(b, len(data), np.log(data).sum()),
+                full_output=True
+            )
+            if ier != 1:
+                raise FitSolverError(mesg=mesg)
+            a = theta[0]
+
+            if f0 is not None:
+                # The shape parameter a was fixed, so swap back the
+                # parameters.
+                a, b = b, a
+
+        else:
+            # Neither of the shape parameters is fixed.
+
+            # s1 and s2 are used in the extra arguments passed to _beta_mle_ab
+            # by optimize.fsolve.
+            s1 = np.log(data).sum()
+            s2 = sc.log1p(-data).sum()
+
+            # Use the "method of moments" to estimate the initial
+            # guess for a and b.
+            fac = xbar * (1 - xbar) / data.var(ddof=0) - 1
+            a = xbar * fac
+            b = (1 - xbar) * fac
+
+            # Compute the MLE for a and b by solving _beta_mle_ab.
+            theta, info, ier, mesg = optimize.fsolve(
+                _beta_mle_ab, [a, b],
+                args=(len(data), s1, s2),
+                full_output=True
+            )
+            if ier != 1:
+                raise FitSolverError(mesg=mesg)
+            a, b = theta
+
+        return a, b, floc, fscale
+
+    def _entropy(self, a, b):
+        def regular(a, b):
+            return (sc.betaln(a, b) - (a - 1) * sc.psi(a) -
+                    (b - 1) * sc.psi(b) + (a + b - 2) * sc.psi(a + b))
+
+        def asymptotic_ab_large(a, b):
+            sum_ab = a + b
+            log_term = 0.5 * (
+                np.log(2*np.pi) + np.log(a) + np.log(b) - 3*np.log(sum_ab) + 1
+            )
+            t1 = 110/sum_ab + 20*sum_ab**-2.0 + sum_ab**-3.0 - 2*sum_ab**-4.0
+            t2 = -50/a - 10*a**-2.0 - a**-3.0 + a**-4.0
+            t3 = -50/b - 10*b**-2.0 - b**-3.0 + b**-4.0
+            return log_term + (t1 + t2 + t3) / 120
+
+        def asymptotic_b_large(a, b):
+            sum_ab = a + b
+            t1 = sc.gammaln(a) - (a - 1) * sc.psi(a)
+            t2 = (
+                - 1/(2*b) + 1/(12*b) - b**-2.0/12 - b**-3.0/120 + b**-4.0/120
+                + b**-5.0/252 - b**-6.0/252 + 1/sum_ab - 1/(12*sum_ab)
+                + sum_ab**-2.0/6 + sum_ab**-3.0/120 - sum_ab**-4.0/60
+                - sum_ab**-5.0/252 + sum_ab**-6.0/126
+            )
+            log_term = sum_ab*np.log1p(a/b) + np.log(b) - 2*np.log(sum_ab)
+            return t1 + t2 + log_term
+
+        def threshold_large(v):
+            if v == 1.0:
+                return 1000
+
+            j = np.log10(v)
+            digits = int(j)
+            d = int(v / 10 ** digits) + 2
+            return d*10**(7 + j)
+
+        if a >= 4.96e6 and b >= 4.96e6:
+            return asymptotic_ab_large(a, b)
+        elif a <= 4.9e6 and b - a >= 1e6 and b >= threshold_large(a):
+            return asymptotic_b_large(a, b)
+        elif b <= 4.9e6 and a - b >= 1e6 and a >= threshold_large(b):
+            return asymptotic_b_large(b, a)
+        else:
+            return regular(a, b)
+
+
+beta = beta_gen(a=0.0, b=1.0, name='beta')
+
+
+class betaprime_gen(rv_continuous):
+    r"""A beta prime continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `betaprime` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{x^{a-1} (1+x)^{-a-b}}{\beta(a, b)}
+
+    for :math:`x >= 0`, :math:`a > 0`, :math:`b > 0`, where
+    :math:`\beta(a, b)` is the beta function (see `scipy.special.beta`).
+
+    `betaprime` takes ``a`` and ``b`` as shape parameters.
+
+    The distribution is related to the `beta` distribution as follows:
+    If :math:`X` follows a beta distribution with parameters :math:`a, b`,
+    then :math:`Y = X/(1-X)` has a beta prime distribution with
+    parameters :math:`a, b` ([1]_).
+
+    The beta prime distribution is a reparametrized version of the
+    F distribution.  The beta prime distribution with shape parameters
+    ``a`` and ``b`` and ``scale = s`` is equivalent to the F distribution
+    with parameters ``d1 = 2*a``, ``d2 = 2*b`` and ``scale = (a/b)*s``.
+    For example,
+
+    >>> from scipy.stats import betaprime, f
+    >>> x = [1, 2, 5, 10]
+    >>> a = 12
+    >>> b = 5
+    >>> betaprime.pdf(x, a, b, scale=2)
+    array([0.00541179, 0.08331299, 0.14669185, 0.03150079])
+    >>> f.pdf(x, 2*a, 2*b, scale=(a/b)*2)
+    array([0.00541179, 0.08331299, 0.14669185, 0.03150079])
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Beta prime distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Beta_prime_distribution
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        u1 = gamma.rvs(a, size=size, random_state=random_state)
+        u2 = gamma.rvs(b, size=size, random_state=random_state)
+        return u1 / u2
+
+    def _pdf(self, x, a, b):
+        # betaprime.pdf(x, a, b) = x**(a-1) * (1+x)**(-a-b) / beta(a, b)
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return sc.xlogy(a - 1.0, x) - sc.xlog1py(a + b, x) - sc.betaln(a, b)
+
+    def _cdf(self, x, a, b):
+        # note: f2 is the direct way to compute the cdf if the relationship
+        # to the beta distribution is used.
+        # however, for very large x, x/(1+x) == 1. since the distribution
+        # has very fat tails if b is small, this can cause inaccurate results
+        # use the following relationship of the incomplete beta function:
+        # betainc(x, a, b) = 1 - betainc(1-x, b, a)
+        # see gh-17631
+        return _lazywhere(
+            x > 1, [x, a, b],
+            lambda x_, a_, b_: beta._sf(1/(1+x_), b_, a_),
+            f2=lambda x_, a_, b_: beta._cdf(x_/(1+x_), a_, b_))
+
+    def _sf(self, x, a, b):
+        return _lazywhere(
+            x > 1, [x, a, b],
+            lambda x_, a_, b_: beta._cdf(1/(1+x_), b_, a_),
+            f2=lambda x_, a_, b_: beta._sf(x_/(1+x_), a_, b_)
+        )
+
+    def _ppf(self, p, a, b):
+        p, a, b = np.broadcast_arrays(p, a, b)
+        # By default, compute the ppf by solving the following:
+        # p = beta._cdf(x/(1+x), a, b). This implies x = r/(1-r) with
+        # r = beta._ppf(p, a, b). This can cause numerical issues if r is
+        # very close to 1. In that case, invert the alternative expression of
+        # the cdf: p = beta._sf(1/(1+x), b, a).
+        r = stats.beta._ppf(p, a, b)
+        with np.errstate(divide='ignore'):
+            out = r / (1 - r)
+        rnear1 = r > 0.9999
+        if np.isscalar(r):
+            if rnear1:
+                out = 1/stats.beta._isf(p, b, a) - 1
+        else:
+            out[rnear1] = 1/stats.beta._isf(p[rnear1], b[rnear1], a[rnear1]) - 1
+        return out
+
+    def _munp(self, n, a, b):
+        return _lazywhere(
+            b > n, (a, b),
+            lambda a, b: np.prod([(a+i-1)/(b-i) for i in range(1, int(n)+1)], axis=0),
+            fillvalue=np.inf)
+
+
+betaprime = betaprime_gen(a=0.0, name='betaprime')
+
+
+class bradford_gen(rv_continuous):
+    r"""A Bradford continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `bradford` is:
+
+    .. math::
+
+        f(x, c) = \frac{c}{\log(1+c) (1+cx)}
+
+    for :math:`0 <= x <= 1` and :math:`c > 0`.
+
+    `bradford` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # bradford.pdf(x, c) = c / (k * (1+c*x))
+        return c / (c*x + 1.0) / sc.log1p(c)
+
+    def _cdf(self, x, c):
+        return sc.log1p(c*x) / sc.log1p(c)
+
+    def _ppf(self, q, c):
+        return sc.expm1(q * sc.log1p(c)) / c
+
+    def _stats(self, c, moments='mv'):
+        k = np.log(1.0+c)
+        mu = (c-k)/(c*k)
+        mu2 = ((c+2.0)*k-2.0*c)/(2*c*k*k)
+        g1 = None
+        g2 = None
+        if 's' in moments:
+            g1 = np.sqrt(2)*(12*c*c-9*c*k*(c+2)+2*k*k*(c*(c+3)+3))
+            g1 /= np.sqrt(c*(c*(k-2)+2*k))*(3*c*(k-2)+6*k)
+        if 'k' in moments:
+            g2 = (c**3*(k-3)*(k*(3*k-16)+24)+12*k*c*c*(k-4)*(k-3) +
+                  6*c*k*k*(3*k-14) + 12*k**3)
+            g2 /= 3*c*(c*(k-2)+2*k)**2
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        k = np.log(1+c)
+        return k/2.0 - np.log(c/k)
+
+
+bradford = bradford_gen(a=0.0, b=1.0, name='bradford')
+
+
+class burr_gen(rv_continuous):
+    r"""A Burr (Type III) continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    fisk : a special case of either `burr` or `burr12` with ``d=1``
+    burr12 : Burr Type XII distribution
+    mielke : Mielke Beta-Kappa / Dagum distribution
+
+    Notes
+    -----
+    The probability density function for `burr` is:
+
+    .. math::
+
+        f(x; c, d) = c d \frac{x^{-c - 1}}
+                              {{(1 + x^{-c})}^{d + 1}}
+
+    for :math:`x >= 0` and :math:`c, d > 0`.
+
+    `burr` takes ``c`` and ``d`` as shape parameters for :math:`c` and
+    :math:`d`.
+
+    This is the PDF corresponding to the third CDF given in Burr's list;
+    specifically, it is equation (11) in Burr's paper [1]_. The distribution
+    is also commonly referred to as the Dagum distribution [2]_. If the
+    parameter :math:`c < 1` then the mean of the distribution does not
+    exist and if :math:`c < 2` the variance does not exist [2]_.
+    The PDF is finite at the left endpoint :math:`x = 0` if :math:`c * d >= 1`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Burr, I. W. "Cumulative frequency functions", Annals of
+       Mathematical Statistics, 13(2), pp 215-232 (1942).
+    .. [2] https://en.wikipedia.org/wiki/Dagum_distribution
+    .. [3] Kleiber, Christian. "A guide to the Dagum distributions."
+       Modeling Income Distributions and Lorenz Curves  pp 97-117 (2008).
+
+    %(example)s
+
+    """
+    # Do not set _support_mask to rv_continuous._open_support_mask
+    # Whether the left-hand endpoint is suitable for pdf evaluation is dependent
+    # on the values of c and d: if c*d >= 1, the pdf is finite, otherwise infinite.
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        id = _ShapeInfo("d", False, (0, np.inf), (False, False))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        # burr.pdf(x, c, d) = c * d * x**(-c-1) * (1+x**(-c))**(-d-1)
+        output = _lazywhere(
+            x == 0, [x, c, d],
+            lambda x_, c_, d_: c_ * d_ * (x_**(c_*d_-1)) / (1 + x_**c_),
+            f2=lambda x_, c_, d_: (c_ * d_ * (x_ ** (-c_ - 1.0)) /
+                                   ((1 + x_ ** (-c_)) ** (d_ + 1.0))))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _logpdf(self, x, c, d):
+        output = _lazywhere(
+            x == 0, [x, c, d],
+            lambda x_, c_, d_: (np.log(c_) + np.log(d_) + sc.xlogy(c_*d_ - 1, x_)
+                                - (d_+1) * sc.log1p(x_**(c_))),
+            f2=lambda x_, c_, d_: (np.log(c_) + np.log(d_)
+                                   + sc.xlogy(-c_ - 1, x_)
+                                   - sc.xlog1py(d_+1, x_**(-c_))))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _cdf(self, x, c, d):
+        return (1 + x**(-c))**(-d)
+
+    def _logcdf(self, x, c, d):
+        return sc.log1p(x**(-c)) * (-d)
+
+    def _sf(self, x, c, d):
+        return np.exp(self._logsf(x, c, d))
+
+    def _logsf(self, x, c, d):
+        return np.log1p(- (1 + x**(-c))**(-d))
+
+    def _ppf(self, q, c, d):
+        return (q**(-1.0/d) - 1)**(-1.0/c)
+
+    def _isf(self, q, c, d):
+        _q = sc.xlog1py(-1.0 / d, -q)
+        return sc.expm1(_q) ** (-1.0 / c)
+
+    def _stats(self, c, d):
+        nc = np.arange(1, 5).reshape(4,1) / c
+        # ek is the kth raw moment, e1 is the mean e2-e1**2 variance etc.
+        e1, e2, e3, e4 = sc.beta(d + nc, 1. - nc) * d
+        mu = np.where(c > 1.0, e1, np.nan)
+        mu2_if_c = e2 - mu**2
+        mu2 = np.where(c > 2.0, mu2_if_c, np.nan)
+        g1 = _lazywhere(
+            c > 3.0,
+            (c, e1, e2, e3, mu2_if_c),
+            lambda c, e1, e2, e3, mu2_if_c: ((e3 - 3*e2*e1 + 2*e1**3)
+                                             / np.sqrt((mu2_if_c)**3)),
+            fillvalue=np.nan)
+        g2 = _lazywhere(
+            c > 4.0,
+            (c, e1, e2, e3, e4, mu2_if_c),
+            lambda c, e1, e2, e3, e4, mu2_if_c: (
+                ((e4 - 4*e3*e1 + 6*e2*e1**2 - 3*e1**4) / mu2_if_c**2) - 3),
+            fillvalue=np.nan)
+        if np.ndim(c) == 0:
+            return mu.item(), mu2.item(), g1.item(), g2.item()
+        return mu, mu2, g1, g2
+
+    def _munp(self, n, c, d):
+        def __munp(n, c, d):
+            nc = 1. * n / c
+            return d * sc.beta(1.0 - nc, d + nc)
+        n, c, d = np.asarray(n), np.asarray(c), np.asarray(d)
+        return _lazywhere((c > n) & (n == n) & (d == d), (c, d, n),
+                          lambda c, d, n: __munp(n, c, d),
+                          np.nan)
+
+
+burr = burr_gen(a=0.0, name='burr')
+
+
+class burr12_gen(rv_continuous):
+    r"""A Burr (Type XII) continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    fisk : a special case of either `burr` or `burr12` with ``d=1``
+    burr : Burr Type III distribution
+
+    Notes
+    -----
+    The probability density function for `burr12` is:
+
+    .. math::
+
+        f(x; c, d) = c d \frac{x^{c-1}}
+                              {(1 + x^c)^{d + 1}}
+
+    for :math:`x >= 0` and :math:`c, d > 0`.
+
+    `burr12` takes ``c`` and ``d`` as shape parameters for :math:`c`
+    and :math:`d`.
+
+    This is the PDF corresponding to the twelfth CDF given in Burr's list;
+    specifically, it is equation (20) in Burr's paper [1]_.
+
+    %(after_notes)s
+
+    The Burr type 12 distribution is also sometimes referred to as
+    the Singh-Maddala distribution from NIST [2]_.
+
+    References
+    ----------
+    .. [1] Burr, I. W. "Cumulative frequency functions", Annals of
+       Mathematical Statistics, 13(2), pp 215-232 (1942).
+
+    .. [2] https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/b12pdf.htm
+
+    .. [3] "Burr distribution",
+       https://en.wikipedia.org/wiki/Burr_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        id = _ShapeInfo("d", False, (0, np.inf), (False, False))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        # burr12.pdf(x, c, d) = c * d * x**(c-1) * (1+x**(c))**(-d-1)
+        return np.exp(self._logpdf(x, c, d))
+
+    def _logpdf(self, x, c, d):
+        return np.log(c) + np.log(d) + sc.xlogy(c - 1, x) + sc.xlog1py(-d-1, x**c)
+
+    def _cdf(self, x, c, d):
+        return -sc.expm1(self._logsf(x, c, d))
+
+    def _logcdf(self, x, c, d):
+        return sc.log1p(-(1 + x**c)**(-d))
+
+    def _sf(self, x, c, d):
+        return np.exp(self._logsf(x, c, d))
+
+    def _logsf(self, x, c, d):
+        return sc.xlog1py(-d, x**c)
+
+    def _ppf(self, q, c, d):
+        # The following is an implementation of
+        #   ((1 - q)**(-1.0/d) - 1)**(1.0/c)
+        # that does a better job handling small values of q.
+        return sc.expm1(-1/d * sc.log1p(-q))**(1/c)
+
+    def _isf(self, p, c, d):
+        return sc.expm1(-1/d * np.log(p))**(1/c)
+
+    def _munp(self, n, c, d):
+        def moment_if_exists(n, c, d):
+            nc = 1. * n / c
+            return d * sc.beta(1.0 + nc, d - nc)
+
+        return _lazywhere(c * d > n, (n, c, d), moment_if_exists,
+                          fillvalue=np.nan)
+
+
+burr12 = burr12_gen(a=0.0, name='burr12')
+
+
+class fisk_gen(burr_gen):
+    r"""A Fisk continuous random variable.
+
+    The Fisk distribution is also known as the log-logistic distribution.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    burr
+
+    Notes
+    -----
+    The probability density function for `fisk` is:
+
+    .. math::
+
+        f(x, c) = \frac{c x^{c-1}}
+                       {(1 + x^c)^2}
+
+    for :math:`x >= 0` and :math:`c > 0`.
+
+    Please note that the above expression can be transformed into the following
+    one, which is also commonly used:
+
+    .. math::
+
+        f(x, c) = \frac{c x^{-c-1}}
+                       {(1 + x^{-c})^2}
+
+    `fisk` takes ``c`` as a shape parameter for :math:`c`.
+
+    `fisk` is a special case of `burr` or `burr12` with ``d=1``.
+
+    Suppose ``X`` is a logistic random variable with location ``l``
+    and scale ``s``. Then ``Y = exp(X)`` is a Fisk (log-logistic)
+    random variable with ``scale = exp(l)`` and shape ``c = 1/s``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2)
+        return burr._pdf(x, c, 1.0)
+
+    def _cdf(self, x, c):
+        return burr._cdf(x, c, 1.0)
+
+    def _sf(self, x, c):
+        return burr._sf(x, c, 1.0)
+
+    def _logpdf(self, x, c):
+        # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2)
+        return burr._logpdf(x, c, 1.0)
+
+    def _logcdf(self, x, c):
+        return burr._logcdf(x, c, 1.0)
+
+    def _logsf(self, x, c):
+        return burr._logsf(x, c, 1.0)
+
+    def _ppf(self, x, c):
+        return burr._ppf(x, c, 1.0)
+
+    def _isf(self, q, c):
+        return burr._isf(q, c, 1.0)
+
+    def _munp(self, n, c):
+        return burr._munp(n, c, 1.0)
+
+    def _stats(self, c):
+        return burr._stats(c, 1.0)
+
+    def _entropy(self, c):
+        return 2 - np.log(c)
+
+
+fisk = fisk_gen(a=0.0, name='fisk')
+
+
+class cauchy_gen(rv_continuous):
+    r"""A Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `cauchy` is
+
+    .. math::
+
+        f(x) = \frac{1}{\pi (1 + x^2)}
+
+    for a real number :math:`x`.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``ppf` and ``isf`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # cauchy.pdf(x) = 1 / (pi * (1 + x**2))
+        with np.errstate(over='ignore'):
+            return 1.0/np.pi/(1.0+x*x)
+
+    def _logpdf(self, x):
+        # The formulas
+        #     log(1/(pi*(1 + x**2))) = -log(pi) - log(1 + x**2)
+        #                            = -log(pi) - log(x**2*(1 + 1/x**2))
+        #                            = -log(pi) - (2log(|x|) + log1p(1/x**2))
+        # are used here.
+        absx = np.abs(x)
+        # In the following _lazywhere, `f` provides better precision than `f2`
+        # for small and moderate x, while `f2` avoids the overflow that can
+        # occur with absx**2.
+        y = _lazywhere(absx < 1, (absx,),
+                       f=lambda absx: -_LOG_PI - np.log1p(absx**2),
+                       f2=lambda absx: (-_LOG_PI -
+                                        (2*np.log(absx) + np.log1p((1/absx)**2))))
+        return y
+
+    def _cdf(self, x):
+        return np.arctan2(1, -x)/np.pi
+
+    def _ppf(self, q):
+        return scu._cauchy_ppf(q, 0, 1)
+
+    def _sf(self, x):
+        return np.arctan2(1, x)/np.pi
+
+    def _isf(self, q):
+        return scu._cauchy_isf(q, 0, 1)
+
+    def _stats(self):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _entropy(self):
+        return np.log(4*np.pi)
+
+    def _fitstart(self, data, args=None):
+        # Initialize ML guesses using quartiles instead of moments.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return p50, (p75 - p25)/2
+
+
+cauchy = cauchy_gen(name='cauchy')
+
+
+class chi_gen(rv_continuous):
+    r"""A chi continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `chi` is:
+
+    .. math::
+
+        f(x, k) = \frac{1}{2^{k/2-1} \Gamma \left( k/2 \right)}
+                   x^{k-1} \exp \left( -x^2/2 \right)
+
+    for :math:`x >= 0` and :math:`k > 0` (degrees of freedom, denoted ``df``
+    in the implementation). :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    Special cases of `chi` are:
+
+        - ``chi(1, loc, scale)`` is equivalent to `halfnorm`
+        - ``chi(2, 0, scale)`` is equivalent to `rayleigh`
+        - ``chi(3, 0, scale)`` is equivalent to `maxwell`
+
+    `chi` takes ``df`` as a shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return np.sqrt(chi2.rvs(df, size=size, random_state=random_state))
+
+    def _pdf(self, x, df):
+        #                   x**(df-1) * exp(-x**2/2)
+        # chi.pdf(x, df) =  -------------------------
+        #                   2**(df/2-1) * gamma(df/2)
+        return np.exp(self._logpdf(x, df))
+
+    def _logpdf(self, x, df):
+        l = np.log(2) - .5*np.log(2)*df - sc.gammaln(.5*df)
+        return l + sc.xlogy(df - 1., x) - .5*x**2
+
+    def _cdf(self, x, df):
+        return sc.gammainc(.5*df, .5*x**2)
+
+    def _sf(self, x, df):
+        return sc.gammaincc(.5*df, .5*x**2)
+
+    def _ppf(self, q, df):
+        return np.sqrt(2*sc.gammaincinv(.5*df, q))
+
+    def _isf(self, q, df):
+        return np.sqrt(2*sc.gammainccinv(.5*df, q))
+
+    def _stats(self, df):
+        # poch(df/2, 1/2) = gamma(df/2 + 1/2) / gamma(df/2)
+        mu = np.sqrt(2) * sc.poch(0.5 * df, 0.5)
+        mu2 = df - mu*mu
+        g1 = (2*mu**3.0 + mu*(1-2*df))/np.asarray(np.power(mu2, 1.5))
+        g2 = 2*df*(1.0-df)-6*mu**4 + 4*mu**2 * (2*df-1)
+        g2 /= np.asarray(mu2**2.0)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+
+        def regular_formula(df):
+            return (sc.gammaln(.5 * df)
+                    + 0.5 * (df - np.log(2) - (df - 1) * sc.digamma(0.5 * df)))
+
+        def asymptotic_formula(df):
+            return (0.5 + np.log(np.pi)/2 - (df**-1)/6 - (df**-2)/6
+                    - 4/45*(df**-3) + (df**-4)/15)
+
+        return _lazywhere(df < 3e2, (df, ), regular_formula,
+                          f2=asymptotic_formula)
+
+
+chi = chi_gen(a=0.0, name='chi')
+
+
+class chi2_gen(rv_continuous):
+    r"""A chi-squared continuous random variable.
+
+    For the noncentral chi-square distribution, see `ncx2`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ncx2
+
+    Notes
+    -----
+    The probability density function for `chi2` is:
+
+    .. math::
+
+        f(x, k) = \frac{1}{2^{k/2} \Gamma \left( k/2 \right)}
+                   x^{k/2-1} \exp \left( -x/2 \right)
+
+    for :math:`x > 0`  and :math:`k > 0` (degrees of freedom, denoted ``df``
+    in the implementation).
+
+    `chi2` takes ``df`` as a shape parameter.
+
+    The chi-squared distribution is a special case of the gamma
+    distribution, with gamma parameters ``a = df/2``, ``loc = 0`` and
+    ``scale = 2``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return random_state.chisquare(df, size)
+
+    def _pdf(self, x, df):
+        # chi2.pdf(x, df) = 1 / (2*gamma(df/2)) * (x/2)**(df/2-1) * exp(-x/2)
+        return np.exp(self._logpdf(x, df))
+
+    def _logpdf(self, x, df):
+        return sc.xlogy(df/2.-1, x) - x/2. - sc.gammaln(df/2.) - (np.log(2)*df)/2.
+
+    def _cdf(self, x, df):
+        return sc.chdtr(df, x)
+
+    def _sf(self, x, df):
+        return sc.chdtrc(df, x)
+
+    def _isf(self, p, df):
+        return sc.chdtri(df, p)
+
+    def _ppf(self, p, df):
+        return 2*sc.gammaincinv(df/2, p)
+
+    def _stats(self, df):
+        mu = df
+        mu2 = 2*df
+        g1 = 2*np.sqrt(2.0/df)
+        g2 = 12.0/df
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+        half_df = 0.5 * df
+
+        def regular_formula(half_df):
+            return (half_df + np.log(2) + sc.gammaln(half_df) +
+                    (1 - half_df) * sc.psi(half_df))
+
+        def asymptotic_formula(half_df):
+            # plug in the above formula the following asymptotic
+            # expansions:
+            # ln(gamma(a)) ~ (a - 0.5) * ln(a) - a + 0.5 * ln(2 * pi) +
+            #                 1/(12 * a) - 1/(360 * a**3)
+            # psi(a) ~ ln(a) - 1/(2 * a) - 1/(3 * a**2) + 1/120 * a**4)
+            c = np.log(2) + 0.5*(1 + np.log(2*np.pi))
+            h = 0.5/half_df
+            return (h*(-2/3 + h*(-1/3 + h*(-4/45 + h/7.5))) +
+                    0.5*np.log(half_df) + c)
+
+        return _lazywhere(half_df < 125, (half_df, ),
+                          regular_formula,
+                          f2=asymptotic_formula)
+
+
+chi2 = chi2_gen(a=0.0, name='chi2')
+
+
+class cosine_gen(rv_continuous):
+    r"""A cosine continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The cosine distribution is an approximation to the normal distribution.
+    The probability density function for `cosine` is:
+
+    .. math::
+
+        f(x) = \frac{1}{2\pi} (1+\cos(x))
+
+    for :math:`-\pi \le x \le \pi`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # cosine.pdf(x) = 1/(2*pi) * (1+cos(x))
+        return 1.0/2/np.pi*(1+np.cos(x))
+
+    def _logpdf(self, x):
+        c = np.cos(x)
+        return _lazywhere(c != -1, (c,),
+                          lambda c: np.log1p(c) - np.log(2*np.pi),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x):
+        return scu._cosine_cdf(x)
+
+    def _sf(self, x):
+        return scu._cosine_cdf(-x)
+
+    def _ppf(self, p):
+        return scu._cosine_invcdf(p)
+
+    def _isf(self, p):
+        return -scu._cosine_invcdf(p)
+
+    def _stats(self):
+        v = (np.pi * np.pi / 3.0) - 2.0
+        k = -6.0 * (np.pi**4 - 90) / (5.0 * (np.pi * np.pi - 6)**2)
+        return 0.0, v, 0.0, k
+
+    def _entropy(self):
+        return np.log(4*np.pi)-1.0
+
+
+cosine = cosine_gen(a=-np.pi, b=np.pi, name='cosine')
+
+
+class dgamma_gen(rv_continuous):
+    r"""A double gamma continuous random variable.
+
+    The double gamma distribution is also known as the reflected gamma
+    distribution [1]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dgamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{1}{2\Gamma(a)} |x|^{a-1} \exp(-|x|)
+
+    for a real number :math:`x` and :math:`a > 0`. :math:`\Gamma` is the
+    gamma function (`scipy.special.gamma`).
+
+    `dgamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate
+           Distributions, Volume 1", Second Edition, John Wiley and Sons
+           (1994).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        u = random_state.uniform(size=size)
+        gm = gamma.rvs(a, size=size, random_state=random_state)
+        return gm * np.where(u >= 0.5, 1, -1)
+
+    def _pdf(self, x, a):
+        # dgamma.pdf(x, a) = 1 / (2*gamma(a)) * abs(x)**(a-1) * exp(-abs(x))
+        ax = abs(x)
+        return 1.0/(2*sc.gamma(a))*ax**(a-1.0) * np.exp(-ax)
+
+    def _logpdf(self, x, a):
+        ax = abs(x)
+        return sc.xlogy(a - 1.0, ax) - ax - np.log(2) - sc.gammaln(a)
+
+    def _cdf(self, x, a):
+        return np.where(x > 0,
+                        0.5 + 0.5*sc.gammainc(a, x),
+                        0.5*sc.gammaincc(a, -x))
+
+    def _sf(self, x, a):
+        return np.where(x > 0,
+                        0.5*sc.gammaincc(a, x),
+                        0.5 + 0.5*sc.gammainc(a, -x))
+
+    def _entropy(self, a):
+        return stats.gamma._entropy(a) - np.log(0.5)
+
+    def _ppf(self, q, a):
+        return np.where(q > 0.5,
+                        sc.gammaincinv(a, 2*q - 1),
+                        -sc.gammainccinv(a, 2*q))
+
+    def _isf(self, q, a):
+        return np.where(q > 0.5,
+                        -sc.gammaincinv(a, 2*q - 1),
+                        sc.gammainccinv(a, 2*q))
+
+    def _stats(self, a):
+        mu2 = a*(a+1.0)
+        return 0.0, mu2, 0.0, (a+2.0)*(a+3.0)/mu2-3.0
+
+
+dgamma = dgamma_gen(name='dgamma')
+
+
+class dpareto_lognorm_gen(rv_continuous):
+    r"""A double Pareto lognormal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dpareto_lognorm` is:
+
+    .. math::
+
+        f(x, \mu, \sigma, \alpha, \beta) =
+        \frac{\alpha \beta}{(\alpha + \beta) x}
+        \phi\left( \frac{\log x - \mu}{\sigma} \right)
+        \left( R(y_1) + R(y_2) \right)
+
+    where :math:`R(t) = \frac{1 - \Phi(t)}{\phi(t)}`,
+    :math:`\phi` and :math:`\Phi` are the normal PDF and CDF, respectively,
+    :math:`y_1 = \alpha \sigma - \frac{\log x - \mu}{\sigma}`,
+    and :math:`y_2 = \beta \sigma + \frac{\log x - \mu}{\sigma}`
+    for real numbers :math:`x` and :math:`\mu`, :math:`\sigma > 0`,
+    :math:`\alpha > 0`, and :math:`\beta > 0` [1]_.
+
+    `dpareto_lognorm` takes
+    ``u`` as a shape parameter for :math:`\mu`,
+    ``s`` as a shape parameter for :math:`\sigma`,
+    ``a`` as a shape parameter for :math:`\alpha`, and
+    ``b`` as a shape parameter for :math:`\beta`.
+
+    A random variable :math:`X` distributed according to the PDF above
+    can be represented as :math:`X = U \frac{V_1}{V_2}` where :math:`U`,
+    :math:`V_1`, and :math:`V_2` are independent, :math:`U` is lognormally
+    distributed such that :math:`\log U \sim N(\mu, \sigma^2)`, and
+    :math:`V_1` and :math:`V_2` follow Pareto distributions with parameters
+    :math:`\alpha` and :math:`\beta`, respectively [2]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Hajargasht, Gholamreza, and William E. Griffiths. "Pareto-lognormal
+           distributions: Inequality, poverty, and estimation from grouped income
+           data." Economic Modelling 33 (2013): 593-604.
+    .. [2] Reed, William J., and Murray Jorgensen. "The double Pareto-lognormal
+           distribution - a new parametric model for size distributions."
+           Communications in Statistics - Theory and Methods 33.8 (2004): 1733-1753.
+
+    %(example)s
+
+    """
+    _logphi = norm._logpdf
+    _logPhi = norm._logcdf
+    _logPhic = norm._logsf
+    _phi = norm._pdf
+    _Phi = norm._cdf
+    _Phic = norm._sf
+
+    def _R(self, z):
+        return self._Phic(z) / self._phi(z)
+
+    def _logR(self, z):
+        return self._logPhic(z) - self._logphi(z)
+
+    def _shape_info(self):
+        return [_ShapeInfo("u", False, (-np.inf, np.inf), (False, False)),
+                _ShapeInfo("s", False, (0, np.inf), (False, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _argcheck(self, u, s, a, b):
+        return (s > 0) & (a > 0) & (b > 0)
+
+    def _rvs(self, u, s, a, b, size=None, random_state=None):
+        # From [1] after Equation (12): "To generate pseudo-random
+        # deviates from the dPlN distribution, one can exponentiate
+        # pseudo-random deviates from NL generated using (6)."
+        Z = random_state.normal(u, s, size=size)
+        E1 = random_state.standard_exponential(size=size)
+        E2 = random_state.standard_exponential(size=size)
+        return np.exp(Z + E1 / a - E2 / b)
+
+    def _logpdf(self, x, u, s, a, b):
+        with np.errstate(invalid='ignore', divide='ignore'):
+            log_y, m = np.log(x), u  # compare against [1] Eq. 1
+            z = (log_y - m) / s
+            x1 = a * s - z
+            x2 = b * s + z
+            out = np.asarray(np.log(a) + np.log(b) - np.log(a + b) - log_y)
+            out += self._logphi(z)
+            out += np.logaddexp(self._logR(x1), self._logR(x2))
+        out[(x == 0) | np.isinf(x)] = -np.inf
+        return out[()]
+
+    def _logcdf(self, x, u, s, a, b):
+        with np.errstate(invalid='ignore', divide='ignore'):
+            log_y, m = np.log(x), u  # compare against [1] Eq. 2
+            z = (log_y - m) / s
+            x1 = a * s - z
+            x2 = b * s + z
+            t1 = self._logPhi(z)
+            t2 = self._logphi(z)
+            t3 = (np.log(b) + self._logR(x1))
+            t4 = (np.log(a) + self._logR(x2))
+            t1, t2, t3, t4, one = np.broadcast_arrays(t1, t2, t3, t4, 1)
+            # t3 can be smaller than t4, so we have to consider log of negative number
+            # This would be much simpler, but `return_sign` is available, so use it?
+            # t5 =  sc.logsumexp([t3, t4 + np.pi*1j])
+            t5, sign =  sc.logsumexp([t3, t4], b=[one, -one], axis=0, return_sign=True)
+            temp = [t1, t2 + t5 - np.log(a + b)]
+            out = np.asarray(sc.logsumexp(temp, b=[one, -one*sign], axis=0))
+        out[x == 0] = -np.inf
+        return out[()]
+
+    def _logsf(self, x, u, s, a, b):
+        return _log1mexp(self._logcdf(x, u, s, a, b))
+
+    # Infrastructure doesn't seem to do this, so...
+
+    def _pdf(self, x, u, s, a, b):
+        return np.exp(self._logpdf(x, u, s, a, b))
+
+    def _cdf(self, x, u, s, a, b):
+        return np.exp(self._logcdf(x, u, s, a, b))
+
+    def _sf(self, x, u, s, a, b):
+        return np.exp(self._logsf(x, u, s, a, b))
+
+    def _munp(self, n, u, s, a, b):
+        m, k = u, float(n)  # compare against [1] Eq. 6
+        out = (a * b) / ((a - k) * (b + k)) * np.exp(k * m + k ** 2 * s ** 2 / 2)
+        out = np.asarray(out)
+        out[a <= k] = np.nan
+        return out
+
+
+dpareto_lognorm = dpareto_lognorm_gen(a=0, name='dpareto_lognorm')
+
+
+class dweibull_gen(rv_continuous):
+    r"""A double Weibull continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dweibull` is given by
+
+    .. math::
+
+        f(x, c) = c / 2 |x|^{c-1} \exp(-|x|^c)
+
+    for a real number :math:`x` and :math:`c > 0`.
+
+    `dweibull` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        u = random_state.uniform(size=size)
+        w = weibull_min.rvs(c, size=size, random_state=random_state)
+        return w * (np.where(u >= 0.5, 1, -1))
+
+    def _pdf(self, x, c):
+        # dweibull.pdf(x, c) = c / 2 * abs(x)**(c-1) * exp(-abs(x)**c)
+        ax = abs(x)
+        Px = c / 2.0 * ax**(c-1.0) * np.exp(-ax**c)
+        return Px
+
+    def _logpdf(self, x, c):
+        ax = abs(x)
+        return np.log(c) - np.log(2.0) + sc.xlogy(c - 1.0, ax) - ax**c
+
+    def _cdf(self, x, c):
+        Cx1 = 0.5 * np.exp(-abs(x)**c)
+        return np.where(x > 0, 1 - Cx1, Cx1)
+
+    def _ppf(self, q, c):
+        fac = 2. * np.where(q <= 0.5, q, 1. - q)
+        fac = np.power(-np.log(fac), 1.0 / c)
+        return np.where(q > 0.5, fac, -fac)
+
+    def _sf(self, x, c):
+        half_weibull_min_sf = 0.5 * stats.weibull_min._sf(np.abs(x), c)
+        return np.where(x > 0, half_weibull_min_sf, 1 - half_weibull_min_sf)
+
+    def _isf(self, q, c):
+        double_q = 2. * np.where(q <= 0.5, q, 1. - q)
+        weibull_min_isf = stats.weibull_min._isf(double_q, c)
+        return np.where(q > 0.5, -weibull_min_isf, weibull_min_isf)
+
+    def _munp(self, n, c):
+        return (1 - (n % 2)) * sc.gamma(1.0 + 1.0 * n / c)
+
+    # since we know that all odd moments are zeros, return them at once.
+    # returning Nones from _stats makes the public stats call _munp
+    # so overall we're saving one or two gamma function evaluations here.
+    def _stats(self, c):
+        return 0, None, 0, None
+
+    def _entropy(self, c):
+        h = stats.weibull_min._entropy(c) - np.log(0.5)
+        return h
+
+
+dweibull = dweibull_gen(name='dweibull')
+
+
+class expon_gen(rv_continuous):
+    r"""An exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `expon` is:
+
+    .. math::
+
+        f(x) = \exp(-x)
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    A common parameterization for `expon` is in terms of the rate parameter
+    ``lambda``, such that ``pdf = lambda * exp(-lambda * x)``. This
+    parameterization corresponds to using ``scale = 1 / lambda``.
+
+    The exponential distribution is a special case of the gamma
+    distributions, with gamma shape parameter ``a = 1``.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.standard_exponential(size)
+
+    def _pdf(self, x):
+        # expon.pdf(x) = exp(-x)
+        return np.exp(-x)
+
+    def _logpdf(self, x):
+        return -x
+
+    def _cdf(self, x):
+        return -sc.expm1(-x)
+
+    def _ppf(self, q):
+        return -sc.log1p(-q)
+
+    def _sf(self, x):
+        return np.exp(-x)
+
+    def _logsf(self, x):
+        return -x
+
+    def _isf(self, q):
+        return -np.log(q)
+
+    def _stats(self):
+        return 1.0, 1.0, 2.0, 6.0
+
+    def _entropy(self):
+        return 1.0
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        When `method='MLE'`,
+        this function uses explicit formulas for the maximum likelihood
+        estimation of the exponential distribution parameters, so the
+        `optimizer`, `loc` and `scale` keyword arguments are
+        ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if len(args) > 0:
+            raise TypeError("Too many arguments.")
+
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        data_min = data.min()
+
+        if floc is None:
+            # ML estimate of the location is the minimum of the data.
+            loc = data_min
+        else:
+            loc = floc
+            if data_min < loc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("expon", lower=floc, upper=np.inf)
+
+        if fscale is None:
+            # ML estimate of the scale is the shifted mean.
+            scale = data.mean() - loc
+        else:
+            scale = fscale
+
+        # We expect the return values to be floating point, so ensure it
+        # by explicitly converting to float.
+        return float(loc), float(scale)
+
+
+expon = expon_gen(a=0.0, name='expon')
+
+
+class exponnorm_gen(rv_continuous):
+    r"""An exponentially modified Normal continuous random variable.
+
+    Also known as the exponentially modified Gaussian distribution [1]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `exponnorm` is:
+
+    .. math::
+
+        f(x, K) = \frac{1}{2K} \exp\left(\frac{1}{2 K^2} - x / K \right)
+                  \text{erfc}\left(-\frac{x - 1/K}{\sqrt{2}}\right)
+
+    where :math:`x` is a real number and :math:`K > 0`.
+
+    It can be thought of as the sum of a standard normal random variable
+    and an independent exponentially distributed random variable with rate
+    ``1/K``.
+
+    %(after_notes)s
+
+    An alternative parameterization of this distribution (for example, in
+    the Wikipedia article [1]_) involves three parameters, :math:`\mu`,
+    :math:`\lambda` and :math:`\sigma`.
+
+    In the present parameterization this corresponds to having ``loc`` and
+    ``scale`` equal to :math:`\mu` and :math:`\sigma`, respectively, and
+    shape parameter :math:`K = 1/(\sigma\lambda)`.
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] Exponentially modified Gaussian distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("K", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, K, size=None, random_state=None):
+        expval = random_state.standard_exponential(size) * K
+        gval = random_state.standard_normal(size)
+        return expval + gval
+
+    def _pdf(self, x, K):
+        return np.exp(self._logpdf(x, K))
+
+    def _logpdf(self, x, K):
+        invK = 1.0 / K
+        exparg = invK * (0.5 * invK - x)
+        return exparg + _norm_logcdf(x - invK) - np.log(K)
+
+    def _cdf(self, x, K):
+        invK = 1.0 / K
+        expval = invK * (0.5 * invK - x)
+        logprod = expval + _norm_logcdf(x - invK)
+        return _norm_cdf(x) - np.exp(logprod)
+
+    def _sf(self, x, K):
+        invK = 1.0 / K
+        expval = invK * (0.5 * invK - x)
+        logprod = expval + _norm_logcdf(x - invK)
+        return _norm_cdf(-x) + np.exp(logprod)
+
+    def _stats(self, K):
+        K2 = K * K
+        opK2 = 1.0 + K2
+        skw = 2 * K**3 * opK2**(-1.5)
+        krt = 6.0 * K2 * K2 * opK2**(-2)
+        return K, opK2, skw, krt
+
+
+exponnorm = exponnorm_gen(name='exponnorm')
+
+
+def _pow1pm1(x, y):
+    """
+    Compute (1 + x)**y - 1.
+
+    Uses expm1 and xlog1py to avoid loss of precision when
+    (1 + x)**y is close to 1.
+
+    Note that the inverse of this function with respect to x is
+    ``_pow1pm1(x, 1/y)``.  That is, if
+
+        t = _pow1pm1(x, y)
+
+    then
+
+        x = _pow1pm1(t, 1/y)
+    """
+    return np.expm1(sc.xlog1py(y, x))
+
+
+class exponweib_gen(rv_continuous):
+    r"""An exponentiated Weibull continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min, numpy.random.Generator.weibull
+
+    Notes
+    -----
+    The probability density function for `exponweib` is:
+
+    .. math::
+
+        f(x, a, c) = a c [1-\exp(-x^c)]^{a-1} \exp(-x^c) x^{c-1}
+
+    and its cumulative distribution function is:
+
+    .. math::
+
+        F(x, a, c) = [1-\exp(-x^c)]^a
+
+    for :math:`x > 0`, :math:`a > 0`, :math:`c > 0`.
+
+    `exponweib` takes :math:`a` and :math:`c` as shape parameters:
+
+    * :math:`a` is the exponentiation parameter,
+      with the special case :math:`a=1` corresponding to the
+      (non-exponentiated) Weibull distribution `weibull_min`.
+    * :math:`c` is the shape parameter of the non-exponentiated Weibull law.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Exponentiated_Weibull_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        return [ia, ic]
+
+    def _pdf(self, x, a, c):
+        # exponweib.pdf(x, a, c) =
+        #     a * c * (1-exp(-x**c))**(a-1) * exp(-x**c)*x**(c-1)
+        return np.exp(self._logpdf(x, a, c))
+
+    def _logpdf(self, x, a, c):
+        negxc = -x**c
+        exm1c = -sc.expm1(negxc)
+        logp = (np.log(a) + np.log(c) + sc.xlogy(a - 1.0, exm1c) +
+                negxc + sc.xlogy(c - 1.0, x))
+        return logp
+
+    def _cdf(self, x, a, c):
+        exm1c = -sc.expm1(-x**c)
+        return exm1c**a
+
+    def _ppf(self, q, a, c):
+        return (-sc.log1p(-q**(1.0/a)))**np.asarray(1.0/c)
+
+    def _sf(self, x, a, c):
+        return -_pow1pm1(-np.exp(-x**c), a)
+
+    def _isf(self, p, a, c):
+        return (-np.log(-_pow1pm1(-p, 1/a)))**(1/c)
+
+
+exponweib = exponweib_gen(a=0.0, name='exponweib')
+
+
+class exponpow_gen(rv_continuous):
+    r"""An exponential power continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `exponpow` is:
+
+    .. math::
+
+        f(x, b) = b x^{b-1} \exp(1 + x^b - \exp(x^b))
+
+    for :math:`x \ge 0`, :math:`b > 0`.  Note that this is a different
+    distribution from the exponential power distribution that is also known
+    under the names "generalized normal" or "generalized Gaussian".
+
+    `exponpow` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Exponentialpower.pdf
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, b):
+        # exponpow.pdf(x, b) = b * x**(b-1) * exp(1 + x**b - exp(x**b))
+        return np.exp(self._logpdf(x, b))
+
+    def _logpdf(self, x, b):
+        xb = x**b
+        f = 1 + np.log(b) + sc.xlogy(b - 1.0, x) + xb - np.exp(xb)
+        return f
+
+    def _cdf(self, x, b):
+        return -sc.expm1(-sc.expm1(x**b))
+
+    def _sf(self, x, b):
+        return np.exp(-sc.expm1(x**b))
+
+    def _isf(self, x, b):
+        return (sc.log1p(-np.log(x)))**(1./b)
+
+    def _ppf(self, q, b):
+        return pow(sc.log1p(-sc.log1p(-q)), 1.0/b)
+
+
+exponpow = exponpow_gen(a=0.0, name='exponpow')
+
+
+class fatiguelife_gen(rv_continuous):
+    r"""A fatigue-life (Birnbaum-Saunders) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `fatiguelife` is:
+
+    .. math::
+
+        f(x, c) = \frac{x+1}{2c\sqrt{2\pi x^3}} \exp(-\frac{(x-1)^2}{2x c^2})
+
+    for :math:`x >= 0` and :math:`c > 0`.
+
+    `fatiguelife` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Birnbaum-Saunders distribution",
+           https://en.wikipedia.org/wiki/Birnbaum-Saunders_distribution
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        z = random_state.standard_normal(size)
+        x = 0.5*c*z
+        x2 = x*x
+        t = 1.0 + 2*x2 + 2*x*np.sqrt(1 + x2)
+        return t
+
+    def _pdf(self, x, c):
+        # fatiguelife.pdf(x, c) =
+        #     (x+1) / (2*c*sqrt(2*pi*x**3)) * exp(-(x-1)**2/(2*x*c**2))
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return (np.log(x+1) - (x-1)**2 / (2.0*x*c**2) - np.log(2*c) -
+                0.5*(np.log(2*np.pi) + 3*np.log(x)))
+
+    def _cdf(self, x, c):
+        return _norm_cdf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x)))
+
+    def _ppf(self, q, c):
+        tmp = c * _norm_ppf(q)
+        return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2
+
+    def _sf(self, x, c):
+        return _norm_sf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x)))
+
+    def _isf(self, q, c):
+        tmp = -c * _norm_ppf(q)
+        return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2
+
+    def _stats(self, c):
+        # NB: the formula for kurtosis in wikipedia seems to have an error:
+        # it's 40, not 41. At least it disagrees with the one from Wolfram
+        # Alpha.  And the latter one, below, passes the tests, while the wiki
+        # one doesn't So far I didn't have the guts to actually check the
+        # coefficients from the expressions for the raw moments.
+        c2 = c*c
+        mu = c2 / 2.0 + 1.0
+        den = 5.0 * c2 + 4.0
+        mu2 = c2*den / 4.0
+        g1 = 4 * c * (11*c2 + 6.0) / np.power(den, 1.5)
+        g2 = 6 * c2 * (93*c2 + 40.0) / den**2.0
+        return mu, mu2, g1, g2
+
+
+fatiguelife = fatiguelife_gen(a=0.0, name='fatiguelife')
+
+
+class foldcauchy_gen(rv_continuous):
+    r"""A folded Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `foldcauchy` is:
+
+    .. math::
+
+        f(x, c) = \frac{1}{\pi (1+(x-c)^2)} + \frac{1}{\pi (1+(x+c)^2)}
+
+    for :math:`x \ge 0` and :math:`c \ge 0`.
+
+    `foldcauchy` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return c >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        return abs(cauchy.rvs(loc=c, size=size,
+                              random_state=random_state))
+
+    def _pdf(self, x, c):
+        # foldcauchy.pdf(x, c) = 1/(pi*(1+(x-c)**2)) + 1/(pi*(1+(x+c)**2))
+        return 1.0/np.pi*(1.0/(1+(x-c)**2) + 1.0/(1+(x+c)**2))
+
+    def _cdf(self, x, c):
+        return 1.0/np.pi*(np.arctan(x-c) + np.arctan(x+c))
+
+    def _sf(self, x, c):
+        # 1 - CDF(x, c) = 1 - (atan(x - c) + atan(x + c))/pi
+        #               = ((pi/2 - atan(x - c)) + (pi/2 - atan(x + c)))/pi
+        #               = (acot(x - c) + acot(x + c))/pi
+        #               = (atan2(1, x - c) + atan2(1, x + c))/pi
+        return (np.arctan2(1, x - c) + np.arctan2(1, x + c))/np.pi
+
+    def _stats(self, c):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy')
+
+
+class f_gen(rv_continuous):
+    r"""An F continuous random variable.
+
+    For the noncentral F distribution, see `ncf`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ncf
+
+    Notes
+    -----
+    The F distribution with :math:`df_1 > 0` and :math:`df_2 > 0` degrees of freedom is
+    the distribution of the ratio of two independent chi-squared distributions with
+    :math:`df_1` and :math:`df_2` degrees of freedom, after rescaling by
+    :math:`df_2 / df_1`.
+
+    The probability density function for `f` is:
+
+    .. math::
+
+        f(x, df_1, df_2) = \frac{df_2^{df_2/2} df_1^{df_1/2} x^{df_1 / 2-1}}
+                                {(df_2+df_1 x)^{(df_1+df_2)/2}
+                                 B(df_1/2, df_2/2)}
+
+    for :math:`x > 0`.
+
+    `f` accepts shape parameters ``dfn`` and ``dfd`` for :math:`df_1`, the degrees of
+    freedom of the chi-squared distribution in the numerator, and :math:`df_2`, the
+    degrees of freedom of the chi-squared distribution in the denominator, respectively.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        idfn = _ShapeInfo("dfn", False, (0, np.inf), (False, False))
+        idfd = _ShapeInfo("dfd", False, (0, np.inf), (False, False))
+        return [idfn, idfd]
+
+    def _rvs(self, dfn, dfd, size=None, random_state=None):
+        return random_state.f(dfn, dfd, size)
+
+    def _pdf(self, x, dfn, dfd):
+        #                      df2**(df2/2) * df1**(df1/2) * x**(df1/2-1)
+        # F.pdf(x, df1, df2) = --------------------------------------------
+        #                      (df2+df1*x)**((df1+df2)/2) * B(df1/2, df2/2)
+        return np.exp(self._logpdf(x, dfn, dfd))
+
+    def _logpdf(self, x, dfn, dfd):
+        n = 1.0 * dfn
+        m = 1.0 * dfd
+        lPx = (m/2 * np.log(m) + n/2 * np.log(n) + sc.xlogy(n/2 - 1, x)
+               - (((n+m)/2) * np.log(m + n*x) + sc.betaln(n/2, m/2)))
+        return lPx
+
+    def _cdf(self, x, dfn, dfd):
+        return sc.fdtr(dfn, dfd, x)
+
+    def _sf(self, x, dfn, dfd):
+        return sc.fdtrc(dfn, dfd, x)
+
+    def _ppf(self, q, dfn, dfd):
+        return sc.fdtri(dfn, dfd, q)
+
+    def _stats(self, dfn, dfd):
+        v1, v2 = 1. * dfn, 1. * dfd
+        v2_2, v2_4, v2_6, v2_8 = v2 - 2., v2 - 4., v2 - 6., v2 - 8.
+
+        mu = _lazywhere(
+            v2 > 2, (v2, v2_2),
+            lambda v2, v2_2: v2 / v2_2,
+            np.inf)
+
+        mu2 = _lazywhere(
+            v2 > 4, (v1, v2, v2_2, v2_4),
+            lambda v1, v2, v2_2, v2_4:
+            2 * v2 * v2 * (v1 + v2_2) / (v1 * v2_2**2 * v2_4),
+            np.inf)
+
+        g1 = _lazywhere(
+            v2 > 6, (v1, v2_2, v2_4, v2_6),
+            lambda v1, v2_2, v2_4, v2_6:
+            (2 * v1 + v2_2) / v2_6 * np.sqrt(v2_4 / (v1 * (v1 + v2_2))),
+            np.nan)
+        g1 *= np.sqrt(8.)
+
+        g2 = _lazywhere(
+            v2 > 8, (g1, v2_6, v2_8),
+            lambda g1, v2_6, v2_8: (8 + g1 * g1 * v2_6) / v2_8,
+            np.nan)
+        g2 *= 3. / 2.
+
+        return mu, mu2, g1, g2
+
+    def _entropy(self, dfn, dfd):
+        # the formula found in literature is incorrect. This one yields the
+        # same result as numerical integration using the generic entropy
+        # definition. This is also tested in tests/test_conntinous_basic
+        half_dfn = 0.5 * dfn
+        half_dfd = 0.5 * dfd
+        half_sum = 0.5 * (dfn + dfd)
+
+        return (np.log(dfd) - np.log(dfn) + sc.betaln(half_dfn, half_dfd) +
+                (1 - half_dfn) * sc.psi(half_dfn) - (1 + half_dfd) *
+                sc.psi(half_dfd) + half_sum * sc.psi(half_sum))
+
+
+f = f_gen(a=0.0, name='f')
+
+
+## Folded Normal
+##   abs(Z) where (Z is normal with mu=L and std=S so that c=abs(L)/S)
+##
+##  note: regress docs have scale parameter correct, but first parameter
+##    he gives is a shape parameter A = c * scale
+
+##  Half-normal is folded normal with shape-parameter c=0.
+
+class foldnorm_gen(rv_continuous):
+    r"""A folded normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `foldnorm` is:
+
+    .. math::
+
+        f(x, c) = \sqrt{2/\pi} cosh(c x) \exp(-\frac{x^2+c^2}{2})
+
+    for :math:`x \ge 0` and :math:`c \ge 0`.
+
+    `foldnorm` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return c >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        return abs(random_state.standard_normal(size) + c)
+
+    def _pdf(self, x, c):
+        # foldnormal.pdf(x, c) = sqrt(2/pi) * cosh(c*x) * exp(-(x**2+c**2)/2)
+        return _norm_pdf(x + c) + _norm_pdf(x-c)
+
+    def _cdf(self, x, c):
+        sqrt_two = np.sqrt(2)
+        return 0.5 * (sc.erf((x - c)/sqrt_two) + sc.erf((x + c)/sqrt_two))
+
+    def _sf(self, x, c):
+        return _norm_sf(x - c) + _norm_sf(x + c)
+
+    def _stats(self, c):
+        # Regina C. Elandt, Technometrics 3, 551 (1961)
+        # https://www.jstor.org/stable/1266561
+        #
+        c2 = c*c
+        expfac = np.exp(-0.5*c2) / np.sqrt(2.*np.pi)
+
+        mu = 2.*expfac + c * sc.erf(c/np.sqrt(2))
+        mu2 = c2 + 1 - mu*mu
+
+        g1 = 2. * (mu*mu*mu - c2*mu - expfac)
+        g1 /= np.power(mu2, 1.5)
+
+        g2 = c2 * (c2 + 6.) + 3 + 8.*expfac*mu
+        g2 += (2. * (c2 - 3.) - 3. * mu**2) * mu**2
+        g2 = g2 / mu2**2.0 - 3.
+
+        return mu, mu2, g1, g2
+
+
+foldnorm = foldnorm_gen(a=0.0, name='foldnorm')
+
+
+class weibull_min_gen(rv_continuous):
+    r"""Weibull minimum continuous random variable.
+
+    The Weibull Minimum Extreme Value distribution, from extreme value theory
+    (Fisher-Gnedenko theorem), is also often simply called the Weibull
+    distribution. It arises as the limiting distribution of the rescaled
+    minimum of iid random variables.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_max, numpy.random.Generator.weibull, exponweib
+
+    Notes
+    -----
+    The probability density function for `weibull_min` is:
+
+    .. math::
+
+        f(x, c) = c x^{c-1} \exp(-x^c)
+
+    for :math:`x > 0`, :math:`c > 0`.
+
+    `weibull_min` takes ``c`` as a shape parameter for :math:`c`.
+    (named :math:`k` in Wikipedia article and :math:`a` in
+    ``numpy.random.weibull``).  Special shape values are :math:`c=1` and
+    :math:`c=2` where Weibull distribution reduces to the `expon` and
+    `rayleigh` distributions respectively.
+
+    Suppose ``X`` is an exponentially distributed random variable with
+    scale ``s``. Then ``Y = X**k`` is `weibull_min` distributed with shape
+    ``c = 1/k`` and scale ``s**k``.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Weibull_distribution
+
+    https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # weibull_min.pdf(x, c) = c * x**(c-1) * exp(-x**c)
+        return c*pow(x, c-1)*np.exp(-pow(x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-pow(x, c))
+
+    def _ppf(self, q, c):
+        return pow(-sc.log1p(-q), 1.0/c)
+
+    def _sf(self, x, c):
+        return np.exp(self._logsf(x, c))
+
+    def _logsf(self, x, c):
+        return -pow(x, c)
+
+    def _isf(self, q, c):
+        return (-np.log(q))**(1/c)
+
+    def _munp(self, n, c):
+        return sc.gamma(1.0+n*1.0/c)
+
+    def _entropy(self, c):
+        return -_EULER / c - np.log(c) + _EULER + 1
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        If ``method='mm'``, parameters fixed by the user are respected, and the
+        remaining parameters are used to match distribution and sample moments
+        where possible. For example, if the user fixes the location with
+        ``floc``, the parameters will only match the distribution skewness and
+        variance to the sample skewness and variance; no attempt will be made
+        to match the means or minimize a norm of the errors.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+
+        if isinstance(data, CensoredData):
+            if data.num_censored() == 0:
+                data = data._uncensor()
+            else:
+                return super().fit(data, *args, **kwds)
+
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        # this extracts fixed shape, location, and scale however they
+        # are specified, and also leaves them in `kwds`
+        data, fc, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+        method = kwds.get("method", "mle").lower()
+
+        # See https://en.wikipedia.org/wiki/Weibull_distribution#Moments for
+        # moment formulas.
+        def skew(c):
+            gamma1 = sc.gamma(1+1/c)
+            gamma2 = sc.gamma(1+2/c)
+            gamma3 = sc.gamma(1+3/c)
+            num = 2 * gamma1**3 - 3*gamma1*gamma2 + gamma3
+            den = (gamma2 - gamma1**2)**(3/2)
+            return num/den
+
+        # For c in [1e2, 3e4], population skewness appears to approach
+        # asymptote near -1.139, but past c > 3e4, skewness begins to vary
+        # wildly, and MoM won't provide a good guess. Get out early.
+        s = stats.skew(data)
+        max_c = 1e4
+        s_min = skew(max_c)
+        if s < s_min and method != "mm" and fc is None and not args:
+            return super().fit(data, *args, **kwds)
+
+        # If method is method of moments, we don't need the user's guesses.
+        # Otherwise, extract the guesses from args and kwds.
+        if method == "mm":
+            c, loc, scale = None, None, None
+        else:
+            c = args[0] if len(args) else None
+            loc = kwds.pop('loc', None)
+            scale = kwds.pop('scale', None)
+
+        if fc is None and c is None:  # not fixed and no guess: use MoM
+            # Solve for c that matches sample distribution skewness to sample
+            # skewness.
+            # we start having numerical issues with `weibull_min` with
+            # parameters outside this range - and not just in this method.
+            # We could probably improve the situation by doing everything
+            # in the log space, but that is for another time.
+            c = root_scalar(lambda c: skew(c) - s, bracket=[0.02, max_c],
+                            method='bisect').root
+        elif fc is not None:  # fixed: use it
+            c = fc
+
+        if fscale is None and scale is None:
+            v = np.var(data)
+            scale = np.sqrt(v / (sc.gamma(1+2/c) - sc.gamma(1+1/c)**2))
+        elif fscale is not None:
+            scale = fscale
+
+        if floc is None and loc is None:
+            m = np.mean(data)
+            loc = m - scale*sc.gamma(1 + 1/c)
+        elif floc is not None:
+            loc = floc
+
+        if method == 'mm':
+            return c, loc, scale
+        else:
+            # At this point, parameter "guesses" may equal the fixed parameters
+            # in kwds. No harm in passing them as guesses, too.
+            return super().fit(data, c, loc=loc, scale=scale, **kwds)
+
+
+weibull_min = weibull_min_gen(a=0.0, name='weibull_min')
+
+
+class truncweibull_min_gen(rv_continuous):
+    r"""A doubly truncated Weibull minimum continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min, truncexpon
+
+    Notes
+    -----
+    The probability density function for `truncweibull_min` is:
+
+    .. math::
+
+        f(x, a, b, c) = \frac{c x^{c-1} \exp(-x^c)}{\exp(-a^c) - \exp(-b^c)}
+
+    for :math:`a < x <= b`, :math:`0 \le a < b` and :math:`c > 0`.
+
+    `truncweibull_min` takes :math:`a`, :math:`b`, and :math:`c` as shape
+    parameters.
+
+    Notice that the truncation values, :math:`a` and :math:`b`, are defined in
+    standardized form:
+
+    .. math::
+
+        a = (u_l - loc)/scale
+        b = (u_r - loc)/scale
+
+    where :math:`u_l` and :math:`u_r` are the specific left and right
+    truncation values, respectively. In other words, the support of the
+    distribution becomes :math:`(a*scale + loc) < x <= (b*scale + loc)` when
+    :math:`loc` and/or :math:`scale` are provided.
+
+    %(after_notes)s
+
+    References
+    ----------
+
+    .. [1] Rinne, H. "The Weibull Distribution: A Handbook". CRC Press (2009).
+
+    %(example)s
+
+    """
+    def _argcheck(self, c, a, b):
+        return (a >= 0.) & (b > a) & (c > 0.)
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        ia = _ShapeInfo("a", False, (0, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ic, ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but default a=b=c=1 is not valid
+        return super()._fitstart(data, args=(1, 0, 1))
+
+    def _get_support(self, c, a, b):
+        return a, b
+
+    def _pdf(self, x, c, a, b):
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return (c * pow(x, c-1) * np.exp(-pow(x, c))) / denum
+
+    def _logpdf(self, x, c, a, b):
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c) - logdenum
+
+    def _cdf(self, x, c, a, b):
+        num = (np.exp(-pow(a, c)) - np.exp(-pow(x, c)))
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return num / denum
+
+    def _logcdf(self, x, c, a, b):
+        lognum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(x, c)))
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return lognum - logdenum
+
+    def _sf(self, x, c, a, b):
+        num = (np.exp(-pow(x, c)) - np.exp(-pow(b, c)))
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return num / denum
+
+    def _logsf(self, x, c, a, b):
+        lognum = np.log(np.exp(-pow(x, c)) - np.exp(-pow(b, c)))
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return lognum - logdenum
+
+    def _isf(self, q, c, a, b):
+        return pow(
+            -np.log((1 - q) * np.exp(-pow(b, c)) + q * np.exp(-pow(a, c))), 1/c
+            )
+
+    def _ppf(self, q, c, a, b):
+        return pow(
+            -np.log((1 - q) * np.exp(-pow(a, c)) + q * np.exp(-pow(b, c))), 1/c
+            )
+
+    def _munp(self, n, c, a, b):
+        gamma_fun = sc.gamma(n/c + 1.) * (
+            sc.gammainc(n/c + 1., pow(b, c)) - sc.gammainc(n/c + 1., pow(a, c))
+            )
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return gamma_fun / denum
+
+
+truncweibull_min = truncweibull_min_gen(name='truncweibull_min')
+truncweibull_min._support = ('a', 'b')
+
+
+class weibull_max_gen(rv_continuous):
+    r"""Weibull maximum continuous random variable.
+
+    The Weibull Maximum Extreme Value distribution, from extreme value theory
+    (Fisher-Gnedenko theorem), is the limiting distribution of rescaled
+    maximum of iid random variables. This is the distribution of -X
+    if X is from the `weibull_min` function.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min
+
+    Notes
+    -----
+    The probability density function for `weibull_max` is:
+
+    .. math::
+
+        f(x, c) = c (-x)^{c-1} \exp(-(-x)^c)
+
+    for :math:`x < 0`, :math:`c > 0`.
+
+    `weibull_max` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Weibull_distribution
+
+    https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # weibull_max.pdf(x, c) = c * (-x)**(c-1) * exp(-(-x)**c)
+        return c*pow(-x, c-1)*np.exp(-pow(-x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + sc.xlogy(c-1, -x) - pow(-x, c)
+
+    def _cdf(self, x, c):
+        return np.exp(-pow(-x, c))
+
+    def _logcdf(self, x, c):
+        return -pow(-x, c)
+
+    def _sf(self, x, c):
+        return -sc.expm1(-pow(-x, c))
+
+    def _ppf(self, q, c):
+        return -pow(-np.log(q), 1.0/c)
+
+    def _munp(self, n, c):
+        val = sc.gamma(1.0+n*1.0/c)
+        if int(n) % 2:
+            sgn = -1
+        else:
+            sgn = 1
+        return sgn * val
+
+    def _entropy(self, c):
+        return -_EULER / c - np.log(c) + _EULER + 1
+
+
+weibull_max = weibull_max_gen(b=0.0, name='weibull_max')
+
+
+class genlogistic_gen(rv_continuous):
+    r"""A generalized logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genlogistic` is:
+
+    .. math::
+
+        f(x, c) = c \frac{\exp(-x)}
+                         {(1 + \exp(-x))^{c+1}}
+
+    for real :math:`x` and :math:`c > 0`. In literature, different
+    generalizations of the logistic distribution can be found. This is the type 1
+    generalized logistic distribution according to [1]_. It is also referred to
+    as the skew-logistic distribution [2]_.
+
+    `genlogistic` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson et al. "Continuous Univariate Distributions", Volume 2,
+           Wiley. 1995.
+    .. [2] "Generalized Logistic Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Generalized_logistic_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # genlogistic.pdf(x, c) = c * exp(-x) / (1 + exp(-x))**(c+1)
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        # Two mathematically equivalent expressions for log(pdf(x, c)):
+        #     log(pdf(x, c)) = log(c) - x - (c + 1)*log(1 + exp(-x))
+        #                    = log(c) + c*x - (c + 1)*log(1 + exp(x))
+        mult = -(c - 1) * (x < 0) - 1
+        absx = np.abs(x)
+        return np.log(c) + mult*absx - (c+1) * sc.log1p(np.exp(-absx))
+
+    def _cdf(self, x, c):
+        Cx = (1+np.exp(-x))**(-c)
+        return Cx
+
+    def _logcdf(self, x, c):
+        return -c * np.log1p(np.exp(-x))
+
+    def _ppf(self, q, c):
+        return -np.log(sc.powm1(q, -1.0/c))
+
+    def _sf(self, x, c):
+        return -sc.expm1(self._logcdf(x, c))
+
+    def _isf(self, q, c):
+        return self._ppf(1 - q, c)
+
+    def _stats(self, c):
+        mu = _EULER + sc.psi(c)
+        mu2 = np.pi*np.pi/6.0 + sc.zeta(2, c)
+        g1 = -2*sc.zeta(3, c) + 2*_ZETA3
+        g1 /= np.power(mu2, 1.5)
+        g2 = np.pi**4/15.0 + 6*sc.zeta(4, c)
+        g2 /= mu2**2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        return _lazywhere(c < 8e6, (c, ),
+                          lambda c: -np.log(c) + sc.psi(c + 1) + _EULER + 1,
+                          # asymptotic expansion: psi(c) ~ log(c) - 1/(2 * c)
+                          # a = -log(c) + psi(c + 1)
+                          #   = -log(c) + psi(c) + 1/c
+                          #   ~ -log(c) + log(c) - 1/(2 * c) + 1/c
+                          #   = 1/(2 * c)
+                          f2=lambda c: 1/(2 * c) + _EULER + 1)
+
+
+genlogistic = genlogistic_gen(name='genlogistic')
+
+
+class genpareto_gen(rv_continuous):
+    r"""A generalized Pareto continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genpareto` is:
+
+    .. math::
+
+        f(x, c) = (1 + c x)^{-1 - 1/c}
+
+    defined for :math:`x \ge 0` if :math:`c \ge 0`, and for
+    :math:`0 \le x \le -1/c` if :math:`c < 0`.
+
+    `genpareto` takes ``c`` as a shape parameter for :math:`c`.
+
+    For :math:`c=0`, `genpareto` reduces to the exponential
+    distribution, `expon`:
+
+    .. math::
+
+        f(x, 0) = \exp(-x)
+
+    For :math:`c=-1`, `genpareto` is uniform on ``[0, 1]``:
+
+    .. math::
+
+        f(x, -1) = 1
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return np.isfinite(c)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        c = np.asarray(c)
+        b = _lazywhere(c < 0, (c,),
+                       lambda c: -1. / c,
+                       np.inf)
+        a = np.where(c >= 0, self.a, self.a)
+        return a, b
+
+    def _pdf(self, x, c):
+        # genpareto.pdf(x, c) = (1 + c * x)**(-1 - 1/c)
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.xlog1py(c + 1., c*x) / c,
+                          -x)
+
+    def _cdf(self, x, c):
+        return -sc.inv_boxcox1p(-x, -c)
+
+    def _sf(self, x, c):
+        return sc.inv_boxcox(-x, -c)
+
+    def _logsf(self, x, c):
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.log1p(c*x) / c,
+                          -x)
+
+    def _ppf(self, q, c):
+        return -sc.boxcox1p(-q, -c)
+
+    def _isf(self, q, c):
+        return -sc.boxcox(q, -c)
+
+    def _stats(self, c, moments='mv'):
+        if 'm' not in moments:
+            m = None
+        else:
+            m = _lazywhere(c < 1, (c,),
+                           lambda xi: 1/(1 - xi),
+                           np.inf)
+        if 'v' not in moments:
+            v = None
+        else:
+            v = _lazywhere(c < 1/2, (c,),
+                           lambda xi: 1 / (1 - xi)**2 / (1 - 2*xi),
+                           np.nan)
+        if 's' not in moments:
+            s = None
+        else:
+            s = _lazywhere(c < 1/3, (c,),
+                           lambda xi: (2 * (1 + xi) * np.sqrt(1 - 2*xi) /
+                                       (1 - 3*xi)),
+                           np.nan)
+        if 'k' not in moments:
+            k = None
+        else:
+            k = _lazywhere(c < 1/4, (c,),
+                           lambda xi: (3 * (1 - 2*xi) * (2*xi**2 + xi + 3) /
+                                       (1 - 3*xi) / (1 - 4*xi) - 3),
+                           np.nan)
+        return m, v, s, k
+
+    def _munp(self, n, c):
+        def __munp(n, c):
+            val = 0.0
+            k = np.arange(0, n + 1)
+            for ki, cnk in zip(k, sc.comb(n, k)):
+                val = val + cnk * (-1) ** ki / (1.0 - c * ki)
+            return np.where(c * n < 1, val * (-1.0 / c) ** n, np.inf)
+        return _lazywhere(c != 0, (c,),
+                          lambda c: __munp(n, c),
+                          sc.gamma(n + 1))
+
+    def _entropy(self, c):
+        return 1. + c
+
+
+genpareto = genpareto_gen(a=0.0, name='genpareto')
+
+
+class genexpon_gen(rv_continuous):
+    r"""A generalized exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genexpon` is:
+
+    .. math::
+
+        f(x, a, b, c) = (a + b (1 - \exp(-c x)))
+                        \exp(-a x - b x + \frac{b}{c}  (1-\exp(-c x)))
+
+    for :math:`x \ge 0`, :math:`a, b, c > 0`.
+
+    `genexpon` takes :math:`a`, :math:`b` and :math:`c` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    H.K. Ryu, "An Extension of Marshall and Olkin's Bivariate Exponential
+    Distribution", Journal of the American Statistical Association, 1993.
+
+    N. Balakrishnan, Asit P. Basu (editors), *The Exponential Distribution:
+    Theory, Methods and Applications*, Gordon and Breach, 1995.
+    ISBN 10: 2884491929
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        return [ia, ib, ic]
+
+    def _pdf(self, x, a, b, c):
+        # genexpon.pdf(x, a, b, c) = (a + b * (1 - exp(-c*x))) * \
+        #                            exp(-a*x - b*x + b/c * (1-exp(-c*x)))
+        return (a + b*(-sc.expm1(-c*x)))*np.exp((-a-b)*x +
+                                                b*(-sc.expm1(-c*x))/c)
+
+    def _logpdf(self, x, a, b, c):
+        return np.log(a+b*(-sc.expm1(-c*x))) + (-a-b)*x+b*(-sc.expm1(-c*x))/c
+
+    def _cdf(self, x, a, b, c):
+        return -sc.expm1((-a-b)*x + b*(-sc.expm1(-c*x))/c)
+
+    def _ppf(self, p, a, b, c):
+        s = a + b
+        t = (b - c*np.log1p(-p))/s
+        return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c
+
+    def _sf(self, x, a, b, c):
+        return np.exp((-a-b)*x + b*(-sc.expm1(-c*x))/c)
+
+    def _isf(self, p, a, b, c):
+        s = a + b
+        t = (b - c*np.log(p))/s
+        return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c
+
+
+genexpon = genexpon_gen(a=0.0, name='genexpon')
+
+
+class genextreme_gen(rv_continuous):
+    r"""A generalized extreme value continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_r
+
+    Notes
+    -----
+    For :math:`c=0`, `genextreme` is equal to `gumbel_r` with
+    probability density function
+
+    .. math::
+
+        f(x) = \exp(-\exp(-x)) \exp(-x),
+
+    where :math:`-\infty < x < \infty`.
+
+    For :math:`c \ne 0`, the probability density function for `genextreme` is:
+
+    .. math::
+
+        f(x, c) = \exp(-(1-c x)^{1/c}) (1-c x)^{1/c-1},
+
+    where :math:`-\infty < x \le 1/c` if :math:`c > 0` and
+    :math:`1/c \le x < \infty` if :math:`c < 0`.
+
+    Note that several sources and software packages use the opposite
+    convention for the sign of the shape parameter :math:`c`.
+
+    `genextreme` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return np.isfinite(c)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        _b = np.where(c > 0, 1.0 / np.maximum(c, _XMIN), np.inf)
+        _a = np.where(c < 0, 1.0 / np.minimum(c, -_XMIN), -np.inf)
+        return _a, _b
+
+    def _loglogcdf(self, x, c):
+        # Returns log(-log(cdf(x, c)))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: sc.log1p(-c*x)/c, -x)
+
+    def _pdf(self, x, c):
+        # genextreme.pdf(x, c) =
+        #     exp(-exp(-x))*exp(-x),                    for c==0
+        #     exp(-(1-c*x)**(1/c))*(1-c*x)**(1/c-1),    for x \le 1/c, c > 0
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        cx = _lazywhere((x == x) & (c != 0), (x, c), lambda x, c: c*x, 0.0)
+        logex2 = sc.log1p(-cx)
+        logpex2 = self._loglogcdf(x, c)
+        pex2 = np.exp(logpex2)
+        # Handle special cases
+        np.putmask(logpex2, (c == 0) & (x == -np.inf), 0.0)
+        logpdf = _lazywhere(~((cx == 1) | (cx == -np.inf)),
+                            (pex2, logpex2, logex2),
+                            lambda pex2, lpex2, lex2: -pex2 + lpex2 - lex2,
+                            fillvalue=-np.inf)
+        np.putmask(logpdf, (c == 1) & (x == 1), 0.0)
+        return logpdf
+
+    def _logcdf(self, x, c):
+        return -np.exp(self._loglogcdf(x, c))
+
+    def _cdf(self, x, c):
+        return np.exp(self._logcdf(x, c))
+
+    def _sf(self, x, c):
+        return -sc.expm1(self._logcdf(x, c))
+
+    def _ppf(self, q, c):
+        x = -np.log(-np.log(q))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.expm1(-c * x) / c, x)
+
+    def _isf(self, q, c):
+        x = -np.log(-sc.log1p(-q))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.expm1(-c * x) / c, x)
+
+    def _stats(self, c):
+        def g(n):
+            return sc.gamma(n * c + 1)
+        g1 = g(1)
+        g2 = g(2)
+        g3 = g(3)
+        g4 = g(4)
+        g2mg12 = np.where(abs(c) < 1e-7, (c*np.pi)**2.0/6.0, g2-g1**2.0)
+        def gam2k_f(c):
+            return sc.expm1(sc.gammaln(2.0*c+1.0)-2*sc.gammaln(c + 1.0))/c**2.0
+        gam2k = _lazywhere(abs(c) >= 1e-7, (c,), f=gam2k_f, fillvalue=np.pi**2.0/6.0)
+        eps = 1e-14
+        def gamk_f(c):
+            return sc.expm1(sc.gammaln(c + 1))/c
+        gamk = _lazywhere(abs(c) >= eps, (c,), f=gamk_f, fillvalue=-_EULER)
+
+        # mean
+        m = np.where(c < -1.0, np.nan, -gamk)
+        
+        # variance
+        v = np.where(c < -0.5, np.nan, g1**2.0*gam2k)
+
+        # skewness
+        def sk1_eval(c, *args):
+            def sk1_eval_f(c, g1, g2, g3, g2mg12):
+                return np.sign(c)*(-g3 + (g2 + 2*g2mg12)*g1)/g2mg12**1.5
+            return _lazywhere(c >= -1./3, (c,)+args, f=sk1_eval_f, fillvalue=np.nan)
+
+        sk_fill = 12*np.sqrt(6)*_ZETA3/np.pi**3
+        args = (g1, g2, g3, g2mg12)
+        sk = _lazywhere(abs(c) > eps**0.29, (c,)+args, f=sk1_eval, fillvalue=sk_fill)
+
+        # kurtosis
+        def ku1_eval(c, *args):
+            def ku1_eval_f(g1, g2, g3, g4, g2mg12):
+                return (g4 + (-4*g3 + 3*(g2 + g2mg12)*g1)*g1)/g2mg12**2 - 3
+            return _lazywhere(c >= -1./4, args, ku1_eval_f, fillvalue=np.nan)
+
+        args = (g1, g2, g3, g4, g2mg12)
+        ku = _lazywhere(abs(c) > eps**0.23, (c,)+args, f=ku1_eval, fillvalue=12.0/5.0)
+
+        return m, v, sk, ku
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        # This is better than the default shape of (1,).
+        g = _skew(data)
+        if g < 0:
+            a = 0.5
+        else:
+            a = -0.5
+        return super()._fitstart(data, args=(a,))
+
+    def _munp(self, n, c):
+        k = np.arange(0, n+1)
+        vals = 1.0/c**n * np.sum(
+            sc.comb(n, k) * (-1)**k * sc.gamma(c*k + 1),
+            axis=0)
+        return np.where(c*n > -1, vals, np.inf)
+
+    def _entropy(self, c):
+        return _EULER*(1 - c) + 1
+
+
+genextreme = genextreme_gen(name='genextreme')
+
+
+def _digammainv(y):
+    """Inverse of the digamma function (real positive arguments only).
+
+    This function is used in the `fit` method of `gamma_gen`.
+    The function uses either optimize.fsolve or optimize.newton
+    to solve `sc.digamma(x) - y = 0`.  There is probably room for
+    improvement, but currently it works over a wide range of y:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> y = 64*rng.standard_normal(1000000)
+    >>> y.min(), y.max()
+    (-311.43592651416662, 351.77388222276869)
+    >>> x = [_digammainv(t) for t in y]
+    >>> np.abs(sc.digamma(x) - y).max()
+    1.1368683772161603e-13
+
+    """
+    _em = 0.5772156649015328606065120
+
+    def func(x):
+        return sc.digamma(x) - y
+
+    if y > -0.125:
+        x0 = np.exp(y) + 0.5
+        if y < 10:
+            # Some experimentation shows that newton reliably converges
+            # must faster than fsolve in this y range.  For larger y,
+            # newton sometimes fails to converge.
+            value = optimize.newton(func, x0, tol=1e-10)
+            return value
+    elif y > -3:
+        x0 = np.exp(y/2.332) + 0.08661
+    else:
+        x0 = 1.0 / (-y - _em)
+
+    value, info, ier, mesg = optimize.fsolve(func, x0, xtol=1e-11,
+                                             full_output=True)
+    if ier != 1:
+        raise RuntimeError(f"_digammainv: fsolve failed, y = {y!r}")
+
+    return value[0]
+
+
+## Gamma (Use MATLAB and MATHEMATICA (b=theta=scale, a=alpha=shape) definition)
+
+## gamma(a, loc, scale)  with a an integer is the Erlang distribution
+## gamma(1, loc, scale)  is the Exponential distribution
+## gamma(df/2, 0, 2) is the chi2 distribution with df degrees of freedom.
+
+class gamma_gen(rv_continuous):
+    r"""A gamma continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    erlang, expon
+
+    Notes
+    -----
+    The probability density function for `gamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{x^{a-1} e^{-x}}{\Gamma(a)}
+
+    for :math:`x \ge 0`, :math:`a > 0`. Here :math:`\Gamma(a)` refers to the
+    gamma function.
+
+    `gamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    When :math:`a` is an integer, `gamma` reduces to the Erlang
+    distribution, and when :math:`a=1` to the exponential distribution.
+
+    Gamma distributions are sometimes parameterized with two variables,
+    with a probability density function of:
+
+    .. math::
+
+        f(x, \alpha, \beta) =
+        \frac{\beta^\alpha x^{\alpha - 1} e^{-\beta x }}{\Gamma(\alpha)}
+
+    Note that this parameterization is equivalent to the above, with
+    ``scale = 1 / beta``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        return random_state.standard_gamma(a, size)
+
+    def _pdf(self, x, a):
+        # gamma.pdf(x, a) = x**(a-1) * exp(-x) / gamma(a)
+        return np.exp(self._logpdf(x, a))
+
+    def _logpdf(self, x, a):
+        return sc.xlogy(a-1.0, x) - x - sc.gammaln(a)
+
+    def _cdf(self, x, a):
+        return sc.gammainc(a, x)
+
+    def _sf(self, x, a):
+        return sc.gammaincc(a, x)
+
+    def _ppf(self, q, a):
+        return sc.gammaincinv(a, q)
+
+    def _isf(self, q, a):
+        return sc.gammainccinv(a, q)
+
+    def _stats(self, a):
+        return a, a, 2.0/np.sqrt(a), 6.0/a
+
+    def _munp(self, n, a):
+        return sc.poch(a, n)
+
+    def _entropy(self, a):
+
+        def regular_formula(a):
+            return sc.psi(a) * (1-a) + a + sc.gammaln(a)
+
+        def asymptotic_formula(a):
+            # plug in above formula the expansions:
+            # psi(a) ~ ln(a) - 1/2a - 1/12a^2 + 1/120a^4
+            # gammaln(a) ~ a * ln(a) - a - 1/2 * ln(a) + 1/2 ln(2 * pi) +
+            #              1/12a - 1/360a^3
+            return (0.5 * (1. + np.log(2*np.pi) + np.log(a)) - 1/(3 * a)
+                    - (a**-2.)/12 - (a**-3.)/90 + (a**-4.)/120)
+
+        return _lazywhere(a < 250, (a, ), regular_formula,
+                          f2=asymptotic_formula)
+
+    def _fitstart(self, data):
+        # The skewness of the gamma distribution is `2 / np.sqrt(a)`.
+        # We invert that to estimate the shape `a` using the skewness
+        # of the data.  The formula is regularized with 1e-8 in the
+        # denominator to allow for degenerate data where the skewness
+        # is close to 0.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        sk = _skew(data)
+        a = 4 / (1e-8 + sk**2)
+        return super()._fitstart(data, args=(a,))
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        When the location is fixed by using the argument `floc`
+        and `method='MLE'`, this
+        function uses explicit formulas or solves a simpler numerical
+        problem than the full ML optimization problem.  So in that case,
+        the `optimizer`, `loc` and `scale` arguments are ignored.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        floc = kwds.get('floc', None)
+        method = kwds.get('method', 'mle')
+
+        if (isinstance(data, CensoredData) or
+                floc is None and method.lower() != 'mm'):
+            # loc is not fixed or we're not doing standard MLE.
+            # Use the default fit method.
+            return super().fit(data, *args, **kwds)
+
+        # We already have this value, so just pop it from kwds.
+        kwds.pop('floc', None)
+
+        f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a'])
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if f0 is not None and floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            # Without this check, this function would just return the
+            # parameters that were given.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        # Fixed location is handled by shifting the data.
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # Use explicit formulas for mm (gh-19884)
+        if method.lower() == 'mm':
+            m1 = np.mean(data)
+            m2 = np.var(data)
+            m3 = np.mean((data - m1) ** 3)
+            a, loc, scale = f0, floc, fscale
+            # Three unknowns
+            if a is None and loc is None and scale is None:
+                scale = m3 / (2 * m2)
+            # Two unknowns
+            if loc is None and scale is None:
+                scale = np.sqrt(m2 / a)
+            if a is None and scale is None:
+                scale = m2 / (m1 - loc)
+            if a is None and loc is None:
+                a = m2 / (scale ** 2)
+            # One unknown
+            if a is None:
+                a = (m1 - loc) / scale
+            if loc is None:
+                loc = m1 - a * scale
+            if scale is None:
+                scale = (m1 - loc) / a
+            return a, loc, scale
+
+        # Special case: loc is fixed.
+
+        # NB: data == loc is ok if a >= 1; the below check is more strict.
+        if np.any(data <= floc):
+            raise FitDataError("gamma", lower=floc, upper=np.inf)
+
+        if floc != 0:
+            # Don't do the subtraction in-place, because `data` might be a
+            # view of the input array.
+            data = data - floc
+        xbar = data.mean()
+
+        # Three cases to handle:
+        # * shape and scale both free
+        # * shape fixed, scale free
+        # * shape free, scale fixed
+
+        if fscale is None:
+            # scale is free
+            if f0 is not None:
+                # shape is fixed
+                a = f0
+            else:
+                # shape and scale are both free.
+                # The MLE for the shape parameter `a` is the solution to:
+                # np.log(a) - sc.digamma(a) - np.log(xbar) +
+                #                             np.log(data).mean() = 0
+                s = np.log(xbar) - np.log(data).mean()
+                aest = (3-s + np.sqrt((s-3)**2 + 24*s)) / (12*s)
+                xa = aest*(1-0.4)
+                xb = aest*(1+0.4)
+                a = optimize.brentq(lambda a: np.log(a) - sc.digamma(a) - s,
+                                    xa, xb, disp=0)
+
+            # The MLE for the scale parameter is just the data mean
+            # divided by the shape parameter.
+            scale = xbar / a
+        else:
+            # scale is fixed, shape is free
+            # The MLE for the shape parameter `a` is the solution to:
+            # sc.digamma(a) - np.log(data).mean() + np.log(fscale) = 0
+            c = np.log(data).mean() - np.log(fscale)
+            a = _digammainv(c)
+            scale = fscale
+
+        return a, floc, scale
+
+
+gamma = gamma_gen(a=0.0, name='gamma')
+
+
+class erlang_gen(gamma_gen):
+    """An Erlang continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gamma
+
+    Notes
+    -----
+    The Erlang distribution is a special case of the Gamma distribution, with
+    the shape parameter `a` an integer.  Note that this restriction is not
+    enforced by `erlang`. It will, however, generate a warning the first time
+    a non-integer value is used for the shape parameter.
+
+    Refer to `gamma` for examples.
+
+    """
+
+    def _argcheck(self, a):
+        allint = np.all(np.floor(a) == a)
+        if not allint:
+            # An Erlang distribution shouldn't really have a non-integer
+            # shape parameter, so warn the user.
+            message = ('The shape parameter of the erlang distribution '
+                       f'has been given a non-integer value {a!r}.')
+            warnings.warn(message, RuntimeWarning, stacklevel=3)
+        return a > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", True, (1, np.inf), (True, False))]
+
+    def _fitstart(self, data):
+        # Override gamma_gen_fitstart so that an integer initial value is
+        # used.  (Also regularize the division, to avoid issues when
+        # _skew(data) is 0 or close to 0.)
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        a = int(4.0 / (1e-8 + _skew(data)**2))
+        return super(gamma_gen, self)._fitstart(data, args=(a,))
+
+    # Trivial override of the fit method, so we can monkey-patch its
+    # docstring.
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        The Erlang distribution is generally defined to have integer values
+        for the shape parameter.  This is not enforced by the `erlang` class.
+        When fitting the distribution, it will generally return a non-integer
+        value for the shape parameter.  By using the keyword argument
+        `f0=`, the fit method can be constrained to fit the data to
+        a specific integer shape parameter.""")
+    def fit(self, data, *args, **kwds):
+        return super().fit(data, *args, **kwds)
+
+
+erlang = erlang_gen(a=0.0, name='erlang')
+
+
+class gengamma_gen(rv_continuous):
+    r"""A generalized gamma continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gamma, invgamma, weibull_min
+
+    Notes
+    -----
+    The probability density function for `gengamma` is ([1]_):
+
+    .. math::
+
+        f(x, a, c) = \frac{|c| x^{c a-1} \exp(-x^c)}{\Gamma(a)}
+
+    for :math:`x \ge 0`, :math:`a > 0`, and :math:`c \ne 0`.
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `gengamma` takes :math:`a` and :math:`c` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] E.W. Stacy, "A Generalization of the Gamma Distribution",
+       Annals of Mathematical Statistics, Vol 33(3), pp. 1187--1192.
+
+    %(example)s
+
+    """
+    def _argcheck(self, a, c):
+        return (a > 0) & (c != 0)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False))
+        return [ia, ic]
+
+    def _pdf(self, x, a, c):
+        return np.exp(self._logpdf(x, a, c))
+
+    def _logpdf(self, x, a, c):
+        return _lazywhere((x != 0) | (c > 0), (x, c),
+                          lambda x, c: (np.log(abs(c)) + sc.xlogy(c*a - 1, x)
+                                        - x**c - sc.gammaln(a)),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x, a, c):
+        xc = x**c
+        val1 = sc.gammainc(a, xc)
+        val2 = sc.gammaincc(a, xc)
+        return np.where(c > 0, val1, val2)
+
+    def _rvs(self, a, c, size=None, random_state=None):
+        r = random_state.standard_gamma(a, size=size)
+        return r**(1./c)
+
+    def _sf(self, x, a, c):
+        xc = x**c
+        val1 = sc.gammainc(a, xc)
+        val2 = sc.gammaincc(a, xc)
+        return np.where(c > 0, val2, val1)
+
+    def _ppf(self, q, a, c):
+        val1 = sc.gammaincinv(a, q)
+        val2 = sc.gammainccinv(a, q)
+        return np.where(c > 0, val1, val2)**(1.0/c)
+
+    def _isf(self, q, a, c):
+        val1 = sc.gammaincinv(a, q)
+        val2 = sc.gammainccinv(a, q)
+        return np.where(c > 0, val2, val1)**(1.0/c)
+
+    def _munp(self, n, a, c):
+        # Pochhammer symbol: sc.pocha,n) = gamma(a+n)/gamma(a)
+        return sc.poch(a, n*1.0/c)
+
+    def _entropy(self, a, c):
+        def regular(a, c):
+            val = sc.psi(a)
+            A = a * (1 - val) + val / c
+            B = sc.gammaln(a) - np.log(abs(c))
+            h = A + B
+            return h
+
+        def asymptotic(a, c):
+            # using asymptotic expansions for gammaln and psi (see gh-18093)
+            return (norm._entropy() - np.log(a)/2
+                    - np.log(np.abs(c)) + (a**-1.)/6 - (a**-3.)/90
+                    + (np.log(a) - (a**-1.)/2 - (a**-2.)/12 + (a**-4.)/120)/c)
+
+        h = _lazywhere(a >= 2e2, (a, c), f=asymptotic, f2=regular)
+        return h
+
+
+gengamma = gengamma_gen(a=0.0, name='gengamma')
+
+
+class genhalflogistic_gen(rv_continuous):
+    r"""A generalized half-logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genhalflogistic` is:
+
+    .. math::
+
+        f(x, c) = \frac{2 (1 - c x)^{1/(c-1)}}{[1 + (1 - c x)^{1/c}]^2}
+
+    for :math:`0 \le x \le 1/c`, and :math:`c > 0`.
+
+    `genhalflogistic` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        return self.a, 1.0/c
+
+    def _pdf(self, x, c):
+        # genhalflogistic.pdf(x, c) =
+        #    2 * (1-c*x)**(1/c-1) / (1+(1-c*x)**(1/c))**2
+        limit = 1.0/c
+        tmp = np.asarray(1-c*x)
+        tmp0 = tmp**(limit-1)
+        tmp2 = tmp0*tmp
+        return 2*tmp0 / (1+tmp2)**2
+
+    def _cdf(self, x, c):
+        limit = 1.0/c
+        tmp = np.asarray(1-c*x)
+        tmp2 = tmp**(limit)
+        return (1.0-tmp2) / (1+tmp2)
+
+    def _ppf(self, q, c):
+        return 1.0/c*(1-((1.0-q)/(1.0+q))**c)
+
+    def _entropy(self, c):
+        return 2 - (2*c+1)*np.log(2)
+
+
+genhalflogistic = genhalflogistic_gen(a=0.0, name='genhalflogistic')
+
+
+class genhyperbolic_gen(rv_continuous):
+    r"""A generalized hyperbolic continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    t, norminvgauss, geninvgauss, laplace, cauchy
+
+    Notes
+    -----
+    The probability density function for `genhyperbolic` is:
+
+    .. math::
+
+        f(x, p, a, b) =
+            \frac{(a^2 - b^2)^{p/2}}
+            {\sqrt{2\pi}a^{p-1/2}
+            K_p\Big(\sqrt{a^2 - b^2}\Big)}
+            e^{bx} \times \frac{K_{p - 1/2}
+            (a \sqrt{1 + x^2})}
+            {(\sqrt{1 + x^2})^{1/2 - p}}
+
+    for :math:`x, p \in ( - \infty; \infty)`,
+    :math:`|b| < a` if :math:`p \ge 0`,
+    :math:`|b| \le a` if :math:`p < 0`.
+    :math:`K_{p}(.)` denotes the modified Bessel function of the second
+    kind and order :math:`p` (`scipy.special.kv`)
+
+    `genhyperbolic` takes ``p`` as a tail parameter,
+    ``a`` as a shape parameter,
+    ``b`` as a skewness parameter.
+
+    %(after_notes)s
+
+    The original parameterization of the Generalized Hyperbolic Distribution
+    is found in [1]_ as follows
+
+    .. math::
+
+        f(x, \lambda, \alpha, \beta, \delta, \mu) =
+           \frac{(\gamma/\delta)^\lambda}{\sqrt{2\pi}K_\lambda(\delta \gamma)}
+           e^{\beta (x - \mu)} \times \frac{K_{\lambda - 1/2}
+           (\alpha \sqrt{\delta^2 + (x - \mu)^2})}
+           {(\sqrt{\delta^2 + (x - \mu)^2} / \alpha)^{1/2 - \lambda}}
+
+    for :math:`x \in ( - \infty; \infty)`,
+    :math:`\gamma := \sqrt{\alpha^2 - \beta^2}`,
+    :math:`\lambda, \mu \in ( - \infty; \infty)`,
+    :math:`\delta \ge 0, |\beta| < \alpha` if :math:`\lambda \ge 0`,
+    :math:`\delta > 0, |\beta| \le \alpha` if :math:`\lambda < 0`.
+
+    The location-scale-based parameterization implemented in
+    SciPy is based on [2]_, where :math:`a = \alpha\delta`,
+    :math:`b = \beta\delta`, :math:`p = \lambda`,
+    :math:`scale=\delta` and :math:`loc=\mu`
+
+    Moments are implemented based on [3]_ and [4]_.
+
+    For the distributions that are a special case such as Student's t,
+    it is not recommended to rely on the implementation of genhyperbolic.
+    To avoid potential numerical problems and for performance reasons,
+    the methods of the specific distributions should be used.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions
+       on Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3),
+       pp. 151-157, 1978. https://www.jstor.org/stable/4615705
+
+    .. [2] Eberlein E., Prause K. (2002) The Generalized Hyperbolic Model:
+        Financial Derivatives and Risk Measures. In: Geman H., Madan D.,
+        Pliska S.R., Vorst T. (eds) Mathematical Finance - Bachelier
+        Congress 2000. Springer Finance. Springer, Berlin, Heidelberg.
+        :doi:`10.1007/978-3-662-12429-1_12`
+
+    .. [3] Scott, David J, Würtz, Diethelm, Dong, Christine and Tran,
+       Thanh Tam, (2009), Moments of the generalized hyperbolic
+       distribution, MPRA Paper, University Library of Munich, Germany,
+       https://EconPapers.repec.org/RePEc:pra:mprapa:19081.
+
+    .. [4] E. Eberlein and E. A. von Hammerstein. Generalized hyperbolic
+       and inverse Gaussian distributions: Limiting cases and approximation
+       of processes. FDM Preprint 80, April 2003. University of Freiburg.
+       https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content
+
+    %(example)s
+
+    """
+
+    def _argcheck(self, p, a, b):
+        return (np.logical_and(np.abs(b) < a, p >= 0)
+                | np.logical_and(np.abs(b) <= a, p < 0))
+
+    def _shape_info(self):
+        ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False))
+        ia = _ShapeInfo("a", False, (0, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False))
+        return [ip, ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default p = a = b = 1 is not valid; the
+        # distribution requires |b| < a if p >= 0.
+        return super()._fitstart(data, args=(1, 1, 0.5))
+
+    def _logpdf(self, x, p, a, b):
+        # kve instead of kv works better for large values of p
+        # and smaller values of sqrt(a^2  - b^2)
+        @np.vectorize
+        def _logpdf_single(x, p, a, b):
+            return _stats.genhyperbolic_logpdf(x, p, a, b)
+
+        return _logpdf_single(x, p, a, b)
+
+    def _pdf(self, x, p, a, b):
+        # kve instead of kv works better for large values of p
+        # and smaller values of sqrt(a^2  - b^2)
+        @np.vectorize
+        def _pdf_single(x, p, a, b):
+            return _stats.genhyperbolic_pdf(x, p, a, b)
+
+        return _pdf_single(x, p, a, b)
+
+    # np.vectorize isn't currently designed to be used as a decorator,
+    # so use a lambda instead.  This allows us to decorate the function
+    # with `np.vectorize` and still provide the `otypes` parameter.
+    @lambda func: np.vectorize(func, otypes=[np.float64])
+    @staticmethod
+    def _integrate_pdf(x0, x1, p, a, b):
+        """
+        Integrate the pdf of the genhyberbolic distribution from x0 to x1.
+        This is a private function used by _cdf() and _sf() only; either x0
+        will be -inf or x1 will be inf.
+        """
+        user_data = np.array([p, a, b], float).ctypes.data_as(ctypes.c_void_p)
+        llc = LowLevelCallable.from_cython(_stats, '_genhyperbolic_pdf',
+                                           user_data)
+        d = np.sqrt((a + b)*(a - b))
+        mean = b/d * sc.kv(p + 1, d) / sc.kv(p, d)
+        epsrel = 1e-10
+        epsabs = 0
+        if x0 < mean < x1:
+            # If the interval includes the mean, integrate over the two
+            # intervals [x0, mean] and [mean, x1] and add. If we try to do
+            # the integral in one call of quad and the non-infinite endpoint
+            # is far in the tail, quad might return an incorrect result
+            # because it does not "see" the peak of the PDF.
+            intgrl = (integrate.quad(llc, x0, mean,
+                                     epsrel=epsrel, epsabs=epsabs)[0]
+                      + integrate.quad(llc, mean, x1,
+                                       epsrel=epsrel, epsabs=epsabs)[0])
+        else:
+            intgrl = integrate.quad(llc, x0, x1,
+                                    epsrel=epsrel, epsabs=epsabs)[0]
+        if np.isnan(intgrl):
+            msg = ("Infinite values encountered in scipy.special.kve. "
+                   "Values replaced by NaN to avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+        return max(0.0, min(1.0, intgrl))
+
+    def _cdf(self, x, p, a, b):
+        return self._integrate_pdf(-np.inf, x, p, a, b)
+
+    def _sf(self, x, p, a, b):
+        return self._integrate_pdf(x, np.inf, p, a, b)
+
+    def _rvs(self, p, a, b, size=None, random_state=None):
+        # note: X = b * V + sqrt(V) * X  has a
+        # generalized hyperbolic distribution
+        # if X is standard normal and V is
+        # geninvgauss(p = p, b = t2, loc = loc, scale = t3)
+        t1 = np.float_power(a, 2) - np.float_power(b, 2)
+        # b in the GIG
+        t2 = np.float_power(t1, 0.5)
+        # scale in the GIG
+        t3 = np.float_power(t1, - 0.5)
+        gig = geninvgauss.rvs(
+            p=p,
+            b=t2,
+            scale=t3,
+            size=size,
+            random_state=random_state
+            )
+        normst = norm.rvs(size=size, random_state=random_state)
+
+        return b * gig + np.sqrt(gig) * normst
+
+    def _stats(self, p, a, b):
+        # https://mpra.ub.uni-muenchen.de/19081/1/MPRA_paper_19081.pdf
+        # https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content
+        # standardized moments
+        p, a, b = np.broadcast_arrays(p, a, b)
+        t1 = np.float_power(a, 2) - np.float_power(b, 2)
+        t1 = np.float_power(t1, 0.5)
+        t2 = np.float_power(1, 2) * np.float_power(t1, - 1)
+        integers = np.linspace(0, 4, 5)
+        # make integers perpendicular to existing dimensions
+        integers = integers.reshape(integers.shape + (1,) * p.ndim)
+        b0, b1, b2, b3, b4 = sc.kv(p + integers, t1)
+        r1, r2, r3, r4 = (b / b0 for b in (b1, b2, b3, b4))
+
+        m = b * t2 * r1
+        v = (
+            t2 * r1 + np.float_power(b, 2) * np.float_power(t2, 2) *
+            (r2 - np.float_power(r1, 2))
+        )
+        m3e = (
+            np.float_power(b, 3) * np.float_power(t2, 3) *
+            (r3 - 3 * b2 * b1 * np.float_power(b0, -2) +
+             2 * np.float_power(r1, 3)) +
+            3 * b * np.float_power(t2, 2) *
+            (r2 - np.float_power(r1, 2))
+        )
+        s = m3e * np.float_power(v, - 3 / 2)
+        m4e = (
+            np.float_power(b, 4) * np.float_power(t2, 4) *
+            (r4 - 4 * b3 * b1 * np.float_power(b0, - 2) +
+             6 * b2 * np.float_power(b1, 2) * np.float_power(b0, - 3) -
+             3 * np.float_power(r1, 4)) +
+            np.float_power(b, 2) * np.float_power(t2, 3) *
+            (6 * r3 - 12 * b2 * b1 * np.float_power(b0, - 2) +
+             6 * np.float_power(r1, 3)) +
+            3 * np.float_power(t2, 2) * r2
+        )
+        k = m4e * np.float_power(v, -2) - 3
+
+        return m, v, s, k
+
+
+genhyperbolic = genhyperbolic_gen(name='genhyperbolic')
+
+
+class gompertz_gen(rv_continuous):
+    r"""A Gompertz (or truncated Gumbel) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gompertz` is:
+
+    .. math::
+
+        f(x, c) = c \exp(x) \exp(-c (e^x-1))
+
+    for :math:`x \ge 0`, :math:`c > 0`.
+
+    `gompertz` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # gompertz.pdf(x, c) = c * exp(x) * exp(-c*(exp(x)-1))
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + x - c * sc.expm1(x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-c * sc.expm1(x))
+
+    def _ppf(self, q, c):
+        return sc.log1p(-1.0 / c * sc.log1p(-q))
+
+    def _sf(self, x, c):
+        return np.exp(-c * sc.expm1(x))
+
+    def _isf(self, p, c):
+        return sc.log1p(-np.log(p)/c)
+
+    def _entropy(self, c):
+        return 1.0 - np.log(c) - sc._ufuncs._scaled_exp1(c)/c
+
+
+gompertz = gompertz_gen(a=0.0, name='gompertz')
+
+
+def _average_with_log_weights(x, logweights):
+    x = np.asarray(x)
+    logweights = np.asarray(logweights)
+    maxlogw = logweights.max()
+    weights = np.exp(logweights - maxlogw)
+    return np.average(x, weights=weights)
+
+
+class gumbel_r_gen(rv_continuous):
+    r"""A right-skewed Gumbel continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_l, gompertz, genextreme
+
+    Notes
+    -----
+    The probability density function for `gumbel_r` is:
+
+    .. math::
+
+        f(x) = \exp(-(x + e^{-x}))
+
+    for real :math:`x`.
+
+    The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett
+    distribution.  It is also related to the extreme value distribution,
+    log-Weibull and Gompertz distributions.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # gumbel_r.pdf(x) = exp(-(x + exp(-x)))
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return -x - np.exp(-x)
+
+    def _cdf(self, x):
+        return np.exp(-np.exp(-x))
+
+    def _logcdf(self, x):
+        return -np.exp(-x)
+
+    def _ppf(self, q):
+        return -np.log(-np.log(q))
+
+    def _sf(self, x):
+        return -sc.expm1(-np.exp(-x))
+
+    def _isf(self, p):
+        return -np.log(-np.log1p(-p))
+
+    def _stats(self):
+        return _EULER, np.pi*np.pi/6.0, 12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5
+
+    def _entropy(self):
+        # https://en.wikipedia.org/wiki/Gumbel_distribution
+        return _EULER + 1.
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # By the method of maximum likelihood, the estimators of the
+        # location and scale are the roots of the equations defined in
+        # `func` and the value of the expression for `loc` that follows.
+        # The first `func` is a first order derivative of the log-likelihood
+        # equation and the second is from Source: Statistical Distributions,
+        # 3rd Edition. Evans, Hastings, and Peacock (2000), Page 101.
+
+        def get_loc_from_scale(scale):
+            return -scale * (sc.logsumexp(-data / scale) - np.log(len(data)))
+
+        if fscale is not None:
+            # if the scale is fixed, the location can be analytically
+            # determined.
+            scale = fscale
+            loc = get_loc_from_scale(scale)
+        else:
+            # A different function is solved depending on whether the location
+            # is fixed.
+            if floc is not None:
+                loc = floc
+
+                # equation to use if the location is fixed.
+                # note that one cannot use the equation in Evans, Hastings,
+                # and Peacock (2000) (since it assumes that the derivative
+                # w.r.t. the log-likelihood is zero). however, it is easy to
+                # derive the MLE condition directly if loc is fixed
+                def func(scale):
+                    term1 = (loc - data) * np.exp((loc - data) / scale) + data
+                    term2 = len(data) * (loc + scale)
+                    return term1.sum() - term2
+            else:
+
+                # equation to use if both location and scale are free
+                def func(scale):
+                    sdata = -data / scale
+                    wavg = _average_with_log_weights(data, logweights=sdata)
+                    return data.mean() - wavg - scale
+
+            # set brackets for `root_scalar` to use when optimizing over the
+            # scale such that a root is likely between them. Use user supplied
+            # guess or default 1.
+            brack_start = kwds.get('scale', 1)
+            lbrack, rbrack = brack_start / 2, brack_start * 2
+
+            # if a root is not between the brackets, iteratively expand them
+            # until they include a sign change, checking after each bracket is
+            # modified.
+            def interval_contains_root(lbrack, rbrack):
+                # return true if the signs disagree.
+                return (np.sign(func(lbrack)) !=
+                        np.sign(func(rbrack)))
+            while (not interval_contains_root(lbrack, rbrack)
+                   and (lbrack > 0 or rbrack < np.inf)):
+                lbrack /= 2
+                rbrack *= 2
+
+            res = optimize.root_scalar(func, bracket=(lbrack, rbrack),
+                                       rtol=1e-14, xtol=1e-14)
+            scale = res.root
+            loc = floc if floc is not None else get_loc_from_scale(scale)
+        return loc, scale
+
+
+gumbel_r = gumbel_r_gen(name='gumbel_r')
+
+
+class gumbel_l_gen(rv_continuous):
+    r"""A left-skewed Gumbel continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_r, gompertz, genextreme
+
+    Notes
+    -----
+    The probability density function for `gumbel_l` is:
+
+    .. math::
+
+        f(x) = \exp(x - e^x)
+
+    for real :math:`x`.
+
+    The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett
+    distribution.  It is also related to the extreme value distribution,
+    log-Weibull and Gompertz distributions.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # gumbel_l.pdf(x) = exp(x - exp(x))
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return x - np.exp(x)
+
+    def _cdf(self, x):
+        return -sc.expm1(-np.exp(x))
+
+    def _ppf(self, q):
+        return np.log(-sc.log1p(-q))
+
+    def _logsf(self, x):
+        return -np.exp(x)
+
+    def _sf(self, x):
+        return np.exp(-np.exp(x))
+
+    def _isf(self, x):
+        return np.log(-np.log(x))
+
+    def _stats(self):
+        return -_EULER, np.pi*np.pi/6.0, \
+               -12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5
+
+    def _entropy(self):
+        return _EULER + 1.
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        # The fit method of `gumbel_r` can be used for this distribution with
+        # small modifications. The process to do this is
+        # 1. pass the sign negated data into `gumbel_r.fit`
+        #    - if the location is fixed, it should also be negated.
+        # 2. negate the sign of the resulting location, leaving the scale
+        #    unmodified.
+        # `gumbel_r.fit` holds necessary input checks.
+
+        if kwds.get('floc') is not None:
+            kwds['floc'] = -kwds['floc']
+        loc_r, scale_r, = gumbel_r.fit(-np.asarray(data), *args, **kwds)
+        return -loc_r, scale_r
+
+
+gumbel_l = gumbel_l_gen(name='gumbel_l')
+
+
+class halfcauchy_gen(rv_continuous):
+    r"""A Half-Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halfcauchy` is:
+
+    .. math::
+
+        f(x) = \frac{2}{\pi (1 + x^2)}
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # halfcauchy.pdf(x) = 2 / (pi * (1 + x**2))
+        return 2.0/np.pi/(1.0+x*x)
+
+    def _logpdf(self, x):
+        return np.log(2.0/np.pi) - sc.log1p(x*x)
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arctan(x)
+
+    def _ppf(self, q):
+        return np.tan(np.pi/2*q)
+
+    def _sf(self, x):
+        return 2.0/np.pi * np.arctan2(1, x)
+
+    def _isf(self, p):
+        return 1.0/np.tan(np.pi*p/2)
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+    def _entropy(self):
+        return np.log(2*np.pi)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # location is independent from the scale
+        data_min = np.min(data)
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halfcauchy", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            # if not provided, location MLE is the minimal data point
+            loc = data_min
+
+        # find scale
+        def find_scale(loc, data):
+            shifted_data = data - loc
+            n = data.size
+            shifted_data_squared = np.square(shifted_data)
+
+            def fun_to_solve(scale):
+                denominator = scale**2 + shifted_data_squared
+                return 2 * np.sum(shifted_data_squared/denominator) - n
+
+            small = np.finfo(1.0).tiny**0.5  # avoid underflow
+            res = root_scalar(fun_to_solve, bracket=(small, np.max(shifted_data)))
+            return res.root
+
+        if fscale is not None:
+            scale = fscale
+        else:
+            scale = find_scale(loc, data)
+
+        return loc, scale
+
+
+halfcauchy = halfcauchy_gen(a=0.0, name='halfcauchy')
+
+
+class halflogistic_gen(rv_continuous):
+    r"""A half-logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halflogistic` is:
+
+    .. math::
+
+        f(x) = \frac{ 2 e^{-x} }{ (1+e^{-x})^2 }
+             = \frac{1}{2} \text{sech}(x/2)^2
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Asgharzadeh et al (2011). "Comparisons of Methods of Estimation for the
+           Half-Logistic Distribution". Selcuk J. Appl. Math. 93-108.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # halflogistic.pdf(x) = 2 * exp(-x) / (1+exp(-x))**2
+        #                     = 1/2 * sech(x/2)**2
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return np.log(2) - x - 2. * sc.log1p(np.exp(-x))
+
+    def _cdf(self, x):
+        return np.tanh(x/2.0)
+
+    def _ppf(self, q):
+        return 2*np.arctanh(q)
+
+    def _sf(self, x):
+        return 2 * sc.expit(-x)
+
+    def _isf(self, q):
+        return _lazywhere(q < 0.5, (q, ),
+                          lambda q: -sc.logit(0.5 * q),
+                          f2=lambda q: 2*np.arctanh(1 - q))
+
+    def _munp(self, n):
+        if n == 0:
+            return 1  # otherwise returns NaN
+        if n == 1:
+            return 2*np.log(2)
+        if n == 2:
+            return np.pi*np.pi/3.0
+        if n == 3:
+            return 9*_ZETA3
+        if n == 4:
+            return 7*np.pi**4 / 15.0
+        return 2*(1-pow(2.0, 1-n))*sc.gamma(n+1)*sc.zeta(n, 1)
+
+    def _entropy(self):
+        return 2-np.log(2)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        def find_scale(data, loc):
+            # scale is solution to a fix point problem ([1] 2.6)
+            # use approximate MLE as starting point ([1] 3.1)
+            n_observations = data.shape[0]
+            sorted_data = np.sort(data, axis=0)
+            p = np.arange(1, n_observations + 1)/(n_observations + 1)
+            q = 1 - p
+            pp1 = 1 + p
+            alpha = p - 0.5 * q * pp1 * np.log(pp1 / q)
+            beta = 0.5 * q * pp1
+            sorted_data = sorted_data - loc
+            B = 2 * np.sum(alpha[1:] * sorted_data[1:])
+            C = 2 * np.sum(beta[1:] * sorted_data[1:]**2)
+            # starting guess
+            scale = ((B + np.sqrt(B**2 + 8 * n_observations * C))
+                    /(4 * n_observations))
+
+            # relative tolerance of fix point iterator
+            rtol = 1e-8
+            relative_residual = 1
+            shifted_mean = sorted_data.mean()  # y_mean - y_min
+
+            # find fix point by repeated application of eq. (2.6)
+            # simplify as
+            # exp(-x) / (1 + exp(-x)) = 1 / (1 + exp(x))
+            #                         = expit(-x))
+            while relative_residual > rtol:
+                sum_term = sorted_data * sc.expit(-sorted_data/scale)
+                scale_new = shifted_mean - 2/n_observations * sum_term.sum()
+                relative_residual = abs((scale - scale_new)/scale)
+                scale = scale_new
+            return scale
+
+        # location is independent from the scale
+        data_min = np.min(data)
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halflogistic", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            # if not provided, location MLE is the minimal data point
+            loc = data_min
+
+        # scale depends on location
+        scale = fscale if fscale is not None else find_scale(data, loc)
+
+        return loc, scale
+
+
+halflogistic = halflogistic_gen(a=0.0, name='halflogistic')
+
+
+class halfnorm_gen(rv_continuous):
+    r"""A half-normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halfnorm` is:
+
+    .. math::
+
+        f(x) = \sqrt{2/\pi} \exp(-x^2 / 2)
+
+    for :math:`x >= 0`.
+
+    `halfnorm` is a special case of `chi` with ``df=1``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return abs(random_state.standard_normal(size=size))
+
+    def _pdf(self, x):
+        # halfnorm.pdf(x) = sqrt(2/pi) * exp(-x**2/2)
+        return np.sqrt(2.0/np.pi)*np.exp(-x*x/2.0)
+
+    def _logpdf(self, x):
+        return 0.5 * np.log(2.0/np.pi) - x*x/2.0
+
+    def _cdf(self, x):
+        return sc.erf(x / np.sqrt(2))
+
+    def _ppf(self, q):
+        return _norm_ppf((1+q)/2.0)
+
+    def _sf(self, x):
+        return 2 * _norm_sf(x)
+
+    def _isf(self, p):
+        return _norm_isf(p/2)
+
+    def _stats(self):
+        return (np.sqrt(2.0/np.pi),
+                1-2.0/np.pi,
+                np.sqrt(2)*(4-np.pi)/(np.pi-2)**1.5,
+                8*(np.pi-3)/(np.pi-2)**2)
+
+    def _entropy(self):
+        return 0.5*np.log(np.pi/2.0)+0.5
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        data_min = np.min(data)
+
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halfnorm", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            loc = data_min
+
+        if fscale is not None:
+            scale = fscale
+        else:
+            scale = stats.moment(data, order=2, center=loc)**0.5
+
+        return loc, scale
+
+
+halfnorm = halfnorm_gen(a=0.0, name='halfnorm')
+
+
+class hypsecant_gen(rv_continuous):
+    r"""A hyperbolic secant continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `hypsecant` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi} \text{sech}(x)
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # hypsecant.pdf(x) = 1/pi * sech(x)
+        return 1.0/(np.pi*np.cosh(x))
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arctan(np.exp(x))
+
+    def _ppf(self, q):
+        return np.log(np.tan(np.pi*q/2.0))
+
+    def _sf(self, x):
+        return 2.0/np.pi*np.arctan(np.exp(-x))
+
+    def _isf(self, q):
+        return -np.log(np.tan(np.pi*q/2.0))
+
+    def _stats(self):
+        return 0, np.pi*np.pi/4, 0, 2
+
+    def _entropy(self):
+        return np.log(2*np.pi)
+
+
+hypsecant = hypsecant_gen(name='hypsecant')
+
+
+class gausshyper_gen(rv_continuous):
+    r"""A Gauss hypergeometric continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gausshyper` is:
+
+    .. math::
+
+        f(x, a, b, c, z) = C x^{a-1} (1-x)^{b-1} (1+zx)^{-c}
+
+    for :math:`0 \le x \le 1`, :math:`a,b > 0`, :math:`c` a real number,
+    :math:`z > -1`, and :math:`C = \frac{1}{B(a, b) F[2, 1](c, a; a+b; -z)}`.
+    :math:`F[2, 1]` is the Gauss hypergeometric function
+    `scipy.special.hyp2f1`.
+
+    `gausshyper` takes :math:`a`, :math:`b`, :math:`c` and :math:`z` as shape
+    parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Armero, C., and M. J. Bayarri. "Prior Assessments for Prediction in
+           Queues." *Journal of the Royal Statistical Society*. Series D (The
+           Statistician) 43, no. 1 (1994): 139-53. doi:10.2307/2348939
+
+    %(example)s
+
+    """
+
+    def _argcheck(self, a, b, c, z):
+        # z > -1 per gh-10134
+        return (a > 0) & (b > 0) & (c == c) & (z > -1)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False))
+        iz = _ShapeInfo("z", False, (-1, np.inf), (False, False))
+        return [ia, ib, ic, iz]
+
+    def _pdf(self, x, a, b, c, z):
+        normalization_constant = sc.beta(a, b) * sc.hyp2f1(c, a, a + b, -z)
+        return (1./normalization_constant * x**(a - 1.) * (1. - x)**(b - 1.0)
+                / (1.0 + z*x)**c)
+
+    def _munp(self, n, a, b, c, z):
+        fac = sc.beta(n+a, b) / sc.beta(a, b)
+        num = sc.hyp2f1(c, a+n, a+b+n, -z)
+        den = sc.hyp2f1(c, a, a+b, -z)
+        return fac*num / den
+
+
+gausshyper = gausshyper_gen(a=0.0, b=1.0, name='gausshyper')
+
+
+class invgamma_gen(rv_continuous):
+    r"""An inverted gamma continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invgamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{x^{-a-1}}{\Gamma(a)} \exp(-\frac{1}{x})
+
+    for :math:`x >= 0`, :math:`a > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    `invgamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    `invgamma` is a special case of `gengamma` with ``c=-1``, and it is a
+    different parameterization of the scaled inverse chi-squared distribution.
+    Specifically, if the scaled inverse chi-squared distribution is
+    parameterized with degrees of freedom :math:`\nu` and scaling parameter
+    :math:`\tau^2`, then it can be modeled using `invgamma` with
+    ``a=`` :math:`\nu/2` and ``scale=`` :math:`\nu \tau^2/2`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # invgamma.pdf(x, a) = x**(-a-1) / gamma(a) * exp(-1/x)
+        return np.exp(self._logpdf(x, a))
+
+    def _logpdf(self, x, a):
+        return -(a+1) * np.log(x) - sc.gammaln(a) - 1.0/x
+
+    def _cdf(self, x, a):
+        return sc.gammaincc(a, 1.0 / x)
+
+    def _ppf(self, q, a):
+        return 1.0 / sc.gammainccinv(a, q)
+
+    def _sf(self, x, a):
+        return sc.gammainc(a, 1.0 / x)
+
+    def _isf(self, q, a):
+        return 1.0 / sc.gammaincinv(a, q)
+
+    def _stats(self, a, moments='mvsk'):
+        m1 = _lazywhere(a > 1, (a,), lambda x: 1. / (x - 1.), np.inf)
+        m2 = _lazywhere(a > 2, (a,), lambda x: 1. / (x - 1.)**2 / (x - 2.),
+                        np.inf)
+
+        g1, g2 = None, None
+        if 's' in moments:
+            g1 = _lazywhere(
+                a > 3, (a,),
+                lambda x: 4. * np.sqrt(x - 2.) / (x - 3.), np.nan)
+        if 'k' in moments:
+            g2 = _lazywhere(
+                a > 4, (a,),
+                lambda x: 6. * (5. * x - 11.) / (x - 3.) / (x - 4.), np.nan)
+        return m1, m2, g1, g2
+
+    def _entropy(self, a):
+        def regular(a):
+            h = a - (a + 1.0) * sc.psi(a) + sc.gammaln(a)
+            return h
+
+        def asymptotic(a):
+            # gammaln(a) ~ a * ln(a) - a - 0.5 * ln(a) + 0.5 * ln(2 * pi)
+            # psi(a) ~ ln(a) - 1 / (2 * a)
+            h = ((1 - 3*np.log(a) + np.log(2) + np.log(np.pi))/2
+                 + 2/3*a**-1. + a**-2./12 - a**-3./90 - a**-4./120)
+            return h
+
+        h = _lazywhere(a >= 2e2, (a,), f=asymptotic, f2=regular)
+        return h
+
+
+invgamma = invgamma_gen(a=0.0, name='invgamma')
+
+
+class invgauss_gen(rv_continuous):
+    r"""An inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invgauss` is:
+
+    .. math::
+
+        f(x; \mu) = \frac{1}{\sqrt{2 \pi x^3}}
+                    \exp\left(-\frac{(x-\mu)^2}{2 \mu^2 x}\right)
+
+    for :math:`x \ge 0` and :math:`\mu > 0`.
+
+    `invgauss` takes ``mu`` as a shape parameter for :math:`\mu`.
+
+    %(after_notes)s
+
+    A common shape-scale parameterization of the inverse Gaussian distribution
+    has density
+
+    .. math::
+
+        f(x; \nu, \lambda) = \sqrt{\frac{\lambda}{2 \pi x^3}}
+                    \exp\left( -\frac{\lambda(x-\nu)^2}{2 \nu^2 x}\right)
+
+    Using ``nu`` for :math:`\nu` and ``lam`` for :math:`\lambda`, this
+    parameterization is equivalent to the one above with ``mu = nu/lam``,
+    ``loc = 0``, and ``scale = lam``.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``ppf`` and ``isf`` methods. [1]_
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return random_state.wald(mu, 1.0, size=size)
+
+    def _pdf(self, x, mu):
+        # invgauss.pdf(x, mu) =
+        #                  1 / sqrt(2*pi*x**3) * exp(-(x-mu)**2/(2*x*mu**2))
+        return 1.0/np.sqrt(2*np.pi*x**3.0)*np.exp(-1.0/(2*x)*((x-mu)/mu)**2)
+
+    def _logpdf(self, x, mu):
+        return -0.5*np.log(2*np.pi) - 1.5*np.log(x) - ((x-mu)/mu)**2/(2*x)
+
+    # approach adapted from equations in
+    # https://journal.r-project.org/archive/2016-1/giner-smyth.pdf,
+    # not R code. see gh-13616
+
+    def _logcdf(self, x, mu):
+        fac = 1 / np.sqrt(x)
+        a = _norm_logcdf(fac * ((x / mu) - 1))
+        b = 2 / mu + _norm_logcdf(-fac * ((x / mu) + 1))
+        return a + np.log1p(np.exp(b - a))
+
+    def _logsf(self, x, mu):
+        fac = 1 / np.sqrt(x)
+        a = _norm_logsf(fac * ((x / mu) - 1))
+        b = 2 / mu + _norm_logcdf(-fac * (x + mu) / mu)
+        return a + np.log1p(-np.exp(b - a))
+
+    def _sf(self, x, mu):
+        return np.exp(self._logsf(x, mu))
+
+    def _cdf(self, x, mu):
+        return np.exp(self._logcdf(x, mu))
+
+    def _ppf(self, x, mu):
+        with np.errstate(divide='ignore', over='ignore', invalid='ignore'):
+            x, mu = np.broadcast_arrays(x, mu)
+            ppf = np.asarray(scu._invgauss_ppf(x, mu, 1))
+            i_wt = x > 0.5  # "wrong tail" - sometimes too inaccurate
+            ppf[i_wt] = scu._invgauss_isf(1-x[i_wt], mu[i_wt], 1)
+            i_nan = np.isnan(ppf)
+            ppf[i_nan] = super()._ppf(x[i_nan], mu[i_nan])
+        return ppf
+
+    def _isf(self, x, mu):
+        with np.errstate(divide='ignore', over='ignore', invalid='ignore'):
+            x, mu = np.broadcast_arrays(x, mu)
+            isf = scu._invgauss_isf(x, mu, 1)
+            i_wt = x > 0.5  # "wrong tail" - sometimes too inaccurate
+            isf[i_wt] = scu._invgauss_ppf(1-x[i_wt], mu[i_wt], 1)
+            i_nan = np.isnan(isf)
+            isf[i_nan] = super()._isf(x[i_nan], mu[i_nan])
+        return isf
+
+    def _stats(self, mu):
+        return mu, mu**3.0, 3*np.sqrt(mu), 15*mu
+
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        method = kwds.get('method', 'mle')
+
+        if (isinstance(data, CensoredData) or isinstance(self, wald_gen)
+                or method.lower() == 'mm'):
+            return super().fit(data, *args, **kwds)
+
+        data, fshape_s, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                   args, kwds)
+        '''
+        Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+        and Peacock (2000), Page 121. Their shape parameter is equivalent to
+        SciPy's with the conversion `fshape_s = fshape / scale`.
+
+        MLE formulas are not used in 3 conditions:
+        - `loc` is not fixed
+        - `mu` is fixed
+        These cases fall back on the superclass fit method.
+        - `loc` is fixed but translation results in negative data raises
+          a `FitDataError`.
+        '''
+        if floc is None or fshape_s is not None:
+            return super().fit(data, *args, **kwds)
+        elif np.any(data - floc < 0):
+            raise FitDataError("invgauss", lower=0, upper=np.inf)
+        else:
+            data = data - floc
+            fshape_n = np.mean(data)
+            if fscale is None:
+                fscale = len(data) / (np.sum(data ** -1 - fshape_n ** -1))
+            fshape_s = fshape_n / fscale
+        return fshape_s, floc, fscale
+
+    def _entropy(self, mu):
+        """
+        Ref.: https://moser-isi.ethz.ch/docs/papers/smos-2012-10.pdf (eq. 9)
+        """
+        # a = log(2*pi*e*mu**3)
+        #   = 1 + log(2*pi) + 3 * log(mu)
+        a = 1. + np.log(2 * np.pi) + 3 * np.log(mu)
+        # b = exp(2/mu) * exp1(2/mu)
+        #   = _scaled_exp1(2/mu) / (2/mu)
+        r = 2/mu
+        b = sc._ufuncs._scaled_exp1(r)/r
+        return 0.5 * a - 1.5 * b
+
+
+invgauss = invgauss_gen(a=0.0, name='invgauss')
+
+
+class geninvgauss_gen(rv_continuous):
+    r"""A Generalized Inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `geninvgauss` is:
+
+    .. math::
+
+        f(x, p, b) = x^{p-1} \exp(-b (x + 1/x) / 2) / (2 K_p(b))
+
+    where ``x > 0``, `p` is a real number and ``b > 0``\([1]_).
+    :math:`K_p` is the modified Bessel function of second kind of order `p`
+    (`scipy.special.kv`).
+
+    %(after_notes)s
+
+    The inverse Gaussian distribution `stats.invgauss(mu)` is a special case of
+    `geninvgauss` with ``p = -1/2``, ``b = 1 / mu`` and ``scale = mu``.
+
+    Generating random variates is challenging for this distribution. The
+    implementation is based on [2]_.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, P. Blaesild, C. Halgreen, "First hitting time
+       models for the generalized inverse gaussian distribution",
+       Stochastic Processes and their Applications 7, pp. 49--54, 1978.
+
+    .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
+       random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
+
+    %(example)s
+
+    """
+    def _argcheck(self, p, b):
+        return (p == p) & (b > 0)
+
+    def _shape_info(self):
+        ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ip, ib]
+
+    def _logpdf(self, x, p, b):
+        # kve instead of kv works better for large values of b
+        # warn if kve produces infinite values and replace by nan
+        # otherwise c = -inf and the results are often incorrect
+        def logpdf_single(x, p, b):
+            return _stats.geninvgauss_logpdf(x, p, b)
+
+        logpdf_single = np.vectorize(logpdf_single, otypes=[np.float64])
+
+        z = logpdf_single(x, p, b)
+        if np.isnan(z).any():
+            msg = ("Infinite values encountered in scipy.special.kve(p, b). "
+                   "Values replaced by NaN to avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+        return z
+
+    def _pdf(self, x, p, b):
+        # relying on logpdf avoids overflow of x**(p-1) for large x and p
+        return np.exp(self._logpdf(x, p, b))
+
+    def _cdf(self, x, p, b):
+        _a, _b = self._get_support(p, b)
+
+        def _cdf_single(x, p, b):
+            user_data = np.array([p, b], float).ctypes.data_as(ctypes.c_void_p)
+            llc = LowLevelCallable.from_cython(_stats, '_geninvgauss_pdf',
+                                               user_data)
+
+            return integrate.quad(llc, _a, x)[0]
+
+        _cdf_single = np.vectorize(_cdf_single, otypes=[np.float64])
+
+        return _cdf_single(x, p, b)
+
+    def _logquasipdf(self, x, p, b):
+        # log of the quasi-density (w/o normalizing constant) used in _rvs
+        return _lazywhere(x > 0, (x, p, b),
+                          lambda x, p, b: (p - 1)*np.log(x) - b*(x + 1/x)/2,
+                          -np.inf)
+
+    def _rvs(self, p, b, size=None, random_state=None):
+        # if p and b are scalar, use _rvs_scalar, otherwise need to create
+        # output by iterating over parameters
+        if np.isscalar(p) and np.isscalar(b):
+            out = self._rvs_scalar(p, b, size, random_state)
+        elif p.size == 1 and b.size == 1:
+            out = self._rvs_scalar(p.item(), b.item(), size, random_state)
+        else:
+            # When this method is called, size will be a (possibly empty)
+            # tuple of integers.  It will not be None; if `size=None` is passed
+            # to `rvs()`, size will be the empty tuple ().
+
+            p, b = np.broadcast_arrays(p, b)
+            # p and b now have the same shape.
+
+            # `shp` is the shape of the blocks of random variates that are
+            # generated for each combination of parameters associated with
+            # broadcasting p and b.
+            # bc is a tuple the same length as size.  The values
+            # in bc are bools.  If bc[j] is True, it means that
+            # entire axis is filled in for a given combination of the
+            # broadcast arguments.
+            shp, bc = _check_shape(p.shape, size)
+
+            # `numsamples` is the total number of variates to be generated
+            # for each combination of the input arguments.
+            numsamples = int(np.prod(shp))
+
+            # `out` is the array to be returned.  It is filled in the
+            # loop below.
+            out = np.empty(size)
+
+            it = np.nditer([p, b],
+                           flags=['multi_index'],
+                           op_flags=[['readonly'], ['readonly']])
+            while not it.finished:
+                # Convert the iterator's multi_index into an index into the
+                # `out` array where the call to _rvs_scalar() will be stored.
+                # Where bc is True, we use a full slice; otherwise we use the
+                # index value from it.multi_index.  len(it.multi_index) might
+                # be less than len(bc), and in that case we want to align these
+                # two sequences to the right, so the loop variable j runs from
+                # -len(size) to 0.  This doesn't cause an IndexError, as
+                # bc[j] will be True in those cases where it.multi_index[j]
+                # would cause an IndexError.
+                idx = tuple((it.multi_index[j] if not bc[j] else slice(None))
+                            for j in range(-len(size), 0))
+                out[idx] = self._rvs_scalar(it[0], it[1], numsamples,
+                                            random_state).reshape(shp)
+                it.iternext()
+
+        if size == ():
+            out = out.item()
+        return out
+
+    def _rvs_scalar(self, p, b, numsamples, random_state):
+        # following [2], the quasi-pdf is used instead of the pdf for the
+        # generation of rvs
+        invert_res = False
+        if not numsamples:
+            numsamples = 1
+        if p < 0:
+            # note: if X is geninvgauss(p, b), then 1/X is geninvgauss(-p, b)
+            p = -p
+            invert_res = True
+        m = self._mode(p, b)
+
+        # determine method to be used following [2]
+        ratio_unif = True
+        if p >= 1 or b > 1:
+            # ratio of uniforms with mode shift below
+            mode_shift = True
+        elif b >= min(0.5, 2 * np.sqrt(1 - p) / 3):
+            # ratio of uniforms without mode shift below
+            mode_shift = False
+        else:
+            # new algorithm in [2]
+            ratio_unif = False
+
+        # prepare sampling of rvs
+        size1d = tuple(np.atleast_1d(numsamples))
+        N = np.prod(size1d)  # number of rvs needed, reshape upon return
+        x = np.zeros(N)
+        simulated = 0
+
+        if ratio_unif:
+            # use ratio of uniforms method
+            if mode_shift:
+                a2 = -2 * (p + 1) / b - m
+                a1 = 2 * m * (p - 1) / b - 1
+                # find roots of x**3 + a2*x**2 + a1*x + m (Cardano's formula)
+                p1 = a1 - a2**2 / 3
+                q1 = 2 * a2**3 / 27 - a2 * a1 / 3 + m
+                phi = np.arccos(-q1 * np.sqrt(-27 / p1**3) / 2)
+                s1 = -np.sqrt(-4 * p1 / 3)
+                root1 = s1 * np.cos(phi / 3 + np.pi / 3) - a2 / 3
+                root2 = -s1 * np.cos(phi / 3) - a2 / 3
+                # root3 = s1 * np.cos(phi / 3 - np.pi / 3) - a2 / 3
+
+                # if g is the quasipdf, rescale: g(x) / g(m) which we can write
+                # as exp(log(g(x)) - log(g(m))). This is important
+                # since for large values of p and b, g cannot be evaluated.
+                # denote the rescaled quasipdf by h
+                lm = self._logquasipdf(m, p, b)
+                d1 = self._logquasipdf(root1, p, b) - lm
+                d2 = self._logquasipdf(root2, p, b) - lm
+                # compute the bounding rectangle w.r.t. h. Note that
+                # np.exp(0.5*d1) = np.sqrt(g(root1)/g(m)) = np.sqrt(h(root1))
+                vmin = (root1 - m) * np.exp(0.5 * d1)
+                vmax = (root2 - m) * np.exp(0.5 * d2)
+                umax = 1  # umax = sqrt(h(m)) = 1
+
+                def logqpdf(x):
+                    return self._logquasipdf(x, p, b) - lm
+
+                c = m
+            else:
+                # ratio of uniforms without mode shift
+                # compute np.sqrt(quasipdf(m))
+                umax = np.exp(0.5*self._logquasipdf(m, p, b))
+                xplus = ((1 + p) + np.sqrt((1 + p)**2 + b**2))/b
+                vmin = 0
+                # compute xplus * np.sqrt(quasipdf(xplus))
+                vmax = xplus * np.exp(0.5 * self._logquasipdf(xplus, p, b))
+                c = 0
+
+                def logqpdf(x):
+                    return self._logquasipdf(x, p, b)
+
+            if vmin >= vmax:
+                raise ValueError("vmin must be smaller than vmax.")
+            if umax <= 0:
+                raise ValueError("umax must be positive.")
+
+            i = 1
+            while simulated < N:
+                k = N - simulated
+                # simulate uniform rvs on [0, umax] and [vmin, vmax]
+                u = umax * random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                v = vmin + (vmax - vmin) * v
+                rvs = v / u + c
+                # rewrite acceptance condition u**2 <= pdf(rvs) by taking logs
+                accept = (2*np.log(u) <= logqpdf(rvs))
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = rvs[accept]
+                    simulated += num_accept
+
+                if (simulated == 0) and (i*N >= 50000):
+                    msg = ("Not a single random variate could be generated "
+                           f"in {i*N} attempts. Sampling does not appear to "
+                           "work for the provided parameters.")
+                    raise RuntimeError(msg)
+                i += 1
+        else:
+            # use new algorithm in [2]
+            x0 = b / (1 - p)
+            xs = np.max((x0, 2 / b))
+            k1 = np.exp(self._logquasipdf(m, p, b))
+            A1 = k1 * x0
+            if x0 < 2 / b:
+                k2 = np.exp(-b)
+                if p > 0:
+                    A2 = k2 * ((2 / b)**p - x0**p) / p
+                else:
+                    A2 = k2 * np.log(2 / b**2)
+            else:
+                k2, A2 = 0, 0
+            k3 = xs**(p - 1)
+            A3 = 2 * k3 * np.exp(-xs * b / 2) / b
+            A = A1 + A2 + A3
+
+            # [2]: rejection constant is < 2.73; so expected runtime is finite
+            while simulated < N:
+                k = N - simulated
+                h, rvs = np.zeros(k), np.zeros(k)
+                # simulate uniform rvs on [x1, x2] and [0, y2]
+                u = random_state.uniform(size=k)
+                v = A * random_state.uniform(size=k)
+                cond1 = v <= A1
+                cond2 = np.logical_not(cond1) & (v <= A1 + A2)
+                cond3 = np.logical_not(cond1 | cond2)
+                # subdomain (0, x0)
+                rvs[cond1] = x0 * v[cond1] / A1
+                h[cond1] = k1
+                # subdomain (x0, 2 / b)
+                if p > 0:
+                    rvs[cond2] = (x0**p + (v[cond2] - A1) * p / k2)**(1 / p)
+                else:
+                    rvs[cond2] = b * np.exp((v[cond2] - A1) * np.exp(b))
+                h[cond2] = k2 * rvs[cond2]**(p - 1)
+                # subdomain (xs, infinity)
+                z = np.exp(-xs * b / 2) - b * (v[cond3] - A1 - A2) / (2 * k3)
+                rvs[cond3] = -2 / b * np.log(z)
+                h[cond3] = k3 * np.exp(-rvs[cond3] * b / 2)
+                # apply rejection method
+                accept = (np.log(u * h) <= self._logquasipdf(rvs, p, b))
+                num_accept = sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = rvs[accept]
+                    simulated += num_accept
+
+        rvs = np.reshape(x, size1d)
+        if invert_res:
+            rvs = 1 / rvs
+        return rvs
+
+    def _mode(self, p, b):
+        # distinguish cases to avoid catastrophic cancellation (see [2])
+        if p < 1:
+            return b / (np.sqrt((p - 1)**2 + b**2) + 1 - p)
+        else:
+            return (np.sqrt((1 - p)**2 + b**2) - (1 - p)) / b
+
+    def _munp(self, n, p, b):
+        num = sc.kve(p + n, b)
+        denom = sc.kve(p, b)
+        inf_vals = np.isinf(num) | np.isinf(denom)
+        if inf_vals.any():
+            msg = ("Infinite values encountered in the moment calculation "
+                   "involving scipy.special.kve. Values replaced by NaN to "
+                   "avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+            m = np.full_like(num, np.nan, dtype=np.float64)
+            m[~inf_vals] = num[~inf_vals] / denom[~inf_vals]
+        else:
+            m = num / denom
+        return m
+
+
+geninvgauss = geninvgauss_gen(a=0.0, name="geninvgauss")
+
+
+class norminvgauss_gen(rv_continuous):
+    r"""A Normal Inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `norminvgauss` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{a \, K_1(a \sqrt{1 + x^2})}{\pi \sqrt{1 + x^2}} \,
+                     \exp(\sqrt{a^2 - b^2} + b x)
+
+    where :math:`x` is a real number, the parameter :math:`a` is the tail
+    heaviness and :math:`b` is the asymmetry parameter satisfying
+    :math:`a > 0` and :math:`|b| <= a`.
+    :math:`K_1` is the modified Bessel function of second kind
+    (`scipy.special.k1`).
+
+    %(after_notes)s
+
+    A normal inverse Gaussian random variable `Y` with parameters `a` and `b`
+    can be expressed as a normal mean-variance mixture:
+    ``Y = b * V + sqrt(V) * X`` where `X` is ``norm(0,1)`` and `V` is
+    ``invgauss(mu=1/sqrt(a**2 - b**2))``. This representation is used
+    to generate random variates.
+
+    Another common parametrization of the distribution (see Equation 2.1 in
+    [2]_) is given by the following expression of the pdf:
+
+    .. math::
+
+        g(x, \alpha, \beta, \delta, \mu) =
+        \frac{\alpha\delta K_1\left(\alpha\sqrt{\delta^2 + (x - \mu)^2}\right)}
+        {\pi \sqrt{\delta^2 + (x - \mu)^2}} \,
+        e^{\delta \sqrt{\alpha^2 - \beta^2} + \beta (x - \mu)}
+
+    In SciPy, this corresponds to
+    `a = alpha * delta, b = beta * delta, loc = mu, scale=delta`.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions on
+           Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3),
+           pp. 151-157, 1978.
+
+    .. [2] O. Barndorff-Nielsen, "Normal Inverse Gaussian Distributions and
+           Stochastic Volatility Modelling", Scandinavian Journal of
+           Statistics, Vol. 24, pp. 1-13, 1997.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, a, b):
+        return (a > 0) & (np.absolute(b) < a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default a = b = 1 is not valid; the distribution
+        # requires |b| < a.
+        return super()._fitstart(data, args=(1, 0.5))
+
+    def _pdf(self, x, a, b):
+        gamma = np.sqrt(a**2 - b**2)
+        fac1 = a / np.pi
+        sq = np.hypot(1, x)  # reduce overflows
+        return fac1 * sc.k1e(a * sq) * np.exp(b*x - a*sq + gamma) / sq
+
+    def _sf(self, x, a, b):
+        if np.isscalar(x):
+            # If x is a scalar, then so are a and b.
+            return integrate.quad(self._pdf, x, np.inf, args=(a, b))[0]
+        else:
+            a = np.atleast_1d(a)
+            b = np.atleast_1d(b)
+            result = []
+            for (x0, a0, b0) in zip(x, a, b):
+                result.append(integrate.quad(self._pdf, x0, np.inf,
+                                             args=(a0, b0))[0])
+            return np.array(result)
+
+    def _isf(self, q, a, b):
+        def _isf_scalar(q, a, b):
+
+            def eq(x, a, b, q):
+                # Solve eq(x, a, b, q) = 0 to obtain isf(x, a, b) = q.
+                return self._sf(x, a, b) - q
+
+            # Find a bracketing interval for the root.
+            # Start at the mean, and grow the length of the interval
+            # by 2 each iteration until there is a sign change in eq.
+            xm = self.mean(a, b)
+            em = eq(xm, a, b, q)
+            if em == 0:
+                # Unlikely, but might as well check.
+                return xm
+            if em > 0:
+                delta = 1
+                left = xm
+                right = xm + delta
+                while eq(right, a, b, q) > 0:
+                    delta = 2*delta
+                    right = xm + delta
+            else:
+                # em < 0
+                delta = 1
+                right = xm
+                left = xm - delta
+                while eq(left, a, b, q) < 0:
+                    delta = 2*delta
+                    left = xm - delta
+            result = optimize.brentq(eq, left, right, args=(a, b, q),
+                                     xtol=self.xtol)
+            return result
+
+        if np.isscalar(q):
+            return _isf_scalar(q, a, b)
+        else:
+            result = []
+            for (q0, a0, b0) in zip(q, a, b):
+                result.append(_isf_scalar(q0, a0, b0))
+            return np.array(result)
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        # note: X = b * V + sqrt(V) * X is norminvgaus(a,b) if X is standard
+        # normal and V is invgauss(mu=1/sqrt(a**2 - b**2))
+        gamma = np.sqrt(a**2 - b**2)
+        ig = invgauss.rvs(mu=1/gamma, size=size, random_state=random_state)
+        return b * ig + np.sqrt(ig) * norm.rvs(size=size,
+                                               random_state=random_state)
+
+    def _stats(self, a, b):
+        gamma = np.sqrt(a**2 - b**2)
+        mean = b / gamma
+        variance = a**2 / gamma**3
+        skewness = 3.0 * b / (a * np.sqrt(gamma))
+        kurtosis = 3.0 * (1 + 4 * b**2 / a**2) / gamma
+        return mean, variance, skewness, kurtosis
+
+
+norminvgauss = norminvgauss_gen(name="norminvgauss")
+
+
+class invweibull_gen(rv_continuous):
+    """An inverted Weibull continuous random variable.
+
+    This distribution is also known as the Fréchet distribution or the
+    type II extreme value distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invweibull` is:
+
+    .. math::
+
+        f(x, c) = c x^{-c-1} \\exp(-x^{-c})
+
+    for :math:`x > 0`, :math:`c > 0`.
+
+    `invweibull` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    F.R.S. de Gusmao, E.M.M Ortega and G.M. Cordeiro, "The generalized inverse
+    Weibull distribution", Stat. Papers, vol. 52, pp. 591-619, 2011.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # invweibull.pdf(x, c) = c * x**(-c-1) * exp(-x**(-c))
+        xc1 = np.power(x, -c - 1.0)
+        xc2 = np.power(x, -c)
+        xc2 = np.exp(-xc2)
+        return c * xc1 * xc2
+
+    def _cdf(self, x, c):
+        xc1 = np.power(x, -c)
+        return np.exp(-xc1)
+
+    def _sf(self, x, c):
+        return -np.expm1(-x**-c)
+
+    def _ppf(self, q, c):
+        return np.power(-np.log(q), -1.0/c)
+
+    def _isf(self, p, c):
+        return (-np.log1p(-p))**(-1/c)
+
+    def _munp(self, n, c):
+        return sc.gamma(1 - n / c)
+
+    def _entropy(self, c):
+        return 1+_EULER + _EULER / c - np.log(c)
+
+    def _fitstart(self, data, args=None):
+        # invweibull requires c > 1 for the first moment to exist, so use 2.0
+        args = (2.0,) if args is None else args
+        return super()._fitstart(data, args=args)
+
+
+invweibull = invweibull_gen(a=0, name='invweibull')
+
+
+class jf_skew_t_gen(rv_continuous):
+    r"""Jones and Faddy skew-t distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `jf_skew_t` is:
+
+    .. math::
+
+        f(x; a, b) = C_{a,b}^{-1}
+                    \left(1+\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{a+1/2}
+                    \left(1-\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{b+1/2}
+
+    for real numbers :math:`a>0` and :math:`b>0`, where
+    :math:`C_{a,b} = 2^{a+b-1}B(a,b)(a+b)^{1/2}`, and :math:`B` denotes the
+    beta function (`scipy.special.beta`).
+
+    When :math:`ab`, the distribution is positively skewed. If :math:`a=b`, then
+    we recover the `t` distribution with :math:`2a` degrees of freedom.
+
+    `jf_skew_t` takes :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] M.C. Jones and M.J. Faddy. "A skew extension of the t distribution,
+           with applications" *Journal of the Royal Statistical Society*.
+           Series B (Statistical Methodology) 65, no. 1 (2003): 159-174.
+           :doi:`10.1111/1467-9868.00378`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        c = 2 ** (a + b - 1) * sc.beta(a, b) * np.sqrt(a + b)
+        d1 = (1 + x / np.sqrt(a + b + x ** 2)) ** (a + 0.5)
+        d2 = (1 - x / np.sqrt(a + b + x ** 2)) ** (b + 0.5)
+        return d1 * d2 / c
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        d1 = random_state.beta(a, b, size)
+        d2 = (2 * d1 - 1) * np.sqrt(a + b)
+        d3 = 2 * np.sqrt(d1 * (1 - d1))
+        return d2 / d3
+
+    def _cdf(self, x, a, b):
+        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
+        return sc.betainc(a, b, y)
+
+    def _sf(self, x, a, b):
+        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
+        return sc.betaincc(a, b, y)
+
+    def _ppf(self, q, a, b):
+        d1 = beta.ppf(q, a, b)
+        d2 = (2 * d1 - 1) * np.sqrt(a + b)
+        d3 = 2 * np.sqrt(d1 * (1 - d1))
+        return d2 / d3
+
+    def _munp(self, n, a, b):
+        """Returns the n-th moment(s) where all the following hold:
+
+        - n >= 0
+        - a > n / 2
+        - b > n / 2
+
+        The result is np.nan in all other cases.
+        """
+        def nth_moment(n_k, a_k, b_k):
+            """Computes E[T^(n_k)] where T is skew-t distributed with
+            parameters a_k and b_k.
+            """
+            num = (a_k + b_k) ** (0.5 * n_k)
+            denom = 2 ** n_k * sc.beta(a_k, b_k)
+
+            indices = np.arange(n_k + 1)
+            sgn = np.where(indices % 2 > 0, -1, 1)
+            d = sc.beta(a_k + 0.5 * n_k - indices, b_k - 0.5 * n_k + indices)
+            sum_terms = sc.comb(n_k, indices) * sgn * d
+
+            return num / denom * sum_terms.sum()
+
+        nth_moment_valid = (a > 0.5 * n) & (b > 0.5 * n) & (n >= 0)
+        return _lazywhere(
+            nth_moment_valid,
+            (n, a, b),
+            np.vectorize(nth_moment, otypes=[np.float64]),
+            np.nan,
+        )
+
+
+jf_skew_t = jf_skew_t_gen(name='jf_skew_t')
+
+
+class johnsonsb_gen(rv_continuous):
+    r"""A Johnson SB continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    johnsonsu
+
+    Notes
+    -----
+    The probability density function for `johnsonsb` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{b}{x(1-x)}  \phi(a + b \log \frac{x}{1-x} )
+
+    where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0`
+    and :math:`x \in [0,1]`.  :math:`\phi` is the pdf of the normal
+    distribution.
+
+    `johnsonsb` takes :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, a, b):
+        return (b > 0) & (a == a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        # johnsonsb.pdf(x, a, b) = b / (x*(1-x)) * phi(a + b * log(x/(1-x)))
+        trm = _norm_pdf(a + b*sc.logit(x))
+        return b*1.0/(x*(1-x))*trm
+
+    def _cdf(self, x, a, b):
+        return _norm_cdf(a + b*sc.logit(x))
+
+    def _ppf(self, q, a, b):
+        return sc.expit(1.0 / b * (_norm_ppf(q) - a))
+
+    def _sf(self, x, a, b):
+        return _norm_sf(a + b*sc.logit(x))
+
+    def _isf(self, q, a, b):
+        return sc.expit(1.0 / b * (_norm_isf(q) - a))
+
+
+johnsonsb = johnsonsb_gen(a=0.0, b=1.0, name='johnsonsb')
+
+
+class johnsonsu_gen(rv_continuous):
+    r"""A Johnson SU continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    johnsonsb
+
+    Notes
+    -----
+    The probability density function for `johnsonsu` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{b}{\sqrt{x^2 + 1}}
+                     \phi(a + b \log(x + \sqrt{x^2 + 1}))
+
+    where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0`.
+    :math:`\phi` is the pdf of the normal distribution.
+
+    `johnsonsu` takes :math:`a` and :math:`b` as shape parameters.
+
+    The first four central moments are calculated according to the formulas
+    in [1]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Taylor Enterprises. "Johnson Family of Distributions".
+       https://variation.com/wp-content/distribution_analyzer_help/hs126.htm
+
+    %(example)s
+
+    """
+    def _argcheck(self, a, b):
+        return (b > 0) & (a == a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        # johnsonsu.pdf(x, a, b) = b / sqrt(x**2 + 1) *
+        #                          phi(a + b * log(x + sqrt(x**2 + 1)))
+        x2 = x*x
+        trm = _norm_pdf(a + b * np.arcsinh(x))
+        return b*1.0/np.sqrt(x2+1.0)*trm
+
+    def _cdf(self, x, a, b):
+        return _norm_cdf(a + b * np.arcsinh(x))
+
+    def _ppf(self, q, a, b):
+        return np.sinh((_norm_ppf(q) - a) / b)
+
+    def _sf(self, x, a, b):
+        return _norm_sf(a + b * np.arcsinh(x))
+
+    def _isf(self, x, a, b):
+        return np.sinh((_norm_isf(x) - a) / b)
+
+    def _stats(self, a, b, moments='mv'):
+        # Naive implementation of first and second moment to address gh-18071.
+        # https://variation.com/wp-content/distribution_analyzer_help/hs126.htm
+        # Numerical improvements left to future enhancements.
+        mu, mu2, g1, g2 = None, None, None, None
+
+        bn2 = b**-2.
+        expbn2 = np.exp(bn2)
+        a_b = a / b
+
+        if 'm' in moments:
+            mu = -expbn2**0.5 * np.sinh(a_b)
+        if 'v' in moments:
+            mu2 = 0.5*sc.expm1(bn2)*(expbn2*np.cosh(2*a_b) + 1)
+        if 's' in moments:
+            t1 = expbn2**.5 * sc.expm1(bn2)**0.5
+            t2 = 3*np.sinh(a_b)
+            t3 = expbn2 * (expbn2 + 2) * np.sinh(3*a_b)
+            denom = np.sqrt(2) * (1 + expbn2 * np.cosh(2*a_b))**(3/2)
+            g1 = -t1 * (t2 + t3) / denom
+        if 'k' in moments:
+            t1 = 3 + 6*expbn2
+            t2 = 4*expbn2**2 * (expbn2 + 2) * np.cosh(2*a_b)
+            t3 = expbn2**2 * np.cosh(4*a_b)
+            t4 = -3 + 3*expbn2**2 + 2*expbn2**3 + expbn2**4
+            denom = 2*(1 + expbn2*np.cosh(2*a_b))**2
+            g2 = (t1 + t2 + t3*t4) / denom - 3
+        return mu, mu2, g1, g2
+
+
+johnsonsu = johnsonsu_gen(name='johnsonsu')
+
+
+class landau_gen(rv_continuous):
+    r"""A Landau continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `landau` ([1]_, [2]_) is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi}\int_0^\infty \exp(-t \log t - xt)\sin(\pi t) dt
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    Often (e.g. [2]_), the Landau distribution is parameterized in terms of a
+    location parameter :math:`\mu` and scale parameter :math:`c`, the latter of
+    which *also* introduces a location shift. If ``mu`` and ``c`` are used to
+    represent these parameters, this corresponds with SciPy's parameterization
+    with ``loc = mu + 2*c / np.pi * np.log(c)`` and ``scale = c``.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    References
+    ----------
+    .. [1] Landau, L. (1944). "On the energy loss of fast particles by
+           ionization". J. Phys. (USSR). 8: 201.
+    .. [2] "Landau Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Landau_distribution
+    .. [3] Chambers, J. M., Mallows, C. L., & Stuck, B. (1976).
+           "A method for simulating stable random variables."
+           Journal of the American Statistical Association, 71(354), 340-344.
+    .. [4] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [5] Yoshimura, T. "Numerical Evaluation and High Precision Approximation
+           Formula for Landau Distribution".
+           :doi:`10.36227/techrxiv.171822215.53612870/v2`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _entropy(self):
+        # Computed with mpmath - see gh-19145
+        return 2.37263644000448182
+
+    def _pdf(self, x):
+        return scu._landau_pdf(x, 0, 1)
+
+    def _cdf(self, x):
+        return scu._landau_cdf(x, 0, 1)
+
+    def _sf(self, x):
+        return scu._landau_sf(x, 0, 1)
+
+    def _ppf(self, p):
+        return scu._landau_ppf(p, 0, 1)
+
+    def _isf(self, p):
+        return scu._landau_isf(p, 0, 1)
+
+    def _stats(self):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _munp(self, n):
+        return np.nan if n > 0 else 1
+
+    def _fitstart(self, data, args=None):
+        # Initialize ML guesses using quartiles instead of moments.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return p50, (p75 - p25)/2
+
+    def _rvs(self, size=None, random_state=None):
+        # Method from https://www.jstor.org/stable/2285309 Eq. 2.4
+        pi_2 = np.pi / 2
+        U = random_state.uniform(-np.pi / 2, np.pi / 2, size=size)
+        W = random_state.standard_exponential(size=size)
+        S = 2 / np.pi * ((pi_2 + U) * np.tan(U)
+                         - np.log((pi_2 * W * np.cos(U)) / (pi_2 + U)))
+        return S
+
+
+landau = landau_gen(name='landau')
+
+
+class laplace_gen(rv_continuous):
+    r"""A Laplace continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `laplace` is
+
+    .. math::
+
+        f(x) = \frac{1}{2} \exp(-|x|)
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.laplace(0, 1, size=size)
+
+    def _pdf(self, x):
+        # laplace.pdf(x) = 1/2 * exp(-abs(x))
+        return 0.5*np.exp(-abs(x))
+
+    def _cdf(self, x):
+        with np.errstate(over='ignore'):
+            return np.where(x > 0, 1.0 - 0.5*np.exp(-x), 0.5*np.exp(x))
+
+    def _sf(self, x):
+        # By symmetry...
+        return self._cdf(-x)
+
+    def _ppf(self, q):
+        return np.where(q > 0.5, -np.log(2*(1-q)), np.log(2*q))
+
+    def _isf(self, q):
+        # By symmetry...
+        return -self._ppf(q)
+
+    def _stats(self):
+        return 0, 2, 0, 3
+
+    def _entropy(self):
+        return np.log(2)+1
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        This function uses explicit formulas for the maximum likelihood
+        estimation of the Laplace distribution parameters, so the keyword
+        arguments `loc`, `scale`, and `optimizer` are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+        # and Peacock (2000), Page 124
+
+        if floc is None:
+            floc = np.median(data)
+
+        if fscale is None:
+            fscale = (np.sum(np.abs(data - floc))) / len(data)
+
+        return floc, fscale
+
+
+laplace = laplace_gen(name='laplace')
+
+
+class laplace_asymmetric_gen(rv_continuous):
+    r"""An asymmetric Laplace continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    laplace : Laplace distribution
+
+    Notes
+    -----
+    The probability density function for `laplace_asymmetric` is
+
+    .. math::
+
+       f(x, \kappa) &= \frac{1}{\kappa+\kappa^{-1}}\exp(-x\kappa),\quad x\ge0\\
+                    &= \frac{1}{\kappa+\kappa^{-1}}\exp(x/\kappa),\quad x<0\\
+
+    for :math:`-\infty < x < \infty`, :math:`\kappa > 0`.
+
+    `laplace_asymmetric` takes ``kappa`` as a shape parameter for
+    :math:`\kappa`. For :math:`\kappa = 1`, it is identical to a
+    Laplace distribution.
+
+    %(after_notes)s
+
+    Note that the scale parameter of some references is the reciprocal of
+    SciPy's ``scale``. For example, :math:`\lambda = 1/2` in the
+    parameterization of [1]_ is equivalent to ``scale = 2`` with
+    `laplace_asymmetric`.
+
+    References
+    ----------
+    .. [1] "Asymmetric Laplace distribution", Wikipedia
+            https://en.wikipedia.org/wiki/Asymmetric_Laplace_distribution
+
+    .. [2] Kozubowski TJ and Podgórski K. A Multivariate and
+           Asymmetric Generalization of Laplace Distribution,
+           Computational Statistics 15, 531--540 (2000).
+           :doi:`10.1007/PL00022717`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("kappa", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, kappa):
+        return np.exp(self._logpdf(x, kappa))
+
+    def _logpdf(self, x, kappa):
+        kapinv = 1/kappa
+        lPx = x * np.where(x >= 0, -kappa, kapinv)
+        lPx -= np.log(kappa+kapinv)
+        return lPx
+
+    def _cdf(self, x, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(x >= 0,
+                        1 - np.exp(-x*kappa)*(kapinv/kappkapinv),
+                        np.exp(x*kapinv)*(kappa/kappkapinv))
+
+    def _sf(self, x, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(x >= 0,
+                        np.exp(-x*kappa)*(kapinv/kappkapinv),
+                        1 - np.exp(x*kapinv)*(kappa/kappkapinv))
+
+    def _ppf(self, q, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(q >= kappa/kappkapinv,
+                        -np.log((1 - q)*kappkapinv*kappa)*kapinv,
+                        np.log(q*kappkapinv/kappa)*kappa)
+
+    def _isf(self, q, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(q <= kapinv/kappkapinv,
+                        -np.log(q*kappkapinv*kappa)*kapinv,
+                        np.log((1 - q)*kappkapinv/kappa)*kappa)
+
+    def _stats(self, kappa):
+        kapinv = 1/kappa
+        mn = kapinv - kappa
+        var = kapinv*kapinv + kappa*kappa
+        g1 = 2.0*(1-np.power(kappa, 6))/np.power(1+np.power(kappa, 4), 1.5)
+        g2 = 6.0*(1+np.power(kappa, 8))/np.power(1+np.power(kappa, 4), 2)
+        return mn, var, g1, g2
+
+    def _entropy(self, kappa):
+        return 1 + np.log(kappa+1/kappa)
+
+
+laplace_asymmetric = laplace_asymmetric_gen(name='laplace_asymmetric')
+
+
+def _check_fit_input_parameters(dist, data, args, kwds):
+    if not isinstance(data, CensoredData):
+        data = np.asarray(data)
+
+    floc = kwds.get('floc', None)
+    fscale = kwds.get('fscale', None)
+
+    num_shapes = len(dist.shapes.split(",")) if dist.shapes else 0
+    fshape_keys = []
+    fshapes = []
+
+    # user has many options for fixing the shape, so here we standardize it
+    # into 'f' + the number of the shape.
+    # Adapted from `_reduce_func` in `_distn_infrastructure.py`:
+    if dist.shapes:
+        shapes = dist.shapes.replace(',', ' ').split()
+        for j, s in enumerate(shapes):
+            key = 'f' + str(j)
+            names = [key, 'f' + s, 'fix_' + s]
+            val = _get_fixed_fit_value(kwds, names)
+            fshape_keys.append(key)
+            fshapes.append(val)
+            if val is not None:
+                kwds[key] = val
+
+    # determine if there are any unknown arguments in kwds
+    known_keys = {'loc', 'scale', 'optimizer', 'method',
+                  'floc', 'fscale', *fshape_keys}
+    unknown_keys = set(kwds).difference(known_keys)
+    if unknown_keys:
+        raise TypeError(f"Unknown keyword arguments: {unknown_keys}.")
+
+    if len(args) > num_shapes:
+        raise TypeError("Too many positional arguments.")
+
+    if None not in {floc, fscale, *fshapes}:
+        # This check is for consistency with `rv_continuous.fit`.
+        # Without this check, this function would just return the
+        # parameters that were given.
+        raise RuntimeError("All parameters fixed. There is nothing to "
+                           "optimize.")
+
+    uncensored = data._uncensor() if isinstance(data, CensoredData) else data
+    if not np.isfinite(uncensored).all():
+        raise ValueError("The data contains non-finite values.")
+
+    return (data, *fshapes, floc, fscale)
+
+
+class levy_gen(rv_continuous):
+    r"""A Levy continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    levy_stable, levy_l
+
+    Notes
+    -----
+    The probability density function for `levy` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{1}{2x}\right)
+
+    for :math:`x > 0`.
+
+    This is the same as the Levy-stable distribution with :math:`a=1/2` and
+    :math:`b=1`.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import levy
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> mean, var, skew, kurt = levy.stats(moments='mvsk')
+
+    Display the probability density function (``pdf``):
+
+    >>> # `levy` is very heavy-tailed.
+    >>> # To show a nice plot, let's cut off the upper 40 percent.
+    >>> a, b = levy.ppf(0), levy.ppf(0.6)
+    >>> x = np.linspace(a, b, 100)
+    >>> ax.plot(x, levy.pdf(x),
+    ...        'r-', lw=5, alpha=0.6, label='levy pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = levy()
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = levy.ppf([0.001, 0.5, 0.999])
+    >>> np.allclose([0.001, 0.5, 0.999], levy.cdf(vals))
+    True
+
+    Generate random numbers:
+
+    >>> r = levy.rvs(size=1000)
+
+    And compare the histogram:
+
+    >>> # manual binning to ignore the tail
+    >>> bins = np.concatenate((np.linspace(a, b, 20), [np.max(r)]))
+    >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim([x[0], x[-1]])
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # levy.pdf(x) = 1 / (x * sqrt(2*pi*x)) * exp(-1/(2*x))
+        return 1 / np.sqrt(2*np.pi*x) / x * np.exp(-1/(2*x))
+
+    def _cdf(self, x):
+        # Equivalent to 2*norm.sf(np.sqrt(1/x))
+        return sc.erfc(np.sqrt(0.5 / x))
+
+    def _sf(self, x):
+        return sc.erf(np.sqrt(0.5 / x))
+
+    def _ppf(self, q):
+        # Equivalent to 1.0/(norm.isf(q/2)**2) or 0.5/(erfcinv(q)**2)
+        val = _norm_isf(q/2)
+        return 1.0 / (val * val)
+
+    def _isf(self, p):
+        return 1/(2*sc.erfinv(p)**2)
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+levy = levy_gen(a=0.0, name="levy")
+
+
+class levy_l_gen(rv_continuous):
+    r"""A left-skewed Levy continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    levy, levy_stable
+
+    Notes
+    -----
+    The probability density function for `levy_l` is:
+
+    .. math::
+        f(x) = \frac{1}{|x| \sqrt{2\pi |x|}} \exp{ \left(-\frac{1}{2|x|} \right)}
+
+    for :math:`x < 0`.
+
+    This is the same as the Levy-stable distribution with :math:`a=1/2` and
+    :math:`b=-1`.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import levy_l
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> mean, var, skew, kurt = levy_l.stats(moments='mvsk')
+
+    Display the probability density function (``pdf``):
+
+    >>> # `levy_l` is very heavy-tailed.
+    >>> # To show a nice plot, let's cut off the lower 40 percent.
+    >>> a, b = levy_l.ppf(0.4), levy_l.ppf(1)
+    >>> x = np.linspace(a, b, 100)
+    >>> ax.plot(x, levy_l.pdf(x),
+    ...        'r-', lw=5, alpha=0.6, label='levy_l pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = levy_l()
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = levy_l.ppf([0.001, 0.5, 0.999])
+    >>> np.allclose([0.001, 0.5, 0.999], levy_l.cdf(vals))
+    True
+
+    Generate random numbers:
+
+    >>> r = levy_l.rvs(size=1000)
+
+    And compare the histogram:
+
+    >>> # manual binning to ignore the tail
+    >>> bins = np.concatenate(([np.min(r)], np.linspace(a, b, 20)))
+    >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim([x[0], x[-1]])
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # levy_l.pdf(x) = 1 / (abs(x) * sqrt(2*pi*abs(x))) * exp(-1/(2*abs(x)))
+        ax = abs(x)
+        return 1/np.sqrt(2*np.pi*ax)/ax*np.exp(-1/(2*ax))
+
+    def _cdf(self, x):
+        ax = abs(x)
+        return 2 * _norm_cdf(1 / np.sqrt(ax)) - 1
+
+    def _sf(self, x):
+        ax = abs(x)
+        return 2 * _norm_sf(1 / np.sqrt(ax))
+
+    def _ppf(self, q):
+        val = _norm_ppf((q + 1.0) / 2)
+        return -1.0 / (val * val)
+
+    def _isf(self, p):
+        return -1/_norm_isf(p/2)**2
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+levy_l = levy_l_gen(b=0.0, name="levy_l")
+
+
+class logistic_gen(rv_continuous):
+    r"""A logistic (or Sech-squared) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `logistic` is:
+
+    .. math::
+
+        f(x) = \frac{\exp(-x)}
+                    {(1+\exp(-x))^2}
+
+    `logistic` is a special case of `genlogistic` with ``c=1``.
+
+    Remark that the survival function (``logistic.sf``) is equal to the
+    Fermi-Dirac distribution describing fermionic statistics.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.logistic(size=size)
+
+    def _pdf(self, x):
+        # logistic.pdf(x) = exp(-x) / (1+exp(-x))**2
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        y = -np.abs(x)
+        return y - 2. * sc.log1p(np.exp(y))
+
+    def _cdf(self, x):
+        return sc.expit(x)
+
+    def _logcdf(self, x):
+        return sc.log_expit(x)
+
+    def _ppf(self, q):
+        return sc.logit(q)
+
+    def _sf(self, x):
+        return sc.expit(-x)
+
+    def _logsf(self, x):
+        return sc.log_expit(-x)
+
+    def _isf(self, q):
+        return -sc.logit(q)
+
+    def _stats(self):
+        return 0, np.pi*np.pi/3.0, 0, 6.0/5.0
+
+    def _entropy(self):
+        # https://en.wikipedia.org/wiki/Logistic_distribution
+        return 2.0
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+        n = len(data)
+
+        # rv_continuous provided guesses
+        loc, scale = self._fitstart(data)
+        # these are trumped by user-provided guesses
+        loc, scale = kwds.get('loc', loc), kwds.get('scale', scale)
+
+        # the maximum likelihood estimators `a` and `b` of the location and
+        # scale parameters are roots of the two equations described in `func`.
+        # Source: Statistical Distributions, 3rd Edition. Evans, Hastings, and
+        # Peacock (2000), Page 130
+
+        def dl_dloc(loc, scale=fscale):
+            c = (data - loc) / scale
+            return np.sum(sc.expit(c)) - n/2
+
+        def dl_dscale(scale, loc=floc):
+            c = (data - loc) / scale
+            return np.sum(c*np.tanh(c/2)) - n
+
+        def func(params):
+            loc, scale = params
+            return dl_dloc(loc, scale), dl_dscale(scale, loc)
+
+        if fscale is not None and floc is None:
+            res = optimize.root(dl_dloc, (loc,))
+            loc = res.x[0]
+            scale = fscale
+        elif floc is not None and fscale is None:
+            res = optimize.root(dl_dscale, (scale,))
+            scale = res.x[0]
+            loc = floc
+        else:
+            res = optimize.root(func, (loc, scale))
+            loc, scale = res.x
+
+        # Note: gh-18176 reported data for which the reported MLE had
+        # `scale < 0`. To fix the bug, we return abs(scale). This is OK because
+        # `dl_dscale` and `dl_dloc` are even and odd functions of `scale`,
+        # respectively, so if `-scale` is a solution, so is `scale`.
+        scale = abs(scale)
+        return ((loc, scale) if res.success
+                else super().fit(data, *args, **kwds))
+
+
+logistic = logistic_gen(name='logistic')
+
+
+class loggamma_gen(rv_continuous):
+    r"""A log gamma continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `loggamma` is:
+
+    .. math::
+
+        f(x, c) = \frac{\exp(c x - \exp(x))}
+                       {\Gamma(c)}
+
+    for all :math:`x, c > 0`. Here, :math:`\Gamma` is the
+    gamma function (`scipy.special.gamma`).
+
+    `loggamma` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        # Use the property of the gamma distribution Gamma(c)
+        #    Gamma(c) ~ Gamma(c + 1)*U**(1/c),
+        # where U is uniform on [0, 1]. (See, e.g.,
+        # G. Marsaglia and W.W. Tsang, "A simple method for generating gamma
+        # variables", https://doi.org/10.1145/358407.358414)
+        # So
+        #    log(Gamma(c)) ~ log(Gamma(c + 1)) + log(U)/c
+        # Generating a sample with this formulation is a bit slower
+        # than the more obvious log(Gamma(c)), but it avoids loss
+        # of precision when c << 1.
+        return (np.log(random_state.gamma(c + 1, size=size))
+                + np.log(random_state.uniform(size=size))/c)
+
+    def _pdf(self, x, c):
+        # loggamma.pdf(x, c) = exp(c*x-exp(x)) / gamma(c)
+        return np.exp(c*x-np.exp(x)-sc.gammaln(c))
+
+    def _logpdf(self, x, c):
+        return c*x - np.exp(x) - sc.gammaln(c)
+
+    def _cdf(self, x, c):
+        # This function is gammainc(c, exp(x)), where gammainc(c, z) is
+        # the regularized incomplete gamma function.
+        # The first term in a series expansion of gamminc(c, z) is
+        # z**c/Gamma(c+1); see 6.5.29 of Abramowitz & Stegun (and refer
+        # back to 6.5.1, 6.5.2 and 6.5.4 for the relevant notation).
+        # This can also be found in the wikipedia article
+        # https://en.wikipedia.org/wiki/Incomplete_gamma_function.
+        # Here we use that formula when x is sufficiently negative that
+        # exp(x) will result in subnormal numbers and lose precision.
+        # We evaluate the log of the expression first to allow the possible
+        # cancellation of the terms in the division, and then exponentiate.
+        # That is,
+        #     exp(x)**c/Gamma(c+1) = exp(log(exp(x)**c/Gamma(c+1)))
+        #                          = exp(c*x - gammaln(c+1))
+        return _lazywhere(x < _LOGXMIN, (x, c),
+                          lambda x, c: np.exp(c*x - sc.gammaln(c+1)),
+                          f2=lambda x, c: sc.gammainc(c, np.exp(x)))
+
+    def _ppf(self, q, c):
+        # The expression used when g < _XMIN inverts the one term expansion
+        # given in the comments of _cdf().
+        g = sc.gammaincinv(c, q)
+        return _lazywhere(g < _XMIN, (g, q, c),
+                          lambda g, q, c: (np.log(q) + sc.gammaln(c+1))/c,
+                          f2=lambda g, q, c: np.log(g))
+
+    def _sf(self, x, c):
+        # See the comments for _cdf() for how x < _LOGXMIN is handled.
+        return _lazywhere(x < _LOGXMIN, (x, c),
+                          lambda x, c: -np.expm1(c*x - sc.gammaln(c+1)),
+                          f2=lambda x, c: sc.gammaincc(c, np.exp(x)))
+
+    def _isf(self, q, c):
+        # The expression used when g < _XMIN inverts the complement of
+        # the one term expansion given in the comments of _cdf().
+        g = sc.gammainccinv(c, q)
+        return _lazywhere(g < _XMIN, (g, q, c),
+                          lambda g, q, c: (np.log1p(-q) + sc.gammaln(c+1))/c,
+                          f2=lambda g, q, c: np.log(g))
+
+    def _stats(self, c):
+        # See, for example, "A Statistical Study of Log-Gamma Distribution", by
+        # Ping Shing Chan (thesis, McMaster University, 1993).
+        mean = sc.digamma(c)
+        var = sc.polygamma(1, c)
+        skewness = sc.polygamma(2, c) / np.power(var, 1.5)
+        excess_kurtosis = sc.polygamma(3, c) / (var*var)
+        return mean, var, skewness, excess_kurtosis
+
+    def _entropy(self, c):
+        def regular(c):
+            h = sc.gammaln(c) - c * sc.digamma(c) + c
+            return h
+
+        def asymptotic(c):
+            # using asymptotic expansions for gammaln and psi (see gh-18093)
+            term = -0.5*np.log(c) + c**-1./6 - c**-3./90 + c**-5./210
+            h = norm._entropy() + term
+            return h
+
+        h = _lazywhere(c >= 45, (c, ), f=asymptotic, f2=regular)
+        return h
+
+
+loggamma = loggamma_gen(name='loggamma')
+
+
+class loglaplace_gen(rv_continuous):
+    r"""A log-Laplace continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `loglaplace` is:
+
+    .. math::
+
+        f(x, c) = \begin{cases}\frac{c}{2} x^{ c-1}  &\text{for } 0 < x < 1\\
+                               \frac{c}{2} x^{-c-1}  &\text{for } x \ge 1
+                  \end{cases}
+
+    for :math:`c > 0`.
+
+    `loglaplace` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    Suppose a random variable ``X`` follows the Laplace distribution with
+    location ``a`` and scale ``b``.  Then ``Y = exp(X)`` follows the
+    log-Laplace distribution with ``c = 1 / b`` and ``scale = exp(a)``.
+
+    References
+    ----------
+    T.J. Kozubowski and K. Podgorski, "A log-Laplace growth rate model",
+    The Mathematical Scientist, vol. 28, pp. 49-60, 2003.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # loglaplace.pdf(x, c) = c / 2 * x**(c-1),   for 0 < x < 1
+        #                      = c / 2 * x**(-c-1),  for x >= 1
+        cd2 = c/2.0
+        c = np.where(x < 1, c, -c)
+        return cd2*x**(c-1)
+
+    def _cdf(self, x, c):
+        return np.where(x < 1, 0.5*x**c, 1-0.5*x**(-c))
+
+    def _sf(self, x, c):
+        return np.where(x < 1, 1 - 0.5*x**c, 0.5*x**(-c))
+
+    def _ppf(self, q, c):
+        return np.where(q < 0.5, (2.0*q)**(1.0/c), (2*(1.0-q))**(-1.0/c))
+
+    def _isf(self, q, c):
+        return np.where(q > 0.5, (2.0*(1.0 - q))**(1.0/c), (2*q)**(-1.0/c))
+
+    def _munp(self, n, c):
+        with np.errstate(divide='ignore'):
+            c2, n2 = c**2, n**2
+            return np.where(n2 < c2, c2 / (c2 - n2), np.inf)
+
+    def _entropy(self, c):
+        return np.log(2.0/c) + 1.0
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        data, fc, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+
+        # Specialize MLE only when location is known.
+        if floc is None:
+            return super(type(self), self).fit(data, *args, **kwds)
+
+        # Raise an error if any observation has zero likelihood.
+        if np.any(data <= floc):
+            raise FitDataError("loglaplace", lower=floc, upper=np.inf)
+
+        # Remove location from data.
+        if floc != 0:
+            data = data - floc
+
+        # When location is zero, the log-Laplace distribution is related to
+        # the Laplace distribution in that if X ~ Laplace(loc=a, scale=b),
+        # then Y = exp(X) ~ LogLaplace(c=1/b, loc=0, scale=exp(a)).  It can
+        # be shown that the MLE for Y is the same as the MLE for X = ln(Y).
+        # Therefore, we reuse the formulas from laplace.fit() and transform
+        # the result back into log-laplace's parameter space.
+        a, b = laplace.fit(np.log(data),
+                           floc=np.log(fscale) if fscale is not None else None,
+                           fscale=1/fc if fc is not None else None,
+                           method='mle')
+        loc = floc
+        scale = np.exp(a) if fscale is None else fscale
+        c = 1 / b if fc is None else fc
+        return c, loc, scale
+
+loglaplace = loglaplace_gen(a=0.0, name='loglaplace')
+
+
+def _lognorm_logpdf(x, s):
+    return _lazywhere(x != 0, (x, s),
+                      lambda x, s: (-np.log(x)**2 / (2 * s**2)
+                                    - np.log(s * x * np.sqrt(2 * np.pi))),
+                      -np.inf)
+
+
+class lognorm_gen(rv_continuous):
+    r"""A lognormal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `lognorm` is:
+
+    .. math::
+
+        f(x, s) = \frac{1}{s x \sqrt{2\pi}}
+                  \exp\left(-\frac{\log^2(x)}{2s^2}\right)
+
+    for :math:`x > 0`, :math:`s > 0`.
+
+    `lognorm` takes ``s`` as a shape parameter for :math:`s`.
+
+    %(after_notes)s
+
+    Suppose a normally distributed random variable ``X`` has  mean ``mu`` and
+    standard deviation ``sigma``. Then ``Y = exp(X)`` is lognormally
+    distributed with ``s = sigma`` and ``scale = exp(mu)``.
+
+    %(example)s
+
+    The logarithm of a log-normally distributed random variable is
+    normally distributed:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> mu, sigma = 2, 0.5
+    >>> X = stats.norm(loc=mu, scale=sigma)
+    >>> Y = stats.lognorm(s=sigma, scale=np.exp(mu))
+    >>> x = np.linspace(*X.interval(0.999))
+    >>> y = Y.rvs(size=10000)
+    >>> ax.plot(x, X.pdf(x), label='X (pdf)')
+    >>> ax.hist(np.log(y), density=True, bins=x, label='log(Y) (histogram)')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("s", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, s, size=None, random_state=None):
+        return np.exp(s * random_state.standard_normal(size))
+
+    def _pdf(self, x, s):
+        # lognorm.pdf(x, s) = 1 / (s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2)
+        return np.exp(self._logpdf(x, s))
+
+    def _logpdf(self, x, s):
+        return _lognorm_logpdf(x, s)
+
+    def _cdf(self, x, s):
+        return _norm_cdf(np.log(x) / s)
+
+    def _logcdf(self, x, s):
+        return _norm_logcdf(np.log(x) / s)
+
+    def _ppf(self, q, s):
+        return np.exp(s * _norm_ppf(q))
+
+    def _sf(self, x, s):
+        return _norm_sf(np.log(x) / s)
+
+    def _logsf(self, x, s):
+        return _norm_logsf(np.log(x) / s)
+
+    def _isf(self, q, s):
+        return np.exp(s * _norm_isf(q))
+
+    def _stats(self, s):
+        p = np.exp(s*s)
+        mu = np.sqrt(p)
+        mu2 = p*(p-1)
+        g1 = np.sqrt(p-1)*(2+p)
+        g2 = np.polyval([1, 2, 3, 0, -6.0], p)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, s):
+        return 0.5 * (1 + np.log(2*np.pi) + 2 * np.log(s))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        When `method='MLE'` and
+        the location parameter is fixed by using the `floc` argument,
+        this function uses explicit formulas for the maximum likelihood
+        estimation of the log-normal shape and scale parameters, so the
+        `optimizer`, `loc` and `scale` keyword arguments are ignored.
+        If the location is free, a likelihood maximum is found by
+        setting its partial derivative wrt to location to 0, and
+        solving by substituting the analytical expressions of shape
+        and scale (or provided parameters).
+        See, e.g., equation 3.1 in
+        A. Clifford Cohen & Betty Jones Whitten (1980)
+        Estimation in the Three-Parameter Lognormal Distribution,
+        Journal of the American Statistical Association, 75:370, 399-404
+        https://doi.org/10.2307/2287466
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fshape, floc, fscale = parameters
+        data_min = np.min(data)
+
+        def get_shape_scale(loc):
+            # Calculate maximum likelihood scale and shape with analytical
+            # formulas unless provided by the user
+            if fshape is None or fscale is None:
+                lndata = np.log(data - loc)
+            scale = fscale or np.exp(lndata.mean())
+            shape = fshape or np.sqrt(np.mean((lndata - np.log(scale))**2))
+            return shape, scale
+
+        def dL_dLoc(loc):
+            # Derivative of (positive) LL w.r.t. loc
+            shape, scale = get_shape_scale(loc)
+            shifted = data - loc
+            return np.sum((1 + np.log(shifted/scale)/shape**2)/shifted)
+
+        def ll(loc):
+            # (Positive) log-likelihood
+            shape, scale = get_shape_scale(loc)
+            return -self.nnlf((shape, loc, scale), data)
+
+        if floc is None:
+            # The location must be less than the minimum of the data.
+            # Back off a bit to avoid numerical issues.
+            spacing = np.spacing(data_min)
+            rbrack = data_min - spacing
+
+            # Find the right end of the bracket by successive doubling of the
+            # distance to data_min. We're interested in a maximum LL, so the
+            # slope dL_dLoc_rbrack should be negative at the right end.
+            # optimization for later: share shape, scale
+            dL_dLoc_rbrack = dL_dLoc(rbrack)
+            ll_rbrack = ll(rbrack)
+            delta = 2 * spacing  # 2 * (data_min - rbrack)
+            while dL_dLoc_rbrack >= -1e-6:
+                rbrack = data_min - delta
+                dL_dLoc_rbrack = dL_dLoc(rbrack)
+                delta *= 2
+
+            if not np.isfinite(rbrack) or not np.isfinite(dL_dLoc_rbrack):
+                # If we never find a negative slope, either we missed it or the
+                # slope is always positive. It's usually the latter,
+                # which means
+                # loc = data_min - spacing
+                # But sometimes when shape and/or scale are fixed there are
+                # other issues, so be cautious.
+                return super().fit(data, *args, **kwds)
+
+            # Now find the left end of the bracket. Guess is `rbrack-1`
+            # unless that is too small of a difference to resolve. Double
+            # the size of the interval until the left end is found.
+            lbrack = np.minimum(np.nextafter(rbrack, -np.inf), rbrack-1)
+            dL_dLoc_lbrack = dL_dLoc(lbrack)
+            delta = 2 * (rbrack - lbrack)
+            while (np.isfinite(lbrack) and np.isfinite(dL_dLoc_lbrack)
+                   and np.sign(dL_dLoc_lbrack) == np.sign(dL_dLoc_rbrack)):
+                lbrack = rbrack - delta
+                dL_dLoc_lbrack = dL_dLoc(lbrack)
+                delta *= 2
+
+            # I don't recall observing this, but just in case...
+            if not np.isfinite(lbrack) or not np.isfinite(dL_dLoc_lbrack):
+                return super().fit(data, *args, **kwds)
+
+            # If we have a valid bracket, find the root
+            res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack))
+            if not res.converged:
+                return super().fit(data, *args, **kwds)
+
+            # If the slope was positive near the minimum of the data,
+            # the maximum LL could be there instead of at the root. Compare
+            # the LL of the two points to decide.
+            ll_root = ll(res.root)
+            loc = res.root if ll_root > ll_rbrack else data_min-spacing
+
+        else:
+            if floc >= data_min:
+                raise FitDataError("lognorm", lower=0., upper=np.inf)
+            loc = floc
+
+        shape, scale = get_shape_scale(loc)
+        if not (self._argcheck(shape) and scale > 0):
+            return super().fit(data, *args, **kwds)
+        return shape, loc, scale
+
+
+lognorm = lognorm_gen(a=0.0, name='lognorm')
+
+
+class gibrat_gen(rv_continuous):
+    r"""A Gibrat continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gibrat` is:
+
+    .. math::
+
+        f(x) = \frac{1}{x \sqrt{2\pi}} \exp(-\frac{1}{2} (\log(x))^2)
+
+    for :math:`x >= 0`.
+
+    `gibrat` is a special case of `lognorm` with ``s=1``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return np.exp(random_state.standard_normal(size))
+
+    def _pdf(self, x):
+        # gibrat.pdf(x) = 1/(x*sqrt(2*pi)) * exp(-1/2*(log(x))**2)
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return _lognorm_logpdf(x, 1.0)
+
+    def _cdf(self, x):
+        return _norm_cdf(np.log(x))
+
+    def _ppf(self, q):
+        return np.exp(_norm_ppf(q))
+
+    def _sf(self, x):
+        return _norm_sf(np.log(x))
+
+    def _isf(self, p):
+        return np.exp(_norm_isf(p))
+
+    def _stats(self):
+        p = np.e
+        mu = np.sqrt(p)
+        mu2 = p * (p - 1)
+        g1 = np.sqrt(p - 1) * (2 + p)
+        g2 = np.polyval([1, 2, 3, 0, -6.0], p)
+        return mu, mu2, g1, g2
+
+    def _entropy(self):
+        return 0.5 * np.log(2 * np.pi) + 0.5
+
+
+gibrat = gibrat_gen(a=0.0, name='gibrat')
+
+
+class maxwell_gen(rv_continuous):
+    r"""A Maxwell continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    A special case of a `chi` distribution,  with ``df=3``, ``loc=0.0``,
+    and given ``scale = a``, where ``a`` is the parameter used in the
+    Mathworld description [1]_.
+
+    The probability density function for `maxwell` is:
+
+    .. math::
+
+        f(x) = \sqrt{2/\pi}x^2 \exp(-x^2/2)
+
+    for :math:`x >= 0`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/MaxwellDistribution.html
+
+    %(example)s
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return chi.rvs(3.0, size=size, random_state=random_state)
+
+    def _pdf(self, x):
+        # maxwell.pdf(x) = sqrt(2/pi)x**2 * exp(-x**2/2)
+        return _SQRT_2_OVER_PI*x*x*np.exp(-x*x/2.0)
+
+    def _logpdf(self, x):
+        # Allow x=0 without 'divide by zero' warnings
+        with np.errstate(divide='ignore'):
+            return _LOG_SQRT_2_OVER_PI + 2*np.log(x) - 0.5*x*x
+
+    def _cdf(self, x):
+        return sc.gammainc(1.5, x*x/2.0)
+
+    def _ppf(self, q):
+        return np.sqrt(2*sc.gammaincinv(1.5, q))
+
+    def _sf(self, x):
+        return sc.gammaincc(1.5, x*x/2.0)
+
+    def _isf(self, q):
+        return np.sqrt(2*sc.gammainccinv(1.5, q))
+
+    def _stats(self):
+        val = 3*np.pi-8
+        return (2*np.sqrt(2.0/np.pi),
+                3-8/np.pi,
+                np.sqrt(2)*(32-10*np.pi)/val**1.5,
+                (-12*np.pi*np.pi + 160*np.pi - 384) / val**2.0)
+
+    def _entropy(self):
+        return _EULER + 0.5*np.log(2*np.pi)-0.5
+
+
+maxwell = maxwell_gen(a=0.0, name='maxwell')
+
+
+class mielke_gen(rv_continuous):
+    r"""A Mielke Beta-Kappa / Dagum continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `mielke` is:
+
+    .. math::
+
+        f(x, k, s) = \frac{k x^{k-1}}{(1+x^s)^{1+k/s}}
+
+    for :math:`x > 0` and :math:`k, s > 0`. The distribution is sometimes
+    called Dagum distribution ([2]_). It was already defined in [3]_, called
+    a Burr Type III distribution (`burr` with parameters ``c=s`` and
+    ``d=k/s``).
+
+    `mielke` takes ``k`` and ``s`` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Mielke, P.W., 1973 "Another Family of Distributions for Describing
+           and Analyzing Precipitation Data." J. Appl. Meteor., 12, 275-280
+    .. [2] Dagum, C., 1977 "A new model for personal income distribution."
+           Economie Appliquee, 33, 327-367.
+    .. [3] Burr, I. W. "Cumulative frequency functions", Annals of
+           Mathematical Statistics, 13(2), pp 215-232 (1942).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ik = _ShapeInfo("k", False, (0, np.inf), (False, False))
+        i_s = _ShapeInfo("s", False, (0, np.inf), (False, False))
+        return [ik, i_s]
+
+    def _pdf(self, x, k, s):
+        return k*x**(k-1.0) / (1.0+x**s)**(1.0+k*1.0/s)
+
+    def _logpdf(self, x, k, s):
+        # Allow x=0 without 'divide by zero' warnings.
+        with np.errstate(divide='ignore'):
+            return np.log(k) + np.log(x)*(k - 1) - np.log1p(x**s)*(1 + k/s)
+
+    def _cdf(self, x, k, s):
+        return x**k / (1.0+x**s)**(k*1.0/s)
+
+    def _ppf(self, q, k, s):
+        qsk = pow(q, s*1.0/k)
+        return pow(qsk/(1.0-qsk), 1.0/s)
+
+    def _munp(self, n, k, s):
+        def nth_moment(n, k, s):
+            # n-th moment is defined for -k < n < s
+            return sc.gamma((k+n)/s)*sc.gamma(1-n/s)/sc.gamma(k/s)
+
+        return _lazywhere(n < s, (n, k, s), nth_moment, np.inf)
+
+
+mielke = mielke_gen(a=0.0, name='mielke')
+
+
+class kappa4_gen(rv_continuous):
+    r"""Kappa 4 parameter distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for kappa4 is:
+
+    .. math::
+
+        f(x, h, k) = (1 - k x)^{1/k - 1} (1 - h (1 - k x)^{1/k})^{1/h-1}
+
+    if :math:`h` and :math:`k` are not equal to 0.
+
+    If :math:`h` or :math:`k` are zero then the pdf can be simplified:
+
+    h = 0 and k != 0::
+
+        kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)*
+                              exp(-(1.0 - k*x)**(1.0/k))
+
+    h != 0 and k = 0::
+
+        kappa4.pdf(x, h, k) = exp(-x)*(1.0 - h*exp(-x))**(1.0/h - 1.0)
+
+    h = 0 and k = 0::
+
+        kappa4.pdf(x, h, k) = exp(-x)*exp(-exp(-x))
+
+    kappa4 takes :math:`h` and :math:`k` as shape parameters.
+
+    The kappa4 distribution returns other distributions when certain
+    :math:`h` and :math:`k` values are used.
+
+    +------+-------------+----------------+------------------+
+    | h    | k=0.0       | k=1.0          | -inf<=k<=inf     |
+    +======+=============+================+==================+
+    | -1.0 | Logistic    |                | Generalized      |
+    |      |             |                | Logistic(1)      |
+    |      |             |                |                  |
+    |      | logistic(x) |                |                  |
+    +------+-------------+----------------+------------------+
+    |  0.0 | Gumbel      | Reverse        | Generalized      |
+    |      |             | Exponential(2) | Extreme Value    |
+    |      |             |                |                  |
+    |      | gumbel_r(x) |                | genextreme(x, k) |
+    +------+-------------+----------------+------------------+
+    |  1.0 | Exponential | Uniform        | Generalized      |
+    |      |             |                | Pareto           |
+    |      |             |                |                  |
+    |      | expon(x)    | uniform(x)     | genpareto(x, -k) |
+    +------+-------------+----------------+------------------+
+
+    (1) There are at least five generalized logistic distributions.
+        Four are described here:
+        https://en.wikipedia.org/wiki/Generalized_logistic_distribution
+        The "fifth" one is the one kappa4 should match which currently
+        isn't implemented in scipy:
+        https://en.wikipedia.org/wiki/Talk:Generalized_logistic_distribution
+        https://www.mathwave.com/help/easyfit/html/analyses/distributions/gen_logistic.html
+    (2) This distribution is currently not in scipy.
+
+    References
+    ----------
+    J.C. Finney, "Optimization of a Skewed Logistic Distribution With Respect
+    to the Kolmogorov-Smirnov Test", A Dissertation Submitted to the Graduate
+    Faculty of the Louisiana State University and Agricultural and Mechanical
+    College, (August, 2004),
+    https://digitalcommons.lsu.edu/gradschool_dissertations/3672
+
+    J.R.M. Hosking, "The four-parameter kappa distribution". IBM J. Res.
+    Develop. 38 (3), 25 1-258 (1994).
+
+    B. Kumphon, A. Kaew-Man, P. Seenoi, "A Rainfall Distribution for the Lampao
+    Site in the Chi River Basin, Thailand", Journal of Water Resource and
+    Protection, vol. 4, 866-869, (2012).
+    :doi:`10.4236/jwarp.2012.410101`
+
+    C. Winchester, "On Estimation of the Four-Parameter Kappa Distribution", A
+    Thesis Submitted to Dalhousie University, Halifax, Nova Scotia, (March
+    2000).
+    http://www.nlc-bnc.ca/obj/s4/f2/dsk2/ftp01/MQ57336.pdf
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, h, k):
+        shape = np.broadcast_arrays(h, k)[0].shape
+        return np.full(shape, fill_value=True)
+
+    def _shape_info(self):
+        ih = _ShapeInfo("h", False, (-np.inf, np.inf), (False, False))
+        ik = _ShapeInfo("k", False, (-np.inf, np.inf), (False, False))
+        return [ih, ik]
+
+    def _get_support(self, h, k):
+        condlist = [np.logical_and(h > 0, k > 0),
+                    np.logical_and(h > 0, k == 0),
+                    np.logical_and(h > 0, k < 0),
+                    np.logical_and(h <= 0, k > 0),
+                    np.logical_and(h <= 0, k == 0),
+                    np.logical_and(h <= 0, k < 0)]
+
+        def f0(h, k):
+            return (1.0 - np.float_power(h, -k))/k
+
+        def f1(h, k):
+            return np.log(h)
+
+        def f3(h, k):
+            a = np.empty(np.shape(h))
+            a[:] = -np.inf
+            return a
+
+        def f5(h, k):
+            return 1.0/k
+
+        _a = _lazyselect(condlist,
+                         [f0, f1, f0, f3, f3, f5],
+                         [h, k],
+                         default=np.nan)
+
+        def f0(h, k):
+            return 1.0/k
+
+        def f1(h, k):
+            a = np.empty(np.shape(h))
+            a[:] = np.inf
+            return a
+
+        _b = _lazyselect(condlist,
+                         [f0, f1, f1, f0, f1, f1],
+                         [h, k],
+                         default=np.nan)
+        return _a, _b
+
+    def _pdf(self, x, h, k):
+        # kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)*
+        #                       (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1)
+        return np.exp(self._logpdf(x, h, k))
+
+    def _logpdf(self, x, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(x, h, k):
+            '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*(
+                      1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1.0)
+               logpdf = ...
+            '''
+            return (sc.xlog1py(1.0/k - 1.0, -k*x) +
+                    sc.xlog1py(1.0/h - 1.0, -h*(1.0 - k*x)**(1.0/k)))
+
+        def f1(x, h, k):
+            '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*np.exp(-(
+                      1.0 - k*x)**(1.0/k))
+               logpdf = ...
+            '''
+            return sc.xlog1py(1.0/k - 1.0, -k*x) - (1.0 - k*x)**(1.0/k)
+
+        def f2(x, h, k):
+            '''pdf = np.exp(-x)*(1.0 - h*np.exp(-x))**(1.0/h - 1.0)
+               logpdf = ...
+            '''
+            return -x + sc.xlog1py(1.0/h - 1.0, -h*np.exp(-x))
+
+        def f3(x, h, k):
+            '''pdf = np.exp(-x-np.exp(-x))
+               logpdf = ...
+            '''
+            return -x - np.exp(-x)
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [x, h, k],
+                           default=np.nan)
+
+    def _cdf(self, x, h, k):
+        return np.exp(self._logcdf(x, h, k))
+
+    def _logcdf(self, x, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(x, h, k):
+            '''cdf = (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h)
+               logcdf = ...
+            '''
+            return (1.0/h)*sc.log1p(-h*(1.0 - k*x)**(1.0/k))
+
+        def f1(x, h, k):
+            '''cdf = np.exp(-(1.0 - k*x)**(1.0/k))
+               logcdf = ...
+            '''
+            return -(1.0 - k*x)**(1.0/k)
+
+        def f2(x, h, k):
+            '''cdf = (1.0 - h*np.exp(-x))**(1.0/h)
+               logcdf = ...
+            '''
+            return (1.0/h)*sc.log1p(-h*np.exp(-x))
+
+        def f3(x, h, k):
+            '''cdf = np.exp(-np.exp(-x))
+               logcdf = ...
+            '''
+            return -np.exp(-x)
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [x, h, k],
+                           default=np.nan)
+
+    def _ppf(self, q, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(q, h, k):
+            return 1.0/k*(1.0 - ((1.0 - (q**h))/h)**k)
+
+        def f1(q, h, k):
+            return 1.0/k*(1.0 - (-np.log(q))**k)
+
+        def f2(q, h, k):
+            '''ppf = -np.log((1.0 - (q**h))/h)
+            '''
+            return -sc.log1p(-(q**h)) + np.log(h)
+
+        def f3(q, h, k):
+            return -np.log(-np.log(q))
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [q, h, k],
+                           default=np.nan)
+
+    def _get_stats_info(self, h, k):
+        condlist = [
+            np.logical_and(h < 0, k >= 0),
+            k < 0,
+        ]
+
+        def f0(h, k):
+            return (-1.0/h*k).astype(int)
+
+        def f1(h, k):
+            return (-1.0/k).astype(int)
+
+        return _lazyselect(condlist, [f0, f1], [h, k], default=5)
+
+    def _stats(self, h, k):
+        maxr = self._get_stats_info(h, k)
+        outputs = [None if np.any(r < maxr) else np.nan for r in range(1, 5)]
+        return outputs[:]
+
+    def _mom1_sc(self, m, *args):
+        maxr = self._get_stats_info(args[0], args[1])
+        if m >= maxr:
+            return np.nan
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+
+kappa4 = kappa4_gen(name='kappa4')
+
+
+class kappa3_gen(rv_continuous):
+    r"""Kappa 3 parameter distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `kappa3` is:
+
+    .. math::
+
+        f(x, a) = a (a + x^a)^{-(a + 1)/a}
+
+    for :math:`x > 0` and :math:`a > 0`.
+
+    `kappa3` takes ``a`` as a shape parameter for :math:`a`.
+
+    References
+    ----------
+    P.W. Mielke and E.S. Johnson, "Three-Parameter Kappa Distribution Maximum
+    Likelihood and Likelihood Ratio Tests", Methods in Weather Research,
+    701-707, (September, 1973),
+    :doi:`10.1175/1520-0493(1973)101<0701:TKDMLE>2.3.CO;2`
+
+    B. Kumphon, "Maximum Entropy and Maximum Likelihood Estimation for the
+    Three-Parameter Kappa Distribution", Open Journal of Statistics, vol 2,
+    415-419 (2012), :doi:`10.4236/ojs.2012.24050`
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # kappa3.pdf(x, a) = a*(a + x**a)**(-(a + 1)/a),     for x > 0
+        return a*(a + x**a)**(-1.0/a-1)
+
+    def _cdf(self, x, a):
+        return x*(a + x**a)**(-1.0/a)
+
+    def _sf(self, x, a):
+        x, a = np.broadcast_arrays(x, a)  # some code paths pass scalars
+        sf = super()._sf(x, a)
+
+        # When the SF is small, another formulation is typically more accurate.
+        # However, it blows up for large `a`, so use it only if it also returns
+        # a small value of the SF.
+        cutoff = 0.01
+        i = sf < cutoff
+        sf2 = -sc.expm1(sc.xlog1py(-1.0 / a[i], a[i] * x[i]**-a[i]))
+        i2 = sf2 > cutoff
+        sf2[i2] = sf[i][i2]  # replace bad values with original values
+
+        sf[i] = sf2
+        return sf
+
+    def _ppf(self, q, a):
+        return (a/(q**-a - 1.0))**(1.0/a)
+
+    def _isf(self, q, a):
+        lg = sc.xlog1py(-a, -q)
+        denom = sc.expm1(lg)
+        return (a / denom)**(1.0 / a)
+
+    def _stats(self, a):
+        outputs = [None if np.any(i < a) else np.nan for i in range(1, 5)]
+        return outputs[:]
+
+    def _mom1_sc(self, m, *args):
+        if np.any(m >= args[0]):
+            return np.nan
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+
+kappa3 = kappa3_gen(a=0.0, name='kappa3')
+
+
+class moyal_gen(rv_continuous):
+    r"""A Moyal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `moyal` is:
+
+    .. math::
+
+        f(x) = \exp(-(x + \exp(-x))/2) / \sqrt{2\pi}
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    This distribution has utility in high-energy physics and radiation
+    detection. It describes the energy loss of a charged relativistic
+    particle due to ionization of the medium [1]_. It also provides an
+    approximation for the Landau distribution. For an in depth description
+    see [2]_. For additional description, see [3]_.
+
+    References
+    ----------
+    .. [1] J.E. Moyal, "XXX. Theory of ionization fluctuations",
+           The London, Edinburgh, and Dublin Philosophical Magazine
+           and Journal of Science, vol 46, 263-280, (1955).
+           :doi:`10.1080/14786440308521076` (gated)
+    .. [2] G. Cordeiro et al., "The beta Moyal: a useful skew distribution",
+           International Journal of Research and Reviews in Applied Sciences,
+           vol 10, 171-192, (2012).
+           http://www.arpapress.com/Volumes/Vol10Issue2/IJRRAS_10_2_02.pdf
+    .. [3] C. Walck, "Handbook on Statistical Distributions for
+           Experimentalists; International Report SUF-PFY/96-01", Chapter 26,
+           University of Stockholm: Stockholm, Sweden, (2007).
+           http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf
+
+    .. versionadded:: 1.1.0
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        u1 = gamma.rvs(a=0.5, scale=2, size=size,
+                       random_state=random_state)
+        return -np.log(u1)
+
+    def _pdf(self, x):
+        return np.exp(-0.5 * (x + np.exp(-x))) / np.sqrt(2*np.pi)
+
+    def _cdf(self, x):
+        return sc.erfc(np.exp(-0.5 * x) / np.sqrt(2))
+
+    def _sf(self, x):
+        return sc.erf(np.exp(-0.5 * x) / np.sqrt(2))
+
+    def _ppf(self, x):
+        return -np.log(2 * sc.erfcinv(x)**2)
+
+    def _stats(self):
+        mu = np.log(2) + np.euler_gamma
+        mu2 = np.pi**2 / 2
+        g1 = 28 * np.sqrt(2) * sc.zeta(3) / np.pi**3
+        g2 = 4.
+        return mu, mu2, g1, g2
+
+    def _munp(self, n):
+        if n == 1.0:
+            return np.log(2) + np.euler_gamma
+        elif n == 2.0:
+            return np.pi**2 / 2 + (np.log(2) + np.euler_gamma)**2
+        elif n == 3.0:
+            tmp1 = 1.5 * np.pi**2 * (np.log(2)+np.euler_gamma)
+            tmp2 = (np.log(2)+np.euler_gamma)**3
+            tmp3 = 14 * sc.zeta(3)
+            return tmp1 + tmp2 + tmp3
+        elif n == 4.0:
+            tmp1 = 4 * 14 * sc.zeta(3) * (np.log(2) + np.euler_gamma)
+            tmp2 = 3 * np.pi**2 * (np.log(2) + np.euler_gamma)**2
+            tmp3 = (np.log(2) + np.euler_gamma)**4
+            tmp4 = 7 * np.pi**4 / 4
+            return tmp1 + tmp2 + tmp3 + tmp4
+        else:
+            # return generic for higher moments
+            # return rv_continuous._mom1_sc(self, n, b)
+            return self._mom1_sc(n)
+
+
+moyal = moyal_gen(name="moyal")
+
+
+class nakagami_gen(rv_continuous):
+    r"""A Nakagami continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `nakagami` is:
+
+    .. math::
+
+        f(x, \nu) = \frac{2 \nu^\nu}{\Gamma(\nu)} x^{2\nu-1} \exp(-\nu x^2)
+
+    for :math:`x >= 0`, :math:`\nu > 0`. The distribution was introduced in
+    [2]_, see also [1]_ for further information.
+
+    `nakagami` takes ``nu`` as a shape parameter for :math:`\nu`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Nakagami distribution", Wikipedia
+           https://en.wikipedia.org/wiki/Nakagami_distribution
+    .. [2] M. Nakagami, "The m-distribution - A general formula of intensity
+           distribution of rapid fading", Statistical methods in radio wave
+           propagation, Pergamon Press, 1960, 3-36.
+           :doi:`10.1016/B978-0-08-009306-2.50005-4`
+
+    %(example)s
+
+    """
+    def _argcheck(self, nu):
+        return nu > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("nu", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, nu):
+        return np.exp(self._logpdf(x, nu))
+
+    def _logpdf(self, x, nu):
+        # nakagami.pdf(x, nu) = 2 * nu**nu / gamma(nu) *
+        #                       x**(2*nu-1) * exp(-nu*x**2)
+        return (np.log(2) + sc.xlogy(nu, nu) - sc.gammaln(nu) +
+                sc.xlogy(2*nu - 1, x) - nu*x**2)
+
+    def _cdf(self, x, nu):
+        return sc.gammainc(nu, nu*x*x)
+
+    def _ppf(self, q, nu):
+        return np.sqrt(1.0/nu*sc.gammaincinv(nu, q))
+
+    def _sf(self, x, nu):
+        return sc.gammaincc(nu, nu*x*x)
+
+    def _isf(self, p, nu):
+        return np.sqrt(1/nu * sc.gammainccinv(nu, p))
+
+    def _stats(self, nu):
+        mu = sc.poch(nu, 0.5)/np.sqrt(nu)
+        mu2 = 1.0-mu*mu
+        g1 = mu * (1 - 4*nu*mu2) / 2.0 / nu / np.power(mu2, 1.5)
+        g2 = -6*mu**4*nu + (8*nu-2)*mu**2-2*nu + 1
+        g2 /= nu*mu2**2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self, nu):
+        shape = np.shape(nu)
+        # because somehow this isn't taken care of by the infrastructure...
+        nu = np.atleast_1d(nu)
+        A = sc.gammaln(nu)
+        B = nu - (nu - 0.5) * sc.digamma(nu)
+        C = -0.5 * np.log(nu) - np.log(2)
+        h = A + B + C
+        # This is the asymptotic sum of A and B (see gh-17868)
+        norm_entropy = stats.norm._entropy()
+        # Above, this is lost to rounding error for large nu, so use the
+        # asymptotic sum when the approximation becomes accurate
+        i = nu > 5e4  # roundoff error ~ approximation error
+        # -1 / (12 * nu) is the O(1/nu) term; see gh-17929
+        h[i] = C[i] + norm_entropy - 1/(12*nu[i])
+        return h.reshape(shape)[()]
+
+    def _rvs(self, nu, size=None, random_state=None):
+        # this relationship can be found in [1] or by a direct calculation
+        return np.sqrt(random_state.standard_gamma(nu, size=size) / nu)
+
+    def _fitstart(self, data, args=None):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        if args is None:
+            args = (1.0,) * self.numargs
+        # Analytical justified estimates
+        # see: https://docs.scipy.org/doc/scipy/reference/tutorial/stats/continuous_nakagami.html
+        loc = np.min(data)
+        scale = np.sqrt(np.sum((data - loc)**2) / len(data))
+        return args + (loc, scale)
+
+
+nakagami = nakagami_gen(a=0.0, name="nakagami")
+
+
+# The function name ncx2 is an abbreviation for noncentral chi squared.
+def _ncx2_log_pdf(x, df, nc):
+    # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2  + xs*ns, and include the
+    # factor of exp(-xs*ns) into the ive function to improve numerical
+    # stability at large values of xs. See also `rice.pdf`.
+    df2 = df/2.0 - 1.0
+    xs, ns = np.sqrt(x), np.sqrt(nc)
+    res = sc.xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2
+    corr = sc.ive(df2, xs*ns) / 2.0
+    # Return res + np.log(corr) avoiding np.log(0)
+    return _lazywhere(
+        corr > 0,
+        (res, corr),
+        f=lambda r, c: r + np.log(c),
+        fillvalue=-np.inf)
+
+
+class ncx2_gen(rv_continuous):
+    r"""A non-central chi-squared continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `ncx2` is:
+
+    .. math::
+
+        f(x, k, \lambda) = \frac{1}{2} \exp(-(\lambda+x)/2)
+            (x/\lambda)^{(k-2)/4}  I_{(k-2)/2}(\sqrt{\lambda x})
+
+    for :math:`x >= 0`, :math:`k > 0` and :math:`\lambda \ge 0`.
+    :math:`k` specifies the degrees of freedom (denoted ``df`` in the
+    implementation) and :math:`\lambda` is the non-centrality parameter
+    (denoted ``nc`` in the implementation). :math:`I_\nu` denotes the
+    modified Bessel function of first order of degree :math:`\nu`
+    (`scipy.special.iv`).
+
+    `ncx2` takes ``df`` and ``nc`` as shape parameters.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, df, nc):
+        return (df > 0) & np.isfinite(df) & (nc >= 0)
+
+    def _shape_info(self):
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (0, np.inf), (True, False))
+        return [idf, inc]
+
+    def _rvs(self, df, nc, size=None, random_state=None):
+        return random_state.noncentral_chisquare(df, nc, size)
+
+    def _logpdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        return _lazywhere(cond, (x, df, nc), f=_ncx2_log_pdf,
+                          f2=lambda x, df, _: chi2._logpdf(x, df))
+
+    def _pdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_pdf,
+                              f2=lambda x, df, _: chi2._pdf(x, df))
+
+    def _cdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_cdf,
+                              f2=lambda x, df, _: chi2._cdf(x, df))
+
+    def _ppf(self, q, df, nc):
+        cond = np.ones_like(q, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (q, df, nc), f=scu._ncx2_ppf,
+                              f2=lambda x, df, _: chi2._ppf(x, df))
+
+    def _sf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_sf,
+                              f2=lambda x, df, _: chi2._sf(x, df))
+
+    def _isf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_isf,
+                              f2=lambda x, df, _: chi2._isf(x, df))
+
+    def _stats(self, df, nc):
+        _ncx2_mean = df + nc
+        def k_plus_cl(k, l, c):
+            return k + c*l
+        _ncx2_variance =  2.0 * k_plus_cl(df, nc, 2.0)
+        _ncx2_skewness = (np.sqrt(8.0) * k_plus_cl(df, nc, 3) /
+                          np.sqrt(k_plus_cl(df, nc, 2.0)**3))
+        _ncx2_kurtosis_excess = (12.0 * k_plus_cl(df, nc, 4.0) /
+                                 k_plus_cl(df, nc, 2.0)**2)
+        return (
+            _ncx2_mean,
+            _ncx2_variance,
+            _ncx2_skewness,
+            _ncx2_kurtosis_excess,
+        )
+
+
+ncx2 = ncx2_gen(a=0.0, name='ncx2')
+
+
+class ncf_gen(rv_continuous):
+    r"""A non-central F distribution continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    scipy.stats.f : Fisher distribution
+
+    Notes
+    -----
+    The probability density function for `ncf` is:
+
+    .. math::
+
+        f(x, n_1, n_2, \lambda) =
+            \exp\left(\frac{\lambda}{2} +
+                      \lambda n_1 \frac{x}{2(n_1 x + n_2)}
+                \right)
+            n_1^{n_1/2} n_2^{n_2/2} x^{n_1/2 - 1} \\
+            (n_2 + n_1 x)^{-(n_1 + n_2)/2}
+            \gamma(n_1/2) \gamma(1 + n_2/2) \\
+            \frac{L^{\frac{n_1}{2}-1}_{n_2/2}
+                \left(-\lambda n_1 \frac{x}{2(n_1 x + n_2)}\right)}
+            {B(n_1/2, n_2/2)
+                \gamma\left(\frac{n_1 + n_2}{2}\right)}
+
+    for :math:`n_1, n_2 > 0`, :math:`\lambda \ge 0`.  Here :math:`n_1` is the
+    degrees of freedom in the numerator, :math:`n_2` the degrees of freedom in
+    the denominator, :math:`\lambda` the non-centrality parameter,
+    :math:`\gamma` is the logarithm of the Gamma function, :math:`L_n^k` is a
+    generalized Laguerre polynomial and :math:`B` is the beta function.
+
+    `ncf` takes ``dfn``, ``dfd`` and ``nc`` as shape parameters. If ``nc=0``,
+    the distribution becomes equivalent to the Fisher distribution.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``stats``, ``sf`` and
+    ``isf`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, dfn, dfd, nc):
+        return (dfn > 0) & (dfd > 0) & (nc >= 0)
+
+    def _shape_info(self):
+        idf1 = _ShapeInfo("dfn", False, (0, np.inf), (False, False))
+        idf2 = _ShapeInfo("dfd", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (0, np.inf), (True, False))
+        return [idf1, idf2, inc]
+
+    def _rvs(self, dfn, dfd, nc, size=None, random_state=None):
+        return random_state.noncentral_f(dfn, dfd, nc, size)
+
+    def _pdf(self, x, dfn, dfd, nc):
+        return scu._ncf_pdf(x, dfn, dfd, nc)
+
+    def _cdf(self, x, dfn, dfd, nc):
+        return sc.ncfdtr(dfn, dfd, nc, x)
+
+    def _ppf(self, q, dfn, dfd, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return sc.ncfdtri(dfn, dfd, nc, q)
+
+    def _sf(self, x, dfn, dfd, nc):
+        return scu._ncf_sf(x, dfn, dfd, nc)
+
+    def _isf(self, x, dfn, dfd, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._ncf_isf(x, dfn, dfd, nc)
+
+    # # Produces bogus values as written - maybe it's close, though?
+    # def _munp(self, n, dfn, dfd, nc):
+    #     val = (dfn * 1.0/dfd)**n
+    #     term = sc.gammaln(n+0.5*dfn) + sc.gammaln(0.5*dfd-n) - sc.gammaln(dfd*0.5)
+    #     val *= np.exp(-nc / 2.0+term)
+    #     val *= sc.hyp1f1(n+0.5*dfn, 0.5*dfn, 0.5*nc)
+    #     return val
+
+    def _stats(self, dfn, dfd, nc, moments='mv'):
+        mu = scu._ncf_mean(dfn, dfd, nc)
+        mu2 = scu._ncf_variance(dfn, dfd, nc)
+        g1 = scu._ncf_skewness(dfn, dfd, nc) if 's' in moments else None
+        g2 = scu._ncf_kurtosis_excess(  # isn't really excess kurtosis!
+            dfn, dfd, nc) - 3 if 'k' in moments else None
+        # Mathematica: Kurtosis[NoncentralFRatioDistribution[27, 27, 0.415784417992261]]
+        return mu, mu2, g1, g2
+
+
+ncf = ncf_gen(a=0.0, name='ncf')
+
+
+class t_gen(rv_continuous):
+    r"""A Student's t continuous random variable.
+
+    For the noncentral t distribution, see `nct`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nct
+
+    Notes
+    -----
+    The probability density function for `t` is:
+
+    .. math::
+
+        f(x, \nu) = \frac{\Gamma((\nu+1)/2)}
+                        {\sqrt{\pi \nu} \Gamma(\nu/2)}
+                    (1+x^2/\nu)^{-(\nu+1)/2}
+
+    where :math:`x` is a real number and the degrees of freedom parameter
+    :math:`\nu` (denoted ``df`` in the implementation) satisfies
+    :math:`\nu > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return random_state.standard_t(df, size=size)
+
+    def _pdf(self, x, df):
+        return _lazywhere(
+            df == np.inf, (x, df),
+            f=lambda x, df: norm._pdf(x),
+            f2=lambda x, df: (
+                np.exp(self._logpdf(x, df))
+            )
+        )
+
+    def _logpdf(self, x, df):
+
+        def t_logpdf(x, df):
+            return (np.log(sc.poch(0.5 * df, 0.5))
+                    - 0.5 * (np.log(df) + np.log(np.pi))
+                    - (df + 1)/2*np.log1p(x * x/df))
+
+        def norm_logpdf(x, df):
+            return norm._logpdf(x)
+
+        return _lazywhere(df == np.inf, (x, df, ), f=norm_logpdf, f2=t_logpdf)
+
+    def _cdf(self, x, df):
+        return sc.stdtr(df, x)
+
+    def _sf(self, x, df):
+        return sc.stdtr(df, -x)
+
+    def _ppf(self, q, df):
+        return sc.stdtrit(df, q)
+
+    def _isf(self, q, df):
+        return -sc.stdtrit(df, q)
+
+    def _stats(self, df):
+        # infinite df -> normal distribution (0.0, 1.0, 0.0, 0.0)
+        infinite_df = np.isposinf(df)
+
+        mu = np.where(df > 1, 0.0, np.inf)
+
+        condlist = ((df > 1) & (df <= 2),
+                    (df > 2) & np.isfinite(df),
+                    infinite_df)
+        choicelist = (lambda df: np.broadcast_to(np.inf, df.shape),
+                      lambda df: df / (df-2.0),
+                      lambda df: np.broadcast_to(1, df.shape))
+        mu2 = _lazyselect(condlist, choicelist, (df,), np.nan)
+
+        g1 = np.where(df > 3, 0.0, np.nan)
+
+        condlist = ((df > 2) & (df <= 4),
+                    (df > 4) & np.isfinite(df),
+                    infinite_df)
+        choicelist = (lambda df: np.broadcast_to(np.inf, df.shape),
+                      lambda df: 6.0 / (df-4.0),
+                      lambda df: np.broadcast_to(0, df.shape))
+        g2 = _lazyselect(condlist, choicelist, (df,), np.nan)
+
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+        if df == np.inf:
+            return norm._entropy()
+
+        def regular(df):
+            half = df/2
+            half1 = (df + 1)/2
+            return (half1*(sc.digamma(half1) - sc.digamma(half))
+                    + np.log(np.sqrt(df)*sc.beta(half, 0.5)))
+
+        def asymptotic(df):
+            # Formula from Wolfram Alpha:
+            # "asymptotic expansion (d+1)/2 * (digamma((d+1)/2) - digamma(d/2))
+            #  + log(sqrt(d) * beta(d/2, 1/2))"
+            h = (norm._entropy() + 1/df + (df**-2.)/4 - (df**-3.)/6
+                 - (df**-4.)/8 + 3/10*(df**-5.) + (df**-6.)/4)
+            return h
+
+        h = _lazywhere(df >= 100, (df, ), f=asymptotic, f2=regular)
+        return h
+
+
+t = t_gen(name='t')
+
+
+class nct_gen(rv_continuous):
+    r"""A non-central Student's t continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    If :math:`Y` is a standard normal random variable and :math:`V` is
+    an independent chi-square random variable (`chi2`) with :math:`k` degrees
+    of freedom, then
+
+    .. math::
+
+        X = \frac{Y + c}{\sqrt{V/k}}
+
+    has a non-central Student's t distribution on the real line.
+    The degrees of freedom parameter :math:`k` (denoted ``df`` in the
+    implementation) satisfies :math:`k > 0` and the noncentrality parameter
+    :math:`c` (denoted ``nc`` in the implementation) is a real number.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, df, nc):
+        return (df > 0) & (nc == nc)
+
+    def _shape_info(self):
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (-np.inf, np.inf), (False, False))
+        return [idf, inc]
+
+    def _rvs(self, df, nc, size=None, random_state=None):
+        n = norm.rvs(loc=nc, size=size, random_state=random_state)
+        c2 = chi2.rvs(df, size=size, random_state=random_state)
+        return n * np.sqrt(df) / np.sqrt(c2)
+
+    def _pdf(self, x, df, nc):
+        return scu._nct_pdf(x, df, nc)
+
+    def _cdf(self, x, df, nc):
+        return sc.nctdtr(df, nc, x)
+
+    def _ppf(self, q, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nct_ppf(q, df, nc)
+
+    def _sf(self, x, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return np.clip(scu._nct_sf(x, df, nc), 0, 1)
+
+    def _isf(self, x, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nct_isf(x, df, nc)
+
+    def _stats(self, df, nc, moments='mv'):
+        mu = scu._nct_mean(df, nc)
+        mu2 = scu._nct_variance(df, nc)
+        g1 = scu._nct_skewness(df, nc) if 's' in moments else None
+        g2 = scu._nct_kurtosis_excess(df, nc) if 'k' in moments else None
+        return mu, mu2, g1, g2
+
+
+nct = nct_gen(name="nct")
+
+
+class pareto_gen(rv_continuous):
+    r"""A Pareto continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `pareto` is:
+
+    .. math::
+
+        f(x, b) = \frac{b}{x^{b+1}}
+
+    for :math:`x \ge 1`, :math:`b > 0`.
+
+    `pareto` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, b):
+        # pareto.pdf(x, b) = b / x**(b+1)
+        return b * x**(-b-1)
+
+    def _cdf(self, x, b):
+        return 1 - x**(-b)
+
+    def _ppf(self, q, b):
+        return pow(1-q, -1.0/b)
+
+    def _sf(self, x, b):
+        return x**(-b)
+
+    def _isf(self, q, b):
+        return np.power(q, -1.0 / b)
+
+    def _stats(self, b, moments='mv'):
+        mu, mu2, g1, g2 = None, None, None, None
+        if 'm' in moments:
+            mask = b > 1
+            bt = np.extract(mask, b)
+            mu = np.full(np.shape(b), fill_value=np.inf)
+            np.place(mu, mask, bt / (bt-1.0))
+        if 'v' in moments:
+            mask = b > 2
+            bt = np.extract(mask, b)
+            mu2 = np.full(np.shape(b), fill_value=np.inf)
+            np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2)
+        if 's' in moments:
+            mask = b > 3
+            bt = np.extract(mask, b)
+            g1 = np.full(np.shape(b), fill_value=np.nan)
+            vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt))
+            np.place(g1, mask, vals)
+        if 'k' in moments:
+            mask = b > 4
+            bt = np.extract(mask, b)
+            g2 = np.full(np.shape(b), fill_value=np.nan)
+            vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) /
+                    np.polyval([1.0, -7.0, 12.0, 0.0], bt))
+            np.place(g2, mask, vals)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, b):
+        return 1 + 1.0/b - np.log(b)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fshape, floc, fscale = parameters
+
+        # ensure that any fixed parameters don't violate constraints of the
+        # distribution before continuing.
+        if floc is not None and np.min(data) - floc < (fscale or 0):
+            raise FitDataError("pareto", lower=1, upper=np.inf)
+
+        ndata = data.shape[0]
+
+        def get_shape(scale, location):
+            # The first-order necessary condition on `shape` can be solved in
+            # closed form
+            return ndata / np.sum(np.log((data - location) / scale))
+
+        if floc is fscale is None:
+            # The support of the distribution is `(x - loc)/scale > 0`.
+            # The method of Lagrange multipliers turns this constraint
+            # into an equation that can be solved numerically.
+            # See gh-12545 for details.
+
+            def dL_dScale(shape, scale):
+                # The partial derivative of the log-likelihood function w.r.t.
+                # the scale.
+                return ndata * shape / scale
+
+            def dL_dLocation(shape, location):
+                # The partial derivative of the log-likelihood function w.r.t.
+                # the location.
+                return (shape + 1) * np.sum(1 / (data - location))
+
+            def fun_to_solve(scale):
+                # optimize the scale by setting the partial derivatives
+                # w.r.t. to location and scale equal and solving.
+                location = np.min(data) - scale
+                shape = fshape or get_shape(scale, location)
+                return dL_dLocation(shape, location) - dL_dScale(shape, scale)
+
+            def interval_contains_root(lbrack, rbrack):
+                # return true if the signs disagree.
+                return (np.sign(fun_to_solve(lbrack)) !=
+                        np.sign(fun_to_solve(rbrack)))
+
+            # set brackets for `root_scalar` to use when optimizing over the
+            # scale such that a root is likely between them. Use user supplied
+            # guess or default 1.
+            brack_start = float(kwds.get('scale', 1))
+            lbrack, rbrack = brack_start / 2, brack_start * 2
+            # if a root is not between the brackets, iteratively expand them
+            # until they include a sign change, checking after each bracket is
+            # modified.
+            while (not interval_contains_root(lbrack, rbrack)
+                   and (lbrack > 0 or rbrack < np.inf)):
+                lbrack /= 2
+                rbrack *= 2
+            res = root_scalar(fun_to_solve, bracket=[lbrack, rbrack])
+            if res.converged:
+                scale = res.root
+                loc = np.min(data) - scale
+                shape = fshape or get_shape(scale, loc)
+
+                # The Pareto distribution requires that its parameters satisfy
+                # the condition `fscale + floc <= min(data)`. However, to
+                # avoid numerical issues, we require that `fscale + floc`
+                # is strictly less than `min(data)`. If this condition
+                # is not satisfied, reduce the scale with `np.nextafter` to
+                # ensure that data does not fall outside of the support.
+                if not (scale + loc) < np.min(data):
+                    scale = np.min(data) - loc
+                    scale = np.nextafter(scale, 0)
+                return shape, loc, scale
+            else:
+                return super().fit(data, **kwds)
+        elif floc is None:
+            loc = np.min(data) - fscale
+        else:
+            loc = floc
+        # Source: Evans, Hastings, and Peacock (2000), Statistical
+        # Distributions, 3rd. Ed., John Wiley and Sons. Page 149.
+        scale = fscale or np.min(data) - loc
+        shape = fshape or get_shape(scale, loc)
+        return shape, loc, scale
+
+
+pareto = pareto_gen(a=1.0, name="pareto")
+
+
+class lomax_gen(rv_continuous):
+    r"""A Lomax (Pareto of the second kind) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `lomax` is:
+
+    .. math::
+
+        f(x, c) = \frac{c}{(1+x)^{c+1}}
+
+    for :math:`x \ge 0`, :math:`c > 0`.
+
+    `lomax` takes ``c`` as a shape parameter for :math:`c`.
+
+    `lomax` is a special case of `pareto` with ``loc=-1.0``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # lomax.pdf(x, c) = c / (1+x)**(c+1)
+        return c*1.0/(1.0+x)**(c+1.0)
+
+    def _logpdf(self, x, c):
+        return np.log(c) - (c+1)*sc.log1p(x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-c*sc.log1p(x))
+
+    def _sf(self, x, c):
+        return np.exp(-c*sc.log1p(x))
+
+    def _logsf(self, x, c):
+        return -c*sc.log1p(x)
+
+    def _ppf(self, q, c):
+        return sc.expm1(-sc.log1p(-q)/c)
+
+    def _isf(self, q, c):
+        return q**(-1.0 / c) - 1
+
+    def _stats(self, c):
+        mu, mu2, g1, g2 = pareto.stats(c, loc=-1.0, moments='mvsk')
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        return 1+1.0/c-np.log(c)
+
+
+lomax = lomax_gen(a=0.0, name="lomax")
+
+
+class pearson3_gen(rv_continuous):
+    r"""A pearson type III continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `pearson3` is:
+
+    .. math::
+
+        f(x, \kappa) = \frac{|\beta|}{\Gamma(\alpha)}
+                       (\beta (x - \zeta))^{\alpha - 1}
+                       \exp(-\beta (x - \zeta))
+
+    where:
+
+    .. math::
+
+            \beta = \frac{2}{\kappa}
+
+            \alpha = \beta^2 = \frac{4}{\kappa^2}
+
+            \zeta = -\frac{\alpha}{\beta} = -\beta
+
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+    Pass the skew :math:`\kappa` into `pearson3` as the shape parameter
+    ``skew``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    References
+    ----------
+    R.W. Vogel and D.E. McMartin, "Probability Plot Goodness-of-Fit and
+    Skewness Estimation Procedures for the Pearson Type 3 Distribution", Water
+    Resources Research, Vol.27, 3149-3158 (1991).
+
+    L.R. Salvosa, "Tables of Pearson's Type III Function", Ann. Math. Statist.,
+    Vol.1, 191-198 (1930).
+
+    "Using Modern Computing Tools to Fit the Pearson Type III Distribution to
+    Aviation Loads Data", Office of Aviation Research (2003).
+
+    """
+    def _preprocess(self, x, skew):
+        # The real 'loc' and 'scale' are handled in the calling pdf(...). The
+        # local variables 'loc' and 'scale' within pearson3._pdf are set to
+        # the defaults just to keep them as part of the equations for
+        # documentation.
+        loc = 0.0
+        scale = 1.0
+
+        # If skew is small, return _norm_pdf. The divide between pearson3
+        # and norm was found by brute force and is approximately a skew of
+        # 0.000016.  No one, I hope, would actually use a skew value even
+        # close to this small.
+        norm2pearson_transition = 0.000016
+
+        ans, x, skew = np.broadcast_arrays(1.0, x, skew)
+        ans = ans.copy()
+
+        # mask is True where skew is small enough to use the normal approx.
+        mask = np.absolute(skew) < norm2pearson_transition
+        invmask = ~mask
+
+        beta = 2.0 / (skew[invmask] * scale)
+        alpha = (scale * beta)**2
+        zeta = loc - alpha / beta
+
+        transx = beta * (x[invmask] - zeta)
+        return ans, x, transx, mask, invmask, beta, alpha, zeta
+
+    def _argcheck(self, skew):
+        # The _argcheck function in rv_continuous only allows positive
+        # arguments.  The skew argument for pearson3 can be zero (which I want
+        # to handle inside pearson3._pdf) or negative.  So just return True
+        # for all skew args.
+        return np.isfinite(skew)
+
+    def _shape_info(self):
+        return [_ShapeInfo("skew", False, (-np.inf, np.inf), (False, False))]
+
+    def _stats(self, skew):
+        m = 0.0
+        v = 1.0
+        s = skew
+        k = 1.5*skew**2
+        return m, v, s, k
+
+    def _pdf(self, x, skew):
+        # pearson3.pdf(x, skew) = abs(beta) / gamma(alpha) *
+        #     (beta * (x - zeta))**(alpha - 1) * exp(-beta*(x - zeta))
+        # Do the calculation in _logpdf since helps to limit
+        # overflow/underflow problems
+        ans = np.exp(self._logpdf(x, skew))
+        if ans.ndim == 0:
+            if np.isnan(ans):
+                return 0.0
+            return ans
+        ans[np.isnan(ans)] = 0.0
+        return ans
+
+    def _logpdf(self, x, skew):
+        #   PEARSON3 logpdf                           GAMMA logpdf
+        #   np.log(abs(beta))
+        # + (alpha - 1)*np.log(beta*(x - zeta))          + (a - 1)*np.log(x)
+        # - beta*(x - zeta)                           - x
+        # - sc.gammalnalpha)                              - sc.gammalna)
+        ans, x, transx, mask, invmask, beta, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = np.log(_norm_pdf(x[mask]))
+        # use logpdf instead of _logpdf to fix issue mentioned in gh-12640
+        # (_logpdf does not return correct result for alpha = 1)
+        ans[invmask] = np.log(abs(beta)) + gamma.logpdf(transx, alpha)
+        return ans
+
+    def _cdf(self, x, skew):
+        ans, x, transx, mask, invmask, _, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = _norm_cdf(x[mask])
+
+        skew = np.broadcast_to(skew, invmask.shape)
+        invmask1a = np.logical_and(invmask, skew > 0)
+        invmask1b = skew[invmask] > 0
+        # use cdf instead of _cdf to fix issue mentioned in gh-12640
+        # (_cdf produces NaNs for inputs outside support)
+        ans[invmask1a] = gamma.cdf(transx[invmask1b], alpha[invmask1b])
+
+        # The gamma._cdf approach wasn't working with negative skew.
+        # Note that multiplying the skew by -1 reflects about x=0.
+        # So instead of evaluating the CDF with negative skew at x,
+        # evaluate the SF with positive skew at -x.
+        invmask2a = np.logical_and(invmask, skew < 0)
+        invmask2b = skew[invmask] < 0
+        # gamma._sf produces NaNs when transx < 0, so use gamma.sf
+        ans[invmask2a] = gamma.sf(transx[invmask2b], alpha[invmask2b])
+
+        return ans
+
+    def _sf(self, x, skew):
+        ans, x, transx, mask, invmask, _, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = _norm_sf(x[mask])
+
+        skew = np.broadcast_to(skew, invmask.shape)
+        invmask1a = np.logical_and(invmask, skew > 0)
+        invmask1b = skew[invmask] > 0
+        ans[invmask1a] = gamma.sf(transx[invmask1b], alpha[invmask1b])
+
+        invmask2a = np.logical_and(invmask, skew < 0)
+        invmask2b = skew[invmask] < 0
+        ans[invmask2a] = gamma.cdf(transx[invmask2b], alpha[invmask2b])
+
+        return ans
+
+    def _rvs(self, skew, size=None, random_state=None):
+        skew = np.broadcast_to(skew, size)
+        ans, _, _, mask, invmask, beta, alpha, zeta = (
+            self._preprocess([0], skew))
+
+        nsmall = mask.sum()
+        nbig = mask.size - nsmall
+        ans[mask] = random_state.standard_normal(nsmall)
+        ans[invmask] = random_state.standard_gamma(alpha, nbig)/beta + zeta
+
+        if size == ():
+            ans = ans[0]
+        return ans
+
+    def _ppf(self, q, skew):
+        ans, q, _, mask, invmask, beta, alpha, zeta = (
+            self._preprocess(q, skew))
+        ans[mask] = _norm_ppf(q[mask])
+        q = q[invmask]
+        q[beta < 0] = 1 - q[beta < 0]  # for negative skew; see gh-17050
+        ans[invmask] = sc.gammaincinv(alpha, q)/beta + zeta
+        return ans
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Note that method of moments (`method='MM'`) is not
+        available for this distribution.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.get("method", None) == 'MM':
+            raise NotImplementedError("Fit `method='MM'` is not available for "
+                                      "the Pearson3 distribution. Please try "
+                                      "the default `method='MLE'`.")
+        else:
+            return super(type(self), self).fit(data, *args, **kwds)
+
+
+pearson3 = pearson3_gen(name="pearson3")
+
+
+class powerlaw_gen(rv_continuous):
+    r"""A power-function continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    pareto
+
+    Notes
+    -----
+    The probability density function for `powerlaw` is:
+
+    .. math::
+
+        f(x, a) = a x^{a-1}
+
+    for :math:`0 \le x \le 1`, :math:`a > 0`.
+
+    `powerlaw` takes ``a`` as a shape parameter for :math:`a`.
+
+    %(after_notes)s
+
+    For example, the support of `powerlaw` can be adjusted from the default
+    interval ``[0, 1]`` to the interval ``[c, c+d]`` by setting ``loc=c`` and
+    ``scale=d``. For a power-law distribution with infinite support, see
+    `pareto`.
+
+    `powerlaw` is a special case of `beta` with ``b=1``.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # powerlaw.pdf(x, a) = a * x**(a-1)
+        return a*x**(a-1.0)
+
+    def _logpdf(self, x, a):
+        return np.log(a) + sc.xlogy(a - 1, x)
+
+    def _cdf(self, x, a):
+        return x**(a*1.0)
+
+    def _logcdf(self, x, a):
+        return a*np.log(x)
+
+    def _ppf(self, q, a):
+        return pow(q, 1.0/a)
+
+    def _sf(self, p, a):
+        return -sc.powm1(p, a)
+
+    def _munp(self, n, a):
+        # The following expression is correct for all real n (provided a > 0).
+        return a / (a + n)
+
+    def _stats(self, a):
+        return (a / (a + 1.0),
+                a / (a + 2.0) / (a + 1.0) ** 2,
+                -2.0 * ((a - 1.0) / (a + 3.0)) * np.sqrt((a + 2.0) / a),
+                6 * np.polyval([1, -1, -6, 2], a) / (a * (a + 3.0) * (a + 4)))
+
+    def _entropy(self, a):
+        return 1 - 1.0/a - np.log(a)
+
+    def _support_mask(self, x, a):
+        return (super()._support_mask(x, a)
+                & ((x != 0) | (a >= 1)))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Notes specifically for ``powerlaw.fit``: If the location is a free
+        parameter and the value returned for the shape parameter is less than
+        one, the true maximum likelihood approaches infinity. This causes
+        numerical difficulties, and the resulting estimates are approximate.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        # Summary of the strategy:
+        #
+        # 1) If the scale and location are fixed, return the shape according
+        #    to a formula.
+        #
+        # 2) If the scale is fixed, there are two possibilities for the other
+        #    parameters - one corresponding with shape less than one, and
+        #    another with shape greater than one. Calculate both, and return
+        #    whichever has the better log-likelihood.
+        #
+        # At this point, the scale is known to be free.
+        #
+        # 3) If the location is fixed, return the scale and shape according to
+        #    formulas (or, if the shape is fixed, the fixed shape).
+        #
+        # At this point, the location and scale are both free. There are
+        # separate equations depending on whether the shape is less than one or
+        # greater than one.
+        #
+        # 4a) If the shape is less than one, there are formulas for shape,
+        #     location, and scale.
+        # 4b) If the shape is greater than one, there are formulas for shape
+        #     and scale, but there is a condition for location to be solved
+        #     numerically.
+        #
+        # If the shape is fixed and less than one, we use 4a.
+        # If the shape is fixed and greater than one, we use 4b.
+        # If the shape is also free, we calculate fits using both 4a and 4b
+        # and choose the one that results a better log-likelihood.
+        #
+        # In many cases, the use of `np.nextafter` is used to avoid numerical
+        # issues.
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        if len(np.unique(data)) == 1:
+            return super().fit(data, *args, **kwds)
+
+        data, fshape, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                 args, kwds)
+        penalized_nllf_args = [data, (self._fitstart(data),)]
+        penalized_nllf = self._reduce_func(penalized_nllf_args, {})[1]
+
+        # ensure that any fixed parameters don't violate constraints of the
+        # distribution before continuing. The support of the distribution
+        # is `0 < (x - loc)/scale < 1`.
+        if floc is not None:
+            if not data.min() > floc:
+                raise FitDataError('powerlaw', 0, 1)
+            if fscale is not None and not data.max() <= floc + fscale:
+                raise FitDataError('powerlaw', 0, 1)
+
+        if fscale is not None:
+            if fscale <= 0:
+                raise ValueError("Negative or zero `fscale` is outside the "
+                                 "range allowed by the distribution.")
+            if fscale <= np.ptp(data):
+                msg = "`fscale` must be greater than the range of data."
+                raise ValueError(msg)
+
+        def get_shape(data, loc, scale):
+            # The first-order necessary condition on `shape` can be solved in
+            # closed form. It can be used no matter the assumption of the
+            # value of the shape.
+            N = len(data)
+            return - N / (np.sum(np.log(data - loc)) - N*np.log(scale))
+
+        def get_scale(data, loc):
+            # analytical solution for `scale` based on the location.
+            # It can be used no matter the assumption of the value of the
+            # shape.
+            return data.max() - loc
+
+        # 1) The location and scale are both fixed. Analytically determine the
+        # shape.
+        if fscale is not None and floc is not None:
+            return get_shape(data, floc, fscale), floc, fscale
+
+        # 2) The scale is fixed. There are two possibilities for the other
+        # parameters. Choose the option with better log-likelihood.
+        if fscale is not None:
+            # using `data.min()` as the optimal location
+            loc_lt1 = np.nextafter(data.min(), -np.inf)
+            shape_lt1 = fshape or get_shape(data, loc_lt1, fscale)
+            ll_lt1 = penalized_nllf((shape_lt1, loc_lt1, fscale), data)
+
+            # using `data.max() - scale` as the optimal location
+            loc_gt1 = np.nextafter(data.max() - fscale, np.inf)
+            shape_gt1 = fshape or get_shape(data, loc_gt1, fscale)
+            ll_gt1 = penalized_nllf((shape_gt1, loc_gt1, fscale), data)
+
+            if ll_lt1 < ll_gt1:
+                return shape_lt1, loc_lt1, fscale
+            else:
+                return shape_gt1, loc_gt1, fscale
+
+        # 3) The location is fixed. Return the analytical scale and the
+        # analytical (or fixed) shape.
+        if floc is not None:
+            scale = get_scale(data, floc)
+            shape = fshape or get_shape(data, floc, scale)
+            return shape, floc, scale
+
+        # 4) Location and scale are both free
+        # 4a) Use formulas that assume `shape <= 1`.
+
+        def fit_loc_scale_w_shape_lt_1():
+            loc = np.nextafter(data.min(), -np.inf)
+            if np.abs(loc) < np.finfo(loc.dtype).tiny:
+                loc = np.sign(loc) * np.finfo(loc.dtype).tiny
+            scale = np.nextafter(get_scale(data, loc), np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return shape, loc, scale
+
+        # 4b) Fit under the assumption that `shape > 1`. The support
+        # of the distribution is `(x - loc)/scale <= 1`. The method of Lagrange
+        # multipliers turns this constraint into the condition that
+        # dL_dScale - dL_dLocation must be zero, which is solved numerically.
+        # (Alternatively, substitute the constraint into the objective
+        # function before deriving the likelihood equation for location.)
+
+        def dL_dScale(data, shape, scale):
+            # The partial derivative of the log-likelihood function w.r.t.
+            # the scale.
+            return -data.shape[0] * shape / scale
+
+        def dL_dLocation(data, shape, loc):
+            # The partial derivative of the log-likelihood function w.r.t.
+            # the location.
+            return (shape - 1) * np.sum(1 / (loc - data))  # -1/(data-loc)
+
+        def dL_dLocation_star(loc):
+            # The derivative of the log-likelihood function w.r.t.
+            # the location, given optimal shape and scale
+            scale = np.nextafter(get_scale(data, loc), -np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return dL_dLocation(data, shape, loc)
+
+        def fun_to_solve(loc):
+            # optimize the location by setting the partial derivatives
+            # w.r.t. to location and scale equal and solving.
+            scale = np.nextafter(get_scale(data, loc), -np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return (dL_dScale(data, shape, scale)
+                    - dL_dLocation(data, shape, loc))
+
+        def fit_loc_scale_w_shape_gt_1():
+            # set brackets for `root_scalar` to use when optimizing over the
+            # location such that a root is likely between them.
+            rbrack = np.nextafter(data.min(), -np.inf)
+
+            # if the sign of `dL_dLocation_star` is positive at rbrack,
+            # we're not going to find the root we're looking for
+            delta = (data.min() - rbrack)
+            while dL_dLocation_star(rbrack) > 0:
+                rbrack = data.min() - delta
+                delta *= 2
+
+            def interval_contains_root(lbrack, rbrack):
+                # Check if the interval (lbrack, rbrack) contains the root.
+                return (np.sign(fun_to_solve(lbrack))
+                        != np.sign(fun_to_solve(rbrack)))
+
+            lbrack = rbrack - 1
+
+            # if the sign doesn't change between the brackets, move the left
+            # bracket until it does. (The right bracket remains fixed at the
+            # maximum permissible value.)
+            i = 1.0
+            while (not interval_contains_root(lbrack, rbrack)
+                   and lbrack != -np.inf):
+                lbrack = (data.min() - i)
+                i *= 2
+
+            root = optimize.root_scalar(fun_to_solve, bracket=(lbrack, rbrack))
+
+            loc = np.nextafter(root.root, -np.inf)
+            scale = np.nextafter(get_scale(data, loc), np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return shape, loc, scale
+
+        # Shape is fixed - choose 4a or 4b accordingly.
+        if fshape is not None and fshape <= 1:
+            return fit_loc_scale_w_shape_lt_1()
+        elif fshape is not None and fshape > 1:
+            return fit_loc_scale_w_shape_gt_1()
+
+        # Shape is free
+        fit_shape_lt1 = fit_loc_scale_w_shape_lt_1()
+        ll_lt1 = self.nnlf(fit_shape_lt1, data)
+
+        fit_shape_gt1 = fit_loc_scale_w_shape_gt_1()
+        ll_gt1 = self.nnlf(fit_shape_gt1, data)
+
+        if ll_lt1 <= ll_gt1 and fit_shape_lt1[0] <= 1:
+            return fit_shape_lt1
+        elif ll_lt1 > ll_gt1 and fit_shape_gt1[0] > 1:
+            return fit_shape_gt1
+        else:
+            return super().fit(data, *args, **kwds)
+
+
+powerlaw = powerlaw_gen(a=0.0, b=1.0, name="powerlaw")
+
+
+class powerlognorm_gen(rv_continuous):
+    r"""A power log-normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `powerlognorm` is:
+
+    .. math::
+
+        f(x, c, s) = \frac{c}{x s} \phi(\log(x)/s)
+                     (\Phi(-\log(x)/s))^{c-1}
+
+    where :math:`\phi` is the normal pdf, and :math:`\Phi` is the normal cdf,
+    and :math:`x > 0`, :math:`s, c > 0`.
+
+    `powerlognorm` takes :math:`c` and :math:`s` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        i_s = _ShapeInfo("s", False, (0, np.inf), (False, False))
+        return [ic, i_s]
+
+    def _pdf(self, x, c, s):
+        return np.exp(self._logpdf(x, c, s))
+
+    def _logpdf(self, x, c, s):
+        return (np.log(c) - np.log(x) - np.log(s) +
+                _norm_logpdf(np.log(x) / s) +
+                _norm_logcdf(-np.log(x) / s) * (c - 1.))
+
+    def _cdf(self, x, c, s):
+        return -sc.expm1(self._logsf(x, c, s))
+
+    def _ppf(self, q, c, s):
+        return self._isf(1 - q, c, s)
+
+    def _sf(self, x, c, s):
+        return np.exp(self._logsf(x, c, s))
+
+    def _logsf(self, x, c, s):
+        return _norm_logcdf(-np.log(x) / s) * c
+
+    def _isf(self, q, c, s):
+        return np.exp(-_norm_ppf(q**(1/c)) * s)
+
+
+powerlognorm = powerlognorm_gen(a=0.0, name="powerlognorm")
+
+
+class powernorm_gen(rv_continuous):
+    r"""A power normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `powernorm` is:
+
+    .. math::
+
+        f(x, c) = c \phi(x) (\Phi(-x))^{c-1}
+
+    where :math:`\phi` is the normal pdf, :math:`\Phi` is the normal cdf,
+    :math:`x` is any real, and :math:`c > 0` [1]_.
+
+    `powernorm` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] NIST Engineering Statistics Handbook, Section 1.3.6.6.13,
+           https://www.itl.nist.gov/div898/handbook//eda/section3/eda366d.htm
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # powernorm.pdf(x, c) = c * phi(x) * (Phi(-x))**(c-1)
+        return c*_norm_pdf(x) * (_norm_cdf(-x)**(c-1.0))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + _norm_logpdf(x) + (c-1)*_norm_logcdf(-x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(self._logsf(x, c))
+
+    def _ppf(self, q, c):
+        return -_norm_ppf(pow(1.0 - q, 1.0 / c))
+
+    def _sf(self, x, c):
+        return np.exp(self._logsf(x, c))
+
+    def _logsf(self, x, c):
+        return c * _norm_logcdf(-x)
+
+    def _isf(self, q, c):
+        return -_norm_ppf(np.exp(np.log(q) / c))
+
+
+powernorm = powernorm_gen(name='powernorm')
+
+
+class rdist_gen(rv_continuous):
+    r"""An R-distributed (symmetric beta) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rdist` is:
+
+    .. math::
+
+        f(x, c) = \frac{(1-x^2)^{c/2-1}}{B(1/2, c/2)}
+
+    for :math:`-1 \le x \le 1`, :math:`c > 0`. `rdist` is also called the
+    symmetric beta distribution: if B has a `beta` distribution with
+    parameters (c/2, c/2), then X = 2*B - 1 follows a R-distribution with
+    parameter c.
+
+    `rdist` takes ``c`` as a shape parameter for :math:`c`.
+
+    This distribution includes the following distribution kernels as
+    special cases::
+
+        c = 2:  uniform
+        c = 3:  `semicircular`
+        c = 4:  Epanechnikov (parabolic)
+        c = 6:  quartic (biweight)
+        c = 8:  triweight
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    # use relation to the beta distribution for pdf, cdf, etc
+    def _pdf(self, x, c):
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return -np.log(2) + beta._logpdf((x + 1)/2, c/2, c/2)
+
+    def _cdf(self, x, c):
+        return beta._cdf((x + 1)/2, c/2, c/2)
+
+    def _sf(self, x, c):
+        return beta._sf((x + 1)/2, c/2, c/2)
+
+    def _ppf(self, q, c):
+        return 2*beta._ppf(q, c/2, c/2) - 1
+
+    def _rvs(self, c, size=None, random_state=None):
+        return 2 * random_state.beta(c/2, c/2, size) - 1
+
+    def _munp(self, n, c):
+        numerator = (1 - (n % 2)) * sc.beta((n + 1.0) / 2, c / 2.0)
+        return numerator / sc.beta(1. / 2, c / 2.)
+
+
+rdist = rdist_gen(a=-1.0, b=1.0, name="rdist")
+
+
+class rayleigh_gen(rv_continuous):
+    r"""A Rayleigh continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rayleigh` is:
+
+    .. math::
+
+        f(x) = x \exp(-x^2/2)
+
+    for :math:`x \ge 0`.
+
+    `rayleigh` is a special case of `chi` with ``df=2``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return chi.rvs(2, size=size, random_state=random_state)
+
+    def _pdf(self, r):
+        # rayleigh.pdf(r) = r * exp(-r**2/2)
+        return np.exp(self._logpdf(r))
+
+    def _logpdf(self, r):
+        return np.log(r) - 0.5 * r * r
+
+    def _cdf(self, r):
+        return -sc.expm1(-0.5 * r**2)
+
+    def _ppf(self, q):
+        return np.sqrt(-2 * sc.log1p(-q))
+
+    def _sf(self, r):
+        return np.exp(self._logsf(r))
+
+    def _logsf(self, r):
+        return -0.5 * r * r
+
+    def _isf(self, q):
+        return np.sqrt(-2 * np.log(q))
+
+    def _stats(self):
+        val = 4 - np.pi
+        return (np.sqrt(np.pi/2),
+                val/2,
+                2*(np.pi-3)*np.sqrt(np.pi)/val**1.5,
+                6*np.pi/val-16/val**2)
+
+    def _entropy(self):
+        return _EULER/2.0 + 1 - 0.5*np.log(2)
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Notes specifically for ``rayleigh.fit``: If the location is fixed with
+        the `floc` parameter, this method uses an analytical formula to find
+        the scale.  Otherwise, this function uses a numerical root finder on
+        the first order conditions of the log-likelihood function to find the
+        MLE.  Only the (optional) `loc` parameter is used as the initial guess
+        for the root finder; the `scale` parameter and any other parameters
+        for the optimizer are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        def scale_mle(loc):
+            # Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+            # and Peacock (2000), Page 175
+            return (np.sum((data - loc) ** 2) / (2 * len(data))) ** .5
+
+        def loc_mle(loc):
+            # This implicit equation for `loc` is used when
+            # both `loc` and `scale` are free.
+            xm = data - loc
+            s1 = xm.sum()
+            s2 = (xm**2).sum()
+            s3 = (1/xm).sum()
+            return s1 - s2/(2*len(data))*s3
+
+        def loc_mle_scale_fixed(loc, scale=fscale):
+            # This implicit equation for `loc` is used when
+            # `scale` is fixed but `loc` is not.
+            xm = data - loc
+            return xm.sum() - scale**2 * (1/xm).sum()
+
+        if floc is not None:
+            # `loc` is fixed, analytically determine `scale`.
+            if np.any(data - floc <= 0):
+                raise FitDataError("rayleigh", lower=1, upper=np.inf)
+            else:
+                return floc, scale_mle(floc)
+
+        # Account for user provided guess of `loc`.
+        loc0 = kwds.get('loc')
+        if loc0 is None:
+            # Use _fitstart to estimate loc; ignore the returned scale.
+            loc0 = self._fitstart(data)[0]
+
+        fun = loc_mle if fscale is None else loc_mle_scale_fixed
+        rbrack = np.nextafter(np.min(data), -np.inf)
+        lbrack = _get_left_bracket(fun, rbrack)
+        res = optimize.root_scalar(fun, bracket=(lbrack, rbrack))
+        if not res.converged:
+            raise FitSolverError(res.flag)
+        loc = res.root
+        scale = fscale or scale_mle(loc)
+        return loc, scale
+
+
+rayleigh = rayleigh_gen(a=0.0, name="rayleigh")
+
+
+class reciprocal_gen(rv_continuous):
+    r"""A loguniform or reciprocal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for this class is:
+
+    .. math::
+
+        f(x, a, b) = \frac{1}{x \log(b/a)}
+
+    for :math:`a \le x \le b`, :math:`b > a > 0`. This class takes
+    :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    This doesn't show the equal probability of ``0.01``, ``0.1`` and
+    ``1``. This is best when the x-axis is log-scaled:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.hist(np.log10(r))
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_xlabel("Value of random variable")
+    >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
+    >>> ticks = ["$10^{{ {} }}$".format(i) for i in [-2, -1, 0]]
+    >>> ax.set_xticklabels(ticks)  # doctest: +SKIP
+    >>> plt.show()
+
+    This random variable will be log-uniform regardless of the base chosen for
+    ``a`` and ``b``. Let's specify with base ``2`` instead:
+
+    >>> rvs = %(name)s(2**-2, 2**0).rvs(size=1000)
+
+    Values of ``1/4``, ``1/2`` and ``1`` are equally likely with this random
+    variable.  Here's the histogram:
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.hist(np.log2(rvs))
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_xlabel("Value of random variable")
+    >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
+    >>> ticks = ["$2^{{ {} }}$".format(i) for i in [-2, -1, 0]]
+    >>> ax.set_xticklabels(ticks)  # doctest: +SKIP
+    >>> plt.show()
+
+    """
+    def _argcheck(self, a, b):
+        return (a > 0) & (b > a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        # Reasonable, since support is [a, b]
+        return super()._fitstart(data, args=(np.min(data), np.max(data)))
+
+    def _get_support(self, a, b):
+        return a, b
+
+    def _pdf(self, x, a, b):
+        # reciprocal.pdf(x, a, b) = 1 / (x*(log(b) - log(a)))
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return -np.log(x) - np.log(np.log(b) - np.log(a))
+
+    def _cdf(self, x, a, b):
+        return (np.log(x)-np.log(a)) / (np.log(b) - np.log(a))
+
+    def _ppf(self, q, a, b):
+        return np.exp(np.log(a) + q*(np.log(b) - np.log(a)))
+
+    def _munp(self, n, a, b):
+        if n == 0:
+            return 1.0
+        t1 = 1 / (np.log(b) - np.log(a)) / n
+        t2 = np.real(np.exp(_log_diff(n * np.log(b), n*np.log(a))))
+        return t1 * t2
+
+    def _entropy(self, a, b):
+        return 0.5*(np.log(a) + np.log(b)) + np.log(np.log(b) - np.log(a))
+
+    fit_note = """\
+        `loguniform`/`reciprocal` is over-parameterized. `fit` automatically
+         fixes `scale` to 1 unless `fscale` is provided by the user.\n\n"""
+
+    @extend_notes_in_docstring(rv_continuous, notes=fit_note)
+    def fit(self, data, *args, **kwds):
+        fscale = kwds.pop('fscale', 1)
+        return super().fit(data, *args, fscale=fscale, **kwds)
+
+    # Details related to the decision of not defining
+    # the survival function for this distribution can be
+    # found in the PR: https://github.com/scipy/scipy/pull/18614
+
+
+loguniform = reciprocal_gen(name="loguniform")
+reciprocal = reciprocal_gen(name="reciprocal")
+loguniform._support = ('a', 'b')
+reciprocal._support = ('a', 'b')
+
+
+class rice_gen(rv_continuous):
+    r"""A Rice continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rice` is:
+
+    .. math::
+
+        f(x, b) = x \exp(- \frac{x^2 + b^2}{2}) I_0(x b)
+
+    for :math:`x >= 0`, :math:`b > 0`. :math:`I_0` is the modified Bessel
+    function of order zero (`scipy.special.i0`).
+
+    `rice` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    The Rice distribution describes the length, :math:`r`, of a 2-D vector with
+    components :math:`(U+u, V+v)`, where :math:`U, V` are constant, :math:`u,
+    v` are independent Gaussian random variables with standard deviation
+    :math:`s`.  Let :math:`R = \sqrt{U^2 + V^2}`. Then the pdf of :math:`r` is
+    ``rice.pdf(x, R/s, scale=s)``.
+
+    %(example)s
+
+    """
+    def _argcheck(self, b):
+        return b >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, b, size=None, random_state=None):
+        # https://en.wikipedia.org/wiki/Rice_distribution
+        t = b/np.sqrt(2) + random_state.standard_normal(size=(2,) + size)
+        return np.sqrt((t*t).sum(axis=0))
+
+    def _cdf(self, x, b):
+        return sc.chndtr(np.square(x), 2, np.square(b))
+
+    def _ppf(self, q, b):
+        return np.sqrt(sc.chndtrix(q, 2, np.square(b)))
+
+    def _pdf(self, x, b):
+        # rice.pdf(x, b) = x * exp(-(x**2+b**2)/2) * I[0](x*b)
+        #
+        # We use (x**2 + b**2)/2 = ((x-b)**2)/2 + xb.
+        # The factor of np.exp(-xb) is then included in the i0e function
+        # in place of the modified Bessel function, i0, improving
+        # numerical stability for large values of xb.
+        return x * np.exp(-(x-b)*(x-b)/2.0) * sc.i0e(x*b)
+
+    def _munp(self, n, b):
+        nd2 = n/2.0
+        n1 = 1 + nd2
+        b2 = b*b/2.0
+        return (2.0**(nd2) * np.exp(-b2) * sc.gamma(n1) *
+                sc.hyp1f1(n1, 1, b2))
+
+
+rice = rice_gen(a=0.0, name="rice")
+
+class irwinhall_gen(rv_continuous):
+    r"""An Irwin-Hall (Uniform Sum) continuous random variable.
+
+    An `Irwin-Hall `_
+    continuous random variable is the sum of :math:`n` independent
+    standard uniform random variables [1]_ [2]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Applications include `Rao's Spacing Test
+    `_,
+    a more powerful alternative to the Rayleigh test
+    when the data are not unimodal, and radar [3]_.
+
+    Conveniently, the pdf and cdf are the :math:`n`-fold convolution of
+    the ones for the standard uniform distribution, which is also the
+    definition of the cardinal B-splines of degree :math:`n-1`
+    having knots evenly spaced from :math:`1` to :math:`n` [4]_ [5]_.
+
+    The Bates distribution, which represents the *mean* of statistically
+    independent, uniformly distributed random variables, is simply the
+    Irwin-Hall distribution scaled by :math:`1/n`. For example, the frozen
+    distribution ``bates = irwinhall(10, scale=1/10)`` represents the
+    distribution of the mean of 10 uniformly distributed random variables.
+    
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] P. Hall, "The distribution of means for samples of size N drawn
+            from a population in which the variate takes values between 0 and 1,
+            all such values being equally probable",
+            Biometrika, Volume 19, Issue 3-4, December 1927, Pages 240-244,
+            :doi:`10.1093/biomet/19.3-4.240`.
+    .. [2] J. O. Irwin, "On the frequency distribution of the means of samples
+            from a population having any law of frequency with finite moments,
+            with special reference to Pearson's Type II,
+            Biometrika, Volume 19, Issue 3-4, December 1927, Pages 225-239,
+            :doi:`0.1093/biomet/19.3-4.225`.
+    .. [3] K. Buchanan, T. Adeyemi, C. Flores-Molina, S. Wheeland and D. Overturf, 
+            "Sidelobe behavior and bandwidth characteristics
+            of distributed antenna arrays,"
+            2018 United States National Committee of
+            URSI National Radio Science Meeting (USNC-URSI NRSM),
+            Boulder, CO, USA, 2018, pp. 1-2.
+            https://www.usnc-ursi-archive.org/nrsm/2018/papers/B15-9.pdf.
+    .. [4] Amos Ron, "Lecture 1: Cardinal B-splines and convolution operators", p. 1
+            https://pages.cs.wisc.edu/~deboor/887/lec1new.pdf.
+    .. [5] Trefethen, N. (2012, July). B-splines and convolution. Chebfun. 
+            Retrieved April 30, 2024, from http://www.chebfun.org/examples/approx/BSplineConv.html.
+
+    %(example)s
+    """  # noqa: E501
+
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        Raises a ``NotImplementedError`` for the Irwin-Hall distribution because
+        the generic `fit` implementation is unreliable and no custom implementation
+        is available. Consider using `scipy.stats.fit`.\n\n""")
+    def fit(self, data, *args, **kwds):
+        fit_notes = ("The generic `fit` implementation is unreliable for this "
+                     "distribution, and no custom implementation is available. "
+                     "Consider using `scipy.stats.fit`.")
+        raise NotImplementedError(fit_notes)
+
+    def _argcheck(self, n):
+        return (n > 0) & _isintegral(n) & np.isrealobj(n)
+
+    def _get_support(self, n):
+        return 0, n
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _munp(self, order, n):
+        # see https://link.springer.com/content/pdf/10.1007/s10959-020-01050-9.pdf
+        # page 640, with m=n, j=n+order
+        def vmunp(order, n):
+            n = np.asarray(n, dtype=np.int64)
+            return (sc.stirling2(n+order, n, exact=True)
+                    / sc.comb(n+order, n, exact=True))
+
+        # exact rationals, but we convert to float anyway
+        return np.vectorize(vmunp, otypes=[np.float64])(order, n)
+
+    @staticmethod
+    def _cardbspl(n):
+        t = np.arange(n+1)
+        return BSpline.basis_element(t)
+
+    def _pdf(self, x, n):
+        def vpdf(x, n):
+            return self._cardbspl(n)(x)
+        return np.vectorize(vpdf, otypes=[np.float64])(x, n)
+
+    def _cdf(self, x, n):
+        def vcdf(x, n):
+            return self._cardbspl(n).antiderivative()(x)
+        return np.vectorize(vcdf, otypes=[np.float64])(x, n)
+
+    def _sf(self, x, n):
+        def vsf(x, n):
+            return self._cardbspl(n).antiderivative()(n-x)
+        return np.vectorize(vsf, otypes=[np.float64])(x, n)
+
+    def _rvs(self, n, size=None, random_state=None, *args):
+        @_vectorize_rvs_over_shapes
+        def _rvs1(n, size=None, random_state=None):
+            n = np.floor(n).astype(int)
+            usize = (n,) if size is None else (n, *size)
+            return random_state.uniform(size=usize).sum(axis=0)
+        return _rvs1(n, size=size, random_state=random_state)
+
+    def _stats(self, n):
+        # mgf = ((exp(t) - 1)/t)**n
+        # m'th derivative follows from the generalized Leibniz rule
+        # Moments follow directly from the definition as the sum of n iid unif(0,1)
+        # and the summation rules for moments of a sum of iid random variables
+        # E(IH((n))) = n*E(U(0,1)) = n/2
+        # Var(IH((n))) = n*Var(U(0,1)) = n/12
+        # Skew(IH((n))) = Skew(U(0,1))/sqrt(n) = 0
+        # Kurt(IH((n))) = Kurt(U(0,1))/n = -6/(5*n) -- Fisher's excess kurtosis
+        # See e.g. https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution
+
+        return n/2, n/12, 0, -6/(5*n)
+
+
+irwinhall = irwinhall_gen(name="irwinhall")
+irwinhall._support = (0.0, 'n')
+
+
+class recipinvgauss_gen(rv_continuous):
+    r"""A reciprocal inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `recipinvgauss` is:
+
+    .. math::
+
+        f(x, \mu) = \frac{1}{\sqrt{2\pi x}}
+                    \exp\left(\frac{-(1-\mu x)^2}{2\mu^2x}\right)
+
+    for :math:`x \ge 0`.
+
+    `recipinvgauss` takes ``mu`` as a shape parameter for :math:`\mu`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, mu):
+        # recipinvgauss.pdf(x, mu) =
+        #                     1/sqrt(2*pi*x) * exp(-(1-mu*x)**2/(2*x*mu**2))
+        return np.exp(self._logpdf(x, mu))
+
+    def _logpdf(self, x, mu):
+        return _lazywhere(x > 0, (x, mu),
+                          lambda x, mu: (-(1 - mu*x)**2.0 / (2*x*mu**2.0)
+                                         - 0.5*np.log(2*np.pi*x)),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x, mu):
+        trm1 = 1.0/mu - x
+        trm2 = 1.0/mu + x
+        isqx = 1.0/np.sqrt(x)
+        return _norm_cdf(-isqx*trm1) - np.exp(2.0/mu)*_norm_cdf(-isqx*trm2)
+
+    def _sf(self, x, mu):
+        trm1 = 1.0/mu - x
+        trm2 = 1.0/mu + x
+        isqx = 1.0/np.sqrt(x)
+        return _norm_cdf(isqx*trm1) + np.exp(2.0/mu)*_norm_cdf(-isqx*trm2)
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return 1.0/random_state.wald(mu, 1.0, size=size)
+
+
+recipinvgauss = recipinvgauss_gen(a=0.0, name='recipinvgauss')
+
+
+class semicircular_gen(rv_continuous):
+    r"""A semicircular continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    rdist
+
+    Notes
+    -----
+    The probability density function for `semicircular` is:
+
+    .. math::
+
+        f(x) = \frac{2}{\pi} \sqrt{1-x^2}
+
+    for :math:`-1 \le x \le 1`.
+
+    The distribution is a special case of `rdist` with ``c = 3``.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Wigner semicircle distribution",
+           https://en.wikipedia.org/wiki/Wigner_semicircle_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        return 2.0/np.pi*np.sqrt(1-x*x)
+
+    def _logpdf(self, x):
+        return np.log(2/np.pi) + 0.5*sc.log1p(-x*x)
+
+    def _cdf(self, x):
+        return 0.5+1.0/np.pi*(x*np.sqrt(1-x*x) + np.arcsin(x))
+
+    def _ppf(self, q):
+        return rdist._ppf(q, 3)
+
+    def _rvs(self, size=None, random_state=None):
+        # generate values uniformly distributed on the area under the pdf
+        # (semi-circle) by randomly generating the radius and angle
+        r = np.sqrt(random_state.uniform(size=size))
+        a = np.cos(np.pi * random_state.uniform(size=size))
+        return r * a
+
+    def _stats(self):
+        return 0, 0.25, 0, -1.0
+
+    def _entropy(self):
+        return 0.64472988584940017414
+
+
+semicircular = semicircular_gen(a=-1.0, b=1.0, name="semicircular")
+
+
+class skewcauchy_gen(rv_continuous):
+    r"""A skewed Cauchy random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    cauchy : Cauchy distribution
+
+    Notes
+    -----
+
+    The probability density function for `skewcauchy` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi \left(\frac{x^2}{\left(a\, \text{sign}(x) + 1
+                                                   \right)^2} + 1 \right)}
+
+    for a real number :math:`x` and skewness parameter :math:`-1 < a < 1`.
+
+    When :math:`a=0`, the distribution reduces to the usual Cauchy
+    distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Skewed generalized *t* distribution", Wikipedia
+       https://en.wikipedia.org/wiki/Skewed_generalized_t_distribution#Skewed_Cauchy_distribution
+
+    %(example)s
+
+    """
+    def _argcheck(self, a):
+        return np.abs(a) < 1
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (-1.0, 1.0), (False, False))]
+
+    def _pdf(self, x, a):
+        return 1 / (np.pi * (x**2 / (a * np.sign(x) + 1)**2 + 1))
+
+    def _cdf(self, x, a):
+        return np.where(x <= 0,
+                        (1 - a) / 2 + (1 - a) / np.pi * np.arctan(x / (1 - a)),
+                        (1 - a) / 2 + (1 + a) / np.pi * np.arctan(x / (1 + a)))
+
+    def _ppf(self, x, a):
+        i = x < self._cdf(0, a)
+        return np.where(i,
+                        np.tan(np.pi / (1 - a) * (x - (1 - a) / 2)) * (1 - a),
+                        np.tan(np.pi / (1 + a) * (x - (1 - a) / 2)) * (1 + a))
+
+    def _stats(self, a, moments='mvsk'):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _fitstart(self, data):
+        # Use 0 as the initial guess of the skewness shape parameter.
+        # For the location and scale, estimate using the median and
+        # quartiles.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return 0.0, p50, (p75 - p25)/2
+
+
+skewcauchy = skewcauchy_gen(name='skewcauchy')
+
+
+class skewnorm_gen(rv_continuous):
+    r"""A skew-normal random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The pdf is::
+
+        skewnorm.pdf(x, a) = 2 * norm.pdf(x) * norm.cdf(a*x)
+
+    `skewnorm` takes a real number :math:`a` as a skewness parameter
+    When ``a = 0`` the distribution is identical to a normal distribution
+    (`norm`). `rvs` implements the method of [1]_.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of ``cdf``, ``ppf`` and ``isf`` methods. [2]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] A. Azzalini and A. Capitanio (1999). Statistical applications of
+        the multivariate skew-normal distribution. J. Roy. Statist. Soc.,
+        B 61, 579-602. :arxiv:`0911.2093`
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, a):
+        return np.isfinite(a)
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (-np.inf, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        return _lazywhere(
+            a == 0, (x, a), lambda x, a: _norm_pdf(x),
+            f2=lambda x, a: 2.*_norm_pdf(x)*_norm_cdf(a*x)
+        )
+
+    def _logpdf(self, x, a):
+        return _lazywhere(
+            a == 0, (x, a), lambda x, a: _norm_logpdf(x),
+            f2=lambda x, a: np.log(2)+_norm_logpdf(x)+_norm_logcdf(a*x),
+        )
+
+    def _cdf(self, x, a):
+        a = np.atleast_1d(a)
+        cdf = scu._skewnorm_cdf(x, 0.0, 1.0, a)
+        # for some reason, a isn't broadcasted if some of x are invalid
+        a = np.broadcast_to(a, cdf.shape)
+        # Boost is not accurate in left tail when a > 0
+        i_small_cdf = (cdf < 1e-6) & (a > 0)
+        cdf[i_small_cdf] = super()._cdf(x[i_small_cdf], a[i_small_cdf])
+        return np.clip(cdf, 0, 1)
+
+    def _ppf(self, x, a):
+        return scu._skewnorm_ppf(x, 0.0, 1.0, a)
+
+    def _sf(self, x, a):
+        # Boost's SF is implemented this way. Use whatever customizations
+        # we made in the _cdf.
+        return self._cdf(-x, -a)
+
+    def _isf(self, x, a):
+        return scu._skewnorm_isf(x, 0.0, 1.0, a)
+
+    def _rvs(self, a, size=None, random_state=None):
+        u0 = random_state.normal(size=size)
+        v = random_state.normal(size=size)
+        d = a/np.sqrt(1 + a**2)
+        u1 = d*u0 + v*np.sqrt(1 - d**2)
+        return np.where(u0 >= 0, u1, -u1)
+
+    def _stats(self, a, moments='mvsk'):
+        output = [None, None, None, None]
+        const = np.sqrt(2/np.pi) * a/np.sqrt(1 + a**2)
+
+        if 'm' in moments:
+            output[0] = const
+        if 'v' in moments:
+            output[1] = 1 - const**2
+        if 's' in moments:
+            output[2] = ((4 - np.pi)/2) * (const/np.sqrt(1 - const**2))**3
+        if 'k' in moments:
+            output[3] = (2*(np.pi - 3)) * (const**4/(1 - const**2)**2)
+
+        return output
+
+    # For odd order, the each noncentral moment of the skew-normal distribution
+    # with location 0 and scale 1 can be expressed as a polynomial in delta,
+    # where delta = a/sqrt(1 + a**2) and `a` is the skew-normal shape
+    # parameter.  The dictionary _skewnorm_odd_moments defines those
+    # polynomials for orders up to 19.  The dict is implemented as a cached
+    # property to reduce the impact of the creation of the dict on import time.
+    @cached_property
+    def _skewnorm_odd_moments(self):
+        skewnorm_odd_moments = {
+            1: Polynomial([1]),
+            3: Polynomial([3, -1]),
+            5: Polynomial([15, -10, 3]),
+            7: Polynomial([105, -105, 63, -15]),
+            9: Polynomial([945, -1260, 1134, -540, 105]),
+            11: Polynomial([10395, -17325, 20790, -14850, 5775, -945]),
+            13: Polynomial([135135, -270270, 405405, -386100, 225225, -73710,
+                            10395]),
+            15: Polynomial([2027025, -4729725, 8513505, -10135125, 7882875,
+                            -3869775, 1091475, -135135]),
+            17: Polynomial([34459425, -91891800, 192972780, -275675400,
+                            268017750, -175429800, 74220300, -18378360,
+                            2027025]),
+            19: Polynomial([654729075, -1964187225, 4714049340, -7856748900,
+                            9166207050, -7499623950, 4230557100, -1571349780,
+                            346621275, -34459425]),
+        }
+        return skewnorm_odd_moments
+
+    def _munp(self, order, a):
+        if order % 2:
+            if order > 19:
+                raise NotImplementedError("skewnorm noncentral moments not "
+                                          "implemented for odd orders greater "
+                                          "than 19.")
+            # Use the precomputed polynomials that were derived from the
+            # moment generating function.
+            delta = a/np.sqrt(1 + a**2)
+            return (delta * self._skewnorm_odd_moments[order](delta**2)
+                    * _SQRT_2_OVER_PI)
+        else:
+            # For even order, the moment is just (order-1)!!, where !! is the
+            # notation for the double factorial; for an odd integer m, m!! is
+            # m*(m-2)*...*3*1.
+            # We could use special.factorial2, but we know the argument is odd,
+            # so avoid the overhead of that function and compute the result
+            # directly here.
+            return sc.gamma((order + 1)/2) * 2**(order/2) / _SQRT_PI
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        If ``method='mm'``, parameters fixed by the user are respected, and the
+        remaining parameters are used to match distribution and sample moments
+        where possible. For example, if the user fixes the location with
+        ``floc``, the parameters will only match the distribution skewness and
+        variance to the sample skewness and variance; no attempt will be made
+        to match the means or minimize a norm of the errors.
+        Note that the maximum possible skewness magnitude of a
+        `scipy.stats.skewnorm` distribution is approximately 0.9952717; if the
+        magnitude of the data's sample skewness exceeds this, the returned
+        shape parameter ``a`` will be infinite.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop("superfit", False):
+            return super().fit(data, *args, **kwds)
+        if isinstance(data, CensoredData):
+            if data.num_censored() == 0:
+                data = data._uncensor()
+            else:
+                return super().fit(data, *args, **kwds)
+
+        # this extracts fixed shape, location, and scale however they
+        # are specified, and also leaves them in `kwds`
+        data, fa, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+        method = kwds.get("method", "mle").lower()
+
+        # See https://en.wikipedia.org/wiki/Skew_normal_distribution for
+        # moment formulas.
+        def skew_d(d):  # skewness in terms of delta
+            return (4-np.pi)/2 * ((d * np.sqrt(2 / np.pi))**3
+                                  / (1 - 2*d**2 / np.pi)**(3/2))
+
+        def d_skew(skew):  # delta in terms of skewness
+            s_23 = np.abs(skew)**(2/3)
+            return np.sign(skew) * np.sqrt(
+                np.pi/2 * s_23 / (s_23 + ((4 - np.pi)/2)**(2/3))
+            )
+
+        # If method is method of moments, we don't need the user's guesses.
+        # Otherwise, extract the guesses from args and kwds.
+        if method == "mm":
+            a, loc, scale = None, None, None
+        else:
+            a = args[0] if len(args) else None
+            loc = kwds.pop('loc', None)
+            scale = kwds.pop('scale', None)
+
+        if fa is None and a is None:  # not fixed and no guess: use MoM
+            # Solve for a that matches sample distribution skewness to sample
+            # skewness.
+            s = stats.skew(data)
+            if method == 'mle':
+                # For MLE initial conditions, clip skewness to a large but
+                # reasonable value in case the data skewness is out-of-range.
+                s = np.clip(s, -0.99, 0.99)
+            else:
+                s_max = skew_d(1)
+                s = np.clip(s, -s_max, s_max)
+            d = d_skew(s)
+            with np.errstate(divide='ignore'):
+                a = np.sqrt(np.divide(d**2, (1-d**2)))*np.sign(s)
+        else:
+            a = fa if fa is not None else a
+            d = a / np.sqrt(1 + a**2)
+
+        if fscale is None and scale is None:
+            v = np.var(data)
+            scale = np.sqrt(v / (1 - 2*d**2/np.pi))
+        elif fscale is not None:
+            scale = fscale
+
+        if floc is None and loc is None:
+            m = np.mean(data)
+            loc = m - scale*d*np.sqrt(2/np.pi)
+        elif floc is not None:
+            loc = floc
+
+        if method == 'mm':
+            return a, loc, scale
+        else:
+            # At this point, parameter "guesses" may equal the fixed parameters
+            # in kwds. No harm in passing them as guesses, too.
+            return super().fit(data, a, loc=loc, scale=scale, **kwds)
+
+
+skewnorm = skewnorm_gen(name='skewnorm')
+
+
+class trapezoid_gen(rv_continuous):
+    r"""A trapezoidal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The trapezoidal distribution can be represented with an up-sloping line
+    from ``loc`` to ``(loc + c*scale)``, then constant to ``(loc + d*scale)``
+    and then downsloping from ``(loc + d*scale)`` to ``(loc+scale)``.  This
+    defines the trapezoid base from ``loc`` to ``(loc+scale)`` and the flat
+    top from ``c`` to ``d`` proportional to the position along the base
+    with ``0 <= c <= d <= 1``.  When ``c=d``, this is equivalent to `triang`
+    with the same values for `loc`, `scale` and `c`.
+    The method of [1]_ is used for computing moments.
+
+    `trapezoid` takes :math:`c` and :math:`d` as shape parameters.
+
+    %(after_notes)s
+
+    The standard form is in the range [0, 1] with c the mode.
+    The location parameter shifts the start to `loc`.
+    The scale parameter changes the width from 1 to `scale`.
+
+    %(example)s
+
+    References
+    ----------
+    .. [1] Kacker, R.N. and Lawrence, J.F. (2007). Trapezoidal and triangular
+       distributions for Type B evaluation of standard uncertainty.
+       Metrologia 44, 117-127. :doi:`10.1088/0026-1394/44/2/003`
+
+
+    """
+    def _argcheck(self, c, d):
+        return (c >= 0) & (c <= 1) & (d >= 0) & (d <= 1) & (d >= c)
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, 1.0), (True, True))
+        id = _ShapeInfo("d", False, (0, 1.0), (True, True))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        u = 2 / (d-c+1)
+
+        return _lazyselect([x < c,
+                            (c <= x) & (x <= d),
+                            x > d],
+                           [lambda x, c, d, u: u * x / c,
+                            lambda x, c, d, u: u,
+                            lambda x, c, d, u: u * (1-x) / (1-d)],
+                           (x, c, d, u))
+
+    def _cdf(self, x, c, d):
+        return _lazyselect([x < c,
+                            (c <= x) & (x <= d),
+                            x > d],
+                           [lambda x, c, d: x**2 / c / (d-c+1),
+                            lambda x, c, d: (c + 2 * (x-c)) / (d-c+1),
+                            lambda x, c, d: 1-((1-x) ** 2
+                                               / (d-c+1) / (1-d))],
+                           (x, c, d))
+
+    def _ppf(self, q, c, d):
+        qc, qd = self._cdf(c, c, d), self._cdf(d, c, d)
+        condlist = [q < qc, q <= qd, q > qd]
+        choicelist = [np.sqrt(q * c * (1 + d - c)),
+                      0.5 * q * (1 + d - c) + 0.5 * c,
+                      1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))]
+        return np.select(condlist, choicelist)
+
+    def _munp(self, n, c, d):
+        # Using the parameterization from Kacker, 2007, with
+        # a=bottom left, c=top left, d=top right, b=bottom right, then
+        #     E[X^n] = h/(n+1)/(n+2) [(b^{n+2}-d^{n+2})/(b-d)
+        #                             - ((c^{n+2} - a^{n+2})/(c-a)]
+        # with h = 2/((b-a) - (d-c)). The corresponding parameterization
+        # in scipy, has a'=loc, c'=loc+c*scale, d'=loc+d*scale, b'=loc+scale,
+        # which for standard form reduces to a'=0, b'=1, c'=c, d'=d.
+        # Substituting into E[X^n] gives the bd' term as (1 - d^{n+2})/(1 - d)
+        # and the ac' term as c^{n-1} for the standard form. The bd' term has
+        # numerical difficulties near d=1, so replace (1 - d^{n+2})/(1-d)
+        # with expm1((n+2)*log(d))/(d-1).
+        # Testing with n=18 for c=(1e-30,1-eps) shows that this is stable.
+        # We still require an explicit test for d=1 to prevent divide by zero,
+        # and now a test for d=0 to prevent log(0).
+        ab_term = c**(n+1)
+        dc_term = _lazyselect(
+            [d == 0.0, (0.0 < d) & (d < 1.0), d == 1.0],
+            [lambda d: 1.0,
+             lambda d: np.expm1((n+2) * np.log(d)) / (d-1.0),
+             lambda d: n+2],
+            [d])
+        val = 2.0 / (1.0+d-c) * (dc_term - ab_term) / ((n+1) * (n+2))
+        return val
+
+    def _entropy(self, c, d):
+        # Using the parameterization from Wikipedia (van Dorp, 2003)
+        # with a=bottom left, c=top left, d=top right, b=bottom right
+        # gives a'=loc, b'=loc+c*scale, c'=loc+d*scale, d'=loc+scale,
+        # which for loc=0, scale=1 is a'=0, b'=c, c'=d, d'=1.
+        # Substituting into the entropy formula from Wikipedia gives
+        # the following result.
+        return 0.5 * (1.0-d+c) / (1.0+d-c) + np.log(0.5 * (1.0+d-c))
+
+
+# deprecation of trapz, see #20486
+deprmsg = ("`trapz` is deprecated in favour of `trapezoid` "
+           "and will be removed in SciPy 1.16.0.")
+
+
+class trapz_gen(trapezoid_gen):
+    # override __call__ protocol from rv_generic to also
+    # deprecate instantiation of frozen distributions
+    """
+
+    .. deprecated:: 1.14.0
+        `trapz` is deprecated and will be removed in SciPy 1.16.
+        Plese use `trapezoid` instead!
+    """
+    def __call__(self, *args, **kwds):
+        warnings.warn(deprmsg, DeprecationWarning, stacklevel=2)
+        return self.freeze(*args, **kwds)
+
+
+trapezoid = trapezoid_gen(a=0.0, b=1.0, name="trapezoid")
+trapz = trapz_gen(a=0.0, b=1.0, name="trapz")
+
+# since the deprecated class gets intantiated upon import (and we only want to
+# warn upon use), add the deprecation to each class method
+_method_names = [
+    "cdf", "entropy", "expect", "fit", "interval", "isf", "logcdf", "logpdf",
+    "logsf", "mean", "median", "moment", "pdf", "ppf", "rvs", "sf", "stats",
+    "std", "var"
+]
+
+
+class _DeprecationWrapper:
+    def __init__(self, method):
+        self.msg = (f"`trapz.{method}` is deprecated in favour of trapezoid.{method}. "
+                     "Please replace all uses of the distribution class "
+                     "`trapz` with `trapezoid`. `trapz` will be removed in SciPy 1.16.")
+        self.method = getattr(trapezoid, method)
+
+    def __call__(self, *args, **kwargs):
+        warnings.warn(self.msg, DeprecationWarning, stacklevel=2)
+        return self.method(*args, **kwargs)
+
+
+for m in _method_names:
+    setattr(trapz, m, _DeprecationWrapper(m))
+
+
+class triang_gen(rv_continuous):
+    r"""A triangular continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The triangular distribution can be represented with an up-sloping line from
+    ``loc`` to ``(loc + c*scale)`` and then downsloping for ``(loc + c*scale)``
+    to ``(loc + scale)``.
+
+    `triang` takes ``c`` as a shape parameter for :math:`0 \le c \le 1`.
+
+    %(after_notes)s
+
+    The standard form is in the range [0, 1] with c the mode.
+    The location parameter shifts the start to `loc`.
+    The scale parameter changes the width from 1 to `scale`.
+
+    %(example)s
+
+    """
+    def _rvs(self, c, size=None, random_state=None):
+        return random_state.triangular(0, c, 1, size)
+
+    def _argcheck(self, c):
+        return (c >= 0) & (c <= 1)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, 1.0), (True, True))]
+
+    def _pdf(self, x, c):
+        # 0: edge case where c=0
+        # 1: generalised case for x < c, don't use x <= c, as it doesn't cope
+        #    with c = 0.
+        # 2: generalised case for x >= c, but doesn't cope with c = 1
+        # 3: edge case where c=1
+        r = _lazyselect([c == 0,
+                         x < c,
+                         (x >= c) & (c != 1),
+                         c == 1],
+                        [lambda x, c: 2 - 2 * x,
+                         lambda x, c: 2 * x / c,
+                         lambda x, c: 2 * (1 - x) / (1 - c),
+                         lambda x, c: 2 * x],
+                        (x, c))
+        return r
+
+    def _cdf(self, x, c):
+        r = _lazyselect([c == 0,
+                         x < c,
+                         (x >= c) & (c != 1),
+                         c == 1],
+                        [lambda x, c: 2*x - x*x,
+                         lambda x, c: x * x / c,
+                         lambda x, c: (x*x - 2*x + c) / (c-1),
+                         lambda x, c: x * x],
+                        (x, c))
+        return r
+
+    def _ppf(self, q, c):
+        return np.where(q < c, np.sqrt(c * q), 1-np.sqrt((1-c) * (1-q)))
+
+    def _stats(self, c):
+        return ((c+1.0)/3.0,
+                (1.0-c+c*c)/18,
+                np.sqrt(2)*(2*c-1)*(c+1)*(c-2) / (5*np.power((1.0-c+c*c), 1.5)),
+                -3.0/5.0)
+
+    def _entropy(self, c):
+        return 0.5-np.log(2)
+
+
+triang = triang_gen(a=0.0, b=1.0, name="triang")
+
+
+class truncexpon_gen(rv_continuous):
+    r"""A truncated exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `truncexpon` is:
+
+    .. math::
+
+        f(x, b) = \frac{\exp(-x)}{1 - \exp(-b)}
+
+    for :math:`0 <= x <= b`.
+
+    `truncexpon` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, b):
+        return self.a, b
+
+    def _pdf(self, x, b):
+        # truncexpon.pdf(x, b) = exp(-x) / (1-exp(-b))
+        return np.exp(-x)/(-sc.expm1(-b))
+
+    def _logpdf(self, x, b):
+        return -x - np.log(-sc.expm1(-b))
+
+    def _cdf(self, x, b):
+        return sc.expm1(-x)/sc.expm1(-b)
+
+    def _ppf(self, q, b):
+        return -sc.log1p(q*sc.expm1(-b))
+
+    def _sf(self, x, b):
+        return (np.exp(-b) - np.exp(-x))/sc.expm1(-b)
+
+    def _isf(self, q, b):
+        return -np.log(np.exp(-b) - q * sc.expm1(-b))
+
+    def _munp(self, n, b):
+        # wrong answer with formula, same as in continuous.pdf
+        # return sc.gamman+1)-sc.gammainc1+n, b)
+        if n == 1:
+            return (1-(b+1)*np.exp(-b))/(-sc.expm1(-b))
+        elif n == 2:
+            return 2*(1-0.5*(b*b+2*b+2)*np.exp(-b))/(-sc.expm1(-b))
+        else:
+            # return generic for higher moments
+            return super()._munp(n, b)
+
+    def _entropy(self, b):
+        eB = np.exp(b)
+        return np.log(eB-1)+(1+eB*(b-1.0))/(1.0-eB)
+
+
+truncexpon = truncexpon_gen(a=0.0, name='truncexpon')
+truncexpon._support = (0.0, 'b')
+
+
+# logsumexp trick for log(p + q) with only log(p) and log(q)
+def _log_sum(log_p, log_q):
+    return sc.logsumexp([log_p, log_q], axis=0)
+
+
+# same as above, but using -exp(x) = exp(x + πi)
+def _log_diff(log_p, log_q):
+    return sc.logsumexp([log_p, log_q+np.pi*1j], axis=0)
+
+
+def _log_gauss_mass(a, b):
+    """Log of Gaussian probability mass within an interval"""
+    a, b = np.broadcast_arrays(a, b)
+
+    # Calculations in right tail are inaccurate, so we'll exploit the
+    # symmetry and work only in the left tail
+    case_left = b <= 0
+    case_right = a > 0
+    case_central = ~(case_left | case_right)
+
+    def mass_case_left(a, b):
+        return _log_diff(_norm_logcdf(b), _norm_logcdf(a))
+
+    def mass_case_right(a, b):
+        return mass_case_left(-b, -a)
+
+    def mass_case_central(a, b):
+        # Previously, this was implemented as:
+        # left_mass = mass_case_left(a, 0)
+        # right_mass = mass_case_right(0, b)
+        # return _log_sum(left_mass, right_mass)
+        # Catastrophic cancellation occurs as np.exp(log_mass) approaches 1.
+        # Correct for this with an alternative formulation.
+        # We're not concerned with underflow here: if only one term
+        # underflows, it was insignificant; if both terms underflow,
+        # the result can't accurately be represented in logspace anyway
+        # because sc.log1p(x) ~ x for small x.
+        return sc.log1p(-_norm_cdf(a) - _norm_cdf(-b))
+
+    # _lazyselect not working; don't care to debug it
+    out = np.full_like(a, fill_value=np.nan, dtype=np.complex128)
+    if a[case_left].size:
+        out[case_left] = mass_case_left(a[case_left], b[case_left])
+    if a[case_right].size:
+        out[case_right] = mass_case_right(a[case_right], b[case_right])
+    if a[case_central].size:
+        out[case_central] = mass_case_central(a[case_central], b[case_central])
+    return np.real(out)  # discard ~0j
+
+
+class truncnorm_gen(rv_continuous):
+    r"""A truncated normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    This distribution is the normal distribution centered on ``loc`` (default
+    0), with standard deviation ``scale`` (default 1), and truncated at ``a``
+    and ``b`` *standard deviations* from ``loc``. For arbitrary ``loc`` and
+    ``scale``, ``a`` and ``b`` are *not* the abscissae at which the shifted
+    and scaled distribution is truncated.
+
+    .. note::
+        If ``a_trunc`` and ``b_trunc`` are the abscissae at which we wish
+        to truncate the distribution (as opposed to the number of standard
+        deviations from ``loc``), then we can calculate the distribution
+        parameters ``a`` and ``b`` as follows::
+
+            a, b = (a_trunc - loc) / scale, (b_trunc - loc) / scale
+
+        This is a common point of confusion. For additional clarification,
+        please see the example below.
+
+    %(example)s
+
+    In the examples above, ``loc=0`` and ``scale=1``, so the plot is truncated
+    at ``a`` on the left and ``b`` on the right. However, suppose we were to
+    produce the same histogram with ``loc = 1`` and ``scale=0.5``.
+
+    >>> loc, scale = 1, 0.5
+    >>> rv = truncnorm(a, b, loc=loc, scale=scale)
+    >>> x = np.linspace(truncnorm.ppf(0.01, a, b),
+    ...                 truncnorm.ppf(0.99, a, b), 100)
+    >>> r = rv.rvs(size=1000)
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim(a, b)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Note that the distribution is no longer appears to be truncated at
+    abscissae ``a`` and ``b``. That is because the *standard* normal
+    distribution is first truncated at ``a`` and ``b``, *then* the resulting
+    distribution is scaled by ``scale`` and shifted by ``loc``. If we instead
+    want the shifted and scaled distribution to be truncated at ``a`` and
+    ``b``, we need to transform these values before passing them as the
+    distribution parameters.
+
+    >>> a_transformed, b_transformed = (a - loc) / scale, (b - loc) / scale
+    >>> rv = truncnorm(a_transformed, b_transformed, loc=loc, scale=scale)
+    >>> x = np.linspace(truncnorm.ppf(0.01, a, b),
+    ...                 truncnorm.ppf(0.99, a, b), 100)
+    >>> r = rv.rvs(size=10000)
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim(a-0.1, b+0.1)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+    """
+
+    def _argcheck(self, a, b):
+        return a < b
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, True))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        # Reasonable, since support is [a, b]
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        return super()._fitstart(data, args=(np.min(data), np.max(data)))
+
+    def _get_support(self, a, b):
+        return a, b
+
+    def _pdf(self, x, a, b):
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return _norm_logpdf(x) - _log_gauss_mass(a, b)
+
+    def _cdf(self, x, a, b):
+        return np.exp(self._logcdf(x, a, b))
+
+    def _logcdf(self, x, a, b):
+        x, a, b = np.broadcast_arrays(x, a, b)
+        logcdf = np.asarray(_log_gauss_mass(a, x) - _log_gauss_mass(a, b))
+        i = logcdf > -0.1  # avoid catastrophic cancellation
+        if np.any(i):
+            logcdf[i] = np.log1p(-np.exp(self._logsf(x[i], a[i], b[i])))
+        return logcdf
+
+    def _sf(self, x, a, b):
+        return np.exp(self._logsf(x, a, b))
+
+    def _logsf(self, x, a, b):
+        x, a, b = np.broadcast_arrays(x, a, b)
+        logsf = np.asarray(_log_gauss_mass(x, b) - _log_gauss_mass(a, b))
+        i = logsf > -0.1  # avoid catastrophic cancellation
+        if np.any(i):
+            logsf[i] = np.log1p(-np.exp(self._logcdf(x[i], a[i], b[i])))
+        return logsf
+
+    def _entropy(self, a, b):
+        A = _norm_cdf(a)
+        B = _norm_cdf(b)
+        Z = B - A
+        C = np.log(np.sqrt(2 * np.pi * np.e) * Z)
+        D = (a * _norm_pdf(a) - b * _norm_pdf(b)) / (2 * Z)
+        h = C + D
+        return h
+
+    def _ppf(self, q, a, b):
+        q, a, b = np.broadcast_arrays(q, a, b)
+
+        case_left = a < 0
+        case_right = ~case_left
+
+        def ppf_left(q, a, b):
+            log_Phi_x = _log_sum(_norm_logcdf(a),
+                                 np.log(q) + _log_gauss_mass(a, b))
+            return sc.ndtri_exp(log_Phi_x)
+
+        def ppf_right(q, a, b):
+            log_Phi_x = _log_sum(_norm_logcdf(-b),
+                                 np.log1p(-q) + _log_gauss_mass(a, b))
+            return -sc.ndtri_exp(log_Phi_x)
+
+        out = np.empty_like(q)
+
+        q_left = q[case_left]
+        q_right = q[case_right]
+
+        if q_left.size:
+            out[case_left] = ppf_left(q_left, a[case_left], b[case_left])
+        if q_right.size:
+            out[case_right] = ppf_right(q_right, a[case_right], b[case_right])
+
+        return out
+
+    def _isf(self, q, a, b):
+        # Mostly copy-paste of _ppf, but I think this is simpler than combining
+        q, a, b = np.broadcast_arrays(q, a, b)
+
+        case_left = b < 0
+        case_right = ~case_left
+
+        def isf_left(q, a, b):
+            log_Phi_x = _log_diff(_norm_logcdf(b),
+                                  np.log(q) + _log_gauss_mass(a, b))
+            return sc.ndtri_exp(np.real(log_Phi_x))
+
+        def isf_right(q, a, b):
+            log_Phi_x = _log_diff(_norm_logcdf(-a),
+                                  np.log1p(-q) + _log_gauss_mass(a, b))
+            return -sc.ndtri_exp(np.real(log_Phi_x))
+
+        out = np.empty_like(q)
+
+        q_left = q[case_left]
+        q_right = q[case_right]
+
+        if q_left.size:
+            out[case_left] = isf_left(q_left, a[case_left], b[case_left])
+        if q_right.size:
+            out[case_right] = isf_right(q_right, a[case_right], b[case_right])
+
+        return out
+
+    def _munp(self, n, a, b):
+        def n_th_moment(n, a, b):
+            """
+            Returns n-th moment. Defined only if n >= 0.
+            Function cannot broadcast due to the loop over n
+            """
+            pA, pB = self._pdf(np.asarray([a, b]), a, b)
+            probs = [pA, -pB]
+            moments = [0, 1]
+            for k in range(1, n+1):
+                # a or b might be infinite, and the corresponding pdf value
+                # is 0 in that case, but nan is returned for the
+                # multiplication.  However, as b->infinity,  pdf(b)*b**k -> 0.
+                # So it is safe to use _lazywhere to avoid the nan.
+                vals = _lazywhere(probs, [probs, [a, b]],
+                                  lambda x, y: x * y**(k-1), fillvalue=0)
+                mk = np.sum(vals) + (k-1) * moments[-2]
+                moments.append(mk)
+            return moments[-1]
+
+        return _lazywhere((n >= 0) & (a == a) & (b == b), (n, a, b),
+                          np.vectorize(n_th_moment, otypes=[np.float64]),
+                          np.nan)
+
+    def _stats(self, a, b, moments='mv'):
+        pA, pB = self.pdf(np.array([a, b]), a, b)
+
+        def _truncnorm_stats_scalar(a, b, pA, pB, moments):
+            m1 = pA - pB
+            mu = m1
+            # use _lazywhere to avoid nan (See detailed comment in _munp)
+            probs = [pA, -pB]
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y,
+                              fillvalue=0)
+            m2 = 1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a-mu, b-mu]], lambda x, y: x*y,
+                              fillvalue=0)
+            # mu2 = m2 - mu**2, but not as numerically stable as:
+            # mu2 = (a-mu)*pA - (b-mu)*pB + 1
+            mu2 = 1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**2,
+                              fillvalue=0)
+            m3 = 2*m1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**3,
+                              fillvalue=0)
+            m4 = 3*m2 + np.sum(vals)
+
+            mu3 = m3 + m1 * (-3*m2 + 2*m1**2)
+            g1 = mu3 / np.power(mu2, 1.5)
+            mu4 = m4 + m1*(-4*m3 + 3*m1*(2*m2 - m1**2))
+            g2 = mu4 / mu2**2 - 3
+            return mu, mu2, g1, g2
+
+        _truncnorm_stats = np.vectorize(_truncnorm_stats_scalar,
+                                        excluded=('moments',))
+        return _truncnorm_stats(a, b, pA, pB, moments)
+
+
+truncnorm = truncnorm_gen(name='truncnorm', momtype=1)
+truncnorm._support = ('a', 'b')
+
+
+class truncpareto_gen(rv_continuous):
+    r"""An upper truncated Pareto continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    pareto : Pareto distribution
+
+    Notes
+    -----
+    The probability density function for `truncpareto` is:
+
+    .. math::
+
+        f(x, b, c) = \frac{b}{1 - c^{-b}} \frac{1}{x^{b+1}}
+
+    for :math:`b > 0`, :math:`c > 1` and :math:`1 \le x \le c`.
+
+    `truncpareto` takes `b` and `c` as shape parameters for :math:`b` and
+    :math:`c`.
+
+    Notice that the upper truncation value :math:`c` is defined in
+    standardized form so that random values of an unscaled, unshifted variable
+    are within the range ``[1, c]``.
+    If ``u_r`` is the upper bound to a scaled and/or shifted variable,
+    then ``c = (u_r - loc) / scale``. In other words, the support of the
+    distribution becomes ``(scale + loc) <= x <= (c*scale + loc)`` when
+    `scale` and/or `loc` are provided.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Burroughs, S. M., and Tebbens S. F.
+        "Upper-truncated power laws in natural systems."
+        Pure and Applied Geophysics 158.4 (2001): 741-757.
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        ib = _ShapeInfo("b", False, (0.0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (1.0, np.inf), (False, False))
+        return [ib, ic]
+
+    def _argcheck(self, b, c):
+        return (b > 0.) & (c > 1.)
+
+    def _get_support(self, b, c):
+        return self.a, c
+
+    def _pdf(self, x, b, c):
+        return b * x**-(b+1) / (1 - 1/c**b)
+
+    def _logpdf(self, x, b, c):
+        return np.log(b) - np.log(-np.expm1(-b*np.log(c))) - (b+1)*np.log(x)
+
+    def _cdf(self, x, b, c):
+        return (1 - x**-b) / (1 - 1/c**b)
+
+    def _logcdf(self, x, b, c):
+        return np.log1p(-x**-b) - np.log1p(-1/c**b)
+
+    def _ppf(self, q, b, c):
+        return pow(1 - (1 - 1/c**b)*q, -1/b)
+
+    def _sf(self, x, b, c):
+        return (x**-b - 1/c**b) / (1 - 1/c**b)
+
+    def _logsf(self, x, b, c):
+        return np.log(x**-b - 1/c**b) - np.log1p(-1/c**b)
+
+    def _isf(self, q, b, c):
+        return pow(1/c**b + (1 - 1/c**b)*q, -1/b)
+
+    def _entropy(self, b, c):
+        return -(np.log(b/(1 - 1/c**b))
+                 + (b+1)*(np.log(c)/(c**b - 1) - 1/b))
+
+    def _munp(self, n, b, c):
+        if (n == b).all():
+            return b*np.log(c) / (1 - 1/c**b)
+        else:
+            return b / (b-n) * (c**b - c**n) / (c**b - 1)
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        b, loc, scale = pareto.fit(data)
+        c = (max(data) - loc)/scale
+        return b, c, loc, scale
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop("superfit", False):
+            return super().fit(data, *args, **kwds)
+
+        def log_mean(x):
+            return np.mean(np.log(x))
+
+        def harm_mean(x):
+            return 1/np.mean(1/x)
+
+        def get_b(c, loc, scale):
+            u = (data-loc)/scale
+            harm_m = harm_mean(u)
+            log_m = log_mean(u)
+            quot = (harm_m-1)/log_m
+            return (1 - (quot-1) / (quot - (1 - 1/c)*harm_m/np.log(c)))/log_m
+
+        def get_c(loc, scale):
+            return (mx - loc)/scale
+
+        def get_loc(fc, fscale):
+            if fscale:  # (fscale and fc) or (fscale and not fc)
+                loc = mn - fscale
+                return loc
+            if fc:
+                loc = (fc*mn - mx)/(fc - 1)
+                return loc
+
+        def get_scale(loc):
+            return mn - loc
+
+        # Functions used for optimisation; partial derivatives of
+        # the Lagrangian, set to equal 0.
+
+        def dL_dLoc(loc, b_=None):
+            # Partial derivative wrt location.
+            # Optimised upon when no parameters, or only b, are fixed.
+            scale = get_scale(loc)
+            c = get_c(loc, scale)
+            b = get_b(c, loc, scale) if b_ is None else b_
+            harm_m = harm_mean((data - loc)/scale)
+            return 1 - (1 + (c - 1)/(c**(b+1) - c)) * (1 - 1/(b+1)) * harm_m
+
+        def dL_dB(b, logc, logm):
+            # Partial derivative wrt b.
+            # Optimised upon whenever at least one parameter but b is fixed,
+            # and b is free.
+            return b - np.log1p(b*logc / (1 - b*logm)) / logc
+
+        def fallback(data, *args, **kwargs):
+            # Should any issue arise, default to the general fit method.
+            return super(truncpareto_gen, self).fit(data, *args, **kwargs)
+
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fb, fc, floc, fscale = parameters
+        mn, mx = data.min(), data.max()
+        mn_inf = np.nextafter(mn, -np.inf)
+
+        if (fb is not None
+                and fc is not None
+                and floc is not None
+                and fscale is not None):
+            raise ValueError("All parameters fixed."
+                             "There is nothing to optimize.")
+        elif fc is None and floc is None and fscale is None:
+            if fb is None:
+                def cond_b(loc):
+                    # b is positive only if this function is positive
+                    scale = get_scale(loc)
+                    c = get_c(loc, scale)
+                    harm_m = harm_mean((data - loc)/scale)
+                    return (1 + 1/(c-1)) * np.log(c) / harm_m - 1
+
+                # This gives an upper bound on loc allowing for a positive b.
+                # Iteratively look for a bracket for root_scalar.
+                mn_inf = np.nextafter(mn, -np.inf)
+                rbrack = mn_inf
+                i = 0
+                lbrack = rbrack - 1
+                while ((lbrack > -np.inf)
+                       and (cond_b(lbrack)*cond_b(rbrack) >= 0)):
+                    i += 1
+                    lbrack = rbrack - np.power(2., i)
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(cond_b, bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+
+                # Determine the MLE for loc.
+                # Iteratively look for a bracket for root_scalar.
+                rbrack = res.root - 1e-3  # grad_loc is numerically ill-behaved
+                lbrack = rbrack - 1
+                i = 0
+                while ((lbrack > -np.inf)
+                       and (dL_dLoc(lbrack)*dL_dLoc(rbrack) >= 0)):
+                    i += 1
+                    lbrack = rbrack - np.power(2., i)
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+                loc = res.root
+                scale = get_scale(loc)
+                c = get_c(loc, scale)
+                b = get_b(c, loc, scale)
+
+                std_data = (data - loc)/scale
+                # The expression of b relies on b being bounded above.
+                up_bound_b = min(1/log_mean(std_data),
+                                 1/(harm_mean(std_data)-1))
+                if not (b < up_bound_b):
+                    return fallback(data, *args, **kwds)
+            else:
+                # We know b is positive (or a FitError will be triggered)
+                # so we let loc get close to min(data).
+                rbrack = mn_inf
+                lbrack = mn_inf - 1
+                i = 0
+                # Iteratively look for a bracket for root_scalar.
+                while (lbrack > -np.inf
+                       and (dL_dLoc(lbrack, fb)
+                            * dL_dLoc(rbrack, fb) >= 0)):
+                    i += 1
+                    lbrack = rbrack - 2**i
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(dL_dLoc, (fb,),
+                                  bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+                loc = res.root
+                scale = get_scale(loc)
+                c = get_c(loc, scale)
+                b = fb
+        else:
+            # At least one of the parameters determining the support is fixed;
+            # the others then have analytical expressions from the constraints.
+            # The completely determined case (fixed c, loc and scale)
+            # has to be checked for not overflowing the support.
+            # If not fixed, b has to be determined numerically.
+            loc = floc if floc is not None else get_loc(fc, fscale)
+            scale = fscale or get_scale(loc)
+            c = fc or get_c(loc, scale)
+
+            # Unscaled, translated values should be positive when the location
+            # is fixed. If it is not the case, we end up with negative `scale`
+            # and `c`, which would trigger a FitError before exiting the
+            # method.
+            if floc is not None and data.min() - floc < 0:
+                raise FitDataError("truncpareto", lower=1, upper=c)
+
+            # Standardised values should be within the distribution support
+            # when all parameters controlling it are fixed. If it not the case,
+            # `fc` is overridden by `c` determined from `floc` and `fscale` when
+            # raising the exception.
+            if fc and (floc is not None) and fscale:
+                if data.max() > fc*fscale + floc:
+                    raise FitDataError("truncpareto", lower=1,
+                                       upper=get_c(loc, scale))
+
+            # The other constraints should be automatically satisfied
+            # from the analytical expressions of the parameters.
+            # If fc or fscale are respectively less than one or less than 0,
+            # a FitError is triggered before exiting the method.
+
+            if fb is None:
+                std_data = (data - loc)/scale
+                logm = log_mean(std_data)
+                logc = np.log(c)
+                # Condition for a positive root to exist.
+                if not (2*logm < logc):
+                    return fallback(data, *args, **kwds)
+
+                lbrack = 1/logm + 1/(logm - logc)
+                rbrack = np.nextafter(1/logm, 0)
+                try:
+                    res = root_scalar(dL_dB, (logc, logm),
+                                      bracket=(lbrack, rbrack))
+                    # we should then never get there
+                    if not res.converged:
+                        return fallback(data, *args, **kwds)
+                    b = res.root
+                except ValueError:
+                    b = rbrack
+            else:
+                b = fb
+
+        # The distribution requires that `scale+loc <= data <= c*scale+loc`.
+        # To avoid numerical issues, some tuning may be necessary.
+        # We adjust `scale` to satisfy the lower bound, and we adjust
+        # `c` to satisfy the upper bound.
+        if not (scale+loc) < mn:
+            if fscale:
+                loc = np.nextafter(loc, -np.inf)
+            else:
+                scale = get_scale(loc)
+                scale = np.nextafter(scale, 0)
+        if not (c*scale+loc) > mx:
+            c = get_c(loc, scale)
+            c = np.nextafter(c, np.inf)
+
+        if not (np.all(self._argcheck(b, c)) and (scale > 0)):
+            return fallback(data, *args, **kwds)
+
+        params_override = b, c, loc, scale
+        if floc is None and fscale is None:
+            # Based on testing in gh-16782, the following methods are only
+            # reliable if either `floc` or `fscale` are provided. They are
+            # fast, though, so might as well see if they are better than the
+            # generic method.
+            params_super = fallback(data, *args, **kwds)
+            nllf_override = self.nnlf(params_override, data)
+            nllf_super = self.nnlf(params_super, data)
+            if nllf_super < nllf_override:
+                return params_super
+
+        return params_override
+
+
+truncpareto = truncpareto_gen(a=1.0, name='truncpareto')
+truncpareto._support = (1.0, 'c')
+
+
+class tukeylambda_gen(rv_continuous):
+    r"""A Tukey-Lamdba continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    A flexible distribution, able to represent and interpolate between the
+    following distributions:
+
+    - Cauchy                (:math:`lambda = -1`)
+    - logistic              (:math:`lambda = 0`)
+    - approx Normal         (:math:`lambda = 0.14`)
+    - uniform from -1 to 1  (:math:`lambda = 1`)
+
+    `tukeylambda` takes a real number :math:`lambda` (denoted ``lam``
+    in the implementation) as a shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, lam):
+        return np.isfinite(lam)
+
+    def _shape_info(self):
+        return [_ShapeInfo("lam", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, lam):
+        b = _lazywhere(lam > 0, (lam,),
+                       f=lambda lam: 1/lam,
+                       fillvalue=np.inf)
+        return -b, b
+
+    def _pdf(self, x, lam):
+        Fx = np.asarray(sc.tklmbda(x, lam))
+        Px = Fx**(lam-1.0) + (np.asarray(1-Fx))**(lam-1.0)
+        with np.errstate(divide='ignore'):
+            Px = 1.0/np.asarray(Px)
+            return np.where((lam <= 0) | (abs(x) < 1.0/np.asarray(lam)), Px, 0.0)
+
+    def _cdf(self, x, lam):
+        return sc.tklmbda(x, lam)
+
+    def _ppf(self, q, lam):
+        return sc.boxcox(q, lam) - sc.boxcox1p(-q, lam)
+
+    def _stats(self, lam):
+        return 0, _tlvar(lam), 0, _tlkurt(lam)
+
+    def _entropy(self, lam):
+        def integ(p):
+            return np.log(pow(p, lam-1)+pow(1-p, lam-1))
+        return integrate.quad(integ, 0, 1)[0]
+
+
+tukeylambda = tukeylambda_gen(name='tukeylambda')
+
+
+class FitUniformFixedScaleDataError(FitDataError):
+    def __init__(self, ptp, fscale):
+        self.args = (
+            "Invalid values in `data`.  Maximum likelihood estimation with "
+            "the uniform distribution and fixed scale requires that "
+            f"np.ptp(data) <= fscale, but np.ptp(data) = {ptp} and "
+            f"fscale = {fscale}."
+        )
+
+
+class uniform_gen(rv_continuous):
+    r"""A uniform continuous random variable.
+
+    In the standard form, the distribution is uniform on ``[0, 1]``. Using
+    the parameters ``loc`` and ``scale``, one obtains the uniform distribution
+    on ``[loc, loc + scale]``.
+
+    %(before_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.uniform(0.0, 1.0, size)
+
+    def _pdf(self, x):
+        return 1.0*(x == x)
+
+    def _cdf(self, x):
+        return x
+
+    def _ppf(self, q):
+        return q
+
+    def _stats(self):
+        return 0.5, 1.0/12, 0, -1.2
+
+    def _entropy(self):
+        return 0.0
+
+    @_call_super_mom
+    def fit(self, data, *args, **kwds):
+        """
+        Maximum likelihood estimate for the location and scale parameters.
+
+        `uniform.fit` uses only the following parameters.  Because exact
+        formulas are used, the parameters related to optimization that are
+        available in the `fit` method of other distributions are ignored
+        here.  The only positional argument accepted is `data`.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to use in calculating the maximum likelihood estimate.
+        floc : float, optional
+            Hold the location parameter fixed to the specified value.
+        fscale : float, optional
+            Hold the scale parameter fixed to the specified value.
+
+        Returns
+        -------
+        loc, scale : float
+            Maximum likelihood estimates for the location and scale.
+
+        Notes
+        -----
+        An error is raised if `floc` is given and any values in `data` are
+        less than `floc`, or if `fscale` is given and `fscale` is less
+        than ``data.max() - data.min()``.  An error is also raised if both
+        `floc` and `fscale` are given.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import uniform
+
+        We'll fit the uniform distribution to `x`:
+
+        >>> x = np.array([2, 2.5, 3.1, 9.5, 13.0])
+
+        For a uniform distribution MLE, the location is the minimum of the
+        data, and the scale is the maximum minus the minimum.
+
+        >>> loc, scale = uniform.fit(x)
+        >>> loc
+        2.0
+        >>> scale
+        11.0
+
+        If we know the data comes from a uniform distribution where the support
+        starts at 0, we can use ``floc=0``:
+
+        >>> loc, scale = uniform.fit(x, floc=0)
+        >>> loc
+        0.0
+        >>> scale
+        13.0
+
+        Alternatively, if we know the length of the support is 12, we can use
+        ``fscale=12``:
+
+        >>> loc, scale = uniform.fit(x, fscale=12)
+        >>> loc
+        1.5
+        >>> scale
+        12.0
+
+        In that last example, the support interval is [1.5, 13.5].  This
+        solution is not unique.  For example, the distribution with ``loc=2``
+        and ``scale=12`` has the same likelihood as the one above.  When
+        `fscale` is given and it is larger than ``data.max() - data.min()``,
+        the parameters returned by the `fit` method center the support over
+        the interval ``[data.min(), data.max()]``.
+
+        """
+        if len(args) > 0:
+            raise TypeError("Too many arguments.")
+
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # MLE for the uniform distribution
+        # --------------------------------
+        # The PDF is
+        #
+        #     f(x, loc, scale) = {1/scale  for loc <= x <= loc + scale
+        #                        {0        otherwise}
+        #
+        # The likelihood function is
+        #     L(x, loc, scale) = (1/scale)**n
+        # where n is len(x), assuming loc <= x <= loc + scale for all x.
+        # The log-likelihood is
+        #     l(x, loc, scale) = -n*log(scale)
+        # The log-likelihood is maximized by making scale as small as possible,
+        # while keeping loc <= x <= loc + scale.   So if neither loc nor scale
+        # are fixed, the log-likelihood is maximized by choosing
+        #     loc = x.min()
+        #     scale = np.ptp(x)
+        # If loc is fixed, it must be less than or equal to x.min(), and then
+        # the scale is
+        #     scale = x.max() - loc
+        # If scale is fixed, it must not be less than np.ptp(x).  If scale is
+        # greater than np.ptp(x), the solution is not unique.  Note that the
+        # likelihood does not depend on loc, except for the requirement that
+        # loc <= x <= loc + scale.  All choices of loc for which
+        #     x.max() - scale <= loc <= x.min()
+        # have the same log-likelihood.  In this case, we choose loc such that
+        # the support is centered over the interval [data.min(), data.max()]:
+        #     loc = x.min() = 0.5*(scale - np.ptp(x))
+
+        if fscale is None:
+            # scale is not fixed.
+            if floc is None:
+                # loc is not fixed, scale is not fixed.
+                loc = data.min()
+                scale = np.ptp(data)
+            else:
+                # loc is fixed, scale is not fixed.
+                loc = floc
+                scale = data.max() - loc
+                if data.min() < loc:
+                    raise FitDataError("uniform", lower=loc, upper=loc + scale)
+        else:
+            # loc is not fixed, scale is fixed.
+            ptp = np.ptp(data)
+            if ptp > fscale:
+                raise FitUniformFixedScaleDataError(ptp=ptp, fscale=fscale)
+            # If ptp < fscale, the ML estimate is not unique; see the comments
+            # above.  We choose the distribution for which the support is
+            # centered over the interval [data.min(), data.max()].
+            loc = data.min() - 0.5*(fscale - ptp)
+            scale = fscale
+
+        # We expect the return values to be floating point, so ensure it
+        # by explicitly converting to float.
+        return float(loc), float(scale)
+
+
+uniform = uniform_gen(a=0.0, b=1.0, name='uniform')
+
+
+class vonmises_gen(rv_continuous):
+    r"""A Von Mises continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    scipy.stats.vonmises_fisher : Von-Mises Fisher distribution on a
+                                  hypersphere
+
+    Notes
+    -----
+    The probability density function for `vonmises` and `vonmises_line` is:
+
+    .. math::
+
+        f(x, \kappa) = \frac{ \exp(\kappa \cos(x)) }{ 2 \pi I_0(\kappa) }
+
+    for :math:`-\pi \le x \le \pi`, :math:`\kappa \ge 0`. :math:`I_0` is the
+    modified Bessel function of order zero (`scipy.special.i0`).
+
+    `vonmises` is a circular distribution which does not restrict the
+    distribution to a fixed interval. Currently, there is no circular
+    distribution framework in SciPy. The ``cdf`` is implemented such that
+    ``cdf(x + 2*np.pi) == cdf(x) + 1``.
+
+    `vonmises_line` is the same distribution, defined on :math:`[-\pi, \pi]`
+    on the real line. This is a regular (i.e. non-circular) distribution.
+
+    Note about distribution parameters: `vonmises` and `vonmises_line` take
+    ``kappa`` as a shape parameter (concentration) and ``loc`` as the location
+    (circular mean). A ``scale`` parameter is accepted but does not have any
+    effect.
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import vonmises
+
+    Define distribution parameters.
+
+    >>> loc = 0.5 * np.pi  # circular mean
+    >>> kappa = 1  # concentration
+
+    Compute the probability density at ``x=0`` via the ``pdf`` method.
+
+    >>> vonmises.pdf(0, loc=loc, kappa=kappa)
+    0.12570826359722018
+
+    Verify that the percentile function ``ppf`` inverts the cumulative
+    distribution function ``cdf`` up to floating point accuracy.
+
+    >>> x = 1
+    >>> cdf_value = vonmises.cdf(x, loc=loc, kappa=kappa)
+    >>> ppf_value = vonmises.ppf(cdf_value, loc=loc, kappa=kappa)
+    >>> x, cdf_value, ppf_value
+    (1, 0.31489339900904967, 1.0000000000000004)
+
+    Draw 1000 random variates by calling the ``rvs`` method.
+
+    >>> sample_size = 1000
+    >>> sample = vonmises(loc=loc, kappa=kappa).rvs(sample_size)
+
+    Plot the von Mises density on a Cartesian and polar grid to emphasize
+    that it is a circular distribution.
+
+    >>> fig = plt.figure(figsize=(12, 6))
+    >>> left = plt.subplot(121)
+    >>> right = plt.subplot(122, projection='polar')
+    >>> x = np.linspace(-np.pi, np.pi, 500)
+    >>> vonmises_pdf = vonmises.pdf(x, loc=loc, kappa=kappa)
+    >>> ticks = [0, 0.15, 0.3]
+
+    The left image contains the Cartesian plot.
+
+    >>> left.plot(x, vonmises_pdf)
+    >>> left.set_yticks(ticks)
+    >>> number_of_bins = int(np.sqrt(sample_size))
+    >>> left.hist(sample, density=True, bins=number_of_bins)
+    >>> left.set_title("Cartesian plot")
+    >>> left.set_xlim(-np.pi, np.pi)
+    >>> left.grid(True)
+
+    The right image contains the polar plot.
+
+    >>> right.plot(x, vonmises_pdf, label="PDF")
+    >>> right.set_yticks(ticks)
+    >>> right.hist(sample, density=True, bins=number_of_bins,
+    ...            label="Histogram")
+    >>> right.set_title("Polar plot")
+    >>> right.legend(bbox_to_anchor=(0.15, 1.06))
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("kappa", False, (0, np.inf), (True, False))]
+
+    def _argcheck(self, kappa):
+        return kappa >= 0
+
+    def _rvs(self, kappa, size=None, random_state=None):
+        return random_state.vonmises(0.0, kappa, size=size)
+
+    @inherit_docstring_from(rv_continuous)
+    def rvs(self, *args, **kwds):
+        rvs = super().rvs(*args, **kwds)
+        return np.mod(rvs + np.pi, 2*np.pi) - np.pi
+
+    def _pdf(self, x, kappa):
+        # vonmises.pdf(x, kappa) = exp(kappa * cos(x)) / (2*pi*I[0](kappa))
+        #                        = exp(kappa * (cos(x) - 1)) /
+        #                          (2*pi*exp(-kappa)*I[0](kappa))
+        #                        = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa))
+        return np.exp(kappa*sc.cosm1(x)) / (2*np.pi*sc.i0e(kappa))
+
+    def _logpdf(self, x, kappa):
+        # vonmises.pdf(x, kappa) = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa))
+        return kappa * sc.cosm1(x) - np.log(2*np.pi) - np.log(sc.i0e(kappa))
+
+    def _cdf(self, x, kappa):
+        return _stats.von_mises_cdf(kappa, x)
+
+    def _stats_skip(self, kappa):
+        return 0, None, 0, None
+
+    def _entropy(self, kappa):
+        # vonmises.entropy(kappa) = -kappa * I[1](kappa) / I[0](kappa) +
+        #                           log(2 * np.pi * I[0](kappa))
+        #                         = -kappa * I[1](kappa) * exp(-kappa) /
+        #                           (I[0](kappa) * exp(-kappa)) +
+        #                           log(2 * np.pi *
+        #                           I[0](kappa) * exp(-kappa) / exp(-kappa))
+        #                         = -kappa * sc.i1e(kappa) / sc.i0e(kappa) +
+        #                           log(2 * np.pi * i0e(kappa)) + kappa
+        return (-kappa * sc.i1e(kappa) / sc.i0e(kappa) +
+                np.log(2 * np.pi * sc.i0e(kappa)) + kappa)
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        The default limits of integration are endpoints of the interval
+        of width ``2*pi`` centered at `loc` (e.g. ``[-pi, pi]`` when
+        ``loc=0``).\n\n""")
+    def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,
+               conditional=False, **kwds):
+        _a, _b = -np.pi, np.pi
+
+        if lb is None:
+            lb = loc + _a
+        if ub is None:
+            ub = loc + _b
+
+        return super().expect(func, args, loc,
+                              scale, lb, ub, conditional, **kwds)
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Fit data is assumed to represent angles and will be wrapped onto the
+        unit circle. `f0` and `fscale` are ignored; the returned shape is
+        always the maximum likelihood estimate and the scale is always
+        1. Initial guesses are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, fshape, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                 args, kwds)
+        if self.a == -np.pi:
+            # vonmises line case, here the default fit method will be used
+            return super().fit(data, *args, **kwds)
+
+        # wrap data to interval [0, 2*pi]
+        data = np.mod(data, 2 * np.pi)
+
+        def find_mu(data):
+            return stats.circmean(data)
+
+        def find_kappa(data, loc):
+            # Usually, sources list the following as the equation to solve for
+            # the MLE of the shape parameter:
+            # r = I[1](kappa)/I[0](kappa), where r = mean resultant length
+            # This is valid when the location is the MLE of location.
+            # More generally, when the location may be fixed at an arbitrary
+            # value, r should be defined as follows:
+            r = np.sum(np.cos(loc - data))/len(data)
+            # See gh-18128 for more information.
+
+            # The function r[0](kappa) := I[1](kappa)/I[0](kappa) is monotonic
+            # increasing from r[0](0) = 0 to r[0](+inf) = 1.  The partial
+            # derivative of the log likelihood function with respect to kappa
+            # is monotonic decreasing in kappa.
+            if r == 1:
+                # All observations are (almost) equal to the mean.  Return
+                # some large kappa such that r[0](kappa) = 1.0 numerically.
+                return 1e16
+            elif r > 0:
+                def solve_for_kappa(kappa):
+                    return sc.i1e(kappa)/sc.i0e(kappa) - r
+
+                # The bounds of the root of r[0](kappa) = r are derived from
+                # selected bounds of r[0](x) given in [1, Eq. 11 & 16].  See
+                # gh-20102 for details.
+                #
+                # [1] Amos, D. E. (1973).  Computation of Modified Bessel
+                #     Functions and Their Ratios.  Mathematics of Computation,
+                #     28(125): 239-251.
+                lower_bound = r/(1-r)/(1+r)
+                upper_bound = 2*lower_bound
+
+                # The bounds are violated numerically for certain values of r,
+                # where solve_for_kappa evaluated at the bounds have the same
+                # sign.  This indicates numerical imprecision of i1e()/i0e().
+                # Return the violated bound in this case as it's more accurate.
+                if solve_for_kappa(lower_bound) >= 0:
+                    return lower_bound
+                elif solve_for_kappa(upper_bound) <= 0:
+                    return upper_bound
+                else:
+                    root_res = root_scalar(solve_for_kappa, method="brentq",
+                                           bracket=(lower_bound, upper_bound))
+                    return root_res.root
+            else:
+                # if the provided floc is very far from the circular mean,
+                # the mean resultant length r can become negative.
+                # In that case, the equation
+                # I[1](kappa)/I[0](kappa) = r does not have a solution.
+                # The maximum likelihood kappa is then 0 which practically
+                # results in the uniform distribution on the circle. As
+                # vonmises is defined for kappa > 0, return instead the
+                # smallest floating point value.
+                # See gh-18190 for more information
+                return np.finfo(float).tiny
+
+        # location likelihood equation has a solution independent of kappa
+        loc = floc if floc is not None else find_mu(data)
+        # shape likelihood equation depends on location
+        shape = fshape if fshape is not None else find_kappa(data, loc)
+
+        loc = np.mod(loc + np.pi, 2 * np.pi) - np.pi  # ensure in [-pi, pi]
+        return shape, loc, 1  # scale is not handled
+
+
+vonmises = vonmises_gen(name='vonmises')
+vonmises_line = vonmises_gen(a=-np.pi, b=np.pi, name='vonmises_line')
+
+
+class wald_gen(invgauss_gen):
+    r"""A Wald continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `wald` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp(- \frac{ (x-1)^2 }{ 2x })
+
+    for :math:`x >= 0`.
+
+    `wald` is a special case of `invgauss` with ``mu=1``.
+
+    %(after_notes)s
+
+    %(example)s
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.wald(1.0, 1.0, size=size)
+
+    def _pdf(self, x):
+        # wald.pdf(x) = 1/sqrt(2*pi*x**3) * exp(-(x-1)**2/(2*x))
+        return invgauss._pdf(x, 1.0)
+
+    def _cdf(self, x):
+        return invgauss._cdf(x, 1.0)
+
+    def _sf(self, x):
+        return invgauss._sf(x, 1.0)
+
+    def _ppf(self, x):
+        return invgauss._ppf(x, 1.0)
+
+    def _isf(self, x):
+        return invgauss._isf(x, 1.0)
+
+    def _logpdf(self, x):
+        return invgauss._logpdf(x, 1.0)
+
+    def _logcdf(self, x):
+        return invgauss._logcdf(x, 1.0)
+
+    def _logsf(self, x):
+        return invgauss._logsf(x, 1.0)
+
+    def _stats(self):
+        return 1.0, 1.0, 3.0, 15.0
+
+    def _entropy(self):
+        return invgauss._entropy(1.0)
+
+
+wald = wald_gen(a=0.0, name="wald")
+
+
+class wrapcauchy_gen(rv_continuous):
+    r"""A wrapped Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `wrapcauchy` is:
+
+    .. math::
+
+        f(x, c) = \frac{1-c^2}{2\pi (1+c^2 - 2c \cos(x))}
+
+    for :math:`0 \le x \le 2\pi`, :math:`0 < c < 1`.
+
+    `wrapcauchy` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return (c > 0) & (c < 1)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, 1), (False, False))]
+
+    def _pdf(self, x, c):
+        # wrapcauchy.pdf(x, c) = (1-c**2) / (2*pi*(1+c**2-2*c*cos(x)))
+        return (1.0-c*c)/(2*np.pi*(1+c*c-2*c*np.cos(x)))
+
+    def _cdf(self, x, c):
+
+        def f1(x, cr):
+            # CDF for 0 <= x < pi
+            return 1/np.pi * np.arctan(cr*np.tan(x/2))
+
+        def f2(x, cr):
+            # CDF for pi <= x <= 2*pi
+            return 1 - 1/np.pi * np.arctan(cr*np.tan((2*np.pi - x)/2))
+
+        cr = (1 + c)/(1 - c)
+        return _lazywhere(x < np.pi, (x, cr), f=f1, f2=f2)
+
+    def _ppf(self, q, c):
+        val = (1.0-c)/(1.0+c)
+        rcq = 2*np.arctan(val*np.tan(np.pi*q))
+        rcmq = 2*np.pi-2*np.arctan(val*np.tan(np.pi*(1-q)))
+        return np.where(q < 1.0/2, rcq, rcmq)
+
+    def _entropy(self, c):
+        return np.log(2*np.pi*(1-c*c))
+
+    def _fitstart(self, data):
+        # Use 0.5 as the initial guess of the shape parameter.
+        # For the location and scale, use the minimum and
+        # peak-to-peak/(2*pi), respectively.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        return 0.5, np.min(data), np.ptp(data)/(2*np.pi)
+
+
+wrapcauchy = wrapcauchy_gen(a=0.0, b=2*np.pi, name='wrapcauchy')
+
+
+class gennorm_gen(rv_continuous):
+    r"""A generalized normal continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    laplace : Laplace distribution
+    norm : normal distribution
+
+    Notes
+    -----
+    The probability density function for `gennorm` is [1]_:
+
+    .. math::
+
+        f(x, \beta) = \frac{\beta}{2 \Gamma(1/\beta)} \exp(-|x|^\beta),
+
+    where :math:`x` is a real number, :math:`\beta > 0` and
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `gennorm` takes ``beta`` as a shape parameter for :math:`\beta`.
+    For :math:`\beta = 1`, it is identical to a Laplace distribution.
+    For :math:`\beta = 2`, it is identical to a normal distribution
+    (with ``scale=1/sqrt(2)``).
+
+    References
+    ----------
+
+    .. [1] "Generalized normal distribution, Version 1",
+           https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1
+
+    .. [2] Nardon, Martina, and Paolo Pianca. "Simulation techniques for
+           generalized Gaussian densities." Journal of Statistical
+           Computation and Simulation 79.11 (2009): 1317-1329
+
+    .. [3] Wicklin, Rick. "Simulate data from a generalized Gaussian
+           distribution" in The DO Loop blog, September 21, 2016,
+           https://blogs.sas.com/content/iml/2016/09/21/simulate-generalized-gaussian-sas.html
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("beta", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, beta):
+        return np.exp(self._logpdf(x, beta))
+
+    def _logpdf(self, x, beta):
+        return np.log(0.5*beta) - sc.gammaln(1.0/beta) - abs(x)**beta
+
+    def _cdf(self, x, beta):
+        c = 0.5 * np.sign(x)
+        # evaluating (.5 + c) first prevents numerical cancellation
+        return (0.5 + c) - c * sc.gammaincc(1.0/beta, abs(x)**beta)
+
+    def _ppf(self, x, beta):
+        c = np.sign(x - 0.5)
+        # evaluating (1. + c) first prevents numerical cancellation
+        return c * sc.gammainccinv(1.0/beta, (1.0 + c) - 2.0*c*x)**(1.0/beta)
+
+    def _sf(self, x, beta):
+        return self._cdf(-x, beta)
+
+    def _isf(self, x, beta):
+        return -self._ppf(x, beta)
+
+    def _stats(self, beta):
+        c1, c3, c5 = sc.gammaln([1.0/beta, 3.0/beta, 5.0/beta])
+        return 0., np.exp(c3 - c1), 0., np.exp(c5 + c1 - 2.0*c3) - 3.
+
+    def _entropy(self, beta):
+        return 1. / beta - np.log(.5 * beta) + sc.gammaln(1. / beta)
+
+    def _rvs(self, beta, size=None, random_state=None):
+        # see [2]_ for the algorithm
+        # see [3]_ for reference implementation in SAS
+        z = random_state.gamma(1/beta, size=size)
+        y = z ** (1/beta)
+        # convert y to array to ensure masking support
+        y = np.asarray(y)
+        mask = random_state.random(size=y.shape) < 0.5
+        y[mask] = -y[mask]
+        return y
+
+
+gennorm = gennorm_gen(name='gennorm')
+
+
+class halfgennorm_gen(rv_continuous):
+    r"""The upper half of a generalized normal continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gennorm : generalized normal distribution
+    expon : exponential distribution
+    halfnorm : half normal distribution
+
+    Notes
+    -----
+    The probability density function for `halfgennorm` is:
+
+    .. math::
+
+        f(x, \beta) = \frac{\beta}{\Gamma(1/\beta)} \exp(-|x|^\beta)
+
+    for :math:`x, \beta > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    `halfgennorm` takes ``beta`` as a shape parameter for :math:`\beta`.
+    For :math:`\beta = 1`, it is identical to an exponential distribution.
+    For :math:`\beta = 2`, it is identical to a half normal distribution
+    (with ``scale=1/sqrt(2)``).
+
+    References
+    ----------
+
+    .. [1] "Generalized normal distribution, Version 1",
+           https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("beta", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, beta):
+        #                                 beta
+        # halfgennorm.pdf(x, beta) =  -------------  exp(-|x|**beta)
+        #                             gamma(1/beta)
+        return np.exp(self._logpdf(x, beta))
+
+    def _logpdf(self, x, beta):
+        return np.log(beta) - sc.gammaln(1.0/beta) - x**beta
+
+    def _cdf(self, x, beta):
+        return sc.gammainc(1.0/beta, x**beta)
+
+    def _ppf(self, x, beta):
+        return sc.gammaincinv(1.0/beta, x)**(1.0/beta)
+
+    def _sf(self, x, beta):
+        return sc.gammaincc(1.0/beta, x**beta)
+
+    def _isf(self, x, beta):
+        return sc.gammainccinv(1.0/beta, x)**(1.0/beta)
+
+    def _entropy(self, beta):
+        return 1.0/beta - np.log(beta) + sc.gammaln(1.0/beta)
+
+
+halfgennorm = halfgennorm_gen(a=0, name='halfgennorm')
+
+
+class crystalball_gen(rv_continuous):
+    r"""
+    Crystalball distribution
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `crystalball` is:
+
+    .. math::
+
+        f(x, \beta, m) =  \begin{cases}
+                            N \exp(-x^2 / 2),  &\text{for } x > -\beta\\
+                            N A (B - x)^{-m}  &\text{for } x \le -\beta
+                          \end{cases}
+
+    where :math:`A = (m / |\beta|)^m  \exp(-\beta^2 / 2)`,
+    :math:`B = m/|\beta| - |\beta|` and :math:`N` is a normalisation constant.
+
+    `crystalball` takes :math:`\beta > 0` and :math:`m > 1` as shape
+    parameters.  :math:`\beta` defines the point where the pdf changes
+    from a power-law to a Gaussian distribution.  :math:`m` is the power
+    of the power-law tail.
+
+    %(after_notes)s
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] "Crystal Ball Function",
+           https://en.wikipedia.org/wiki/Crystal_Ball_function
+
+    %(example)s
+    """
+    def _argcheck(self, beta, m):
+        """
+        Shape parameter bounds are m > 1 and beta > 0.
+        """
+        return (m > 1) & (beta > 0)
+
+    def _shape_info(self):
+        ibeta = _ShapeInfo("beta", False, (0, np.inf), (False, False))
+        im = _ShapeInfo("m", False, (1, np.inf), (False, False))
+        return [ibeta, im]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default m=1 is not valid
+        return super()._fitstart(data, args=(1, 1.5))
+
+    def _pdf(self, x, beta, m):
+        """
+        Return PDF of the crystalball function.
+
+                                            --
+                                           | exp(-x**2 / 2),  for x > -beta
+        crystalball.pdf(x, beta, m) =  N * |
+                                           | A * (B - x)**(-m), for x <= -beta
+                                            --
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return np.exp(-x**2 / 2)
+
+        def lhs(x, beta, m):
+            return ((m/beta)**m * np.exp(-beta**2 / 2.0) *
+                    (m/beta - beta - x)**(-m))
+
+        return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _logpdf(self, x, beta, m):
+        """
+        Return the log of the PDF of the crystalball function.
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return -x**2/2
+
+        def lhs(x, beta, m):
+            return m*np.log(m/beta) - beta**2/2 - m*np.log(m/beta - beta - x)
+
+        return np.log(N) + _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _cdf(self, x, beta, m):
+        """
+        Return CDF of the crystalball function
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return ((m/beta) * np.exp(-beta**2 / 2.0) / (m-1) +
+                    _norm_pdf_C * (_norm_cdf(x) - _norm_cdf(-beta)))
+
+        def lhs(x, beta, m):
+            return ((m/beta)**m * np.exp(-beta**2 / 2.0) *
+                    (m/beta - beta - x)**(-m+1) / (m-1))
+
+        return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _sf(self, x, beta, m):
+        """
+        Survival function of the crystalball distribution.
+        """
+
+        def rhs(x, beta, m):
+            # M is the same as 1/N used elsewhere.
+            M = m/beta/(m - 1)*np.exp(-beta**2/2) + _norm_pdf_C*_norm_cdf(beta)
+            return _norm_pdf_C*_norm_sf(x)/M
+
+        def lhs(x, beta, m):
+            # Default behavior is OK in the left tail of the SF.
+            return 1 - self._cdf(x, beta, m)
+
+        return _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _ppf(self, p, beta, m):
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+        pbeta = N * (m/beta) * np.exp(-beta**2/2) / (m - 1)
+
+        def ppf_less(p, beta, m):
+            eb2 = np.exp(-beta**2/2)
+            C = (m/beta) * eb2 / (m-1)
+            N = 1/(C + _norm_pdf_C * _norm_cdf(beta))
+            return (m/beta - beta -
+                    ((m - 1)*(m/beta)**(-m)/eb2*p/N)**(1/(1-m)))
+
+        def ppf_greater(p, beta, m):
+            eb2 = np.exp(-beta**2/2)
+            C = (m/beta) * eb2 / (m-1)
+            N = 1/(C + _norm_pdf_C * _norm_cdf(beta))
+            return _norm_ppf(_norm_cdf(-beta) + (1/_norm_pdf_C)*(p/N - C))
+
+        return _lazywhere(p < pbeta, (p, beta, m), f=ppf_less, f2=ppf_greater)
+
+    def _munp(self, n, beta, m):
+        """
+        Returns the n-th non-central moment of the crystalball function.
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def n_th_moment(n, beta, m):
+            """
+            Returns n-th moment. Defined only if n+1 < m
+            Function cannot broadcast due to the loop over n
+            """
+            A = (m/beta)**m * np.exp(-beta**2 / 2.0)
+            B = m/beta - beta
+            rhs = (2**((n-1)/2.0) * sc.gamma((n+1)/2) *
+                   (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2)))
+            lhs = np.zeros(rhs.shape)
+            for k in range(int(n) + 1):
+                lhs += (sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) *
+                        (m/beta)**(-m + k + 1))
+            return A * lhs + rhs
+
+        return N * _lazywhere(n + 1 < m, (n, beta, m),
+                              np.vectorize(n_th_moment, otypes=[np.float64]),
+                              np.inf)
+
+
+crystalball = crystalball_gen(name='crystalball', longname="A Crystalball Function")
+
+
+def _argus_phi(chi):
+    """
+    Utility function for the argus distribution used in the pdf, sf and
+    moment calculation.
+    Note that for all x > 0:
+    gammainc(1.5, x**2/2) = 2 * (_norm_cdf(x) - x * _norm_pdf(x) - 0.5).
+    This can be verified directly by noting that the cdf of Gamma(1.5) can
+    be written as erf(sqrt(x)) - 2*sqrt(x)*exp(-x)/sqrt(Pi).
+    We use gammainc instead of the usual definition because it is more precise
+    for small chi.
+    """
+    return sc.gammainc(1.5, chi**2/2) / 2
+
+
+class argus_gen(rv_continuous):
+    r"""
+    Argus distribution
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `argus` is:
+
+    .. math::
+
+        f(x, \chi) = \frac{\chi^3}{\sqrt{2\pi} \Psi(\chi)} x \sqrt{1-x^2}
+                     \exp(-\chi^2 (1 - x^2)/2)
+
+    for :math:`0 < x < 1` and :math:`\chi > 0`, where
+
+    .. math::
+
+        \Psi(\chi) = \Phi(\chi) - \chi \phi(\chi) - 1/2
+
+    with :math:`\Phi` and :math:`\phi` being the CDF and PDF of a standard
+    normal distribution, respectively.
+
+    `argus` takes :math:`\chi` as shape a parameter. Details about sampling
+    from the ARGUS distribution can be found in [2]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "ARGUS distribution",
+           https://en.wikipedia.org/wiki/ARGUS_distribution
+    .. [2] Christoph Baumgarten "Random variate generation by fast numerical
+           inversion in the varying parameter case." Research in Statistics,
+           vol. 1, 2023, doi:10.1080/27684520.2023.2279060.
+
+    .. versionadded:: 0.19.0
+
+    %(example)s
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("chi", False, (0, np.inf), (False, False))]
+
+    def _logpdf(self, x, chi):
+        # for x = 0 or 1, logpdf returns -np.inf
+        with np.errstate(divide='ignore'):
+            y = 1.0 - x*x
+            A = 3*np.log(chi) - _norm_pdf_logC - np.log(_argus_phi(chi))
+            return A + np.log(x) + 0.5*np.log1p(-x*x) - chi**2 * y / 2
+
+    def _pdf(self, x, chi):
+        return np.exp(self._logpdf(x, chi))
+
+    def _cdf(self, x, chi):
+        return 1.0 - self._sf(x, chi)
+
+    def _sf(self, x, chi):
+        return _argus_phi(chi * np.sqrt((1 - x)*(1 + x))) / _argus_phi(chi)
+
+    def _rvs(self, chi, size=None, random_state=None):
+        chi = np.asarray(chi)
+        if chi.size == 1:
+            out = self._rvs_scalar(chi, numsamples=size,
+                                   random_state=random_state)
+        else:
+            shp, bc = _check_shape(chi.shape, size)
+            numsamples = int(np.prod(shp))
+            out = np.empty(size)
+            it = np.nditer([chi],
+                           flags=['multi_index'],
+                           op_flags=[['readonly']])
+            while not it.finished:
+                idx = tuple((it.multi_index[j] if not bc[j] else slice(None))
+                            for j in range(-len(size), 0))
+                r = self._rvs_scalar(it[0], numsamples=numsamples,
+                                     random_state=random_state)
+                out[idx] = r.reshape(shp)
+                it.iternext()
+
+        if size == ():
+            out = out[()]
+        return out
+
+    def _rvs_scalar(self, chi, numsamples=None, random_state=None):
+        # if chi <= 1.8:
+        # use rejection method, see Devroye:
+        # Non-Uniform Random Variate Generation, 1986, section II.3.2.
+        # write: PDF f(x) = c * g(x) * h(x), where
+        # h is [0,1]-valued and g is a density
+        # we use two ways to write f
+        #
+        # Case 1:
+        # write g(x) = 3*x*sqrt(1-x**2), h(x) = exp(-chi**2 (1-x**2) / 2)
+        # If X has a distribution with density g its ppf G_inv is given by:
+        # G_inv(u) = np.sqrt(1 - u**(2/3))
+        #
+        # Case 2:
+        # g(x) = chi**2 * x * exp(-chi**2 * (1-x**2)/2) / (1 - exp(-chi**2 /2))
+        # h(x) = sqrt(1 - x**2), 0 <= x <= 1
+        # one can show that
+        # G_inv(u) = np.sqrt(2*np.log(u*(np.exp(chi**2/2)-1)+1))/chi
+        #          = np.sqrt(1 + 2*np.log(np.exp(-chi**2/2)*(1-u)+u)/chi**2)
+        # the latter expression is used for precision with small chi
+        #
+        # In both cases, the inverse cdf of g can be written analytically, and
+        # we can apply the rejection method:
+        #
+        # REPEAT
+        #    Generate U uniformly distributed on [0, 1]
+        #    Generate X with density g (e.g. via inverse transform sampling:
+        #    X = G_inv(V) with V uniformly distributed on [0, 1])
+        # UNTIL X <= h(X)
+        # RETURN X
+        #
+        # We use case 1 for chi <= 0.5 as it maintains precision for small chi
+        # and case 2 for 0.5 < chi <= 1.8 due to its speed for moderate chi.
+        #
+        # if chi > 1.8:
+        # use relation to the Gamma distribution: if X is ARGUS with parameter
+        # chi), then Y = chi**2 * (1 - X**2) / 2 has density proportional to
+        # sqrt(u) * exp(-u) on [0, chi**2 / 2], i.e. a Gamma(3/2) distribution
+        # conditioned on [0, chi**2 / 2]). Therefore, to sample X from the
+        # ARGUS distribution, we sample Y from the gamma distribution, keeping
+        # only samples on [0, chi**2 / 2], and apply the inverse
+        # transformation X = (1 - 2*Y/chi**2)**(1/2). Since we only
+        # look at chi > 1.8, gamma(1.5).cdf(chi**2/2) is large enough such
+        # Y falls in the interval [0, chi**2 / 2] with a high probability:
+        # stats.gamma(1.5).cdf(1.8**2/2) = 0.644...
+        #
+        # The points to switch between the different methods are determined
+        # by a comparison of the runtime of the different methods. However,
+        # the runtime is platform-dependent. The implemented values should
+        # ensure a good overall performance and are supported by an analysis
+        # of the rejection constants of different methods.
+
+        size1d = tuple(np.atleast_1d(numsamples))
+        N = int(np.prod(size1d))
+        x = np.zeros(N)
+        simulated = 0
+        chi2 = chi * chi
+        if chi <= 0.5:
+            d = -chi2 / 2
+            while simulated < N:
+                k = N - simulated
+                u = random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                z = v**(2/3)
+                # acceptance condition: u <= h(G_inv(v)). This simplifies to
+                accept = (np.log(u) <= d * z)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    # we still need to transform z=v**(2/3) to X = G_inv(v)
+                    rvs = np.sqrt(1 - z[accept])
+                    x[simulated:(simulated + num_accept)] = rvs
+                    simulated += num_accept
+        elif chi <= 1.8:
+            echi = np.exp(-chi2 / 2)
+            while simulated < N:
+                k = N - simulated
+                u = random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                z = 2 * np.log(echi * (1 - v) + v) / chi2
+                # as in case one, simplify u <= h(G_inv(v)) and then transform
+                # z to the target distribution X = G_inv(v)
+                accept = (u**2 + z <= 0)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    rvs = np.sqrt(1 + z[accept])
+                    x[simulated:(simulated + num_accept)] = rvs
+                    simulated += num_accept
+        else:
+            # conditional Gamma for chi > 1.8
+            while simulated < N:
+                k = N - simulated
+                g = random_state.standard_gamma(1.5, size=k)
+                accept = (g <= chi2 / 2)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = g[accept]
+                    simulated += num_accept
+            x = np.sqrt(1 - 2 * x / chi2)
+
+        return np.reshape(x, size1d)
+
+    def _stats(self, chi):
+        # need to ensure that dtype is float
+        # otherwise the mask below does not work for integers
+        chi = np.asarray(chi, dtype=float)
+        phi = _argus_phi(chi)
+        m = np.sqrt(np.pi/8) * chi * sc.ive(1, chi**2/4) / phi
+        # compute second moment, use Taylor expansion for small chi (<= 0.1)
+        mu2 = np.empty_like(chi)
+        mask = chi > 0.1
+        c = chi[mask]
+        mu2[mask] = 1 - 3 / c**2 + c * _norm_pdf(c) / phi[mask]
+        c = chi[~mask]
+        coef = [-358/65690625, 0, -94/1010625, 0, 2/2625, 0, 6/175, 0, 0.4]
+        mu2[~mask] = np.polyval(coef, c)
+        return m, mu2 - m**2, None, None
+
+
+argus = argus_gen(name='argus', longname="An Argus Function", a=0.0, b=1.0)
+
+
+class rv_histogram(rv_continuous):
+    """
+    Generates a distribution given by a histogram.
+    This is useful to generate a template distribution from a binned
+    datasample.
+
+    As a subclass of the `rv_continuous` class, `rv_histogram` inherits from it
+    a collection of generic methods (see `rv_continuous` for the full list),
+    and implements them based on the properties of the provided binned
+    datasample.
+
+    Parameters
+    ----------
+    histogram : tuple of array_like
+        Tuple containing two array_like objects.
+        The first containing the content of n bins,
+        the second containing the (n+1) bin boundaries.
+        In particular, the return value of `numpy.histogram` is accepted.
+
+    density : bool, optional
+        If False, assumes the histogram is proportional to counts per bin;
+        otherwise, assumes it is proportional to a density.
+        For constant bin widths, these are equivalent, but the distinction
+        is important when bin widths vary (see Notes).
+        If None (default), sets ``density=True`` for backwards compatibility,
+        but warns if the bin widths are variable. Set `density` explicitly
+        to silence the warning.
+
+        .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    When a histogram has unequal bin widths, there is a distinction between
+    histograms that are proportional to counts per bin and histograms that are
+    proportional to probability density over a bin. If `numpy.histogram` is
+    called with its default ``density=False``, the resulting histogram is the
+    number of counts per bin, so ``density=False`` should be passed to
+    `rv_histogram`. If `numpy.histogram` is called with ``density=True``, the
+    resulting histogram is in terms of probability density, so ``density=True``
+    should be passed to `rv_histogram`. To avoid warnings, always pass
+    ``density`` explicitly when the input histogram has unequal bin widths.
+
+    There are no additional shape parameters except for the loc and scale.
+    The pdf is defined as a stepwise function from the provided histogram.
+    The cdf is a linear interpolation of the pdf.
+
+    .. versionadded:: 0.19.0
+
+    Examples
+    --------
+
+    Create a scipy.stats distribution from a numpy histogram
+
+    >>> import scipy.stats
+    >>> import numpy as np
+    >>> data = scipy.stats.norm.rvs(size=100000, loc=0, scale=1.5,
+    ...                             random_state=123)
+    >>> hist = np.histogram(data, bins=100)
+    >>> hist_dist = scipy.stats.rv_histogram(hist, density=False)
+
+    Behaves like an ordinary scipy rv_continuous distribution
+
+    >>> hist_dist.pdf(1.0)
+    0.20538577847618705
+    >>> hist_dist.cdf(2.0)
+    0.90818568543056499
+
+    PDF is zero above (below) the highest (lowest) bin of the histogram,
+    defined by the max (min) of the original dataset
+
+    >>> hist_dist.pdf(np.max(data))
+    0.0
+    >>> hist_dist.cdf(np.max(data))
+    1.0
+    >>> hist_dist.pdf(np.min(data))
+    7.7591907244498314e-05
+    >>> hist_dist.cdf(np.min(data))
+    0.0
+
+    PDF and CDF follow the histogram
+
+    >>> import matplotlib.pyplot as plt
+    >>> X = np.linspace(-5.0, 5.0, 100)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_title("PDF from Template")
+    >>> ax.hist(data, density=True, bins=100)
+    >>> ax.plot(X, hist_dist.pdf(X), label='PDF')
+    >>> ax.plot(X, hist_dist.cdf(X), label='CDF')
+    >>> ax.legend()
+    >>> fig.show()
+
+    """
+    _support_mask = rv_continuous._support_mask
+
+    def __init__(self, histogram, *args, density=None, **kwargs):
+        """
+        Create a new distribution using the given histogram
+
+        Parameters
+        ----------
+        histogram : tuple of array_like
+            Tuple containing two array_like objects.
+            The first containing the content of n bins,
+            the second containing the (n+1) bin boundaries.
+            In particular, the return value of np.histogram is accepted.
+        density : bool, optional
+            If False, assumes the histogram is proportional to counts per bin;
+            otherwise, assumes it is proportional to a density.
+            For constant bin widths, these are equivalent.
+            If None (default), sets ``density=True`` for backward
+            compatibility, but warns if the bin widths are variable. Set
+            `density` explicitly to silence the warning.
+        """
+        self._histogram = histogram
+        self._density = density
+        if len(histogram) != 2:
+            raise ValueError("Expected length 2 for parameter histogram")
+        self._hpdf = np.asarray(histogram[0])
+        self._hbins = np.asarray(histogram[1])
+        if len(self._hpdf) + 1 != len(self._hbins):
+            raise ValueError("Number of elements in histogram content "
+                             "and histogram boundaries do not match, "
+                             "expected n and n+1.")
+        self._hbin_widths = self._hbins[1:] - self._hbins[:-1]
+        bins_vary = not np.allclose(self._hbin_widths, self._hbin_widths[0])
+        if density is None and bins_vary:
+            message = ("Bin widths are not constant. Assuming `density=True`."
+                       "Specify `density` explicitly to silence this warning.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+            density = True
+        elif not density:
+            self._hpdf = self._hpdf / self._hbin_widths
+
+        self._hpdf = self._hpdf / float(np.sum(self._hpdf * self._hbin_widths))
+        self._hcdf = np.cumsum(self._hpdf * self._hbin_widths)
+        self._hpdf = np.hstack([0.0, self._hpdf, 0.0])
+        self._hcdf = np.hstack([0.0, self._hcdf])
+        # Set support
+        kwargs['a'] = self.a = self._hbins[0]
+        kwargs['b'] = self.b = self._hbins[-1]
+        super().__init__(*args, **kwargs)
+
+    def _pdf(self, x):
+        """
+        PDF of the histogram
+        """
+        return self._hpdf[np.searchsorted(self._hbins, x, side='right')]
+
+    def _cdf(self, x):
+        """
+        CDF calculated from the histogram
+        """
+        return np.interp(x, self._hbins, self._hcdf)
+
+    def _ppf(self, x):
+        """
+        Percentile function calculated from the histogram
+        """
+        return np.interp(x, self._hcdf, self._hbins)
+
+    def _munp(self, n):
+        """Compute the n-th non-central moment."""
+        integrals = (self._hbins[1:]**(n+1) - self._hbins[:-1]**(n+1)) / (n+1)
+        return np.sum(self._hpdf[1:-1] * integrals)
+
+    def _entropy(self):
+        """Compute entropy of distribution"""
+        res = _lazywhere(self._hpdf[1:-1] > 0.0,
+                         (self._hpdf[1:-1],),
+                         np.log,
+                         0.0)
+        return -np.sum(self._hpdf[1:-1] * res * self._hbin_widths)
+
+    def _updated_ctor_param(self):
+        """
+        Set the histogram as additional constructor argument
+        """
+        dct = super()._updated_ctor_param()
+        dct['histogram'] = self._histogram
+        dct['density'] = self._density
+        return dct
+
+
+class studentized_range_gen(rv_continuous):
+    r"""A studentized range continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    t: Student's t distribution
+
+    Notes
+    -----
+    The probability density function for `studentized_range` is:
+
+    .. math::
+
+         f(x; k, \nu) = \frac{k(k-1)\nu^{\nu/2}}{\Gamma(\nu/2)
+                        2^{\nu/2-1}} \int_{0}^{\infty} \int_{-\infty}^{\infty}
+                        s^{\nu} e^{-\nu s^2/2} \phi(z) \phi(sx + z)
+                        [\Phi(sx + z) - \Phi(z)]^{k-2} \,dz \,ds
+
+    for :math:`x ≥ 0`, :math:`k > 1`, and :math:`\nu > 0`.
+
+    `studentized_range` takes ``k`` for :math:`k` and ``df`` for :math:`\nu`
+    as shape parameters.
+
+    When :math:`\nu` exceeds 100,000, an asymptotic approximation (infinite
+    degrees of freedom) is used to compute the cumulative distribution
+    function [4]_ and probability distribution function.
+
+    %(after_notes)s
+
+    References
+    ----------
+
+    .. [1] "Studentized range distribution",
+           https://en.wikipedia.org/wiki/Studentized_range_distribution
+    .. [2] Batista, Ben Dêivide, et al. "Externally Studentized Normal Midrange
+           Distribution." Ciência e Agrotecnologia, vol. 41, no. 4, 2017, pp.
+           378-389., doi:10.1590/1413-70542017414047716.
+    .. [3] Harter, H. Leon. "Tables of Range and Studentized Range." The Annals
+           of Mathematical Statistics, vol. 31, no. 4, 1960, pp. 1122-1147.
+           JSTOR, www.jstor.org/stable/2237810. Accessed 18 Feb. 2021.
+    .. [4] Lund, R. E., and J. R. Lund. "Algorithm AS 190: Probabilities and
+           Upper Quantiles for the Studentized Range." Journal of the Royal
+           Statistical Society. Series C (Applied Statistics), vol. 32, no. 2,
+           1983, pp. 204-210. JSTOR, www.jstor.org/stable/2347300. Accessed 18
+           Feb. 2021.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import studentized_range
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> k, df = 3, 10
+    >>> x = np.linspace(studentized_range.ppf(0.01, k, df),
+    ...                 studentized_range.ppf(0.99, k, df), 100)
+    >>> ax.plot(x, studentized_range.pdf(x, k, df),
+    ...         'r-', lw=5, alpha=0.6, label='studentized_range pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = studentized_range(k, df)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = studentized_range.ppf([0.001, 0.5, 0.999], k, df)
+    >>> np.allclose([0.001, 0.5, 0.999], studentized_range.cdf(vals, k, df))
+    True
+
+    Rather than using (``studentized_range.rvs``) to generate random variates,
+    which is very slow for this distribution, we can approximate the inverse
+    CDF using an interpolator, and then perform inverse transform sampling
+    with this approximate inverse CDF.
+
+    This distribution has an infinite but thin right tail, so we focus our
+    attention on the leftmost 99.9 percent.
+
+    >>> a, b = studentized_range.ppf([0, .999], k, df)
+    >>> a, b
+    0, 7.41058083802274
+
+    >>> from scipy.interpolate import interp1d
+    >>> rng = np.random.default_rng()
+    >>> xs = np.linspace(a, b, 50)
+    >>> cdf = studentized_range.cdf(xs, k, df)
+    # Create an interpolant of the inverse CDF
+    >>> ppf = interp1d(cdf, xs, fill_value='extrapolate')
+    # Perform inverse transform sampling using the interpolant
+    >>> r = ppf(rng.uniform(size=1000))
+
+    And compare the histogram:
+
+    >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+
+    def _argcheck(self, k, df):
+        return (k > 1) & (df > 0)
+
+    def _shape_info(self):
+        ik = _ShapeInfo("k", False, (1, np.inf), (False, False))
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        return [ik, idf]
+
+    def _fitstart(self, data):
+        # Default is k=1, but that is not a valid value of the parameter.
+        return super()._fitstart(data, args=(2, 1))
+
+    def _munp(self, K, k, df):
+        cython_symbol = '_studentized_range_moment'
+        _a, _b = self._get_support()
+        # all three of these are used to create a numpy array so they must
+        # be the same shape.
+
+        def _single_moment(K, k, df):
+            log_const = _stats._studentized_range_pdf_logconst(k, df)
+            arg = [K, k, df, log_const]
+            usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+
+            ranges = [(-np.inf, np.inf), (0, np.inf), (_a, _b)]
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_moment, 3, 1)
+        return np.asarray(ufunc(K, k, df), dtype=np.float64)[()]
+
+    def _pdf(self, x, k, df):
+
+        def _single_pdf(q, k, df):
+            # The infinite form of the PDF is derived from the infinite
+            # CDF.
+            if df < 100000:
+                cython_symbol = '_studentized_range_pdf'
+                log_const = _stats._studentized_range_pdf_logconst(k, df)
+                arg = [q, k, df, log_const]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf), (0, np.inf)]
+
+            else:
+                cython_symbol = '_studentized_range_pdf_asymptotic'
+                arg = [q, k]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf)]
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_pdf, 3, 1)
+        return np.asarray(ufunc(x, k, df), dtype=np.float64)[()]
+
+    def _cdf(self, x, k, df):
+
+        def _single_cdf(q, k, df):
+            # "When the degrees of freedom V are infinite the probability
+            # integral takes [on a] simpler form," and a single asymptotic
+            # integral is evaluated rather than the standard double integral.
+            # (Lund, Lund, page 205)
+            if df < 100000:
+                cython_symbol = '_studentized_range_cdf'
+                log_const = _stats._studentized_range_cdf_logconst(k, df)
+                arg = [q, k, df, log_const]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf), (0, np.inf)]
+
+            else:
+                cython_symbol = '_studentized_range_cdf_asymptotic'
+                arg = [q, k]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf)]
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_cdf, 3, 1)
+
+        # clip p-values to ensure they are in [0, 1].
+        return np.clip(np.asarray(ufunc(x, k, df), dtype=np.float64)[()], 0, 1)
+
+
+studentized_range = studentized_range_gen(name='studentized_range', a=0,
+                                          b=np.inf)
+
+
+class rel_breitwigner_gen(rv_continuous):
+    r"""A relativistic Breit-Wigner random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    cauchy: Cauchy distribution, also known as the Breit-Wigner distribution.
+
+    Notes
+    -----
+
+    The probability density function for `rel_breitwigner` is
+
+    .. math::
+
+        f(x, \rho) = \frac{k}{(x^2 - \rho^2)^2 + \rho^2}
+
+    where
+
+    .. math::
+        k = \frac{2\sqrt{2}\rho^2\sqrt{\rho^2 + 1}}
+            {\pi\sqrt{\rho^2 + \rho\sqrt{\rho^2 + 1}}}
+
+    The relativistic Breit-Wigner distribution is used in high energy physics
+    to model resonances [1]_. It gives the uncertainty in the invariant mass,
+    :math:`M` [2]_, of a resonance with characteristic mass :math:`M_0` and
+    decay-width :math:`\Gamma`, where :math:`M`, :math:`M_0` and :math:`\Gamma`
+    are expressed in natural units. In SciPy's parametrization, the shape
+    parameter :math:`\rho` is equal to :math:`M_0/\Gamma` and takes values in
+    :math:`(0, \infty)`.
+
+    Equivalently, the relativistic Breit-Wigner distribution is said to give
+    the uncertainty in the center-of-mass energy :math:`E_{\text{cm}}`. In
+    natural units, the speed of light :math:`c` is equal to 1 and the invariant
+    mass :math:`M` is equal to the rest energy :math:`Mc^2`. In the
+    center-of-mass frame, the rest energy is equal to the total energy [3]_.
+
+    %(after_notes)s
+
+    :math:`\rho = M/\Gamma` and :math:`\Gamma` is the scale parameter. For
+    example, if one seeks to model the :math:`Z^0` boson with :math:`M_0
+    \approx 91.1876 \text{ GeV}` and :math:`\Gamma \approx 2.4952\text{ GeV}`
+    [4]_ one can set ``rho=91.1876/2.4952`` and ``scale=2.4952``.
+
+    To ensure a physically meaningful result when using the `fit` method, one
+    should set ``floc=0`` to fix the location parameter to 0.
+
+    References
+    ----------
+    .. [1] Relativistic Breit-Wigner distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Relativistic_Breit-Wigner_distribution
+    .. [2] Invariant mass, Wikipedia,
+           https://en.wikipedia.org/wiki/Invariant_mass
+    .. [3] Center-of-momentum frame, Wikipedia,
+           https://en.wikipedia.org/wiki/Center-of-momentum_frame
+    .. [4] M. Tanabashi et al. (Particle Data Group) Phys. Rev. D 98, 030001 -
+           Published 17 August 2018
+
+    %(example)s
+
+    """
+    def _argcheck(self, rho):
+        return rho > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("rho", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, rho):
+        # C = k / rho**2
+        C = np.sqrt(
+            2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2))
+        ) * 2 / np.pi
+        with np.errstate(over='ignore'):
+            return C / (((x - rho)*(x + rho)/rho)**2 + 1)
+
+    def _cdf(self, x, rho):
+        # C = k / (2 * rho**2) / np.sqrt(1 + 1/rho**2)
+        C = np.sqrt(2/(1 + np.sqrt(1 + 1/rho**2)))/np.pi
+        result = (
+            np.sqrt(-1 + 1j/rho)
+            * np.arctan(x/np.sqrt(-rho*(rho + 1j)))
+        )
+        result = C * 2 * np.imag(result)
+        # Sometimes above formula produces values greater than 1.
+        return np.clip(result, None, 1)
+
+    def _munp(self, n, rho):
+        if n == 0:
+            return 1.
+        if n == 1:
+            # C = k / (2 * rho)
+            C = np.sqrt(
+                2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2))
+            ) / np.pi * rho
+            return C * (np.pi/2 + np.arctan(rho))
+        if n == 2:
+            # C = pi * k / (4 * rho)
+            C = np.sqrt(
+                (1 + 1/rho**2) / (2 * (1 + np.sqrt(1 + 1/rho**2)))
+            ) * rho
+            result = (1 - rho * 1j) / np.sqrt(-1 - 1j/rho)
+            return 2 * C * np.real(result)
+        else:
+            return np.inf
+
+    def _stats(self, rho):
+        # Returning None from stats makes public stats use _munp.
+        # nan values will be omitted from public stats. Skew and
+        # kurtosis are actually infinite.
+        return None, None, np.nan, np.nan
+
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        # Override rv_continuous.fit to better handle case where floc is set.
+        data, _, floc, fscale = _check_fit_input_parameters(
+            self, data, args, kwds
+        )
+
+        censored = isinstance(data, CensoredData)
+        if censored:
+            if data.num_censored() == 0:
+                # There are no censored values in data, so replace the
+                # CensoredData instance with a regular array.
+                data = data._uncensored
+                censored = False
+
+        if floc is None or censored:
+            return super().fit(data, *args, **kwds)
+
+        if fscale is None:
+            # The interquartile range approximates the scale parameter gamma.
+            # The median approximates rho * gamma.
+            p25, p50, p75 = np.quantile(data - floc, [0.25, 0.5, 0.75])
+            scale_0 = p75 - p25
+            rho_0 = p50 / scale_0
+            if not args:
+                args = [rho_0]
+            if "scale" not in kwds:
+                kwds["scale"] = scale_0
+        else:
+            M_0 = np.median(data - floc)
+            rho_0 = M_0 / fscale
+            if not args:
+                args = [rho_0]
+        return super().fit(data, *args, **kwds)
+
+
+rel_breitwigner = rel_breitwigner_gen(a=0.0, name="rel_breitwigner")
+
+
+# Collect names of classes and objects in this module.
+pairs = list(globals().copy().items())
+_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_continuous)
+
+__all__ = _distn_names + _distn_gen_names + ['rv_histogram']
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_correlation.py b/python_embeded/Lib/site-packages/scipy/stats/_correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad5712860f1e323b4969f44904f1a21636d0cd5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_correlation.py
@@ -0,0 +1,210 @@
+import numpy as np
+from scipy import stats
+from scipy.stats._stats_py import _SimpleNormal, SignificanceResult, _get_pvalue
+from scipy.stats._axis_nan_policy import _axis_nan_policy_factory
+
+
+__all__ = ['chatterjeexi']
+
+
+# TODO:
+# - Adjust to respect dtype
+
+
+def _xi_statistic(x, y, y_continuous):
+    # Compute xi correlation statistic
+
+    # `axis=-1` is guaranteed by _axis_nan_policy decorator
+    n = x.shape[-1]
+
+    # "Rearrange the data as (X(1), Y(1)), . . . ,(X(n), Y(n))
+    # such that X(1) ≤ ··· ≤ X(n)"
+    j = np.argsort(x, axis=-1)
+    j, y = np.broadcast_arrays(j, y)
+    y = np.take_along_axis(y, j, axis=-1)
+
+    # "Let ri be the rank of Y(i), that is, the number of j such that Y(j) ≤ Y(i)"
+    r = stats.rankdata(y, method='max', axis=-1)
+    # " additionally define li to be the number of j such that Y(j) ≥ Y(i)"
+    # Could probably compute this from r, but that can be an enhancement
+    l = stats.rankdata(-y, method='max', axis=-1)
+
+    num = np.sum(np.abs(np.diff(r, axis=-1)), axis=-1)
+    if y_continuous:  # [1] Eq. 1.1
+        statistic = 1 - 3 * num / (n ** 2 - 1)
+    else:  # [1] Eq. 1.2
+        den = 2 * np.sum((n - l) * l, axis=-1)
+        statistic = 1 - n * num / den
+
+    return statistic, r, l
+
+
+def _xi_std(r, l, y_continuous):
+    # Compute asymptotic standard deviation of xi under null hypothesis of independence
+
+    # `axis=-1` is guaranteed by _axis_nan_policy decorator
+    n = np.float64(r.shape[-1])
+
+    # "Suppose that X and Y are independent and Y is continuous. Then
+    # √n·ξn(X, Y) → N(0, 2/5) in distribution as n → ∞"
+    if y_continuous:  # [1] Theorem 2.1
+        return np.sqrt(2 / 5) / np.sqrt(n)
+
+    # "Suppose that X and Y are independent. Then √n·ξn(X, Y)
+    # converges to N(0, τ²) in distribution as n → ∞
+    # [1] Eq. 2.2 and surrounding math
+    i = np.arange(1, n + 1)
+    u = np.sort(r, axis=-1)
+    v = np.cumsum(u, axis=-1)
+    an = 1 / n**4 * np.sum((2*n - 2*i + 1) * u**2, axis=-1)
+    bn = 1 / n**5 * np.sum((v + (n - i)*u)**2, axis=-1)
+    cn = 1 / n**3 * np.sum((2*n - 2*i + 1) * u, axis=-1)
+    dn = 1 / n**3 * np.sum((l * (n - l)), axis=-1)
+    tau2 = (an - 2*bn + cn**2) / dn**2
+
+    return np.sqrt(tau2) / np.sqrt(n)
+
+
+def _chatterjeexi_iv(y_continuous, method):
+    # Input validation for `chatterjeexi`
+    # x, y, `axis` input validation taken care of by decorator
+
+    if y_continuous not in {True, False}:
+        raise ValueError('`y_continuous` must be boolean.')
+
+    if not isinstance(method, stats.PermutationMethod):
+        method = method.lower()
+        message = "`method` must be 'asymptotic' or a `PermutationMethod` instance."
+        if method != 'asymptotic':
+            raise ValueError(message)
+
+    return y_continuous, method
+
+
+def _unpack(res):
+    return res.statistic, res.pvalue
+
+
+@_axis_nan_policy_factory(SignificanceResult, paired=True, n_samples=2,
+                          result_to_tuple=_unpack, n_outputs=2, too_small=1)
+def chatterjeexi(x, y, *, axis=0, y_continuous=False, method='asymptotic'):
+    r"""Compute the xi correlation and perform a test of independence
+
+    The xi correlation coefficient is a measure of association between two
+    variables; the value tends to be close to zero when the variables are
+    independent and close to 1 when there is a strong association. Unlike
+    other correlation coefficients, the xi correlation is effective even
+    when the association is not monotonic.
+
+    Parameters
+    ----------
+    x, y : array-like
+        The samples: corresponding observations of the independent and
+        dependent variable. The (N-d) arrays must be broadcastable.
+    axis : int, default: 0
+        Axis along which to perform the test.
+    method : 'asymptotic' or `PermutationMethod` instance, optional
+        Selects the method used to calculate the *p*-value.
+        Default is 'asymptotic'. The following options are available.
+
+        * ``'asymptotic'``: compares the standardized test statistic
+          against the normal distribution.
+        * `PermutationMethod` instance. In this case, the p-value
+          is computed using `permutation_test` with the provided
+          configuration options and other appropriate settings.
+
+    y_continuous : bool, default: False
+        Whether `y` is assumed to be drawn from a continuous distribution.
+        If `y` is drawn from a continuous distribution, results are valid
+        whether this is assumed or not, but enabling this assumption will
+        result in faster computation and typically produce similar results.
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The xi correlation statistic.
+        pvalue : float
+            The associated *p*-value: the probability of a statistic at least as
+            high as the observed value under the null hypothesis of independence.
+
+    See Also
+    --------
+    scipy.stats.pearsonr, scipy.stats.spearmanr, scipy.stats.kendalltau
+
+    Notes
+    -----
+    There is currently no special handling of ties in `x`; they are broken arbitrarily
+    by the implementation.
+
+    [1]_ notes that the statistic is not symmetric in `x` and `y` *by design*:
+    "...we may want to understand if :math:`Y` is a function :math:`X`, and not just
+    if one of the variables is a function of the other." See [1]_ Remark 1.
+
+    References
+    ----------
+    .. [1] Chatterjee, Sourav. "A new coefficient of correlation." Journal of
+           the American Statistical Association 116.536 (2021): 2009-2022.
+           :doi:`10.1080/01621459.2020.1758115`.
+
+    Examples
+    --------
+    Generate perfectly correlated data, and observe that the xi correlation is
+    nearly 1.0.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(348932549825235)
+    >>> x = rng.uniform(0, 10, size=100)
+    >>> y = np.sin(x)
+    >>> res = stats.chatterjeexi(x, y)
+    >>> res.statistic
+    np.float64(0.9012901290129013)
+
+    The probability of observing such a high value of the statistic under the
+    null hypothesis of independence is very low.
+
+    >>> res.pvalue
+    np.float64(2.2206974648177804e-46)
+
+    As noise is introduced, the correlation coefficient decreases.
+
+    >>> noise = rng.normal(scale=[[0.1], [0.5], [1]], size=(3, 100))
+    >>> res = stats.chatterjeexi(x, y + noise, axis=-1)
+    >>> res.statistic
+    array([0.79507951, 0.41824182, 0.16651665])
+
+    Because the distribution of `y` is continuous, it is valid to pass
+    ``y_continuous=True``. The statistic is identical, and the p-value
+    (not shown) is only slightly different.
+
+    >>> stats.chatterjeexi(x, y + noise, y_continuous=True, axis=-1).statistic
+    array([0.79507951, 0.41824182, 0.16651665])
+
+    """
+    # x, y, `axis` input validation taken care of by decorator
+    # In fact, `axis` is guaranteed to be -1
+    y_continuous, method = _chatterjeexi_iv(y_continuous, method)
+
+    # A highly negative statistic is possible, e.g.
+    # x = np.arange(100.), y = (x % 2 == 0)
+    # Unclear whether we should expose `alternative`, though.
+    alternative = 'greater'
+
+    if method == 'asymptotic':
+        xi, r, l = _xi_statistic(x, y, y_continuous)
+        std = _xi_std(r, l, y_continuous)
+        norm = _SimpleNormal()
+        pvalue = _get_pvalue(xi / std, norm, alternative=alternative)
+    elif isinstance(method, stats.PermutationMethod):
+        res = stats.permutation_test(
+            # Could be faster if we just permuted the ranks; for now, keep it simple.
+            data=(y,), statistic=lambda y, axis: _xi_statistic(x, y, y_continuous)[0],
+            alternative=alternative, permutation_type='pairings', **method._asdict(),
+            axis=-1)  # `axis=-1` is guaranteed by _axis_nan_policy decorator
+
+        xi, pvalue = res.statistic, res.pvalue
+
+    return SignificanceResult(xi, pvalue)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_covariance.py b/python_embeded/Lib/site-packages/scipy/stats/_covariance.py
new file mode 100644
index 0000000000000000000000000000000000000000..364cc23a911e45a12390dc0b03c3c59c31f49878
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_covariance.py
@@ -0,0 +1,633 @@
+from functools import cached_property
+
+import numpy as np
+from scipy import linalg
+from scipy.stats import _multivariate
+
+
+__all__ = ["Covariance"]
+
+
+class Covariance:
+    """
+    Representation of a covariance matrix
+
+    Calculations involving covariance matrices (e.g. data whitening,
+    multivariate normal function evaluation) are often performed more
+    efficiently using a decomposition of the covariance matrix instead of the
+    covariance matrix itself. This class allows the user to construct an
+    object representing a covariance matrix using any of several
+    decompositions and perform calculations using a common interface.
+
+    .. note::
+
+        The `Covariance` class cannot be instantiated directly. Instead, use
+        one of the factory methods (e.g. `Covariance.from_diagonal`).
+
+    Examples
+    --------
+    The `Covariance` class is used by calling one of its
+    factory methods to create a `Covariance` object, then pass that
+    representation of the `Covariance` matrix as a shape parameter of a
+    multivariate distribution.
+
+    For instance, the multivariate normal distribution can accept an array
+    representing a covariance matrix:
+
+    >>> from scipy import stats
+    >>> import numpy as np
+    >>> d = [1, 2, 3]
+    >>> A = np.diag(d)  # a diagonal covariance matrix
+    >>> x = [4, -2, 5]  # a point of interest
+    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=A)
+    >>> dist.pdf(x)
+    4.9595685102808205e-08
+
+    but the calculations are performed in a very generic way that does not
+    take advantage of any special properties of the covariance matrix. Because
+    our covariance matrix is diagonal, we can use ``Covariance.from_diagonal``
+    to create an object representing the covariance matrix, and
+    `multivariate_normal` can use this to compute the probability density
+    function more efficiently.
+
+    >>> cov = stats.Covariance.from_diagonal(d)
+    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=cov)
+    >>> dist.pdf(x)
+    4.9595685102808205e-08
+
+    """
+    def __init__(self):
+        message = ("The `Covariance` class cannot be instantiated directly. "
+                   "Please use one of the factory methods "
+                   "(e.g. `Covariance.from_diagonal`).")
+        raise NotImplementedError(message)
+
+    @staticmethod
+    def from_diagonal(diagonal):
+        r"""
+        Return a representation of a covariance matrix from its diagonal.
+
+        Parameters
+        ----------
+        diagonal : array_like
+            The diagonal elements of a diagonal matrix.
+
+        Notes
+        -----
+        Let the diagonal elements of a diagonal covariance matrix :math:`D` be
+        stored in the vector :math:`d`.
+
+        When all elements of :math:`d` are strictly positive, whitening of a
+        data point :math:`x` is performed by computing
+        :math:`x \cdot d^{-1/2}`, where the inverse square root can be taken
+        element-wise.
+        :math:`\log\det{D}` is calculated as :math:`-2 \sum(\log{d})`,
+        where the :math:`\log` operation is performed element-wise.
+
+        This `Covariance` class supports singular covariance matrices. When
+        computing ``_log_pdet``, non-positive elements of :math:`d` are
+        ignored. Whitening is not well defined when the point to be whitened
+        does not lie in the span of the columns of the covariance matrix. The
+        convention taken here is to treat the inverse square root of
+        non-positive elements of :math:`d` as zeros.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = np.diag(rng.random(n))
+        >>> x = rng.random(size=n)
+
+        Extract the diagonal from ``A`` and create the `Covariance` object.
+
+        >>> d = np.diag(A)
+        >>> cov = stats.Covariance.from_diagonal(d)
+
+        Compare the functionality of the `Covariance` object against a
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = np.diag(d**-0.5) @ x
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaDiagonal(diagonal)
+
+    @staticmethod
+    def from_precision(precision, covariance=None):
+        r"""
+        Return a representation of a covariance from its precision matrix.
+
+        Parameters
+        ----------
+        precision : array_like
+            The precision matrix; that is, the inverse of a square, symmetric,
+            positive definite covariance matrix.
+        covariance : array_like, optional
+            The square, symmetric, positive definite covariance matrix. If not
+            provided, this may need to be calculated (e.g. to evaluate the
+            cumulative distribution function of
+            `scipy.stats.multivariate_normal`) by inverting `precision`.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A`, its precision matrix be
+        :math:`P = A^{-1}`, and :math:`L` be the lower Cholesky factor such
+        that :math:`L L^T = P`.
+        Whitening of a data point :math:`x` is performed by computing
+        :math:`x^T L`. :math:`\log\det{A}` is calculated as
+        :math:`-2tr(\log{L})`, where the :math:`\log` operation is performed
+        element-wise.
+
+        This `Covariance` class does not support singular covariance matrices
+        because the precision matrix does not exist for a singular covariance
+        matrix.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite precision matrix ``P`` and a
+        data point ``x``. (If the precision matrix is not already available,
+        consider the other factory methods of the `Covariance` class.)
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> P = rng.random(size=(n, n))
+        >>> P = P @ P.T  # a precision matrix must be positive definite
+        >>> x = rng.random(size=n)
+
+        Create the `Covariance` object.
+
+        >>> cov = stats.Covariance.from_precision(P)
+
+        Compare the functionality of the `Covariance` object against
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = x @ np.linalg.cholesky(P)
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = -np.linalg.slogdet(P)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaPrecision(precision, covariance)
+
+    @staticmethod
+    def from_cholesky(cholesky):
+        r"""
+        Representation of a covariance provided via the (lower) Cholesky factor
+
+        Parameters
+        ----------
+        cholesky : array_like
+            The lower triangular Cholesky factor of the covariance matrix.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A` and :math:`L` be the lower
+        Cholesky factor such that :math:`L L^T = A`.
+        Whitening of a data point :math:`x` is performed by computing
+        :math:`L^{-1} x`. :math:`\log\det{A}` is calculated as
+        :math:`2tr(\log{L})`, where the :math:`\log` operation is performed
+        element-wise.
+
+        This `Covariance` class does not support singular covariance matrices
+        because the Cholesky decomposition does not exist for a singular
+        covariance matrix.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = rng.random(size=(n, n))
+        >>> A = A @ A.T  # make the covariance symmetric positive definite
+        >>> x = rng.random(size=n)
+
+        Perform the Cholesky decomposition of ``A`` and create the
+        `Covariance` object.
+
+        >>> L = np.linalg.cholesky(A)
+        >>> cov = stats.Covariance.from_cholesky(L)
+
+        Compare the functionality of the `Covariance` object against
+        reference implementation.
+
+        >>> from scipy.linalg import solve_triangular
+        >>> res = cov.whiten(x)
+        >>> ref = solve_triangular(L, x, lower=True)
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaCholesky(cholesky)
+
+    @staticmethod
+    def from_eigendecomposition(eigendecomposition):
+        r"""
+        Representation of a covariance provided via eigendecomposition
+
+        Parameters
+        ----------
+        eigendecomposition : sequence
+            A sequence (nominally a tuple) containing the eigenvalue and
+            eigenvector arrays as computed by `scipy.linalg.eigh` or
+            `numpy.linalg.eigh`.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A`, let :math:`V` be matrix of
+        eigenvectors, and let :math:`W` be the diagonal matrix of eigenvalues
+        such that `V W V^T = A`.
+
+        When all of the eigenvalues are strictly positive, whitening of a
+        data point :math:`x` is performed by computing
+        :math:`x^T (V W^{-1/2})`, where the inverse square root can be taken
+        element-wise.
+        :math:`\log\det{A}` is calculated as  :math:`tr(\log{W})`,
+        where the :math:`\log` operation is performed element-wise.
+
+        This `Covariance` class supports singular covariance matrices. When
+        computing ``_log_pdet``, non-positive eigenvalues are ignored.
+        Whitening is not well defined when the point to be whitened
+        does not lie in the span of the columns of the covariance matrix. The
+        convention taken here is to treat the inverse square root of
+        non-positive eigenvalues as zeros.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = rng.random(size=(n, n))
+        >>> A = A @ A.T  # make the covariance symmetric positive definite
+        >>> x = rng.random(size=n)
+
+        Perform the eigendecomposition of ``A`` and create the `Covariance`
+        object.
+
+        >>> w, v = np.linalg.eigh(A)
+        >>> cov = stats.Covariance.from_eigendecomposition((w, v))
+
+        Compare the functionality of the `Covariance` object against
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = x @ (v @ np.diag(w**-0.5))
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaEigendecomposition(eigendecomposition)
+
+    def whiten(self, x):
+        """
+        Perform a whitening transformation on data.
+
+        "Whitening" ("white" as in "white noise", in which each frequency has
+        equal magnitude) transforms a set of random variables into a new set of
+        random variables with unit-diagonal covariance. When a whitening
+        transform is applied to a sample of points distributed according to
+        a multivariate normal distribution with zero mean, the covariance of
+        the transformed sample is approximately the identity matrix.
+
+        Parameters
+        ----------
+        x : array_like
+            An array of points. The last dimension must correspond with the
+            dimensionality of the space, i.e., the number of columns in the
+            covariance matrix.
+
+        Returns
+        -------
+        x_ : array_like
+            The transformed array of points.
+
+        References
+        ----------
+        .. [1] "Whitening Transformation". Wikipedia.
+               https://en.wikipedia.org/wiki/Whitening_transformation
+        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
+               coloring linear transformation". Transactions of VSB 18.2
+               (2018): 31-35. :doi:`10.31490/tces-2018-0013`
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 3
+        >>> A = rng.random(size=(n, n))
+        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
+        >>> precision = np.linalg.inv(cov_array)
+        >>> cov_object = stats.Covariance.from_precision(precision)
+        >>> x = rng.multivariate_normal(np.zeros(n), cov_array, size=(10000))
+        >>> x_ = cov_object.whiten(x)
+        >>> np.cov(x_, rowvar=False)  # near-identity covariance
+        array([[0.97862122, 0.00893147, 0.02430451],
+               [0.00893147, 0.96719062, 0.02201312],
+               [0.02430451, 0.02201312, 0.99206881]])
+
+        """
+        return self._whiten(np.asarray(x))
+
+    def colorize(self, x):
+        """
+        Perform a colorizing transformation on data.
+
+        "Colorizing" ("color" as in "colored noise", in which different
+        frequencies may have different magnitudes) transforms a set of
+        uncorrelated random variables into a new set of random variables with
+        the desired covariance. When a coloring transform is applied to a
+        sample of points distributed according to a multivariate normal
+        distribution with identity covariance and zero mean, the covariance of
+        the transformed sample is approximately the covariance matrix used
+        in the coloring transform.
+
+        Parameters
+        ----------
+        x : array_like
+            An array of points. The last dimension must correspond with the
+            dimensionality of the space, i.e., the number of columns in the
+            covariance matrix.
+
+        Returns
+        -------
+        x_ : array_like
+            The transformed array of points.
+
+        References
+        ----------
+        .. [1] "Whitening Transformation". Wikipedia.
+               https://en.wikipedia.org/wiki/Whitening_transformation
+        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
+               coloring linear transformation". Transactions of VSB 18.2
+               (2018): 31-35. :doi:`10.31490/tces-2018-0013`
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng(1638083107694713882823079058616272161)
+        >>> n = 3
+        >>> A = rng.random(size=(n, n))
+        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
+        >>> cholesky = np.linalg.cholesky(cov_array)
+        >>> cov_object = stats.Covariance.from_cholesky(cholesky)
+        >>> x = rng.multivariate_normal(np.zeros(n), np.eye(n), size=(10000))
+        >>> x_ = cov_object.colorize(x)
+        >>> cov_data = np.cov(x_, rowvar=False)
+        >>> np.allclose(cov_data, cov_array, rtol=3e-2)
+        True
+        """
+        return self._colorize(np.asarray(x))
+
+    @property
+    def log_pdet(self):
+        """
+        Log of the pseudo-determinant of the covariance matrix
+        """
+        return np.array(self._log_pdet, dtype=float)[()]
+
+    @property
+    def rank(self):
+        """
+        Rank of the covariance matrix
+        """
+        return np.array(self._rank, dtype=int)[()]
+
+    @property
+    def covariance(self):
+        """
+        Explicit representation of the covariance matrix
+        """
+        return self._covariance
+
+    @property
+    def shape(self):
+        """
+        Shape of the covariance array
+        """
+        return self._shape
+
+    def _validate_matrix(self, A, name):
+        A = np.atleast_2d(A)
+        m, n = A.shape[-2:]
+        if m != n or A.ndim != 2 or not (np.issubdtype(A.dtype, np.integer) or
+                                         np.issubdtype(A.dtype, np.floating)):
+            message = (f"The input `{name}` must be a square, "
+                       "two-dimensional array of real numbers.")
+            raise ValueError(message)
+        return A
+
+    def _validate_vector(self, A, name):
+        A = np.atleast_1d(A)
+        if A.ndim != 1 or not (np.issubdtype(A.dtype, np.integer) or
+                               np.issubdtype(A.dtype, np.floating)):
+            message = (f"The input `{name}` must be a one-dimensional array "
+                       "of real numbers.")
+            raise ValueError(message)
+        return A
+
+
+class CovViaPrecision(Covariance):
+
+    def __init__(self, precision, covariance=None):
+        precision = self._validate_matrix(precision, 'precision')
+        if covariance is not None:
+            covariance = self._validate_matrix(covariance, 'covariance')
+            message = "`precision.shape` must equal `covariance.shape`."
+            if precision.shape != covariance.shape:
+                raise ValueError(message)
+
+        self._chol_P = np.linalg.cholesky(precision)
+        self._log_pdet = -2*np.log(np.diag(self._chol_P)).sum(axis=-1)
+        self._rank = precision.shape[-1]  # must be full rank if invertible
+        self._precision = precision
+        self._cov_matrix = covariance
+        self._shape = precision.shape
+        self._allow_singular = False
+
+    def _whiten(self, x):
+        return x @ self._chol_P
+
+    @cached_property
+    def _covariance(self):
+        n = self._shape[-1]
+        return (linalg.cho_solve((self._chol_P, True), np.eye(n))
+                if self._cov_matrix is None else self._cov_matrix)
+
+    def _colorize(self, x):
+        return linalg.solve_triangular(self._chol_P.T, x.T, lower=False).T
+
+
+def _dot_diag(x, d):
+    # If d were a full diagonal matrix, x @ d would always do what we want.
+    # Special treatment is needed for n-dimensional `d` in which each row
+    # includes only the diagonal elements of a covariance matrix.
+    return x * d if x.ndim < 2 else x * np.expand_dims(d, -2)
+
+
+class CovViaDiagonal(Covariance):
+
+    def __init__(self, diagonal):
+        diagonal = self._validate_vector(diagonal, 'diagonal')
+
+        i_zero = diagonal <= 0
+        positive_diagonal = np.array(diagonal, dtype=np.float64)
+
+        positive_diagonal[i_zero] = 1  # ones don't affect determinant
+        self._log_pdet = np.sum(np.log(positive_diagonal), axis=-1)
+
+        psuedo_reciprocals = 1 / np.sqrt(positive_diagonal)
+        psuedo_reciprocals[i_zero] = 0
+
+        self._sqrt_diagonal = np.sqrt(diagonal)
+        self._LP = psuedo_reciprocals
+        self._rank = positive_diagonal.shape[-1] - i_zero.sum(axis=-1)
+        self._covariance = np.apply_along_axis(np.diag, -1, diagonal)
+        self._i_zero = i_zero
+        self._shape = self._covariance.shape
+        self._allow_singular = True
+
+    def _whiten(self, x):
+        return _dot_diag(x, self._LP)
+
+    def _colorize(self, x):
+        return _dot_diag(x, self._sqrt_diagonal)
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        return ~np.any(_dot_diag(x, self._i_zero), axis=-1)
+
+
+class CovViaCholesky(Covariance):
+
+    def __init__(self, cholesky):
+        L = self._validate_matrix(cholesky, 'cholesky')
+
+        self._factor = L
+        self._log_pdet = 2*np.log(np.diag(self._factor)).sum(axis=-1)
+        self._rank = L.shape[-1]  # must be full rank for cholesky
+        self._shape = L.shape
+        self._allow_singular = False
+
+    @cached_property
+    def _covariance(self):
+        return self._factor @ self._factor.T
+
+    def _whiten(self, x):
+        res = linalg.solve_triangular(self._factor, x.T, lower=True).T
+        return res
+
+    def _colorize(self, x):
+        return x @ self._factor.T
+
+
+class CovViaEigendecomposition(Covariance):
+
+    def __init__(self, eigendecomposition):
+        eigenvalues, eigenvectors = eigendecomposition
+        eigenvalues = self._validate_vector(eigenvalues, 'eigenvalues')
+        eigenvectors = self._validate_matrix(eigenvectors, 'eigenvectors')
+        message = ("The shapes of `eigenvalues` and `eigenvectors` "
+                   "must be compatible.")
+        try:
+            eigenvalues = np.expand_dims(eigenvalues, -2)
+            eigenvectors, eigenvalues = np.broadcast_arrays(eigenvectors,
+                                                            eigenvalues)
+            eigenvalues = eigenvalues[..., 0, :]
+        except ValueError:
+            raise ValueError(message)
+
+        i_zero = eigenvalues <= 0
+        positive_eigenvalues = np.array(eigenvalues, dtype=np.float64)
+
+        positive_eigenvalues[i_zero] = 1  # ones don't affect determinant
+        self._log_pdet = np.sum(np.log(positive_eigenvalues), axis=-1)
+
+        psuedo_reciprocals = 1 / np.sqrt(positive_eigenvalues)
+        psuedo_reciprocals[i_zero] = 0
+
+        self._LP = eigenvectors * psuedo_reciprocals
+        self._LA = eigenvectors * np.sqrt(eigenvalues)
+        self._rank = positive_eigenvalues.shape[-1] - i_zero.sum(axis=-1)
+        self._w = eigenvalues
+        self._v = eigenvectors
+        self._shape = eigenvectors.shape
+        self._null_basis = eigenvectors * i_zero
+        # This is only used for `_support_mask`, not to decide whether
+        # the covariance is singular or not.
+        self._eps = _multivariate._eigvalsh_to_eps(eigenvalues) * 10**3
+        self._allow_singular = True
+
+    def _whiten(self, x):
+        return x @ self._LP
+
+    def _colorize(self, x):
+        return x @ self._LA.T
+
+    @cached_property
+    def _covariance(self):
+        return (self._v * self._w) @ self._v.T
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        residual = np.linalg.norm(x @ self._null_basis, axis=-1)
+        in_support = residual < self._eps
+        return in_support
+
+
+class CovViaPSD(Covariance):
+    """
+    Representation of a covariance provided via an instance of _PSD
+    """
+
+    def __init__(self, psd):
+        self._LP = psd.U
+        self._log_pdet = psd.log_pdet
+        self._rank = psd.rank
+        self._covariance = psd._M
+        self._shape = psd._M.shape
+        self._psd = psd
+        self._allow_singular = False  # by default
+
+    def _whiten(self, x):
+        return x @ self._LP
+
+    def _support_mask(self, x):
+        return self._psd._support_mask(x)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_crosstab.py b/python_embeded/Lib/site-packages/scipy/stats/_crosstab.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dc80df5af4a24bdf8b485e29d4770f2c9d7c4a4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_crosstab.py
@@ -0,0 +1,204 @@
+import numpy as np
+from scipy.sparse import coo_matrix
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+CrosstabResult = _make_tuple_bunch(
+    "CrosstabResult", ["elements", "count"]
+)
+
+
+def crosstab(*args, levels=None, sparse=False):
+    """
+    Return table of counts for each possible unique combination in ``*args``.
+
+    When ``len(args) > 1``, the array computed by this function is
+    often referred to as a *contingency table* [1]_.
+
+    The arguments must be sequences with the same length.  The second return
+    value, `count`, is an integer array with ``len(args)`` dimensions.  If
+    `levels` is None, the shape of `count` is ``(n0, n1, ...)``, where ``nk``
+    is the number of unique elements in ``args[k]``.
+
+    Parameters
+    ----------
+    *args : sequences
+        A sequence of sequences whose unique aligned elements are to be
+        counted.  The sequences in args must all be the same length.
+    levels : sequence, optional
+        If `levels` is given, it must be a sequence that is the same length as
+        `args`.  Each element in `levels` is either a sequence or None.  If it
+        is a sequence, it gives the values in the corresponding sequence in
+        `args` that are to be counted.  If any value in the sequences in `args`
+        does not occur in the corresponding sequence in `levels`, that value
+        is ignored and not counted in the returned array `count`.  The default
+        value of `levels` for ``args[i]`` is ``np.unique(args[i])``
+    sparse : bool, optional
+        If True, return a sparse matrix.  The matrix will be an instance of
+        the `scipy.sparse.coo_matrix` class.  Because SciPy's sparse matrices
+        must be 2-d, only two input sequences are allowed when `sparse` is
+        True.  Default is False.
+
+    Returns
+    -------
+    res : CrosstabResult
+        An object containing the following attributes:
+
+        elements : tuple of numpy.ndarrays.
+            Tuple of length ``len(args)`` containing the arrays of elements
+            that are counted in `count`.  These can be interpreted as the
+            labels of the corresponding dimensions of `count`. If `levels` was
+            given, then if ``levels[i]`` is not None, ``elements[i]`` will
+            hold the values given in ``levels[i]``.
+        count : numpy.ndarray or scipy.sparse.coo_matrix
+            Counts of the unique elements in ``zip(*args)``, stored in an
+            array. Also known as a *contingency table* when ``len(args) > 1``.
+
+    See Also
+    --------
+    numpy.unique
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] "Contingency table", http://en.wikipedia.org/wiki/Contingency_table
+
+    Examples
+    --------
+    >>> from scipy.stats.contingency import crosstab
+
+    Given the lists `a` and `x`, create a contingency table that counts the
+    frequencies of the corresponding pairs.
+
+    >>> a = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']
+    >>> x = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z']
+    >>> res = crosstab(a, x)
+    >>> avals, xvals = res.elements
+    >>> avals
+    array(['A', 'B'], dtype='>> xvals
+    array(['X', 'Y', 'Z'], dtype='>> res.count
+    array([[2, 3, 0],
+           [1, 0, 4]])
+
+    So ``('A', 'X')`` occurs twice, ``('A', 'Y')`` occurs three times, etc.
+
+    Higher dimensional contingency tables can be created.
+
+    >>> p = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1]
+    >>> res = crosstab(a, x, p)
+    >>> res.count
+    array([[[2, 0],
+            [2, 1],
+            [0, 0]],
+           [[1, 0],
+            [0, 0],
+            [1, 3]]])
+    >>> res.count.shape
+    (2, 3, 2)
+
+    The values to be counted can be set by using the `levels` argument.
+    It allows the elements of interest in each input sequence to be
+    given explicitly instead finding the unique elements of the sequence.
+
+    For example, suppose one of the arguments is an array containing the
+    answers to a survey question, with integer values 1 to 4.  Even if the
+    value 1 does not occur in the data, we want an entry for it in the table.
+
+    >>> q1 = [2, 3, 3, 2, 4, 4, 2, 3, 4, 4, 4, 3, 3, 3, 4]  # 1 does not occur.
+    >>> q2 = [4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 4, 2, 2, 2, 4]  # 3 does not occur.
+    >>> options = [1, 2, 3, 4]
+    >>> res = crosstab(q1, q2, levels=(options, options))
+    >>> res.count
+    array([[0, 0, 0, 0],
+           [1, 1, 0, 1],
+           [1, 4, 0, 1],
+           [0, 3, 0, 3]])
+
+    If `levels` is given, but an element of `levels` is None, the unique values
+    of the corresponding argument are used. For example,
+
+    >>> res = crosstab(q1, q2, levels=(None, options))
+    >>> res.elements
+    [array([2, 3, 4]), [1, 2, 3, 4]]
+    >>> res.count
+    array([[1, 1, 0, 1],
+           [1, 4, 0, 1],
+           [0, 3, 0, 3]])
+
+    If we want to ignore the pairs where 4 occurs in ``q2``, we can
+    give just the values [1, 2] to `levels`, and the 4 will be ignored:
+
+    >>> res = crosstab(q1, q2, levels=(None, [1, 2]))
+    >>> res.elements
+    [array([2, 3, 4]), [1, 2]]
+    >>> res.count
+    array([[1, 1],
+           [1, 4],
+           [0, 3]])
+
+    Finally, let's repeat the first example, but return a sparse matrix:
+
+    >>> res = crosstab(a, x, sparse=True)
+    >>> res.count
+    
+    >>> res.count.toarray()
+    array([[2, 3, 0],
+           [1, 0, 4]])
+
+    """
+    nargs = len(args)
+    if nargs == 0:
+        raise TypeError("At least one input sequence is required.")
+
+    len0 = len(args[0])
+    if not all(len(a) == len0 for a in args[1:]):
+        raise ValueError("All input sequences must have the same length.")
+
+    if sparse and nargs != 2:
+        raise ValueError("When `sparse` is True, only two input sequences "
+                         "are allowed.")
+
+    if levels is None:
+        # Call np.unique with return_inverse=True on each argument.
+        actual_levels, indices = zip(*[np.unique(a, return_inverse=True)
+                                       for a in args])
+    else:
+        # `levels` is not None...
+        if len(levels) != nargs:
+            raise ValueError('len(levels) must equal the number of input '
+                             'sequences')
+
+        args = [np.asarray(arg) for arg in args]
+        mask = np.zeros((nargs, len0), dtype=np.bool_)
+        inv = np.zeros((nargs, len0), dtype=np.intp)
+        actual_levels = []
+        for k, (levels_list, arg) in enumerate(zip(levels, args)):
+            if levels_list is None:
+                levels_list, inv[k, :] = np.unique(arg, return_inverse=True)
+                mask[k, :] = True
+            else:
+                q = arg == np.asarray(levels_list).reshape(-1, 1)
+                mask[k, :] = np.any(q, axis=0)
+                qnz = q.T.nonzero()
+                inv[k, qnz[0]] = qnz[1]
+            actual_levels.append(levels_list)
+
+        mask_all = mask.all(axis=0)
+        indices = tuple(inv[:, mask_all])
+
+    if sparse:
+        count = coo_matrix((np.ones(len(indices[0]), dtype=int),
+                            (indices[0], indices[1])))
+        count.sum_duplicates()
+    else:
+        shape = [len(u) for u in actual_levels]
+        count = np.zeros(shape, dtype=int)
+        np.add.at(count, indices, 1)
+
+    return CrosstabResult(actual_levels, count)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_discrete_distns.py b/python_embeded/Lib/site-packages/scipy/stats/_discrete_distns.py
new file mode 100644
index 0000000000000000000000000000000000000000..44b0f3ced9630f04e01fa61fb856f110d0a6bd73
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_discrete_distns.py
@@ -0,0 +1,2091 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+from functools import partial
+
+from scipy import special
+from scipy.special import entr, logsumexp, betaln, gammaln as gamln, zeta
+from scipy._lib._util import _lazywhere, rng_integers
+from scipy.interpolate import interp1d
+
+from numpy import floor, ceil, log, exp, sqrt, log1p, expm1, tanh, cosh, sinh
+
+import numpy as np
+
+from ._distn_infrastructure import (rv_discrete, get_distribution_names,
+                                    _vectorize_rvs_over_shapes,
+                                    _ShapeInfo, _isintegral,
+                                    rv_discrete_frozen)
+from ._biasedurn import (_PyFishersNCHypergeometric,
+                         _PyWalleniusNCHypergeometric,
+                         _PyStochasticLib3)
+from ._stats_pythran import _poisson_binom
+
+import scipy.special._ufuncs as scu
+
+
+
+class binom_gen(rv_discrete):
+    r"""A binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `binom` is:
+
+    .. math::
+
+       f(k) = \binom{n}{k} p^k (1-p)^{n-k}
+
+    for :math:`k \in \{0, 1, \dots, n\}`, :math:`0 \leq p \leq 1`
+
+    `binom` takes :math:`n` and :math:`p` as shape parameters,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    See Also
+    --------
+    hypergeom, nbinom, nhypergeom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, n, p, size=None, random_state=None):
+        return random_state.binomial(n, p, size)
+
+    def _argcheck(self, n, p):
+        return (n >= 0) & _isintegral(n) & (p >= 0) & (p <= 1)
+
+    def _get_support(self, n, p):
+        return self.a, n
+
+    def _logpmf(self, x, n, p):
+        k = floor(x)
+        combiln = (gamln(n+1) - (gamln(k+1) + gamln(n-k+1)))
+        return combiln + special.xlogy(k, p) + special.xlog1py(n-k, -p)
+
+    def _pmf(self, x, n, p):
+        # binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)
+        return scu._binom_pmf(x, n, p)
+
+    def _cdf(self, x, n, p):
+        k = floor(x)
+        return scu._binom_cdf(k, n, p)
+
+    def _sf(self, x, n, p):
+        k = floor(x)
+        return scu._binom_sf(k, n, p)
+
+    def _isf(self, x, n, p):
+        return scu._binom_isf(x, n, p)
+
+    def _ppf(self, q, n, p):
+        return scu._binom_ppf(q, n, p)
+
+    def _stats(self, n, p, moments='mv'):
+        mu = n * p
+        var = mu - n * np.square(p)
+        g1, g2 = None, None
+        if 's' in moments:
+            pq = p - np.square(p)
+            npq_sqrt = np.sqrt(n * pq)
+            t1 = np.reciprocal(npq_sqrt)
+            t2 = (2.0 * p) / npq_sqrt
+            g1 = t1 - t2
+        if 'k' in moments:
+            pq = p - np.square(p)
+            npq = n * pq
+            t1 = np.reciprocal(npq)
+            t2 = 6.0/n
+            g2 = t1 - t2
+        return mu, var, g1, g2
+
+    def _entropy(self, n, p):
+        k = np.r_[0:n + 1]
+        vals = self._pmf(k, n, p)
+        return np.sum(entr(vals), axis=0)
+
+
+binom = binom_gen(name='binom')
+
+
+class bernoulli_gen(binom_gen):
+    r"""A Bernoulli discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `bernoulli` is:
+
+    .. math::
+
+       f(k) = \begin{cases}1-p  &\text{if } k = 0\\
+                           p    &\text{if } k = 1\end{cases}
+
+    for :math:`k` in :math:`\{0, 1\}`, :math:`0 \leq p \leq 1`
+
+    `bernoulli` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        return binom_gen._rvs(self, 1, p, size=size, random_state=random_state)
+
+    def _argcheck(self, p):
+        return (p >= 0) & (p <= 1)
+
+    def _get_support(self, p):
+        # Overrides binom_gen._get_support!x
+        return self.a, self.b
+
+    def _logpmf(self, x, p):
+        return binom._logpmf(x, 1, p)
+
+    def _pmf(self, x, p):
+        # bernoulli.pmf(k) = 1-p  if k = 0
+        #                  = p    if k = 1
+        return binom._pmf(x, 1, p)
+
+    def _cdf(self, x, p):
+        return binom._cdf(x, 1, p)
+
+    def _sf(self, x, p):
+        return binom._sf(x, 1, p)
+
+    def _isf(self, x, p):
+        return binom._isf(x, 1, p)
+
+    def _ppf(self, q, p):
+        return binom._ppf(q, 1, p)
+
+    def _stats(self, p):
+        return binom._stats(1, p)
+
+    def _entropy(self, p):
+        return entr(p) + entr(1-p)
+
+
+bernoulli = bernoulli_gen(b=1, name='bernoulli')
+
+
+class betabinom_gen(rv_discrete):
+    r"""A beta-binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The beta-binomial distribution is a binomial distribution with a
+    probability of success `p` that follows a beta distribution.
+
+    The probability mass function for `betabinom` is:
+
+    .. math::
+
+       f(k) = \binom{n}{k} \frac{B(k + a, n - k + b)}{B(a, b)}
+
+    for :math:`k \in \{0, 1, \dots, n\}`, :math:`n \geq 0`, :math:`a > 0`,
+    :math:`b > 0`, where :math:`B(a, b)` is the beta function.
+
+    `betabinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
+
+    %(after_notes)s
+
+    .. versionadded:: 1.4.0
+
+    See Also
+    --------
+    beta, binom
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, n, a, b, size=None, random_state=None):
+        p = random_state.beta(a, b, size)
+        return random_state.binomial(n, p, size)
+
+    def _get_support(self, n, a, b):
+        return 0, n
+
+    def _argcheck(self, n, a, b):
+        return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0)
+
+    def _logpmf(self, x, n, a, b):
+        k = floor(x)
+        combiln = -log(n + 1) - betaln(n - k + 1, k + 1)
+        return combiln + betaln(k + a, n - k + b) - betaln(a, b)
+
+    def _pmf(self, x, n, a, b):
+        return exp(self._logpmf(x, n, a, b))
+
+    def _stats(self, n, a, b, moments='mv'):
+        e_p = a / (a + b)
+        e_q = 1 - e_p
+        mu = n * e_p
+        var = n * (a + b + n) * e_p * e_q / (a + b + 1)
+        g1, g2 = None, None
+        if 's' in moments:
+            g1 = 1.0 / sqrt(var)
+            g1 *= (a + b + 2 * n) * (b - a)
+            g1 /= (a + b + 2) * (a + b)
+        if 'k' in moments:
+            g2 = (a + b).astype(e_p.dtype)
+            g2 *= (a + b - 1 + 6 * n)
+            g2 += 3 * a * b * (n - 2)
+            g2 += 6 * n ** 2
+            g2 -= 3 * e_p * b * n * (6 - n)
+            g2 -= 18 * e_p * e_q * n ** 2
+            g2 *= (a + b) ** 2 * (1 + a + b)
+            g2 /= (n * a * b * (a + b + 2) * (a + b + 3) * (a + b + n))
+            g2 -= 3
+        return mu, var, g1, g2
+
+
+betabinom = betabinom_gen(name='betabinom')
+
+
+class nbinom_gen(rv_discrete):
+    r"""A negative binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Negative binomial distribution describes a sequence of i.i.d. Bernoulli
+    trials, repeated until a predefined, non-random number of successes occurs.
+
+    The probability mass function of the number of failures for `nbinom` is:
+
+    .. math::
+
+       f(k) = \binom{k+n-1}{n-1} p^n (1-p)^k
+
+    for :math:`k \ge 0`, :math:`0 < p \leq 1`
+
+    `nbinom` takes :math:`n` and :math:`p` as shape parameters where :math:`n`
+    is the number of successes, :math:`p` is the probability of a single
+    success, and :math:`1-p` is the probability of a single failure.
+
+    Another common parameterization of the negative binomial distribution is
+    in terms of the mean number of failures :math:`\mu` to achieve :math:`n`
+    successes. The mean :math:`\mu` is related to the probability of success
+    as
+
+    .. math::
+
+       p = \frac{n}{n + \mu}
+
+    The number of successes :math:`n` may also be specified in terms of a
+    "dispersion", "heterogeneity", or "aggregation" parameter :math:`\alpha`,
+    which relates the mean :math:`\mu` to the variance :math:`\sigma^2`,
+    e.g. :math:`\sigma^2 = \mu + \alpha \mu^2`. Regardless of the convention
+    used for :math:`\alpha`,
+
+    .. math::
+
+       p &= \frac{\mu}{\sigma^2} \\
+       n &= \frac{\mu^2}{\sigma^2 - \mu}
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf``, ``isf``
+    and ``stats`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    See Also
+    --------
+    hypergeom, binom, nhypergeom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, n, p, size=None, random_state=None):
+        return random_state.negative_binomial(n, p, size)
+
+    def _argcheck(self, n, p):
+        return (n > 0) & (p > 0) & (p <= 1)
+
+    def _pmf(self, x, n, p):
+        # nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
+        return scu._nbinom_pmf(x, n, p)
+
+    def _logpmf(self, x, n, p):
+        coeff = gamln(n+x) - gamln(x+1) - gamln(n)
+        return coeff + n*log(p) + special.xlog1py(x, -p)
+
+    def _cdf(self, x, n, p):
+        k = floor(x)
+        return scu._nbinom_cdf(k, n, p)
+
+    def _logcdf(self, x, n, p):
+        k = floor(x)
+        k, n, p = np.broadcast_arrays(k, n, p)
+        cdf = self._cdf(k, n, p)
+        cond = cdf > 0.5
+        def f1(k, n, p):
+            return np.log1p(-special.betainc(k + 1, n, 1 - p))
+
+        # do calc in place
+        logcdf = cdf
+        with np.errstate(divide='ignore'):
+            logcdf[cond] = f1(k[cond], n[cond], p[cond])
+            logcdf[~cond] = np.log(cdf[~cond])
+        return logcdf
+
+    def _sf(self, x, n, p):
+        k = floor(x)
+        return scu._nbinom_sf(k, n, p)
+
+    def _isf(self, x, n, p):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nbinom_isf(x, n, p)
+
+    def _ppf(self, q, n, p):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nbinom_ppf(q, n, p)
+
+    def _stats(self, n, p):
+        return (
+            scu._nbinom_mean(n, p),
+            scu._nbinom_variance(n, p),
+            scu._nbinom_skewness(n, p),
+            scu._nbinom_kurtosis_excess(n, p),
+        )
+
+
+nbinom = nbinom_gen(name='nbinom')
+
+
+class betanbinom_gen(rv_discrete):
+    r"""A beta-negative-binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The beta-negative-binomial distribution is a negative binomial
+    distribution with a probability of success `p` that follows a
+    beta distribution.
+
+    The probability mass function for `betanbinom` is:
+
+    .. math::
+
+       f(k) = \binom{n + k - 1}{k} \frac{B(a + n, b + k)}{B(a, b)}
+
+    for :math:`k \ge 0`, :math:`n \geq 0`, :math:`a > 0`,
+    :math:`b > 0`, where :math:`B(a, b)` is the beta function.
+
+    `betanbinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Beta_negative_binomial_distribution
+
+    %(after_notes)s
+
+    .. versionadded:: 1.12.0
+
+    See Also
+    --------
+    betabinom : Beta binomial distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, n, a, b, size=None, random_state=None):
+        p = random_state.beta(a, b, size)
+        return random_state.negative_binomial(n, p, size)
+
+    def _argcheck(self, n, a, b):
+        return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0)
+
+    def _logpmf(self, x, n, a, b):
+        k = floor(x)
+        combiln = -np.log(n + k) - betaln(n, k + 1)
+        return combiln + betaln(a + n, b + k) - betaln(a, b)
+
+    def _pmf(self, x, n, a, b):
+        return exp(self._logpmf(x, n, a, b))
+
+    def _stats(self, n, a, b, moments='mv'):
+        # reference: Wolfram Alpha input
+        # BetaNegativeBinomialDistribution[a, b, n]
+        def mean(n, a, b):
+            return n * b / (a - 1.)
+        mu = _lazywhere(a > 1, (n, a, b), f=mean, fillvalue=np.inf)
+        def var(n, a, b):
+            return (n * b * (n + a - 1.) * (a + b - 1.)
+                    / ((a - 2.) * (a - 1.)**2.))
+        var = _lazywhere(a > 2, (n, a, b), f=var, fillvalue=np.inf)
+        g1, g2 = None, None
+        def skew(n, a, b):
+            return ((2 * n + a - 1.) * (2 * b + a - 1.)
+                    / (a - 3.) / sqrt(n * b * (n + a - 1.) * (b + a - 1.)
+                    / (a - 2.)))
+        if 's' in moments:
+            g1 = _lazywhere(a > 3, (n, a, b), f=skew, fillvalue=np.inf)
+        def kurtosis(n, a, b):
+            term = (a - 2.)
+            term_2 = ((a - 1.)**2. * (a**2. + a * (6 * b - 1.)
+                      + 6. * (b - 1.) * b)
+                      + 3. * n**2. * ((a + 5.) * b**2. + (a + 5.)
+                      * (a - 1.) * b + 2. * (a - 1.)**2)
+                      + 3 * (a - 1.) * n
+                      * ((a + 5.) * b**2. + (a + 5.) * (a - 1.) * b
+                      + 2. * (a - 1.)**2.))
+            denominator = ((a - 4.) * (a - 3.) * b * n
+                           * (a + b - 1.) * (a + n - 1.))
+            # Wolfram Alpha uses Pearson kurtosis, so we subtract 3 to get
+            # scipy's Fisher kurtosis
+            return term * term_2 / denominator - 3.
+        if 'k' in moments:
+            g2 = _lazywhere(a > 4, (n, a, b), f=kurtosis, fillvalue=np.inf)
+        return mu, var, g1, g2
+
+
+betanbinom = betanbinom_gen(name='betanbinom')
+
+
+class geom_gen(rv_discrete):
+    r"""A geometric discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `geom` is:
+
+    .. math::
+
+        f(k) = (1-p)^{k-1} p
+
+    for :math:`k \ge 1`, :math:`0 < p \leq 1`
+
+    `geom` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    Note that when drawing random samples, the probability of observations that exceed
+    ``np.iinfo(np.int64).max`` increases rapidly as $p$ decreases below $10^{-17}$. For
+    $p < 10^{-20}$, almost all observations would exceed the maximum ``int64``; however,
+    the output dtype is always ``int64``, so these values are clipped to the maximum.
+
+    %(after_notes)s
+
+    See Also
+    --------
+    planck
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        res = random_state.geometric(p, size=size)
+        # RandomState.geometric can wrap around to negative values; make behavior
+        # consistent with Generator.geometric by replacing with maximum integer.
+        max_int = np.iinfo(res.dtype).max
+        return np.where(res < 0, max_int, res)
+
+    def _argcheck(self, p):
+        return (p <= 1) & (p > 0)
+
+    def _pmf(self, k, p):
+        return np.power(1-p, k-1) * p
+
+    def _logpmf(self, k, p):
+        return special.xlog1py(k - 1, -p) + log(p)
+
+    def _cdf(self, x, p):
+        k = floor(x)
+        return -expm1(log1p(-p)*k)
+
+    def _sf(self, x, p):
+        return np.exp(self._logsf(x, p))
+
+    def _logsf(self, x, p):
+        k = floor(x)
+        return k*log1p(-p)
+
+    def _ppf(self, q, p):
+        vals = ceil(log1p(-q) / log1p(-p))
+        temp = self._cdf(vals-1, p)
+        return np.where((temp >= q) & (vals > 0), vals-1, vals)
+
+    def _stats(self, p):
+        mu = 1.0/p
+        qr = 1.0-p
+        var = qr / p / p
+        g1 = (2.0-p) / sqrt(qr)
+        g2 = np.polyval([1, -6, 6], p)/(1.0-p)
+        return mu, var, g1, g2
+
+    def _entropy(self, p):
+        return -np.log(p) - np.log1p(-p) * (1.0-p) / p
+
+
+geom = geom_gen(a=1, name='geom', longname="A geometric")
+
+
+class hypergeom_gen(rv_discrete):
+    r"""A hypergeometric discrete random variable.
+
+    The hypergeometric distribution models drawing objects from a bin.
+    `M` is the total number of objects, `n` is total number of Type I objects.
+    The random variate represents the number of Type I objects in `N` drawn
+    without replacement from the total population.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The symbols used to denote the shape parameters (`M`, `n`, and `N`) are not
+    universally accepted.  See the Examples for a clarification of the
+    definitions used here.
+
+    The probability mass function is defined as,
+
+    .. math:: p(k, M, n, N) = \frac{\binom{n}{k} \binom{M - n}{N - k}}
+                                   {\binom{M}{N}}
+
+    for :math:`k \in [\max(0, N - M + n), \min(n, N)]`, where the binomial
+    coefficients are defined as,
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf`` and ``stats`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import hypergeom
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have a collection of 20 animals, of which 7 are dogs.  Then if
+    we want to know the probability of finding a given number of dogs if we
+    choose at random 12 of the 20 animals, we can initialize a frozen
+    distribution and plot the probability mass function:
+
+    >>> [M, n, N] = [20, 7, 12]
+    >>> rv = hypergeom(M, n, N)
+    >>> x = np.arange(0, n+1)
+    >>> pmf_dogs = rv.pmf(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, pmf_dogs, 'bo')
+    >>> ax.vlines(x, 0, pmf_dogs, lw=2)
+    >>> ax.set_xlabel('# of dogs in our group of chosen animals')
+    >>> ax.set_ylabel('hypergeom PMF')
+    >>> plt.show()
+
+    Instead of using a frozen distribution we can also use `hypergeom`
+    methods directly.  To for example obtain the cumulative distribution
+    function, use:
+
+    >>> prb = hypergeom.cdf(x, M, n, N)
+
+    And to generate random numbers:
+
+    >>> R = hypergeom.rvs(M, n, N, size=10)
+
+    See Also
+    --------
+    nhypergeom, binom, nbinom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("N", True, (0, np.inf), (True, False))]
+
+    def _rvs(self, M, n, N, size=None, random_state=None):
+        return random_state.hypergeometric(n, M-n, N, size=size)
+
+    def _get_support(self, M, n, N):
+        return np.maximum(N-(M-n), 0), np.minimum(n, N)
+
+    def _argcheck(self, M, n, N):
+        cond = (M > 0) & (n >= 0) & (N >= 0)
+        cond &= (n <= M) & (N <= M)
+        cond &= _isintegral(M) & _isintegral(n) & _isintegral(N)
+        return cond
+
+    def _logpmf(self, k, M, n, N):
+        tot, good = M, n
+        bad = tot - good
+        result = (betaln(good+1, 1) + betaln(bad+1, 1) + betaln(tot-N+1, N+1) -
+                  betaln(k+1, good-k+1) - betaln(N-k+1, bad-N+k+1) -
+                  betaln(tot+1, 1))
+        return result
+
+    def _pmf(self, k, M, n, N):
+        return scu._hypergeom_pmf(k, n, N, M)
+
+    def _cdf(self, k, M, n, N):
+        return scu._hypergeom_cdf(k, n, N, M)
+
+    def _stats(self, M, n, N):
+        M, n, N = 1. * M, 1. * n, 1. * N
+        m = M - n
+
+        # Boost kurtosis_excess doesn't return the same as the value
+        # computed here.
+        g2 = M * (M + 1) - 6. * N * (M - N) - 6. * n * m
+        g2 *= (M - 1) * M * M
+        g2 += 6. * n * N * (M - N) * m * (5. * M - 6)
+        g2 /= n * N * (M - N) * m * (M - 2.) * (M - 3.)
+        return (
+            scu._hypergeom_mean(n, N, M),
+            scu._hypergeom_variance(n, N, M),
+            scu._hypergeom_skewness(n, N, M),
+            g2,
+        )
+
+    def _entropy(self, M, n, N):
+        k = np.r_[N - (M - n):min(n, N) + 1]
+        vals = self.pmf(k, M, n, N)
+        return np.sum(entr(vals), axis=0)
+
+    def _sf(self, k, M, n, N):
+        return scu._hypergeom_sf(k, n, N, M)
+
+    def _logsf(self, k, M, n, N):
+        res = []
+        for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
+            if (quant + 0.5) * (tot + 0.5) < (good - 0.5) * (draw - 0.5):
+                # Less terms to sum if we calculate log(1-cdf)
+                res.append(log1p(-exp(self.logcdf(quant, tot, good, draw))))
+            else:
+                # Integration over probability mass function using logsumexp
+                k2 = np.arange(quant + 1, draw + 1)
+                res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
+        return np.asarray(res)
+
+    def _logcdf(self, k, M, n, N):
+        res = []
+        for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
+            if (quant + 0.5) * (tot + 0.5) > (good - 0.5) * (draw - 0.5):
+                # Less terms to sum if we calculate log(1-sf)
+                res.append(log1p(-exp(self.logsf(quant, tot, good, draw))))
+            else:
+                # Integration over probability mass function using logsumexp
+                k2 = np.arange(0, quant + 1)
+                res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
+        return np.asarray(res)
+
+
+hypergeom = hypergeom_gen(name='hypergeom')
+
+
+class nhypergeom_gen(rv_discrete):
+    r"""A negative hypergeometric discrete random variable.
+
+    Consider a box containing :math:`M` balls:, :math:`n` red and
+    :math:`M-n` blue. We randomly sample balls from the box, one
+    at a time and *without* replacement, until we have picked :math:`r`
+    blue balls. `nhypergeom` is the distribution of the number of
+    red balls :math:`k` we have picked.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The symbols used to denote the shape parameters (`M`, `n`, and `r`) are not
+    universally accepted. See the Examples for a clarification of the
+    definitions used here.
+
+    The probability mass function is defined as,
+
+    .. math:: f(k; M, n, r) = \frac{{{k+r-1}\choose{k}}{{M-r-k}\choose{n-k}}}
+                                   {{M \choose n}}
+
+    for :math:`k \in [0, n]`, :math:`n \in [0, M]`, :math:`r \in [0, M-n]`,
+    and the binomial coefficient is:
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    It is equivalent to observing :math:`k` successes in :math:`k+r-1`
+    samples with :math:`k+r`'th sample being a failure. The former
+    can be modelled as a hypergeometric distribution. The probability
+    of the latter is simply the number of failures remaining
+    :math:`M-n-(r-1)` divided by the size of the remaining population
+    :math:`M-(k+r-1)`. This relationship can be shown as:
+
+    .. math:: NHG(k;M,n,r) = HG(k;M,n,k+r-1)\frac{(M-n-(r-1))}{(M-(k+r-1))}
+
+    where :math:`NHG` is probability mass function (PMF) of the
+    negative hypergeometric distribution and :math:`HG` is the
+    PMF of the hypergeometric distribution.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import nhypergeom
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have a collection of 20 animals, of which 7 are dogs.
+    Then if we want to know the probability of finding a given number
+    of dogs (successes) in a sample with exactly 12 animals that
+    aren't dogs (failures), we can initialize a frozen distribution
+    and plot the probability mass function:
+
+    >>> M, n, r = [20, 7, 12]
+    >>> rv = nhypergeom(M, n, r)
+    >>> x = np.arange(0, n+2)
+    >>> pmf_dogs = rv.pmf(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, pmf_dogs, 'bo')
+    >>> ax.vlines(x, 0, pmf_dogs, lw=2)
+    >>> ax.set_xlabel('# of dogs in our group with given 12 failures')
+    >>> ax.set_ylabel('nhypergeom PMF')
+    >>> plt.show()
+
+    Instead of using a frozen distribution we can also use `nhypergeom`
+    methods directly.  To for example obtain the probability mass
+    function, use:
+
+    >>> prb = nhypergeom.pmf(x, M, n, r)
+
+    And to generate random numbers:
+
+    >>> R = nhypergeom.rvs(M, n, r, size=10)
+
+    To verify the relationship between `hypergeom` and `nhypergeom`, use:
+
+    >>> from scipy.stats import hypergeom, nhypergeom
+    >>> M, n, r = 45, 13, 8
+    >>> k = 6
+    >>> nhypergeom.pmf(k, M, n, r)
+    0.06180776620271643
+    >>> hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1))
+    0.06180776620271644
+
+    See Also
+    --------
+    hypergeom, binom, nbinom
+
+    References
+    ----------
+    .. [1] Negative Hypergeometric Distribution on Wikipedia
+           https://en.wikipedia.org/wiki/Negative_hypergeometric_distribution
+
+    .. [2] Negative Hypergeometric Distribution from
+           http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Negativehypergeometric.pdf
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("r", True, (0, np.inf), (True, False))]
+
+    def _get_support(self, M, n, r):
+        return 0, n
+
+    def _argcheck(self, M, n, r):
+        cond = (n >= 0) & (n <= M) & (r >= 0) & (r <= M-n)
+        cond &= _isintegral(M) & _isintegral(n) & _isintegral(r)
+        return cond
+
+    def _rvs(self, M, n, r, size=None, random_state=None):
+
+        @_vectorize_rvs_over_shapes
+        def _rvs1(M, n, r, size, random_state):
+            # invert cdf by calculating all values in support, scalar M, n, r
+            a, b = self.support(M, n, r)
+            ks = np.arange(a, b+1)
+            cdf = self.cdf(ks, M, n, r)
+            ppf = interp1d(cdf, ks, kind='next', fill_value='extrapolate')
+            rvs = ppf(random_state.uniform(size=size)).astype(int)
+            if size is None:
+                return rvs.item()
+            return rvs
+
+        return _rvs1(M, n, r, size=size, random_state=random_state)
+
+    def _logpmf(self, k, M, n, r):
+        cond = ((r == 0) & (k == 0))
+        result = _lazywhere(~cond, (k, M, n, r),
+                            lambda k, M, n, r:
+                                (-betaln(k+1, r) + betaln(k+r, 1) -
+                                 betaln(n-k+1, M-r-n+1) + betaln(M-r-k+1, 1) +
+                                 betaln(n+1, M-n+1) - betaln(M+1, 1)),
+                            fillvalue=0.0)
+        return result
+
+    def _pmf(self, k, M, n, r):
+        # same as the following but numerically more precise
+        # return comb(k+r-1, k) * comb(M-r-k, n-k) / comb(M, n)
+        return exp(self._logpmf(k, M, n, r))
+
+    def _stats(self, M, n, r):
+        # Promote the datatype to at least float
+        # mu = rn / (M-n+1)
+        M, n, r = 1.*M, 1.*n, 1.*r
+        mu = r*n / (M-n+1)
+
+        var = r*(M+1)*n / ((M-n+1)*(M-n+2)) * (1 - r / (M-n+1))
+
+        # The skew and kurtosis are mathematically
+        # intractable so return `None`. See [2]_.
+        g1, g2 = None, None
+        return mu, var, g1, g2
+
+
+nhypergeom = nhypergeom_gen(name='nhypergeom')
+
+
+# FIXME: Fails _cdfvec
+class logser_gen(rv_discrete):
+    r"""A Logarithmic (Log-Series, Series) discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `logser` is:
+
+    .. math::
+
+        f(k) = - \frac{p^k}{k \log(1-p)}
+
+    for :math:`k \ge 1`, :math:`0 < p < 1`
+
+    `logser` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        # looks wrong for p>0.5, too few k=1
+        # trying to use generic is worse, no k=1 at all
+        return random_state.logseries(p, size=size)
+
+    def _argcheck(self, p):
+        return (p > 0) & (p < 1)
+
+    def _pmf(self, k, p):
+        # logser.pmf(k) = - p**k / (k*log(1-p))
+        return -np.power(p, k) * 1.0 / k / special.log1p(-p)
+
+    def _stats(self, p):
+        r = special.log1p(-p)
+        mu = p / (p - 1.0) / r
+        mu2p = -p / r / (p - 1.0)**2
+        var = mu2p - mu*mu
+        mu3p = -p / r * (1.0+p) / (1.0 - p)**3
+        mu3 = mu3p - 3*mu*mu2p + 2*mu**3
+        g1 = mu3 / np.power(var, 1.5)
+
+        mu4p = -p / r * (
+            1.0 / (p-1)**2 - 6*p / (p - 1)**3 + 6*p*p / (p-1)**4)
+        mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4
+        g2 = mu4 / var**2 - 3.0
+        return mu, var, g1, g2
+
+
+logser = logser_gen(a=1, name='logser', longname='A logarithmic')
+
+
+class poisson_gen(rv_discrete):
+    r"""A Poisson discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `poisson` is:
+
+    .. math::
+
+        f(k) = \exp(-\mu) \frac{\mu^k}{k!}
+
+    for :math:`k \ge 0`.
+
+    `poisson` takes :math:`\mu \geq 0` as shape parameter.
+    When :math:`\mu = 0`, the ``pmf`` method
+    returns ``1.0`` at quantile :math:`k = 0`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (True, False))]
+
+    # Override rv_discrete._argcheck to allow mu=0.
+    def _argcheck(self, mu):
+        return mu >= 0
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return random_state.poisson(mu, size)
+
+    def _logpmf(self, k, mu):
+        Pk = special.xlogy(k, mu) - gamln(k + 1) - mu
+        return Pk
+
+    def _pmf(self, k, mu):
+        # poisson.pmf(k) = exp(-mu) * mu**k / k!
+        return exp(self._logpmf(k, mu))
+
+    def _cdf(self, x, mu):
+        k = floor(x)
+        return special.pdtr(k, mu)
+
+    def _sf(self, x, mu):
+        k = floor(x)
+        return special.pdtrc(k, mu)
+
+    def _ppf(self, q, mu):
+        vals = ceil(special.pdtrik(q, mu))
+        vals1 = np.maximum(vals - 1, 0)
+        temp = special.pdtr(vals1, mu)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, mu):
+        var = mu
+        tmp = np.asarray(mu)
+        mu_nonzero = tmp > 0
+        g1 = _lazywhere(mu_nonzero, (tmp,), lambda x: sqrt(1.0/x), np.inf)
+        g2 = _lazywhere(mu_nonzero, (tmp,), lambda x: 1.0/x, np.inf)
+        return mu, var, g1, g2
+
+
+poisson = poisson_gen(name="poisson", longname='A Poisson')
+
+
+class planck_gen(rv_discrete):
+    r"""A Planck discrete exponential random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `planck` is:
+
+    .. math::
+
+        f(k) = (1-\exp(-\lambda)) \exp(-\lambda k)
+
+    for :math:`k \ge 0` and :math:`\lambda > 0`.
+
+    `planck` takes :math:`\lambda` as shape parameter. The Planck distribution
+    can be written as a geometric distribution (`geom`) with
+    :math:`p = 1 - \exp(-\lambda)` shifted by ``loc = -1``.
+
+    %(after_notes)s
+
+    See Also
+    --------
+    geom
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("lambda", False, (0, np.inf), (False, False))]
+
+    def _argcheck(self, lambda_):
+        return lambda_ > 0
+
+    def _pmf(self, k, lambda_):
+        return -expm1(-lambda_)*exp(-lambda_*k)
+
+    def _cdf(self, x, lambda_):
+        k = floor(x)
+        return -expm1(-lambda_*(k+1))
+
+    def _sf(self, x, lambda_):
+        return exp(self._logsf(x, lambda_))
+
+    def _logsf(self, x, lambda_):
+        k = floor(x)
+        return -lambda_*(k+1)
+
+    def _ppf(self, q, lambda_):
+        vals = ceil(-1.0/lambda_ * log1p(-q)-1)
+        vals1 = (vals-1).clip(*(self._get_support(lambda_)))
+        temp = self._cdf(vals1, lambda_)
+        return np.where(temp >= q, vals1, vals)
+
+    def _rvs(self, lambda_, size=None, random_state=None):
+        # use relation to geometric distribution for sampling
+        p = -expm1(-lambda_)
+        return random_state.geometric(p, size=size) - 1.0
+
+    def _stats(self, lambda_):
+        mu = 1/expm1(lambda_)
+        var = exp(-lambda_)/(expm1(-lambda_))**2
+        g1 = 2*cosh(lambda_/2.0)
+        g2 = 4+2*cosh(lambda_)
+        return mu, var, g1, g2
+
+    def _entropy(self, lambda_):
+        C = -expm1(-lambda_)
+        return lambda_*exp(-lambda_)/C - log(C)
+
+
+planck = planck_gen(a=0, name='planck', longname='A discrete exponential ')
+
+
+class boltzmann_gen(rv_discrete):
+    r"""A Boltzmann (Truncated Discrete Exponential) random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `boltzmann` is:
+
+    .. math::
+
+        f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N))
+
+    for :math:`k = 0,..., N-1`.
+
+    `boltzmann` takes :math:`\lambda > 0` and :math:`N > 0` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("lambda_", False, (0, np.inf), (False, False)),
+                _ShapeInfo("N", True, (0, np.inf), (False, False))]
+
+    def _argcheck(self, lambda_, N):
+        return (lambda_ > 0) & (N > 0) & _isintegral(N)
+
+    def _get_support(self, lambda_, N):
+        return self.a, N - 1
+
+    def _pmf(self, k, lambda_, N):
+        # boltzmann.pmf(k) =
+        #               (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N))
+        fact = (1-exp(-lambda_))/(1-exp(-lambda_*N))
+        return fact*exp(-lambda_*k)
+
+    def _cdf(self, x, lambda_, N):
+        k = floor(x)
+        return (1-exp(-lambda_*(k+1)))/(1-exp(-lambda_*N))
+
+    def _ppf(self, q, lambda_, N):
+        qnew = q*(1-exp(-lambda_*N))
+        vals = ceil(-1.0/lambda_ * log(1-qnew)-1)
+        vals1 = (vals-1).clip(0.0, np.inf)
+        temp = self._cdf(vals1, lambda_, N)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, lambda_, N):
+        z = exp(-lambda_)
+        zN = exp(-lambda_*N)
+        mu = z/(1.0-z)-N*zN/(1-zN)
+        var = z/(1.0-z)**2 - N*N*zN/(1-zN)**2
+        trm = (1-zN)/(1-z)
+        trm2 = (z*trm**2 - N*N*zN)
+        g1 = z*(1+z)*trm**3 - N**3*zN*(1+zN)
+        g1 = g1 / trm2**(1.5)
+        g2 = z*(1+4*z+z*z)*trm**4 - N**4 * zN*(1+4*zN+zN*zN)
+        g2 = g2 / trm2 / trm2
+        return mu, var, g1, g2
+
+
+boltzmann = boltzmann_gen(name='boltzmann', a=0,
+                          longname='A truncated discrete exponential ')
+
+
+class randint_gen(rv_discrete):
+    r"""A uniform discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `randint` is:
+
+    .. math::
+
+        f(k) = \frac{1}{\texttt{high} - \texttt{low}}
+
+    for :math:`k \in \{\texttt{low}, \dots, \texttt{high} - 1\}`.
+
+    `randint` takes :math:`\texttt{low}` and :math:`\texttt{high}` as shape
+    parameters.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import randint
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> low, high = 7, 31
+    >>> mean, var, skew, kurt = randint.stats(low, high, moments='mvsk')
+
+    Display the probability mass function (``pmf``):
+
+    >>> x = np.arange(low - 5, high + 5)
+    >>> ax.plot(x, randint.pmf(x, low, high), 'bo', ms=8, label='randint pmf')
+    >>> ax.vlines(x, 0, randint.pmf(x, low, high), colors='b', lw=5, alpha=0.5)
+
+    Alternatively, the distribution object can be called (as a function) to
+    fix the shape and location. This returns a "frozen" RV object holding the
+    given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pmf``:
+
+    >>> rv = randint(low, high)
+    >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-',
+    ...           lw=1, label='frozen pmf')
+    >>> ax.legend(loc='lower center')
+    >>> plt.show()
+
+    Check the relationship between the cumulative distribution function
+    (``cdf``) and its inverse, the percent point function (``ppf``):
+
+    >>> q = np.arange(low, high)
+    >>> p = randint.cdf(q, low, high)
+    >>> np.allclose(q, randint.ppf(p, low, high))
+    True
+
+    Generate random numbers:
+
+    >>> r = randint.rvs(low, high, size=1000)
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("low", True, (-np.inf, np.inf), (False, False)),
+                _ShapeInfo("high", True, (-np.inf, np.inf), (False, False))]
+
+    def _argcheck(self, low, high):
+        return (high > low) & _isintegral(low) & _isintegral(high)
+
+    def _get_support(self, low, high):
+        return low, high-1
+
+    def _pmf(self, k, low, high):
+        # randint.pmf(k) = 1./(high - low)
+        p = np.ones_like(k) / (np.asarray(high, dtype=np.int64) - low)
+        return np.where((k >= low) & (k < high), p, 0.)
+
+    def _cdf(self, x, low, high):
+        k = floor(x)
+        return (k - low + 1.) / (high - low)
+
+    def _ppf(self, q, low, high):
+        vals = ceil(q * (high - low) + low) - 1
+        vals1 = (vals - 1).clip(low, high)
+        temp = self._cdf(vals1, low, high)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, low, high):
+        m2, m1 = np.asarray(high), np.asarray(low)
+        mu = (m2 + m1 - 1.0) / 2
+        d = m2 - m1
+        var = (d*d - 1) / 12.0
+        g1 = 0.0
+        g2 = -6.0/5.0 * (d*d + 1.0) / (d*d - 1.0)
+        return mu, var, g1, g2
+
+    def _rvs(self, low, high, size=None, random_state=None):
+        """An array of *size* random integers >= ``low`` and < ``high``."""
+        if np.asarray(low).size == 1 and np.asarray(high).size == 1:
+            # no need to vectorize in that case
+            return rng_integers(random_state, low, high, size=size)
+
+        if size is not None:
+            # NumPy's RandomState.randint() doesn't broadcast its arguments.
+            # Use `broadcast_to()` to extend the shapes of low and high
+            # up to size.  Then we can use the numpy.vectorize'd
+            # randint without needing to pass it a `size` argument.
+            low = np.broadcast_to(low, size)
+            high = np.broadcast_to(high, size)
+        randint = np.vectorize(partial(rng_integers, random_state),
+                               otypes=[np.dtype(int)])
+        return randint(low, high)
+
+    def _entropy(self, low, high):
+        return log(high - low)
+
+
+randint = randint_gen(name='randint', longname='A discrete uniform '
+                      '(random integer)')
+
+
+# FIXME: problems sampling.
+class zipf_gen(rv_discrete):
+    r"""A Zipf (Zeta) discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    zipfian
+
+    Notes
+    -----
+    The probability mass function for `zipf` is:
+
+    .. math::
+
+        f(k, a) = \frac{1}{\zeta(a) k^a}
+
+    for :math:`k \ge 1`, :math:`a > 1`.
+
+    `zipf` takes :math:`a > 1` as shape parameter. :math:`\zeta` is the
+    Riemann zeta function (`scipy.special.zeta`)
+
+    The Zipf distribution is also known as the zeta distribution, which is
+    a special case of the Zipfian distribution (`zipfian`).
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Zeta Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Zeta_distribution
+
+    %(example)s
+
+    Confirm that `zipf` is the large `n` limit of `zipfian`.
+
+    >>> import numpy as np
+    >>> from scipy.stats import zipf, zipfian
+    >>> k = np.arange(11)
+    >>> np.allclose(zipf.pmf(k, a), zipfian.pmf(k, a, n=10000000))
+    True
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (1, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        return random_state.zipf(a, size=size)
+
+    def _argcheck(self, a):
+        return a > 1
+
+    def _pmf(self, k, a):
+        k = k.astype(np.float64)
+        # zipf.pmf(k, a) = 1/(zeta(a) * k**a)
+        Pk = 1.0 / special.zeta(a, 1) * k**-a
+        return Pk
+
+    def _munp(self, n, a):
+        return _lazywhere(
+            a > n + 1, (a, n),
+            lambda a, n: special.zeta(a - n, 1) / special.zeta(a, 1),
+            np.inf)
+
+
+zipf = zipf_gen(a=1, name='zipf', longname='A Zipf')
+
+
+def _gen_harmonic_gt1(n, a):
+    """Generalized harmonic number, a > 1"""
+    # See https://en.wikipedia.org/wiki/Harmonic_number; search for "hurwitz"
+    return zeta(a, 1) - zeta(a, n+1)
+
+
+def _gen_harmonic_leq1(n, a):
+    """Generalized harmonic number, a <= 1"""
+    if not np.size(n):
+        return n
+    n_max = np.max(n)  # loop starts at maximum of all n
+    out = np.zeros_like(a, dtype=float)
+    # add terms of harmonic series; starting from smallest to avoid roundoff
+    for i in np.arange(n_max, 0, -1, dtype=float):
+        mask = i <= n  # don't add terms after nth
+        out[mask] += 1/i**a[mask]
+    return out
+
+
+def _gen_harmonic(n, a):
+    """Generalized harmonic number"""
+    n, a = np.broadcast_arrays(n, a)
+    return _lazywhere(a > 1, (n, a),
+                      f=_gen_harmonic_gt1, f2=_gen_harmonic_leq1)
+
+
+class zipfian_gen(rv_discrete):
+    r"""A Zipfian discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    zipf
+
+    Notes
+    -----
+    The probability mass function for `zipfian` is:
+
+    .. math::
+
+        f(k, a, n) = \frac{1}{H_{n,a} k^a}
+
+    for :math:`k \in \{1, 2, \dots, n-1, n\}`, :math:`a \ge 0`,
+    :math:`n \in \{1, 2, 3, \dots\}`.
+
+    `zipfian` takes :math:`a` and :math:`n` as shape parameters.
+    :math:`H_{n,a}` is the :math:`n`:sup:`th` generalized harmonic
+    number of order :math:`a`.
+
+    The Zipfian distribution reduces to the Zipf (zeta) distribution as
+    :math:`n \rightarrow \infty`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Zipf's Law", Wikipedia, https://en.wikipedia.org/wiki/Zipf's_law
+    .. [2] Larry Leemis, "Zipf Distribution", Univariate Distribution
+           Relationships. http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+
+    %(example)s
+
+    Confirm that `zipfian` reduces to `zipf` for large `n`, ``a > 1``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import zipf, zipfian
+    >>> k = np.arange(11)
+    >>> np.allclose(zipfian.pmf(k, a=3.5, n=10000000), zipf.pmf(k, a=3.5))
+    True
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (False, False))]
+
+    def _argcheck(self, a, n):
+        # we need np.asarray here because moment (maybe others) don't convert
+        return (a >= 0) & (n > 0) & (n == np.asarray(n, dtype=int))
+
+    def _get_support(self, a, n):
+        return 1, n
+
+    def _pmf(self, k, a, n):
+        k = k.astype(np.float64)
+        return 1.0 / _gen_harmonic(n, a) * k**-a
+
+    def _cdf(self, k, a, n):
+        return _gen_harmonic(k, a) / _gen_harmonic(n, a)
+
+    def _sf(self, k, a, n):
+        k = k + 1  # # to match SciPy convention
+        # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+        return ((k**a*(_gen_harmonic(n, a) - _gen_harmonic(k, a)) + 1)
+                / (k**a*_gen_harmonic(n, a)))
+
+    def _stats(self, a, n):
+        # see # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+        Hna = _gen_harmonic(n, a)
+        Hna1 = _gen_harmonic(n, a-1)
+        Hna2 = _gen_harmonic(n, a-2)
+        Hna3 = _gen_harmonic(n, a-3)
+        Hna4 = _gen_harmonic(n, a-4)
+        mu1 = Hna1/Hna
+        mu2n = (Hna2*Hna - Hna1**2)
+        mu2d = Hna**2
+        mu2 = mu2n / mu2d
+        g1 = (Hna3/Hna - 3*Hna1*Hna2/Hna**2 + 2*Hna1**3/Hna**3)/mu2**(3/2)
+        g2 = (Hna**3*Hna4 - 4*Hna**2*Hna1*Hna3 + 6*Hna*Hna1**2*Hna2
+              - 3*Hna1**4) / mu2n**2
+        g2 -= 3
+        return mu1, mu2, g1, g2
+
+
+zipfian = zipfian_gen(a=1, name='zipfian', longname='A Zipfian')
+
+
+class dlaplace_gen(rv_discrete):
+    r"""A  Laplacian discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `dlaplace` is:
+
+    .. math::
+
+        f(k) = \tanh(a/2) \exp(-a |k|)
+
+    for integers :math:`k` and :math:`a > 0`.
+
+    `dlaplace` takes :math:`a` as shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pmf(self, k, a):
+        # dlaplace.pmf(k) = tanh(a/2) * exp(-a*abs(k))
+        return tanh(a/2.0) * exp(-a * abs(k))
+
+    def _cdf(self, x, a):
+        k = floor(x)
+
+        def f(k, a):
+            return 1.0 - exp(-a * k) / (exp(a) + 1)
+
+        def f2(k, a):
+            return exp(a * (k + 1)) / (exp(a) + 1)
+
+        return _lazywhere(k >= 0, (k, a), f=f, f2=f2)
+
+    def _ppf(self, q, a):
+        const = 1 + exp(a)
+        vals = ceil(np.where(q < 1.0 / (1 + exp(-a)),
+                             log(q*const) / a - 1,
+                             -log((1-q) * const) / a))
+        vals1 = vals - 1
+        return np.where(self._cdf(vals1, a) >= q, vals1, vals)
+
+    def _stats(self, a):
+        ea = exp(a)
+        mu2 = 2.*ea/(ea-1.)**2
+        mu4 = 2.*ea*(ea**2+10.*ea+1.) / (ea-1.)**4
+        return 0., mu2, 0., mu4/mu2**2 - 3.
+
+    def _entropy(self, a):
+        return a / sinh(a) - log(tanh(a/2.0))
+
+    def _rvs(self, a, size=None, random_state=None):
+        # The discrete Laplace is equivalent to the two-sided geometric
+        # distribution with PMF:
+        #   f(k) = (1 - alpha)/(1 + alpha) * alpha^abs(k)
+        #   Reference:
+        #     https://www.sciencedirect.com/science/
+        #     article/abs/pii/S0378375804003519
+        # Furthermore, the two-sided geometric distribution is
+        # equivalent to the difference between two iid geometric
+        # distributions.
+        #   Reference (page 179):
+        #     https://pdfs.semanticscholar.org/61b3/
+        #     b99f466815808fd0d03f5d2791eea8b541a1.pdf
+        # Thus, we can leverage the following:
+        #   1) alpha = e^-a
+        #   2) probability_of_success = 1 - alpha (Bernoulli trial)
+        probOfSuccess = -np.expm1(-np.asarray(a))
+        x = random_state.geometric(probOfSuccess, size=size)
+        y = random_state.geometric(probOfSuccess, size=size)
+        return x - y
+
+
+dlaplace = dlaplace_gen(a=-np.inf,
+                        name='dlaplace', longname='A discrete Laplacian')
+
+
+class poisson_binom_gen(rv_discrete):
+    r"""A Poisson Binomial discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    binom
+
+    Notes
+    -----
+    The probability mass function for `poisson_binom` is:
+
+    .. math::
+
+     f(k; p_1, p_2, ..., p_n) = \sum_{A \in F_k} \prod_{i \in A} p_i \prod_{j \in A^C} 1 - p_j
+
+    where :math:`k \in \{0, 1, \dots, n-1, n\}`, :math:`F_k` is the set of all
+    subsets of :math:`k` integers that can be selected :math:`\{0, 1, \dots, n-1, n\}`,
+    and :math:`A^C` is the complement of a set :math:`A`.
+
+    `poisson_binom` accepts a single array argument ``p`` for shape parameters
+    :math:`0 ≤ p_i ≤ 1`, where the last axis corresponds with the index :math:`i` and
+    any others are for batch dimensions. Broadcasting behaves according to the usual
+    rules except that the last axis of ``p`` is ignored. Instances of this class do
+    not support serialization/unserialization.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Poisson binomial distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Poisson_binomial_distribution
+    .. [2] Biscarri, William, Sihai Dave Zhao, and Robert J. Brunner. "A simple and
+           fast method for computing the Poisson binomial distribution function".
+           Computational Statistics & Data Analysis 122 (2018) 92-100.
+           :doi:`10.1016/j.csda.2018.01.007`
+
+    %(example)s
+
+    """  # noqa: E501
+    def _shape_info(self):
+        # message = 'Fitting is not implemented for this distribution."
+        # raise NotImplementedError(message)
+        return []
+
+    def _argcheck(self, *args):
+        p = np.stack(args, axis=0)
+        conds = (0 <= p) & (p <= 1)
+        return np.all(conds, axis=0)
+
+    def _rvs(self, *args, size=None, random_state=None):
+        # convenient to work along the last axis here to avoid interference with `size`
+        p = np.stack(args, axis=-1)
+        # Size passed by the user is the *shape of the returned array*, so it won't
+        # contain the length of the last axis of p.
+        size = (p.shape if size is None else
+                (size, 1) if np.isscalar(size) else tuple(size) + (1,))
+        size = np.broadcast_shapes(p.shape, size)
+        return bernoulli._rvs(p, size=size, random_state=random_state).sum(axis=-1)
+
+    def _get_support(self, *args):
+        return 0, len(args)
+
+    def _pmf(self, k, *args):
+        k = np.atleast_1d(k).astype(np.int64)
+        k, *args = np.broadcast_arrays(k, *args)
+        args = np.asarray(args, dtype=np.float64)
+        return _poisson_binom(k, args, 'pmf')
+
+    def _cdf(self, k, *args):
+        k = np.atleast_1d(k).astype(np.int64)
+        k, *args = np.broadcast_arrays(k, *args)
+        args = np.asarray(args, dtype=np.float64)
+        return _poisson_binom(k, args, 'cdf')
+
+    def _stats(self, *args, **kwds):
+        p = np.stack(args, axis=0)
+        mean = np.sum(p, axis=0)
+        var = np.sum(p * (1-p), axis=0)
+        return (mean, var, None, None)
+
+    def __call__(self, *args, **kwds):
+        return poisson_binomial_frozen(self, *args, **kwds)
+
+
+poisson_binom = poisson_binom_gen(name='poisson_binom', longname='A Poisson binomial',
+                                  shapes='p')
+
+# The _parse_args methods don't work with vector-valued shape parameters, so we rewrite
+# them. Note that `p` is accepted as an array with the index `i` of `p_i` corresponding
+# with the last axis; we return it as a tuple (p_1, p_2, ..., p_n) so that it looks
+# like `n` scalar (or arrays of scalar-valued) shape parameters to the infrastructure.
+
+def _parse_args_rvs(self, p, loc=0, size=None):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, size
+
+def _parse_args_stats(self, p, loc=0, moments='mv'):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, moments
+
+def _parse_args(self, p, loc=0):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0
+
+# The infrastructure manually binds these methods to the instance, so
+# we can only override them by manually binding them, too.
+_pb_obj, _pb_cls = poisson_binom, poisson_binom_gen  # shorter names (for PEP8)
+poisson_binom._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls)
+poisson_binom._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls)
+poisson_binom._parse_args = _parse_args.__get__(_pb_obj, _pb_cls)
+
+class poisson_binomial_frozen(rv_discrete_frozen):
+    # copied from rv_frozen; we just need to bind the `_parse_args` methods
+    def __init__(self, dist, *args, **kwds):                        # verbatim
+        self.args = args                                            # verbatim
+        self.kwds = kwds                                            # verbatim
+
+        # create a new instance                                     # verbatim
+        self.dist = dist.__class__(**dist._updated_ctor_param())    # verbatim
+
+        # Here is the only modification
+        self.dist._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls)
+        self.dist._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls)
+        self.dist._parse_args = _parse_args.__get__(_pb_obj, _pb_cls)
+
+        shapes, _, _ = self.dist._parse_args(*args, **kwds)         # verbatim
+        self.a, self.b = self.dist._get_support(*shapes)            # verbatim
+
+    def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):
+        a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)
+        # Here's the modification: we pass all args (including `loc`) into the `args`
+        # parameter of `expect` so the shape only goes through `_parse_args` once.
+        return self.dist.expect(func, self.args, loc, lb, ub, conditional, **kwds)
+
+
+class skellam_gen(rv_discrete):
+    r"""A  Skellam discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Probability distribution of the difference of two correlated or
+    uncorrelated Poisson random variables.
+
+    Let :math:`k_1` and :math:`k_2` be two Poisson-distributed r.v. with
+    expected values :math:`\lambda_1` and :math:`\lambda_2`. Then,
+    :math:`k_1 - k_2` follows a Skellam distribution with parameters
+    :math:`\mu_1 = \lambda_1 - \rho \sqrt{\lambda_1 \lambda_2}` and
+    :math:`\mu_2 = \lambda_2 - \rho \sqrt{\lambda_1 \lambda_2}`, where
+    :math:`\rho` is the correlation coefficient between :math:`k_1` and
+    :math:`k_2`. If the two Poisson-distributed r.v. are independent then
+    :math:`\rho = 0`.
+
+    Parameters :math:`\mu_1` and :math:`\mu_2` must be strictly positive.
+
+    For details see: https://en.wikipedia.org/wiki/Skellam_distribution
+
+    `skellam` takes :math:`\mu_1` and :math:`\mu_2` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("mu1", False, (0, np.inf), (False, False)),
+                _ShapeInfo("mu2", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, mu1, mu2, size=None, random_state=None):
+        n = size
+        return (random_state.poisson(mu1, n) -
+                random_state.poisson(mu2, n))
+
+    def _pmf(self, x, mu1, mu2):
+        with np.errstate(over='ignore'):  # see gh-17432
+            px = np.where(x < 0,
+                          scu._ncx2_pdf(2*mu2, 2*(1-x), 2*mu1)*2,
+                          scu._ncx2_pdf(2*mu1, 2*(1+x), 2*mu2)*2)
+            # ncx2.pdf() returns nan's for extremely low probabilities
+        return px
+
+    def _cdf(self, x, mu1, mu2):
+        x = floor(x)
+        with np.errstate(over='ignore'):  # see gh-17432
+            px = np.where(x < 0,
+                          scu._ncx2_cdf(2*mu2, -2*x, 2*mu1),
+                          1 - scu._ncx2_cdf(2*mu1, 2*(x+1), 2*mu2))
+        return px
+
+    def _stats(self, mu1, mu2):
+        mean = mu1 - mu2
+        var = mu1 + mu2
+        g1 = mean / sqrt((var)**3)
+        g2 = 1 / var
+        return mean, var, g1, g2
+
+
+skellam = skellam_gen(a=-np.inf, name="skellam", longname='A Skellam')
+
+
+class yulesimon_gen(rv_discrete):
+    r"""A Yule-Simon discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+
+    The probability mass function for the `yulesimon` is:
+
+    .. math::
+
+        f(k) =  \alpha B(k, \alpha+1)
+
+    for :math:`k=1,2,3,...`, where :math:`\alpha>0`.
+    Here :math:`B` refers to the `scipy.special.beta` function.
+
+    The sampling of random variates is based on pg 553, Section 6.3 of [1]_.
+    Our notation maps to the referenced logic via :math:`\alpha=a-1`.
+
+    For details see the wikipedia entry [2]_.
+
+    References
+    ----------
+    .. [1] Devroye, Luc. "Non-uniform Random Variate Generation",
+         (1986) Springer, New York.
+
+    .. [2] https://en.wikipedia.org/wiki/Yule-Simon_distribution
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("alpha", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, alpha, size=None, random_state=None):
+        E1 = random_state.standard_exponential(size)
+        E2 = random_state.standard_exponential(size)
+        ans = ceil(-E1 / log1p(-exp(-E2 / alpha)))
+        return ans
+
+    def _pmf(self, x, alpha):
+        return alpha * special.beta(x, alpha + 1)
+
+    def _argcheck(self, alpha):
+        return (alpha > 0)
+
+    def _logpmf(self, x, alpha):
+        return log(alpha) + special.betaln(x, alpha + 1)
+
+    def _cdf(self, x, alpha):
+        return 1 - x * special.beta(x, alpha + 1)
+
+    def _sf(self, x, alpha):
+        return x * special.beta(x, alpha + 1)
+
+    def _logsf(self, x, alpha):
+        return log(x) + special.betaln(x, alpha + 1)
+
+    def _stats(self, alpha):
+        mu = np.where(alpha <= 1, np.inf, alpha / (alpha - 1))
+        mu2 = np.where(alpha > 2,
+                       alpha**2 / ((alpha - 2.0) * (alpha - 1)**2),
+                       np.inf)
+        mu2 = np.where(alpha <= 1, np.nan, mu2)
+        g1 = np.where(alpha > 3,
+                      sqrt(alpha - 2) * (alpha + 1)**2 / (alpha * (alpha - 3)),
+                      np.inf)
+        g1 = np.where(alpha <= 2, np.nan, g1)
+        g2 = np.where(alpha > 4,
+                      alpha + 3 + ((11 * alpha**3 - 49 * alpha - 22) /
+                                   (alpha * (alpha - 4) * (alpha - 3))),
+                      np.inf)
+        g2 = np.where(alpha <= 2, np.nan, g2)
+        return mu, mu2, g1, g2
+
+
+yulesimon = yulesimon_gen(name='yulesimon', a=1)
+
+
+class _nchypergeom_gen(rv_discrete):
+    r"""A noncentral hypergeometric discrete random variable.
+
+    For subclassing by nchypergeom_fisher_gen and nchypergeom_wallenius_gen.
+
+    """
+
+    rvs_name = None
+    dist = None
+
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("N", True, (0, np.inf), (True, False)),
+                _ShapeInfo("odds", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, M, n, N, odds):
+        N, m1, n = M, n, N  # follow Wikipedia notation
+        m2 = N - m1
+        x_min = np.maximum(0, n - m2)
+        x_max = np.minimum(n, m1)
+        return x_min, x_max
+
+    def _argcheck(self, M, n, N, odds):
+        M, n = np.asarray(M), np.asarray(n),
+        N, odds = np.asarray(N), np.asarray(odds)
+        cond1 = (M.astype(int) == M) & (M >= 0)
+        cond2 = (n.astype(int) == n) & (n >= 0)
+        cond3 = (N.astype(int) == N) & (N >= 0)
+        cond4 = odds > 0
+        cond5 = N <= M
+        cond6 = n <= M
+        return cond1 & cond2 & cond3 & cond4 & cond5 & cond6
+
+    def _rvs(self, M, n, N, odds, size=None, random_state=None):
+
+        @_vectorize_rvs_over_shapes
+        def _rvs1(M, n, N, odds, size, random_state):
+            length = np.prod(size)
+            urn = _PyStochasticLib3()
+            rv_gen = getattr(urn, self.rvs_name)
+            rvs = rv_gen(N, n, M, odds, length, random_state)
+            rvs = rvs.reshape(size)
+            return rvs
+
+        return _rvs1(M, n, N, odds, size=size, random_state=random_state)
+
+    def _pmf(self, x, M, n, N, odds):
+
+        x, M, n, N, odds = np.broadcast_arrays(x, M, n, N, odds)
+        if x.size == 0:  # np.vectorize doesn't work with zero size input
+            return np.empty_like(x)
+
+        @np.vectorize
+        def _pmf1(x, M, n, N, odds):
+            urn = self.dist(N, n, M, odds, 1e-12)
+            return urn.probability(x)
+
+        return _pmf1(x, M, n, N, odds)
+
+    def _stats(self, M, n, N, odds, moments):
+
+        @np.vectorize
+        def _moments1(M, n, N, odds):
+            urn = self.dist(N, n, M, odds, 1e-12)
+            return urn.moments()
+
+        m, v = (_moments1(M, n, N, odds) if ("m" in moments or "v" in moments)
+                else (None, None))
+        s, k = None, None
+        return m, v, s, k
+
+
+class nchypergeom_fisher_gen(_nchypergeom_gen):
+    r"""A Fisher's noncentral hypergeometric discrete random variable.
+
+    Fisher's noncentral hypergeometric distribution models drawing objects of
+    two types from a bin. `M` is the total number of objects, `n` is the
+    number of Type I objects, and `odds` is the odds ratio: the odds of
+    selecting a Type I object rather than a Type II object when there is only
+    one object of each type.
+    The random variate represents the number of Type I objects drawn if we
+    take a handful of objects from the bin at once and find out afterwards
+    that we took `N` objects.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nchypergeom_wallenius, hypergeom, nhypergeom
+
+    Notes
+    -----
+    Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
+    with parameters `N`, `n`, and `M` (respectively) as defined above.
+
+    The probability mass function is defined as
+
+    .. math::
+
+        p(x; M, n, N, \omega) =
+        \frac{\binom{n}{x}\binom{M - n}{N-x}\omega^x}{P_0},
+
+    for
+    :math:`x \in [x_l, x_u]`,
+    :math:`M \in {\mathbb N}`,
+    :math:`n \in [0, M]`,
+    :math:`N \in [0, M]`,
+    :math:`\omega > 0`,
+    where
+    :math:`x_l = \max(0, N - (M - n))`,
+    :math:`x_u = \min(N, n)`,
+
+    .. math::
+
+        P_0 = \sum_{y=x_l}^{x_u} \binom{n}{y}\binom{M - n}{N-y}\omega^y,
+
+    and the binomial coefficients are defined as
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    `nchypergeom_fisher` uses the BiasedUrn package by Agner Fog with
+    permission for it to be distributed under SciPy's license.
+
+    The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
+    universally accepted; they are chosen for consistency with `hypergeom`.
+
+    Note that Fisher's noncentral hypergeometric distribution is distinct
+    from Wallenius' noncentral hypergeometric distribution, which models
+    drawing a pre-determined `N` objects from a bin one by one.
+    When the odds ratio is unity, however, both distributions reduce to the
+    ordinary hypergeometric distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Agner Fog, "Biased Urn Theory".
+           https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
+
+    .. [2] "Fisher's noncentral hypergeometric distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Fisher's_noncentral_hypergeometric_distribution
+
+    %(example)s
+
+    """
+
+    rvs_name = "rvs_fisher"
+    dist = _PyFishersNCHypergeometric
+
+
+nchypergeom_fisher = nchypergeom_fisher_gen(
+    name='nchypergeom_fisher',
+    longname="A Fisher's noncentral hypergeometric")
+
+
+class nchypergeom_wallenius_gen(_nchypergeom_gen):
+    r"""A Wallenius' noncentral hypergeometric discrete random variable.
+
+    Wallenius' noncentral hypergeometric distribution models drawing objects of
+    two types from a bin. `M` is the total number of objects, `n` is the
+    number of Type I objects, and `odds` is the odds ratio: the odds of
+    selecting a Type I object rather than a Type II object when there is only
+    one object of each type.
+    The random variate represents the number of Type I objects drawn if we
+    draw a pre-determined `N` objects from a bin one by one.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nchypergeom_fisher, hypergeom, nhypergeom
+
+    Notes
+    -----
+    Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
+    with parameters `N`, `n`, and `M` (respectively) as defined above.
+
+    The probability mass function is defined as
+
+    .. math::
+
+        p(x; N, n, M) = \binom{n}{x} \binom{M - n}{N-x}
+        \int_0^1 \left(1-t^{\omega/D}\right)^x\left(1-t^{1/D}\right)^{N-x} dt
+
+    for
+    :math:`x \in [x_l, x_u]`,
+    :math:`M \in {\mathbb N}`,
+    :math:`n \in [0, M]`,
+    :math:`N \in [0, M]`,
+    :math:`\omega > 0`,
+    where
+    :math:`x_l = \max(0, N - (M - n))`,
+    :math:`x_u = \min(N, n)`,
+
+    .. math::
+
+        D = \omega(n - x) + ((M - n)-(N-x)),
+
+    and the binomial coefficients are defined as
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    `nchypergeom_wallenius` uses the BiasedUrn package by Agner Fog with
+    permission for it to be distributed under SciPy's license.
+
+    The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
+    universally accepted; they are chosen for consistency with `hypergeom`.
+
+    Note that Wallenius' noncentral hypergeometric distribution is distinct
+    from Fisher's noncentral hypergeometric distribution, which models
+    take a handful of objects from the bin at once, finding out afterwards
+    that `N` objects were taken.
+    When the odds ratio is unity, however, both distributions reduce to the
+    ordinary hypergeometric distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Agner Fog, "Biased Urn Theory".
+           https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
+
+    .. [2] "Wallenius' noncentral hypergeometric distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Wallenius'_noncentral_hypergeometric_distribution
+
+    %(example)s
+
+    """
+
+    rvs_name = "rvs_wallenius"
+    dist = _PyWalleniusNCHypergeometric
+
+
+nchypergeom_wallenius = nchypergeom_wallenius_gen(
+    name='nchypergeom_wallenius',
+    longname="A Wallenius' noncentral hypergeometric")
+
+
+# Collect names of classes and objects in this module.
+pairs = list(globals().copy().items())
+_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_discrete)
+
+__all__ = _distn_names + _distn_gen_names
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_distn_infrastructure.py b/python_embeded/Lib/site-packages/scipy/stats/_distn_infrastructure.py
new file mode 100644
index 0000000000000000000000000000000000000000..1749e3832c3ab1c40f0c114807f48af760cd18d5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_distn_infrastructure.py
@@ -0,0 +1,4174 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+
+import sys
+import keyword
+import re
+import types
+import warnings
+from itertools import zip_longest
+
+from scipy._lib import doccer
+from ._distr_params import distcont, distdiscrete
+from scipy._lib._util import check_random_state, _lazywhere
+
+from scipy.special import comb, entr
+
+
+# for root finding for continuous distribution ppf, and maximum likelihood
+# estimation
+from scipy import optimize
+
+# for functions of continuous distributions (e.g. moments, entropy, cdf)
+from scipy import integrate
+
+# to approximate the pdf of a continuous distribution given its cdf
+from scipy._lib._finite_differences import _derivative
+
+# for scipy.stats.entropy. Attempts to import just that function or file
+# have cause import problems
+from scipy import stats
+
+from numpy import (arange, putmask, ones, shape, ndarray, zeros, floor,
+                   logical_and, log, sqrt, place, argmax, vectorize, asarray,
+                   nan, inf, isinf, empty)
+
+import numpy as np
+from ._constants import _XMAX, _LOGXMAX
+from ._censored_data import CensoredData
+from scipy.stats._warnings_errors import FitError
+
+# These are the docstring parts used for substitution in specific
+# distribution docstrings
+
+docheaders = {'methods': """\nMethods\n-------\n""",
+              'notes': """\nNotes\n-----\n""",
+              'examples': """\nExamples\n--------\n"""}
+
+_doc_rvs = """\
+rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None)
+    Random variates.
+"""
+_doc_pdf = """\
+pdf(x, %(shapes)s, loc=0, scale=1)
+    Probability density function.
+"""
+_doc_logpdf = """\
+logpdf(x, %(shapes)s, loc=0, scale=1)
+    Log of the probability density function.
+"""
+_doc_pmf = """\
+pmf(k, %(shapes)s, loc=0, scale=1)
+    Probability mass function.
+"""
+_doc_logpmf = """\
+logpmf(k, %(shapes)s, loc=0, scale=1)
+    Log of the probability mass function.
+"""
+_doc_cdf = """\
+cdf(x, %(shapes)s, loc=0, scale=1)
+    Cumulative distribution function.
+"""
+_doc_logcdf = """\
+logcdf(x, %(shapes)s, loc=0, scale=1)
+    Log of the cumulative distribution function.
+"""
+_doc_sf = """\
+sf(x, %(shapes)s, loc=0, scale=1)
+    Survival function  (also defined as ``1 - cdf``, but `sf` is sometimes more accurate).
+"""  # noqa: E501
+_doc_logsf = """\
+logsf(x, %(shapes)s, loc=0, scale=1)
+    Log of the survival function.
+"""
+_doc_ppf = """\
+ppf(q, %(shapes)s, loc=0, scale=1)
+    Percent point function (inverse of ``cdf`` --- percentiles).
+"""
+_doc_isf = """\
+isf(q, %(shapes)s, loc=0, scale=1)
+    Inverse survival function (inverse of ``sf``).
+"""
+_doc_moment = """\
+moment(order, %(shapes)s, loc=0, scale=1)
+    Non-central moment of the specified order.
+"""
+_doc_stats = """\
+stats(%(shapes)s, loc=0, scale=1, moments='mv')
+    Mean('m'), variance('v'), skew('s'), and/or kurtosis('k').
+"""
+_doc_entropy = """\
+entropy(%(shapes)s, loc=0, scale=1)
+    (Differential) entropy of the RV.
+"""
+_doc_fit = """\
+fit(data)
+    Parameter estimates for generic data.
+    See `scipy.stats.rv_continuous.fit `__ for detailed documentation of the
+    keyword arguments.
+"""  # noqa: E501
+_doc_expect = """\
+expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)
+    Expected value of a function (of one argument) with respect to the distribution.
+"""  # noqa: E501
+_doc_expect_discrete = """\
+expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False)
+    Expected value of a function (of one argument) with respect to the distribution.
+"""
+_doc_median = """\
+median(%(shapes)s, loc=0, scale=1)
+    Median of the distribution.
+"""
+_doc_mean = """\
+mean(%(shapes)s, loc=0, scale=1)
+    Mean of the distribution.
+"""
+_doc_var = """\
+var(%(shapes)s, loc=0, scale=1)
+    Variance of the distribution.
+"""
+_doc_std = """\
+std(%(shapes)s, loc=0, scale=1)
+    Standard deviation of the distribution.
+"""
+_doc_interval = """\
+interval(confidence, %(shapes)s, loc=0, scale=1)
+    Confidence interval with equal areas around the median.
+"""
+_doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf,
+                           _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf,
+                           _doc_logsf, _doc_ppf, _doc_isf, _doc_moment,
+                           _doc_stats, _doc_entropy, _doc_fit,
+                           _doc_expect, _doc_median,
+                           _doc_mean, _doc_var, _doc_std, _doc_interval])
+
+_doc_default_longsummary = """\
+As an instance of the `rv_continuous` class, `%(name)s` object inherits from it
+a collection of generic methods (see below for the full list),
+and completes them with details specific for this particular distribution.
+"""
+
+_doc_default_frozen_note = """
+Alternatively, the object may be called (as a function) to fix the shape,
+location, and scale parameters returning a "frozen" continuous RV object:
+
+rv = %(name)s(%(shapes)s, loc=0, scale=1)
+    - Frozen RV object with the same methods but holding the given shape,
+      location, and scale fixed.
+"""
+_doc_default_example = """\
+Examples
+--------
+>>> import numpy as np
+>>> from scipy.stats import %(name)s
+>>> import matplotlib.pyplot as plt
+>>> fig, ax = plt.subplots(1, 1)
+
+Calculate the first four moments:
+
+%(set_vals_stmt)s
+>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
+
+Display the probability density function (``pdf``):
+
+>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s),
+...                 %(name)s.ppf(0.99, %(shapes)s), 100)
+>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s),
+...        'r-', lw=5, alpha=0.6, label='%(name)s pdf')
+
+Alternatively, the distribution object can be called (as a function)
+to fix the shape, location and scale parameters. This returns a "frozen"
+RV object holding the given parameters fixed.
+
+Freeze the distribution and display the frozen ``pdf``:
+
+>>> rv = %(name)s(%(shapes)s)
+>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+Check accuracy of ``cdf`` and ``ppf``:
+
+>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s)
+>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s))
+True
+
+Generate random numbers:
+
+>>> r = %(name)s.rvs(%(shapes)s, size=1000)
+
+And compare the histogram:
+
+>>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+>>> ax.set_xlim([x[0], x[-1]])
+>>> ax.legend(loc='best', frameon=False)
+>>> plt.show()
+
+"""
+
+_doc_default_locscale = """\
+The probability density above is defined in the "standardized" form. To shift
+and/or scale the distribution use the ``loc`` and ``scale`` parameters.
+Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
+equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
+``y = (x - loc) / scale``. Note that shifting the location of a distribution
+does not make it a "noncentral" distribution; noncentral generalizations of
+some distributions are available in separate classes.
+"""
+
+_doc_default = ''.join([_doc_default_longsummary,
+                        _doc_allmethods,
+                        '\n',
+                        _doc_default_example])
+
+_doc_default_before_notes = ''.join([_doc_default_longsummary,
+                                     _doc_allmethods])
+
+docdict = {
+    'rvs': _doc_rvs,
+    'pdf': _doc_pdf,
+    'logpdf': _doc_logpdf,
+    'cdf': _doc_cdf,
+    'logcdf': _doc_logcdf,
+    'sf': _doc_sf,
+    'logsf': _doc_logsf,
+    'ppf': _doc_ppf,
+    'isf': _doc_isf,
+    'stats': _doc_stats,
+    'entropy': _doc_entropy,
+    'fit': _doc_fit,
+    'moment': _doc_moment,
+    'expect': _doc_expect,
+    'interval': _doc_interval,
+    'mean': _doc_mean,
+    'std': _doc_std,
+    'var': _doc_var,
+    'median': _doc_median,
+    'allmethods': _doc_allmethods,
+    'longsummary': _doc_default_longsummary,
+    'frozennote': _doc_default_frozen_note,
+    'example': _doc_default_example,
+    'default': _doc_default,
+    'before_notes': _doc_default_before_notes,
+    'after_notes': _doc_default_locscale
+}
+
+# Reuse common content between continuous and discrete docs, change some
+# minor bits.
+docdict_discrete = docdict.copy()
+
+docdict_discrete['pmf'] = _doc_pmf
+docdict_discrete['logpmf'] = _doc_logpmf
+docdict_discrete['expect'] = _doc_expect_discrete
+_doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf',
+                     'ppf', 'isf', 'stats', 'entropy', 'expect', 'median',
+                     'mean', 'var', 'std', 'interval']
+for obj in _doc_disc_methods:
+    docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '')
+
+_doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf']
+for obj in _doc_disc_methods_err_varname:
+    docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ')
+
+docdict_discrete.pop('pdf')
+docdict_discrete.pop('logpdf')
+
+_doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods])
+docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods
+
+docdict_discrete['longsummary'] = _doc_default_longsummary.replace(
+    'rv_continuous', 'rv_discrete')
+
+_doc_default_frozen_note = """
+Alternatively, the object may be called (as a function) to fix the shape and
+location parameters returning a "frozen" discrete RV object:
+
+rv = %(name)s(%(shapes)s, loc=0)
+    - Frozen RV object with the same methods but holding the given shape and
+      location fixed.
+"""
+docdict_discrete['frozennote'] = _doc_default_frozen_note
+
+_doc_default_discrete_example = """\
+Examples
+--------
+>>> import numpy as np
+>>> from scipy.stats import %(name)s
+>>> import matplotlib.pyplot as plt
+>>> fig, ax = plt.subplots(1, 1)
+
+Calculate the first four moments:
+
+%(set_vals_stmt)s
+>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
+
+Display the probability mass function (``pmf``):
+
+>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s),
+...               %(name)s.ppf(0.99, %(shapes)s))
+>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf')
+>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5)
+
+Alternatively, the distribution object can be called (as a function)
+to fix the shape and location. This returns a "frozen" RV object holding
+the given parameters fixed.
+
+Freeze the distribution and display the frozen ``pmf``:
+
+>>> rv = %(name)s(%(shapes)s)
+>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,
+...         label='frozen pmf')
+>>> ax.legend(loc='best', frameon=False)
+>>> plt.show()
+
+Check accuracy of ``cdf`` and ``ppf``:
+
+>>> prob = %(name)s.cdf(x, %(shapes)s)
+>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s))
+True
+
+Generate random numbers:
+
+>>> r = %(name)s.rvs(%(shapes)s, size=1000)
+"""
+
+
+_doc_default_discrete_locscale = """\
+The probability mass function above is defined in the "standardized" form.
+To shift distribution use the ``loc`` parameter.
+Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically
+equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``.
+"""
+
+docdict_discrete['example'] = _doc_default_discrete_example
+docdict_discrete['after_notes'] = _doc_default_discrete_locscale
+
+_doc_default_before_notes = ''.join([docdict_discrete['longsummary'],
+                                     docdict_discrete['allmethods']])
+docdict_discrete['before_notes'] = _doc_default_before_notes
+
+_doc_default_disc = ''.join([docdict_discrete['longsummary'],
+                             docdict_discrete['allmethods'],
+                             docdict_discrete['frozennote'],
+                             docdict_discrete['example']])
+docdict_discrete['default'] = _doc_default_disc
+
+# clean up all the separate docstring elements, we do not need them anymore
+for obj in [s for s in dir() if s.startswith('_doc_')]:
+    exec('del ' + obj)
+del obj
+
+
+def _moment(data, n, mu=None):
+    if mu is None:
+        mu = data.mean()
+    return ((data - mu)**n).mean()
+
+
+def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args):
+    if (n == 0):
+        return 1.0
+    elif (n == 1):
+        if mu is None:
+            val = moment_func(1, *args)
+        else:
+            val = mu
+    elif (n == 2):
+        if mu2 is None or mu is None:
+            val = moment_func(2, *args)
+        else:
+            val = mu2 + mu*mu
+    elif (n == 3):
+        if g1 is None or mu2 is None or mu is None:
+            val = moment_func(3, *args)
+        else:
+            mu3 = g1 * np.power(mu2, 1.5)  # 3rd central moment
+            val = mu3+3*mu*mu2+mu*mu*mu  # 3rd non-central moment
+    elif (n == 4):
+        if g1 is None or g2 is None or mu2 is None or mu is None:
+            val = moment_func(4, *args)
+        else:
+            mu4 = (g2+3.0)*(mu2**2.0)  # 4th central moment
+            mu3 = g1*np.power(mu2, 1.5)  # 3rd central moment
+            val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu
+    else:
+        val = moment_func(n, *args)
+
+    return val
+
+
+def _skew(data):
+    """
+    skew is third central moment / variance**(1.5)
+    """
+    data = np.ravel(data)
+    mu = data.mean()
+    m2 = ((data - mu)**2).mean()
+    m3 = ((data - mu)**3).mean()
+    return m3 / np.power(m2, 1.5)
+
+
+def _kurtosis(data):
+    """Fisher's excess kurtosis is fourth central moment / variance**2 - 3."""
+    data = np.ravel(data)
+    mu = data.mean()
+    m2 = ((data - mu)**2).mean()
+    m4 = ((data - mu)**4).mean()
+    return m4 / m2**2 - 3
+
+def _vectorize_rvs_over_shapes(_rvs1):
+    """Decorator that vectorizes _rvs method to work on ndarray shapes"""
+    # _rvs1 must be a _function_ that accepts _scalar_ args as positional
+    # arguments, `size` and `random_state` as keyword arguments.
+    # _rvs1 must return a random variate array with shape `size`. If `size` is
+    # None, _rvs1 must return a scalar.
+    # When applied to _rvs1, this decorator broadcasts ndarray args
+    # and loops over them, calling _rvs1 for each set of scalar args.
+    # For usage example, see _nchypergeom_gen
+    def _rvs(*args, size, random_state):
+        _rvs1_size, _rvs1_indices = _check_shape(args[0].shape, size)
+
+        size = np.array(size)
+        _rvs1_size = np.array(_rvs1_size)
+        _rvs1_indices = np.array(_rvs1_indices)
+
+        if np.all(_rvs1_indices):  # all args are scalars
+            return _rvs1(*args, size, random_state)
+
+        out = np.empty(size)
+
+        # out.shape can mix dimensions associated with arg_shape and _rvs1_size
+        # Sort them to arg_shape + _rvs1_size for easy indexing of dimensions
+        # corresponding with the different sets of scalar args
+        j0 = np.arange(out.ndim)
+        j1 = np.hstack((j0[~_rvs1_indices], j0[_rvs1_indices]))
+        out = np.moveaxis(out, j1, j0)
+
+        for i in np.ndindex(*size[~_rvs1_indices]):
+            # arg can be squeezed because singleton dimensions will be
+            # associated with _rvs1_size, not arg_shape per _check_shape
+            out[i] = _rvs1(*[np.squeeze(arg)[i] for arg in args],
+                           _rvs1_size, random_state)
+
+        return np.moveaxis(out, j0, j1)  # move axes back before returning
+    return _rvs
+
+
+def _fit_determine_optimizer(optimizer):
+    if not callable(optimizer) and isinstance(optimizer, str):
+        if not optimizer.startswith('fmin_'):
+            optimizer = "fmin_"+optimizer
+        if optimizer == 'fmin_':
+            optimizer = 'fmin'
+        try:
+            optimizer = getattr(optimize, optimizer)
+        except AttributeError as e:
+            raise ValueError(f"{optimizer} is not a valid optimizer") from e
+    return optimizer
+
+def _isintegral(x):
+    return x == np.round(x)
+
+def _sum_finite(x):
+    """
+    For a 1D array x, return a tuple containing the sum of the
+    finite values of x and the number of nonfinite values.
+
+    This is a utility function used when evaluating the negative
+    loglikelihood for a distribution and an array of samples.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distn_infrastructure import _sum_finite
+    >>> tot, nbad = _sum_finite(np.array([-2, -np.inf, 5, 1]))
+    >>> tot
+    4.0
+    >>> nbad
+    1
+    """
+    finite_x = np.isfinite(x)
+    bad_count = finite_x.size - np.count_nonzero(finite_x)
+    return np.sum(x[finite_x]), bad_count
+
+
+# Frozen RV class
+class rv_frozen:
+
+    def __init__(self, dist, *args, **kwds):
+        self.args = args
+        self.kwds = kwds
+
+        # create a new instance
+        self.dist = dist.__class__(**dist._updated_ctor_param())
+
+        shapes, _, _ = self.dist._parse_args(*args, **kwds)
+        self.a, self.b = self.dist._get_support(*shapes)
+
+    @property
+    def random_state(self):
+        return self.dist._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self.dist._random_state = check_random_state(seed)
+
+    def cdf(self, x):
+        return self.dist.cdf(x, *self.args, **self.kwds)
+
+    def logcdf(self, x):
+        return self.dist.logcdf(x, *self.args, **self.kwds)
+
+    def ppf(self, q):
+        return self.dist.ppf(q, *self.args, **self.kwds)
+
+    def isf(self, q):
+        return self.dist.isf(q, *self.args, **self.kwds)
+
+    def rvs(self, size=None, random_state=None):
+        kwds = self.kwds.copy()
+        kwds.update({'size': size, 'random_state': random_state})
+        return self.dist.rvs(*self.args, **kwds)
+
+    def sf(self, x):
+        return self.dist.sf(x, *self.args, **self.kwds)
+
+    def logsf(self, x):
+        return self.dist.logsf(x, *self.args, **self.kwds)
+
+    def stats(self, moments='mv'):
+        kwds = self.kwds.copy()
+        kwds.update({'moments': moments})
+        return self.dist.stats(*self.args, **kwds)
+
+    def median(self):
+        return self.dist.median(*self.args, **self.kwds)
+
+    def mean(self):
+        return self.dist.mean(*self.args, **self.kwds)
+
+    def var(self):
+        return self.dist.var(*self.args, **self.kwds)
+
+    def std(self):
+        return self.dist.std(*self.args, **self.kwds)
+
+    def moment(self, order=None):
+        return self.dist.moment(order, *self.args, **self.kwds)
+
+    def entropy(self):
+        return self.dist.entropy(*self.args, **self.kwds)
+
+    def interval(self, confidence=None):
+        return self.dist.interval(confidence, *self.args, **self.kwds)
+
+    def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):
+        # expect method only accepts shape parameters as positional args
+        # hence convert self.args, self.kwds, also loc/scale
+        # See the .expect method docstrings for the meaning of
+        # other parameters.
+        a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)
+        if isinstance(self.dist, rv_discrete):
+            return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds)
+        else:
+            return self.dist.expect(func, a, loc, scale, lb, ub,
+                                    conditional, **kwds)
+
+    def support(self):
+        return self.dist.support(*self.args, **self.kwds)
+
+
+class rv_discrete_frozen(rv_frozen):
+
+    def pmf(self, k):
+        return self.dist.pmf(k, *self.args, **self.kwds)
+
+    def logpmf(self, k):  # No error
+        return self.dist.logpmf(k, *self.args, **self.kwds)
+
+
+class rv_continuous_frozen(rv_frozen):
+
+    def pdf(self, x):
+        return self.dist.pdf(x, *self.args, **self.kwds)
+
+    def logpdf(self, x):
+        return self.dist.logpdf(x, *self.args, **self.kwds)
+
+
+def argsreduce(cond, *args):
+    """Clean arguments to:
+
+    1. Ensure all arguments are iterable (arrays of dimension at least one
+    2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is
+       True, in 1D.
+
+    Return list of processed arguments.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distn_infrastructure import argsreduce
+    >>> rng = np.random.default_rng()
+    >>> A = rng.random((4, 5))
+    >>> B = 2
+    >>> C = rng.random((1, 5))
+    >>> cond = np.ones(A.shape)
+    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
+    >>> A1.shape
+    (4, 5)
+    >>> B1.shape
+    (1,)
+    >>> C1.shape
+    (1, 5)
+    >>> cond[2,:] = 0
+    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
+    >>> A1.shape
+    (15,)
+    >>> B1.shape
+    (1,)
+    >>> C1.shape
+    (15,)
+
+    """
+    # some distributions assume arguments are iterable.
+    newargs = np.atleast_1d(*args)
+
+    # np.atleast_1d returns an array if only one argument, or a list of arrays
+    # if more than one argument.
+    if not isinstance(newargs, (list | tuple)):
+        newargs = (newargs,)
+
+    if np.all(cond):
+        # broadcast arrays with cond
+        *newargs, cond = np.broadcast_arrays(*newargs, cond)
+        return [arg.ravel() for arg in newargs]
+
+    s = cond.shape
+    # np.extract returns flattened arrays, which are not broadcastable together
+    # unless they are either the same size or size == 1.
+    return [(arg if np.size(arg) == 1
+            else np.extract(cond, np.broadcast_to(arg, s)))
+            for arg in newargs]
+
+
+parse_arg_template = """
+def _parse_args(self, %(shape_arg_str)s %(locscale_in)s):
+    return (%(shape_arg_str)s), %(locscale_out)s
+
+def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None):
+    return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size)
+
+def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'):
+    return (%(shape_arg_str)s), %(locscale_out)s, moments
+"""
+
+
+class rv_generic:
+    """Class which encapsulates common functionality between rv_discrete
+    and rv_continuous.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__()
+
+        # figure out if _stats signature has 'moments' keyword
+        sig = _getfullargspec(self._stats)
+        self._stats_has_moments = ((sig.varkw is not None) or
+                                   ('moments' in sig.args) or
+                                   ('moments' in sig.kwonlyargs))
+        self._random_state = check_random_state(seed)
+
+    @property
+    def random_state(self):
+        """Get or set the generator object for generating random variates.
+
+        If `random_state` is None (or `np.random`), the
+        `numpy.random.RandomState` singleton is used.
+        If `random_state` is an int, a new ``RandomState`` instance is used,
+        seeded with `random_state`.
+        If `random_state` is already a ``Generator`` or ``RandomState``
+        instance, that instance is used.
+
+        """
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._random_state = check_random_state(seed)
+
+    def __setstate__(self, state):
+        try:
+            self.__dict__.update(state)
+            # attaches the dynamically created methods on each instance.
+            # if a subclass overrides rv_generic.__setstate__, or implements
+            # it's own _attach_methods, then it must make sure that
+            # _attach_argparser_methods is called.
+            self._attach_methods()
+        except ValueError:
+            # reconstitute an old pickle scipy<1.6, that contains
+            # (_ctor_param, random_state) as state
+            self._ctor_param = state[0]
+            self._random_state = state[1]
+            self.__init__()
+
+    def _attach_methods(self):
+        """Attaches dynamically created methods to the rv_* instance.
+
+        This method must be overridden by subclasses, and must itself call
+         _attach_argparser_methods. This method is called in __init__ in
+         subclasses, and in __setstate__
+        """
+        raise NotImplementedError
+
+    def _attach_argparser_methods(self):
+        """
+        Generates the argument-parsing functions dynamically and attaches
+        them to the instance.
+
+        Should be called from `_attach_methods`, typically in __init__ and
+        during unpickling (__setstate__)
+        """
+        ns = {}
+        exec(self._parse_arg_template, ns)
+        # NB: attach to the instance, not class
+        for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']:
+            setattr(self, name, types.MethodType(ns[name], self))
+
+    def _construct_argparser(
+            self, meths_to_inspect, locscale_in, locscale_out):
+        """Construct the parser string for the shape arguments.
+
+        This method should be called in __init__ of a class for each
+        distribution. It creates the `_parse_arg_template` attribute that is
+        then used by `_attach_argparser_methods` to dynamically create and
+        attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs`
+        methods to the instance.
+
+        If self.shapes is a non-empty string, interprets it as a
+        comma-separated list of shape parameters.
+
+        Otherwise inspects the call signatures of `meths_to_inspect`
+        and constructs the argument-parsing functions from these.
+        In this case also sets `shapes` and `numargs`.
+        """
+
+        if self.shapes:
+            # sanitize the user-supplied shapes
+            if not isinstance(self.shapes, str):
+                raise TypeError('shapes must be a string.')
+
+            shapes = self.shapes.replace(',', ' ').split()
+
+            for field in shapes:
+                if keyword.iskeyword(field):
+                    raise SyntaxError('keywords cannot be used as shapes.')
+                if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field):
+                    raise SyntaxError(
+                        'shapes must be valid python identifiers')
+        else:
+            # find out the call signatures (_pdf, _cdf etc), deduce shape
+            # arguments. Generic methods only have 'self, x', any further args
+            # are shapes.
+            shapes_list = []
+            for meth in meths_to_inspect:
+                shapes_args = _getfullargspec(meth)  # NB does not contain self
+                args = shapes_args.args[1:]       # peel off 'x', too
+
+                if args:
+                    shapes_list.append(args)
+
+                    # *args or **kwargs are not allowed w/automatic shapes
+                    if shapes_args.varargs is not None:
+                        raise TypeError(
+                            '*args are not allowed w/out explicit shapes')
+                    if shapes_args.varkw is not None:
+                        raise TypeError(
+                            '**kwds are not allowed w/out explicit shapes')
+                    if shapes_args.kwonlyargs:
+                        raise TypeError(
+                            'kwonly args are not allowed w/out explicit shapes')
+                    if shapes_args.defaults is not None:
+                        raise TypeError('defaults are not allowed for shapes')
+
+            if shapes_list:
+                shapes = shapes_list[0]
+
+                # make sure the signatures are consistent
+                for item in shapes_list:
+                    if item != shapes:
+                        raise TypeError('Shape arguments are inconsistent.')
+            else:
+                shapes = []
+
+        # have the arguments, construct the method from template
+        shapes_str = ', '.join(shapes) + ', ' if shapes else ''  # NB: not None
+        dct = dict(shape_arg_str=shapes_str,
+                   locscale_in=locscale_in,
+                   locscale_out=locscale_out,
+                   )
+
+        # this string is used by _attach_argparser_methods
+        self._parse_arg_template = parse_arg_template % dct
+
+        self.shapes = ', '.join(shapes) if shapes else None
+        if not hasattr(self, 'numargs'):
+            # allows more general subclassing with *args
+            self.numargs = len(shapes)
+
+    def _construct_doc(self, docdict, shapes_vals=None):
+        """Construct the instance docstring with string substitutions."""
+        tempdict = docdict.copy()
+        tempdict['name'] = self.name or 'distname'
+        tempdict['shapes'] = self.shapes or ''
+
+        if shapes_vals is None:
+            shapes_vals = ()
+        try:
+            vals = ', '.join(f'{val:.3g}' for val in shapes_vals)
+        except TypeError:
+            vals = ', '.join(f'{val}' for val in shapes_vals)
+        tempdict['vals'] = vals
+
+        tempdict['shapes_'] = self.shapes or ''
+        if self.shapes and self.numargs == 1:
+            tempdict['shapes_'] += ','
+
+        if self.shapes:
+            tempdict['set_vals_stmt'] = f'>>> {self.shapes} = {vals}'
+        else:
+            tempdict['set_vals_stmt'] = ''
+
+        if self.shapes is None:
+            # remove shapes from call parameters if there are none
+            for item in ['default', 'before_notes']:
+                tempdict[item] = tempdict[item].replace(
+                    "\n%(shapes)s : array_like\n    shape parameters", "")
+        for i in range(2):
+            if self.shapes is None:
+                # necessary because we use %(shapes)s in two forms (w w/o ", ")
+                self.__doc__ = self.__doc__.replace("%(shapes)s, ", "")
+            try:
+                self.__doc__ = doccer.docformat(self.__doc__, tempdict)
+            except TypeError as e:
+                raise Exception("Unable to construct docstring for "
+                                f"distribution \"{self.name}\": {repr(e)}") from e
+
+        # correct for empty shapes
+        self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')')
+
+    def _construct_default_doc(self, longname=None,
+                               docdict=None, discrete='continuous'):
+        """Construct instance docstring from the default template."""
+        if longname is None:
+            longname = 'A'
+        self.__doc__ = ''.join([f'{longname} {discrete} random variable.',
+                                '\n\n%(before_notes)s\n', docheaders['notes'],
+                                '\n%(example)s'])
+        self._construct_doc(docdict)
+
+    def freeze(self, *args, **kwds):
+        """Freeze the distribution for the given arguments.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution.  Should include all
+            the non-optional arguments, may include ``loc`` and ``scale``.
+
+        Returns
+        -------
+        rv_frozen : rv_frozen instance
+            The frozen distribution.
+
+        """
+        if isinstance(self, rv_continuous):
+            return rv_continuous_frozen(self, *args, **kwds)
+        else:
+            return rv_discrete_frozen(self, *args, **kwds)
+
+    def __call__(self, *args, **kwds):
+        return self.freeze(*args, **kwds)
+    __call__.__doc__ = freeze.__doc__
+
+    # The actual calculation functions (no basic checking need be done)
+    # If these are defined, the others won't be looked at.
+    # Otherwise, the other set can be defined.
+    def _stats(self, *args, **kwds):
+        return None, None, None, None
+
+    # Noncentral moments (also known as the moment about the origin).
+    # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime".
+    # The primed mu is a widely used notation for the noncentral moment.
+    def _munp(self, n, *args):
+        # Silence floating point warnings from integration.
+        with np.errstate(all='ignore'):
+            vals = self.generic_moment(n, *args)
+        return vals
+
+    def _argcheck_rvs(self, *args, **kwargs):
+        # Handle broadcasting and size validation of the rvs method.
+        # Subclasses should not have to override this method.
+        # The rule is that if `size` is not None, then `size` gives the
+        # shape of the result (integer values of `size` are treated as
+        # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.)
+        #
+        # `args` is expected to contain the shape parameters (if any), the
+        # location and the scale in a flat tuple (e.g. if there are two
+        # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`).
+        # The only keyword argument expected is 'size'.
+        size = kwargs.get('size', None)
+        all_bcast = np.broadcast_arrays(*args)
+
+        def squeeze_left(a):
+            while a.ndim > 0 and a.shape[0] == 1:
+                a = a[0]
+            return a
+
+        # Eliminate trivial leading dimensions.  In the convention
+        # used by numpy's random variate generators, trivial leading
+        # dimensions are effectively ignored.  In other words, when `size`
+        # is given, trivial leading dimensions of the broadcast parameters
+        # in excess of the number of dimensions  in size are ignored, e.g.
+        #   >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3)
+        #   array([ 1.00104267,  3.00422496,  4.99799278])
+        # If `size` is not given, the exact broadcast shape is preserved:
+        #   >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]])
+        #   array([[[[ 1.00862899,  3.00061431,  4.99867122]]]])
+        #
+        all_bcast = [squeeze_left(a) for a in all_bcast]
+        bcast_shape = all_bcast[0].shape
+        bcast_ndim = all_bcast[0].ndim
+
+        if size is None:
+            size_ = bcast_shape
+        else:
+            size_ = tuple(np.atleast_1d(size))
+
+        # Check compatibility of size_ with the broadcast shape of all
+        # the parameters.  This check is intended to be consistent with
+        # how the numpy random variate generators (e.g. np.random.normal,
+        # np.random.beta) handle their arguments.   The rule is that, if size
+        # is given, it determines the shape of the output.  Broadcasting
+        # can't change the output size.
+
+        # This is the standard broadcasting convention of extending the
+        # shape with fewer dimensions with enough dimensions of length 1
+        # so that the two shapes have the same number of dimensions.
+        ndiff = bcast_ndim - len(size_)
+        if ndiff < 0:
+            bcast_shape = (1,)*(-ndiff) + bcast_shape
+        elif ndiff > 0:
+            size_ = (1,)*ndiff + size_
+
+        # This compatibility test is not standard.  In "regular" broadcasting,
+        # two shapes are compatible if for each dimension, the lengths are the
+        # same or one of the lengths is 1.  Here, the length of a dimension in
+        # size_ must not be less than the corresponding length in bcast_shape.
+        ok = all([bcdim == 1 or bcdim == szdim
+                  for (bcdim, szdim) in zip(bcast_shape, size_)])
+        if not ok:
+            raise ValueError("size does not match the broadcast shape of "
+                             f"the parameters. {size}, {size_}, {bcast_shape}")
+
+        param_bcast = all_bcast[:-2]
+        loc_bcast = all_bcast[-2]
+        scale_bcast = all_bcast[-1]
+
+        return param_bcast, loc_bcast, scale_bcast, size_
+
+    # These are the methods you must define (standard form functions)
+    # NB: generic _pdf, _logpdf, _cdf are different for
+    # rv_continuous and rv_discrete hence are defined in there
+    def _argcheck(self, *args):
+        """Default check for correct values on args and keywords.
+
+        Returns condition array of 1's where arguments are correct and
+         0's where they are not.
+
+        """
+        cond = 1
+        for arg in args:
+            cond = logical_and(cond, (asarray(arg) > 0))
+        return cond
+
+    def _get_support(self, *args, **kwargs):
+        """Return the support of the (unscaled, unshifted) distribution.
+
+        *Must* be overridden by distributions which have support dependent
+        upon the shape parameters of the distribution.  Any such override
+        *must not* set or change any of the class members, as these members
+        are shared amongst all instances of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        a, b : numeric (float, or int or +/-np.inf)
+            end-points of the distribution's support for the specified
+            shape parameters.
+        """
+        return self.a, self.b
+
+    def _support_mask(self, x, *args):
+        a, b = self._get_support(*args)
+        with np.errstate(invalid='ignore'):
+            return (a <= x) & (x <= b)
+
+    def _open_support_mask(self, x, *args):
+        a, b = self._get_support(*args)
+        with np.errstate(invalid='ignore'):
+            return (a < x) & (x < b)
+
+    def _rvs(self, *args, size=None, random_state=None):
+        # This method must handle size being a tuple, and it must
+        # properly broadcast *args and size.  size might be
+        # an empty tuple, which means a scalar random variate is to be
+        # generated.
+
+        # Use basic inverse cdf algorithm for RV generation as default.
+        U = random_state.uniform(size=size)
+        Y = self._ppf(U, *args)
+        return Y
+
+    def _logcdf(self, x, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._cdf(x, *args))
+
+    def _sf(self, x, *args):
+        return 1.0-self._cdf(x, *args)
+
+    def _logsf(self, x, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._sf(x, *args))
+
+    def _ppf(self, q, *args):
+        return self._ppfvec(q, *args)
+
+    def _isf(self, q, *args):
+        return self._ppf(1.0-q, *args)  # use correct _ppf for subclasses
+
+    # These are actually called, and should not be overwritten if you
+    # want to keep error checking.
+    def rvs(self, *args, **kwds):
+        """Random variates of given type.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        scale : array_like, optional
+            Scale parameter (default=1).
+        size : int or tuple of ints, optional
+            Defining number of random variates (default is 1).
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `random_state` is None (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance, that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of given `size`.
+
+        """
+        discrete = kwds.pop('discrete', None)
+        rndm = kwds.pop('random_state', None)
+        args, loc, scale, size = self._parse_args_rvs(*args, **kwds)
+        cond = logical_and(self._argcheck(*args), (scale >= 0))
+        if not np.all(cond):
+            message = ("Domain error in arguments. The `scale` parameter must "
+                       "be positive for all distributions, and many "
+                       "distributions have restrictions on shape parameters. "
+                       f"Please see the `scipy.stats.{self.name}` "
+                       "documentation for details.")
+            raise ValueError(message)
+
+        if np.all(scale == 0):
+            return loc*ones(size, 'd')
+
+        # extra gymnastics needed for a custom random_state
+        if rndm is not None:
+            random_state_saved = self._random_state
+            random_state = check_random_state(rndm)
+        else:
+            random_state = self._random_state
+
+        vals = self._rvs(*args, size=size, random_state=random_state)
+
+        vals = vals * scale + loc
+
+        # do not forget to restore the _random_state
+        if rndm is not None:
+            self._random_state = random_state_saved
+
+        # Cast to int if discrete
+        if discrete and not isinstance(self, rv_sample):
+            if size == ():
+                vals = int(vals)
+            else:
+                vals = vals.astype(np.int64)
+
+        return vals
+
+    def stats(self, *args, **kwds):
+        """Some statistics of the given RV.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional (continuous RVs only)
+            scale parameter (default=1)
+        moments : str, optional
+            composed of letters ['mvsk'] defining which moments to compute:
+            'm' = mean,
+            'v' = variance,
+            's' = (Fisher's) skew,
+            'k' = (Fisher's) kurtosis.
+            (default is 'mv')
+
+        Returns
+        -------
+        stats : sequence
+            of requested moments.
+
+        """
+        args, loc, scale, moments = self._parse_args_stats(*args, **kwds)
+        # scale = 1 by construction for discrete RVs
+        loc, scale = map(asarray, (loc, scale))
+        args = tuple(map(asarray, args))
+        cond = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        output = []
+        default = np.full(shape(cond), fill_value=self.badvalue)
+
+        # Use only entries that are valid in calculation
+        if np.any(cond):
+            goodargs = argsreduce(cond, *(args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+
+            if self._stats_has_moments:
+                mu, mu2, g1, g2 = self._stats(*goodargs,
+                                              **{'moments': moments})
+            else:
+                mu, mu2, g1, g2 = self._stats(*goodargs)
+
+            if 'm' in moments:
+                if mu is None:
+                    mu = self._munp(1, *goodargs)
+                out0 = default.copy()
+                place(out0, cond, mu * scale + loc)
+                output.append(out0)
+
+            if 'v' in moments:
+                if mu2 is None:
+                    mu2p = self._munp(2, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    # if mean is inf then var is also inf
+                    with np.errstate(invalid='ignore'):
+                        mu2 = np.where(~np.isinf(mu), mu2p - mu**2, np.inf)
+                out0 = default.copy()
+                place(out0, cond, mu2 * scale * scale)
+                output.append(out0)
+
+            if 's' in moments:
+                if g1 is None:
+                    mu3p = self._munp(3, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    if mu2 is None:
+                        mu2p = self._munp(2, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu2 = mu2p - mu * mu
+                    with np.errstate(invalid='ignore'):
+                        mu3 = (-mu*mu - 3*mu2)*mu + mu3p
+                        g1 = mu3 / np.power(mu2, 1.5)
+                out0 = default.copy()
+                place(out0, cond, g1)
+                output.append(out0)
+
+            if 'k' in moments:
+                if g2 is None:
+                    mu4p = self._munp(4, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    if mu2 is None:
+                        mu2p = self._munp(2, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu2 = mu2p - mu * mu
+                    if g1 is None:
+                        mu3 = None
+                    else:
+                        # (mu2**1.5) breaks down for nan and inf
+                        mu3 = g1 * np.power(mu2, 1.5)
+                    if mu3 is None:
+                        mu3p = self._munp(3, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu3 = (-mu * mu - 3 * mu2) * mu + mu3p
+                    with np.errstate(invalid='ignore'):
+                        mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p
+                        g2 = mu4 / mu2**2.0 - 3.0
+                out0 = default.copy()
+                place(out0, cond, g2)
+                output.append(out0)
+        else:  # no valid args
+            output = [default.copy() for _ in moments]
+
+        output = [out[()] for out in output]
+        if len(output) == 1:
+            return output[0]
+        else:
+            return tuple(output)
+
+    def entropy(self, *args, **kwds):
+        """Differential entropy of the RV.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        scale : array_like, optional  (continuous distributions only).
+            Scale parameter (default=1).
+
+        Notes
+        -----
+        Entropy is defined base `e`:
+
+        >>> import numpy as np
+        >>> from scipy.stats._distn_infrastructure import rv_discrete
+        >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
+        >>> np.allclose(drv.entropy(), np.log(2.0))
+        True
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        # NB: for discrete distributions scale=1 by construction in _parse_args
+        loc, scale = map(asarray, (loc, scale))
+        args = tuple(map(asarray, args))
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        output = zeros(shape(cond0), 'd')
+        place(output, (1-cond0), self.badvalue)
+        goodargs = argsreduce(cond0, scale, *args)
+        goodscale = goodargs[0]
+        goodargs = goodargs[1:]
+        place(output, cond0, self.vecentropy(*goodargs) + log(goodscale))
+        return output[()]
+
+    def moment(self, order, *args, **kwds):
+        """non-central moment of distribution of specified order.
+
+        Parameters
+        ----------
+        order : int, order >= 1
+            Order of moment.
+        arg1, arg2, arg3,... : float
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        """
+        n = order
+        shapes, loc, scale = self._parse_args(*args, **kwds)
+        args = np.broadcast_arrays(*(*shapes, loc, scale))
+        *shapes, loc, scale = args
+
+        i0 = np.logical_and(self._argcheck(*shapes), scale > 0)
+        i1 = np.logical_and(i0, loc == 0)
+        i2 = np.logical_and(i0, loc != 0)
+
+        args = argsreduce(i0, *shapes, loc, scale)
+        *shapes, loc, scale = args
+
+        if (floor(n) != n):
+            raise ValueError("Moment must be an integer.")
+        if (n < 0):
+            raise ValueError("Moment must be positive.")
+        mu, mu2, g1, g2 = None, None, None, None
+        if (n > 0) and (n < 5):
+            if self._stats_has_moments:
+                mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'mvsk'}[n]}
+            else:
+                mdict = {}
+            mu, mu2, g1, g2 = self._stats(*shapes, **mdict)
+        val = np.empty(loc.shape)  # val needs to be indexed by loc
+        val[...] = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, shapes)
+
+        # Convert to transformed  X = L + S*Y
+        # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n)
+        result = zeros(i0.shape)
+        place(result, ~i0, self.badvalue)
+
+        if i1.any():
+            res1 = scale[loc == 0]**n * val[loc == 0]
+            place(result, i1, res1)
+
+        if i2.any():
+            mom = [mu, mu2, g1, g2]
+            arrs = [i for i in mom if i is not None]
+            idx = [i for i in range(4) if mom[i] is not None]
+            if any(idx):
+                arrs = argsreduce(loc != 0, *arrs)
+                j = 0
+                for i in idx:
+                    mom[i] = arrs[j]
+                    j += 1
+            mu, mu2, g1, g2 = mom
+            args = argsreduce(loc != 0, *shapes, loc, scale, val)
+            *shapes, loc, scale, val = args
+
+            res2 = zeros(loc.shape, dtype='d')
+            fac = scale / loc
+            for k in range(n):
+                valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp,
+                                          shapes)
+                res2 += comb(n, k, exact=True)*fac**k * valk
+            res2 += fac**n * val
+            res2 *= loc**n
+            place(result, i2, res2)
+
+        return result[()]
+
+    def median(self, *args, **kwds):
+        """Median of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            Location parameter, Default is 0.
+        scale : array_like, optional
+            Scale parameter, Default is 1.
+
+        Returns
+        -------
+        median : float
+            The median of the distribution.
+
+        See Also
+        --------
+        rv_discrete.ppf
+            Inverse of the CDF
+
+        """
+        return self.ppf(0.5, *args, **kwds)
+
+    def mean(self, *args, **kwds):
+        """Mean of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        mean : float
+            the mean of the distribution
+
+        """
+        kwds['moments'] = 'm'
+        res = self.stats(*args, **kwds)
+        if isinstance(res, ndarray) and res.ndim == 0:
+            return res[()]
+        return res
+
+    def var(self, *args, **kwds):
+        """Variance of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        var : float
+            the variance of the distribution
+
+        """
+        kwds['moments'] = 'v'
+        res = self.stats(*args, **kwds)
+        if isinstance(res, ndarray) and res.ndim == 0:
+            return res[()]
+        return res
+
+    def std(self, *args, **kwds):
+        """Standard deviation of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        std : float
+            standard deviation of the distribution
+
+        """
+        kwds['moments'] = 'v'
+        res = sqrt(self.stats(*args, **kwds))
+        return res
+
+    def interval(self, confidence, *args, **kwds):
+        """Confidence interval with equal areas around the median.
+
+        Parameters
+        ----------
+        confidence : array_like of float
+            Probability that an rv will be drawn from the returned range.
+            Each value should be in the range [0, 1].
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter, Default is 0.
+        scale : array_like, optional
+            scale parameter, Default is 1.
+
+        Returns
+        -------
+        a, b : ndarray of float
+            end-points of range that contain ``100 * alpha %`` of the rv's
+            possible values.
+
+        Notes
+        -----
+        This is implemented as ``ppf([p_tail, 1-p_tail])``, where
+        ``ppf`` is the inverse cumulative distribution function and
+        ``p_tail = (1-confidence)/2``. Suppose ``[c, d]`` is the support of a
+        discrete distribution; then ``ppf([0, 1]) == (c-1, d)``. Therefore,
+        when ``confidence=1`` and the distribution is discrete, the left end
+        of the interval will be beyond the support of the distribution.
+        For discrete distributions, the interval will limit the probability
+        in each tail to be less than or equal to ``p_tail`` (usually
+        strictly less).
+
+        """
+        alpha = confidence
+
+        alpha = asarray(alpha)
+        if np.any((alpha > 1) | (alpha < 0)):
+            raise ValueError("alpha must be between 0 and 1 inclusive")
+        q1 = (1.0-alpha)/2
+        q2 = (1.0+alpha)/2
+        a = self.ppf(q1, *args, **kwds)
+        b = self.ppf(q2, *args, **kwds)
+        return a, b
+
+    def support(self, *args, **kwargs):
+        """Support of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter, Default is 0.
+        scale : array_like, optional
+            scale parameter, Default is 1.
+
+        Returns
+        -------
+        a, b : array_like
+            end-points of the distribution's support.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwargs)
+        arrs = np.broadcast_arrays(*args, loc, scale)
+        args, loc, scale = arrs[:-2], arrs[-2], arrs[-1]
+        cond = self._argcheck(*args) & (scale > 0)
+        _a, _b = self._get_support(*args)
+        if cond.all():
+            return _a * scale + loc, _b * scale + loc
+        elif cond.ndim == 0:
+            return self.badvalue, self.badvalue
+        # promote bounds to at least float to fill in the badvalue
+        _a, _b = np.asarray(_a).astype('d'), np.asarray(_b).astype('d')
+        out_a, out_b = _a * scale + loc, _b * scale + loc
+        place(out_a, 1-cond, self.badvalue)
+        place(out_b, 1-cond, self.badvalue)
+        return out_a, out_b
+
+    def nnlf(self, theta, x):
+        """Negative loglikelihood function.
+        Notes
+        -----
+        This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
+        parameters (including loc and scale).
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = (asarray(x)-loc) / scale
+        n_log_scale = len(x) * log(scale)
+        if np.any(~self._support_mask(x, *args)):
+            return inf
+        return self._nnlf(x, *args) + n_log_scale
+
+    def _nnlf(self, x, *args):
+        return -np.sum(self._logpxf(x, *args), axis=0)
+
+    def _nlff_and_penalty(self, x, args, log_fitfun):
+        # negative log fit function
+        cond0 = ~self._support_mask(x, *args)
+        n_bad = np.count_nonzero(cond0, axis=0)
+        if n_bad > 0:
+            x = argsreduce(~cond0, x)[0]
+        logff = log_fitfun(x, *args)
+        finite_logff = np.isfinite(logff)
+        n_bad += np.sum(~finite_logff, axis=0)
+        if n_bad > 0:
+            penalty = n_bad * log(_XMAX) * 100
+            return -np.sum(logff[finite_logff], axis=0) + penalty
+        return -np.sum(logff, axis=0)
+
+    def _penalized_nnlf(self, theta, x):
+        """Penalized negative loglikelihood function.
+        i.e., - sum (log pdf(x, theta), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = asarray((x-loc) / scale)
+        n_log_scale = len(x) * log(scale)
+        return self._nlff_and_penalty(x, args, self._logpxf) + n_log_scale
+
+    def _penalized_nlpsf(self, theta, x):
+        """Penalized negative log product spacing function.
+        i.e., - sum (log (diff (cdf (x, theta))), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        Follows reference [1] of scipy.stats.fit
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = (np.sort(x) - loc)/scale
+
+        def log_psf(x, *args):
+            x, lj = np.unique(x, return_counts=True)  # fast for sorted x
+            cdf_data = self._cdf(x, *args) if x.size else []
+            if not (x.size and 1 - cdf_data[-1] <= 0):
+                cdf = np.concatenate(([0], cdf_data, [1]))
+                lj = np.concatenate((lj, [1]))
+            else:
+                cdf = np.concatenate(([0], cdf_data))
+            # here we could use logcdf w/ logsumexp trick to take differences,
+            # but in the context of the method, it seems unlikely to matter
+            return lj * np.log(np.diff(cdf) / lj)
+
+        return self._nlff_and_penalty(x, args, log_psf)
+
+
+class _ShapeInfo:
+    def __init__(self, name, integrality=False, domain=(-np.inf, np.inf),
+                 inclusive=(True, True)):
+        self.name = name
+        self.integrality = integrality
+        self.endpoints = domain
+        self.inclusive = inclusive
+
+        domain = list(domain)
+        if np.isfinite(domain[0]) and not inclusive[0]:
+            domain[0] = np.nextafter(domain[0], np.inf)
+        if np.isfinite(domain[1]) and not inclusive[1]:
+            domain[1] = np.nextafter(domain[1], -np.inf)
+        self.domain = domain
+
+
+def _get_fixed_fit_value(kwds, names):
+    """
+    Given names such as ``['f0', 'fa', 'fix_a']``, check that there is
+    at most one non-None value in `kwds` associated with those names.
+    Return that value, or None if none of the names occur in `kwds`.
+    As a side effect, all occurrences of those names in `kwds` are
+    removed.
+    """
+    vals = [(name, kwds.pop(name)) for name in names if name in kwds]
+    if len(vals) > 1:
+        repeated = [name for name, val in vals]
+        raise ValueError("fit method got multiple keyword arguments to "
+                         "specify the same fixed parameter: " +
+                         ', '.join(repeated))
+    return vals[0][1] if vals else None
+
+
+#  continuous random variables: implement maybe later
+#
+#  hf  --- Hazard Function (PDF / SF)
+#  chf  --- Cumulative hazard function (-log(SF))
+#  psf --- Probability sparsity function (reciprocal of the pdf) in
+#                units of percent-point-function (as a function of q).
+#                Also, the derivative of the percent-point function.
+
+
+class rv_continuous(rv_generic):
+    """A generic continuous random variable class meant for subclassing.
+
+    `rv_continuous` is a base class to construct specific distribution classes
+    and instances for continuous random variables. It cannot be used
+    directly as a distribution.
+
+    Parameters
+    ----------
+    momtype : int, optional
+        The type of generic moment calculation to use: 0 for pdf, 1 (default)
+        for ppf.
+    a : float, optional
+        Lower bound of the support of the distribution, default is minus
+        infinity.
+    b : float, optional
+        Upper bound of the support of the distribution, default is plus
+        infinity.
+    xtol : float, optional
+        The tolerance for fixed point calculation for generic ppf.
+    badvalue : float, optional
+        The value in a result arrays that indicates a value that for which
+        some argument restriction is violated, default is np.nan.
+    name : str, optional
+        The name of the instance. This string is used to construct the default
+        example for distributions.
+    longname : str, optional
+        This string is used as part of the first line of the docstring returned
+        when a subclass has no docstring of its own. Note: `longname` exists
+        for backwards compatibility, do not use for new subclasses.
+    shapes : str, optional
+        The shape of the distribution. For example ``"m, n"`` for a
+        distribution that takes two integers as the two shape arguments for all
+        its methods. If not provided, shape parameters will be inferred from
+        the signature of the private methods, ``_pdf`` and ``_cdf`` of the
+        instance.
+    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.
+
+    Methods
+    -------
+    rvs
+    pdf
+    logpdf
+    cdf
+    logcdf
+    sf
+    logsf
+    ppf
+    isf
+    moment
+    stats
+    entropy
+    expect
+    median
+    mean
+    std
+    var
+    interval
+    __call__
+    fit
+    fit_loc_scale
+    nnlf
+    support
+
+    Notes
+    -----
+    Public methods of an instance of a distribution class (e.g., ``pdf``,
+    ``cdf``) check their arguments and pass valid arguments to private,
+    computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid
+    if it is within the support of the distribution.
+    Whether a shape parameter is valid is decided by an ``_argcheck`` method
+    (which defaults to checking that its arguments are strictly positive.)
+
+    **Subclassing**
+
+    New random variables can be defined by subclassing the `rv_continuous` class
+    and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized
+    to location 0 and scale 1).
+
+    If positive argument checking is not correct for your RV
+    then you will also need to re-define the ``_argcheck`` method.
+
+    For most of the scipy.stats distributions, the support interval doesn't
+    depend on the shape parameters. ``x`` being in the support interval is
+    equivalent to ``self.a <= x <= self.b``.  If either of the endpoints of
+    the support do depend on the shape parameters, then
+    i) the distribution must implement the ``_get_support`` method; and
+    ii) those dependent endpoints must be omitted from the distribution's
+    call to the ``rv_continuous`` initializer.
+
+    Correct, but potentially slow defaults exist for the remaining
+    methods but for speed and/or accuracy you can over-ride::
+
+      _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf
+
+    The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``,
+    applied to a uniform random variate. In order to generate random variates
+    efficiently, either the default ``_ppf`` needs to be overwritten (e.g.
+    if the inverse cdf can expressed in an explicit form) or a sampling
+    method needs to be implemented in a custom ``_rvs`` method.
+
+    If possible, you should override ``_isf``, ``_sf`` or ``_logsf``.
+    The main reason would be to improve numerical accuracy: for example,
+    the survival function ``_sf`` is computed as ``1 - _cdf`` which can
+    result in loss of precision if ``_cdf(x)`` is close to one.
+
+    **Methods that can be overwritten by subclasses**
+    ::
+
+      _rvs
+      _pdf
+      _cdf
+      _sf
+      _ppf
+      _isf
+      _stats
+      _munp
+      _entropy
+      _argcheck
+      _get_support
+
+    There are additional (internal and private) generic methods that can
+    be useful for cross-checking and for debugging, but might work in all
+    cases when directly called.
+
+    A note on ``shapes``: subclasses need not specify them explicitly. In this
+    case, `shapes` will be automatically deduced from the signatures of the
+    overridden methods (`pdf`, `cdf` etc).
+    If, for some reason, you prefer to avoid relying on introspection, you can
+    specify ``shapes`` explicitly as an argument to the instance constructor.
+
+
+    **Frozen Distributions**
+
+    Normally, you must provide shape parameters (and, optionally, location and
+    scale parameters to each call of a method of a distribution.
+
+    Alternatively, the object may be called (as a function) to fix the shape,
+    location, and scale parameters returning a "frozen" continuous RV object:
+
+    rv = generic(, loc=0, scale=1)
+        `rv_frozen` object with the same methods but holding the given shape,
+        location, and scale fixed
+
+    **Statistics**
+
+    Statistics are computed using numerical integration by default.
+    For speed you can redefine this using ``_stats``:
+
+     - take shape parameters and return mu, mu2, g1, g2
+     - If you can't compute one of these, return it as None
+     - Can also be defined with a keyword argument ``moments``, which is a
+       string composed of "m", "v", "s", and/or "k".
+       Only the components appearing in string should be computed and
+       returned in the order "m", "v", "s", or "k"  with missing values
+       returned as None.
+
+    Alternatively, you can override ``_munp``, which takes ``n`` and shape
+    parameters and returns the n-th non-central moment of the distribution.
+
+    **Deepcopying / Pickling**
+
+    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
+    etc.), any underlying random number generator is deepcopied with it. An
+    implication is that if a distribution relies on the singleton RandomState
+    before copying, it will rely on a copy of that random state after copying,
+    and ``np.random.seed`` will no longer control the state.
+
+    Examples
+    --------
+    To create a new Gaussian distribution, we would do the following:
+
+    >>> from scipy.stats import rv_continuous
+    >>> class gaussian_gen(rv_continuous):
+    ...     "Gaussian distribution"
+    ...     def _pdf(self, x):
+    ...         return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi)
+    >>> gaussian = gaussian_gen(name='gaussian')
+
+    ``scipy.stats`` distributions are *instances*, so here we subclass
+    `rv_continuous` and create an instance. With this, we now have
+    a fully functional distribution with all relevant methods automagically
+    generated by the framework.
+
+    Note that above we defined a standard normal distribution, with zero mean
+    and unit variance. Shifting and scaling of the distribution can be done
+    by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)``
+    essentially computes ``y = (x - loc) / scale`` and
+    ``gaussian._pdf(y) / scale``.
+
+    """
+
+    def __init__(self, momtype=1, a=None, b=None, xtol=1e-14,
+                 badvalue=None, name=None, longname=None,
+                 shapes=None, seed=None):
+
+        super().__init__(seed)
+
+        # save the ctor parameters, cf generic freeze
+        self._ctor_param = dict(
+            momtype=momtype, a=a, b=b, xtol=xtol,
+            badvalue=badvalue, name=name, longname=longname,
+            shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        if name is None:
+            name = 'Distribution'
+        self.badvalue = badvalue
+        self.name = name
+        self.a = a
+        self.b = b
+        if a is None:
+            self.a = -inf
+        if b is None:
+            self.b = inf
+        self.xtol = xtol
+        self.moment_type = momtype
+        self.shapes = shapes
+
+        self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf],
+                                  locscale_in='loc=0, scale=1',
+                                  locscale_out='loc, scale')
+        self._attach_methods()
+
+        if longname is None:
+            if name[0] in ['aeiouAEIOU']:
+                hstr = "An "
+            else:
+                hstr = "A "
+            longname = hstr + name
+
+        if sys.flags.optimize < 2:
+            # Skip adding docstrings if interpreter is run with -OO
+            if self.__doc__ is None:
+                self._construct_default_doc(longname=longname,
+                                            docdict=docdict,
+                                            discrete='continuous')
+            else:
+                dct = dict(distcont)
+                self._construct_doc(docdict, dct.get(self.name))
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+
+        # these methods will be remade in __setstate__
+        # _random_state attribute is taken care of by rv_generic
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs",
+                 "_cdfvec", "_ppfvec", "vecentropy", "generic_moment"]
+        [dct.pop(attr, None) for attr in attrs]
+        return dct
+
+    def _attach_methods(self):
+        """
+        Attaches dynamically created methods to the rv_continuous instance.
+        """
+        # _attach_methods is responsible for calling _attach_argparser_methods
+        self._attach_argparser_methods()
+
+        # nin correction
+        self._ppfvec = vectorize(self._ppf_single, otypes='d')
+        self._ppfvec.nin = self.numargs + 1
+        self.vecentropy = vectorize(self._entropy, otypes='d')
+        self._cdfvec = vectorize(self._cdf_single, otypes='d')
+        self._cdfvec.nin = self.numargs + 1
+
+        if self.moment_type == 0:
+            self.generic_moment = vectorize(self._mom0_sc, otypes='d')
+        else:
+            self.generic_moment = vectorize(self._mom1_sc, otypes='d')
+        # Because of the *args argument of _mom0_sc, vectorize cannot count the
+        # number of arguments correctly.
+        self.generic_moment.nin = self.numargs + 1
+
+    def _updated_ctor_param(self):
+        """Return the current version of _ctor_param, possibly updated by user.
+
+        Used by freezing.
+        Keep this in sync with the signature of __init__.
+        """
+        dct = self._ctor_param.copy()
+        dct['a'] = self.a
+        dct['b'] = self.b
+        dct['xtol'] = self.xtol
+        dct['badvalue'] = self.badvalue
+        dct['name'] = self.name
+        dct['shapes'] = self.shapes
+        return dct
+
+    def _ppf_to_solve(self, x, q, *args):
+        return self.cdf(*(x, )+args)-q
+
+    def _ppf_single(self, q, *args):
+        factor = 10.
+        left, right = self._get_support(*args)
+
+        if np.isinf(left):
+            left = min(-factor, right)
+            while self._ppf_to_solve(left, q, *args) > 0.:
+                left, right = left * factor, left
+            # left is now such that cdf(left) <= q
+            # if right has changed, then cdf(right) > q
+
+        if np.isinf(right):
+            right = max(factor, left)
+            while self._ppf_to_solve(right, q, *args) < 0.:
+                left, right = right, right * factor
+            # right is now such that cdf(right) >= q
+
+        return optimize.brentq(self._ppf_to_solve,
+                               left, right, args=(q,)+args, xtol=self.xtol)
+
+    # moment from definition
+    def _mom_integ0(self, x, m, *args):
+        return x**m * self.pdf(x, *args)
+
+    def _mom0_sc(self, m, *args):
+        _a, _b = self._get_support(*args)
+        return integrate.quad(self._mom_integ0, _a, _b,
+                              args=(m,)+args)[0]
+
+    # moment calculated using ppf
+    def _mom_integ1(self, q, m, *args):
+        return (self.ppf(q, *args))**m
+
+    def _mom1_sc(self, m, *args):
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+    def _pdf(self, x, *args):
+        return _derivative(self._cdf, x, dx=1e-5, args=args, order=5)
+
+    # Could also define any of these
+    def _logpdf(self, x, *args):
+        p = self._pdf(x, *args)
+        with np.errstate(divide='ignore'):
+            return log(p)
+
+    def _logpxf(self, x, *args):
+        # continuous distributions have PDF, discrete have PMF, but sometimes
+        # the distinction doesn't matter. This lets us use `_logpxf` for both
+        # discrete and continuous distributions.
+        return self._logpdf(x, *args)
+
+    def _cdf_single(self, x, *args):
+        _a, _b = self._get_support(*args)
+        return integrate.quad(self._pdf, _a, x, args=args)[0]
+
+    def _cdf(self, x, *args):
+        return self._cdfvec(x, *args)
+
+    def _logcdf(self, x, *args):
+        median = self._ppf(0.5, *args)
+        with np.errstate(divide='ignore'):
+            return _lazywhere(x < median, (x,) + args,
+                              f=lambda x, *args: np.log(self._cdf(x, *args)),
+                              f2=lambda x, *args: np.log1p(-self._sf(x, *args)))
+
+    def _logsf(self, x, *args):
+        median = self._ppf(0.5, *args)
+        with np.errstate(divide='ignore'):
+            return _lazywhere(x > median, (x,) + args,
+                              f=lambda x, *args: np.log(self._sf(x, *args)),
+                              f2=lambda x, *args: np.log1p(-self._cdf(x, *args)))
+
+    # generic _argcheck, _sf, _ppf, _isf, _rvs are defined
+    # in rv_generic
+
+    def pdf(self, x, *args, **kwds):
+        """Probability density function at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._support_mask(x, *args) & (scale > 0)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args+(scale,)))
+            scale, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._pdf(*goodargs) / scale)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logpdf(self, x, *args, **kwds):
+        """Log of the probability density function at x of the given RV.
+
+        This uses a more numerically accurate calculation if available.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logpdf : array_like
+            Log of the probability density function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._support_mask(x, *args) & (scale > 0)
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args+(scale,)))
+            scale, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._logpdf(*goodargs) - log(scale))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def cdf(self, x, *args, **kwds):
+        """
+        Cumulative distribution function of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        cdf : ndarray
+            Cumulative distribution function evaluated at `x`
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = (x >= np.asarray(_b)) & cond0
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._cdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logcdf(self, x, *args, **kwds):
+        """Log of the cumulative distribution function at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logcdf : array_like
+            Log of the cumulative distribution function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = (x >= _b) & cond0
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._logcdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def sf(self, x, *args, **kwds):
+        """Survival function (1 - `cdf`) at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        sf : array_like
+            Survival function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = cond0 & (x <= _a)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._sf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logsf(self, x, *args, **kwds):
+        """Log of the survival function of the given RV.
+
+        Returns the log of the "survival function," defined as (1 - `cdf`),
+        evaluated at `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logsf : ndarray
+            Log of the survival function evaluated at `x`.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = cond0 & (x <= _a)
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._logsf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def ppf(self, q, *args, **kwds):
+        """Percent point function (inverse of `cdf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            lower tail probability
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        x : array_like
+            quantile corresponding to the lower tail probability q.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        q, loc, scale = map(asarray, (q, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        cond1 = (0 < q) & (q < 1)
+        cond2 = cond0 & (q == 0)
+        cond3 = cond0 & (q == 1)
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue)
+
+        lower_bound = _a * scale + loc
+        upper_bound = _b * scale + loc
+        place(output, cond2, argsreduce(cond2, lower_bound)[0])
+        place(output, cond3, argsreduce(cond3, upper_bound)[0])
+
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+            place(output, cond, self._ppf(*goodargs) * scale + loc)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def isf(self, q, *args, **kwds):
+        """Inverse survival function (inverse of `sf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            upper tail probability
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        x : ndarray or scalar
+            Quantile corresponding to the upper tail probability q.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        q, loc, scale = map(asarray, (q, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        cond1 = (0 < q) & (q < 1)
+        cond2 = cond0 & (q == 1)
+        cond3 = cond0 & (q == 0)
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue)
+
+        lower_bound = _a * scale + loc
+        upper_bound = _b * scale + loc
+        place(output, cond2, argsreduce(cond2, lower_bound)[0])
+        place(output, cond3, argsreduce(cond3, upper_bound)[0])
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+            place(output, cond, self._isf(*goodargs) * scale + loc)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _unpack_loc_scale(self, theta):
+        try:
+            loc = theta[-2]
+            scale = theta[-1]
+            args = tuple(theta[:-2])
+        except IndexError as e:
+            raise ValueError("Not enough input arguments.") from e
+        return loc, scale, args
+
+    def _nnlf_and_penalty(self, x, args):
+        """
+        Compute the penalized negative log-likelihood for the
+        "standardized" data (i.e. already shifted by loc and
+        scaled by scale) for the shape parameters in `args`.
+
+        `x` can be a 1D numpy array or a CensoredData instance.
+        """
+        if isinstance(x, CensoredData):
+            # Filter out the data that is not in the support.
+            xs = x._supported(*self._get_support(*args))
+            n_bad = len(x) - len(xs)
+            i1, i2 = xs._interval.T
+            terms = [
+                # logpdf of the noncensored data.
+                self._logpdf(xs._uncensored, *args),
+                # logcdf of the left-censored data.
+                self._logcdf(xs._left, *args),
+                # logsf of the right-censored data.
+                self._logsf(xs._right, *args),
+                # log of probability of the interval-censored data.
+                np.log(self._delta_cdf(i1, i2, *args)),
+            ]
+        else:
+            cond0 = ~self._support_mask(x, *args)
+            n_bad = np.count_nonzero(cond0)
+            if n_bad > 0:
+                x = argsreduce(~cond0, x)[0]
+            terms = [self._logpdf(x, *args)]
+
+        totals, bad_counts = zip(*[_sum_finite(term) for term in terms])
+        total = sum(totals)
+        n_bad += sum(bad_counts)
+
+        return -total + n_bad * _LOGXMAX * 100
+
+    def _penalized_nnlf(self, theta, x):
+        """Penalized negative loglikelihood function.
+
+        i.e., - sum (log pdf(x, theta), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        if isinstance(x, CensoredData):
+            x = (x - loc) / scale
+            n_log_scale = (len(x) - x.num_censored()) * log(scale)
+        else:
+            x = (x - loc) / scale
+            n_log_scale = len(x) * log(scale)
+
+        return self._nnlf_and_penalty(x, args) + n_log_scale
+
+    def _fitstart(self, data, args=None):
+        """Starting point for fit (shape arguments + loc + scale)."""
+        if args is None:
+            args = (1.0,)*self.numargs
+        loc, scale = self._fit_loc_scale_support(data, *args)
+        return args + (loc, scale)
+
+    def _reduce_func(self, args, kwds, data=None):
+        """
+        Return the (possibly reduced) function to optimize in order to find MLE
+        estimates for the .fit method.
+        """
+        # Convert fixed shape parameters to the standard numeric form: e.g. for
+        # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value
+        # for `f0`, `fa` or 'fix_a'.  The following converts the latter two
+        # into the first (numeric) form.
+        shapes = []
+        if self.shapes:
+            shapes = self.shapes.replace(',', ' ').split()
+            for j, s in enumerate(shapes):
+                key = 'f' + str(j)
+                names = [key, 'f' + s, 'fix_' + s]
+                val = _get_fixed_fit_value(kwds, names)
+                if val is not None:
+                    kwds[key] = val
+
+        args = list(args)
+        Nargs = len(args)
+        fixedn = []
+        names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale']
+        x0 = []
+        for n, key in enumerate(names):
+            if key in kwds:
+                fixedn.append(n)
+                args[n] = kwds.pop(key)
+            else:
+                x0.append(args[n])
+
+        methods = {"mle", "mm"}
+        method = kwds.pop('method', "mle").lower()
+        if method == "mm":
+            n_params = len(shapes) + 2 - len(fixedn)
+            exponents = (np.arange(1, n_params+1))[:, np.newaxis]
+            data_moments = np.sum(data[None, :]**exponents/len(data), axis=1)
+
+            def objective(theta, x):
+                return self._moment_error(theta, x, data_moments)
+
+        elif method == "mle":
+            objective = self._penalized_nnlf
+        else:
+            raise ValueError(f"Method '{method}' not available; "
+                             f"must be one of {methods}")
+
+        if len(fixedn) == 0:
+            func = objective
+            restore = None
+        else:
+            if len(fixedn) == Nargs:
+                raise ValueError(
+                    "All parameters fixed. There is nothing to optimize.")
+
+            def restore(args, theta):
+                # Replace with theta for all numbers not in fixedn
+                # This allows the non-fixed values to vary, but
+                #  we still call self.nnlf with all parameters.
+                i = 0
+                for n in range(Nargs):
+                    if n not in fixedn:
+                        args[n] = theta[i]
+                        i += 1
+                return args
+
+            def func(theta, x):
+                newtheta = restore(args[:], theta)
+                return objective(newtheta, x)
+
+        return x0, func, restore, args
+
+    def _moment_error(self, theta, x, data_moments):
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+
+        dist_moments = np.array([self.moment(i+1, *args, loc=loc, scale=scale)
+                                 for i in range(len(data_moments))])
+        if np.any(np.isnan(dist_moments)):
+            raise ValueError("Method of moments encountered a non-finite "
+                             "distribution moment and cannot continue. "
+                             "Consider trying method='MLE'.")
+
+        return (((data_moments - dist_moments) /
+                 np.maximum(np.abs(data_moments), 1e-8))**2).sum()
+
+    def fit(self, data, *args, **kwds):
+        r"""
+        Return estimates of shape (if applicable), location, and scale
+        parameters from data. The default estimation method is Maximum
+        Likelihood Estimation (MLE), but Method of Moments (MM)
+        is also available.
+
+        Starting estimates for the fit are given by input arguments;
+        for any arguments not provided with starting estimates,
+        ``self._fitstart(data)`` is called to generate such.
+
+        One can hold some parameters fixed to specific values by passing in
+        keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
+        and ``floc`` and ``fscale`` (for location and scale parameters,
+        respectively).
+
+        Parameters
+        ----------
+        data : array_like or `CensoredData` instance
+            Data to use in estimating the distribution parameters.
+        arg1, arg2, arg3,... : floats, optional
+            Starting value(s) for any shape-characterizing arguments (those not
+            provided will be determined by a call to ``_fitstart(data)``).
+            No default value.
+        **kwds : floats, optional
+            - `loc`: initial guess of the distribution's location parameter.
+            - `scale`: initial guess of the distribution's scale parameter.
+
+            Special keyword arguments are recognized as holding certain
+            parameters fixed:
+
+            - f0...fn : hold respective shape parameters fixed.
+              Alternatively, shape parameters to fix can be specified by name.
+              For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a``
+              are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
+              equivalent to ``f1``.
+
+            - floc : hold location parameter fixed to specified value.
+
+            - fscale : hold scale parameter fixed to specified value.
+
+            - optimizer : The optimizer to use.  The optimizer must take
+              ``func`` and starting position as the first two arguments,
+              plus ``args`` (for extra arguments to pass to the
+              function to be optimized) and ``disp``.
+              The ``fit`` method calls the optimizer with ``disp=0`` to suppress output.
+              The optimizer must return the estimated parameters.
+
+            - method : The method to use. The default is "MLE" (Maximum
+              Likelihood Estimate); "MM" (Method of Moments)
+              is also available.
+
+        Raises
+        ------
+        TypeError, ValueError
+            If an input is invalid
+        `~scipy.stats.FitError`
+            If fitting fails or the fit produced would be invalid
+
+        Returns
+        -------
+        parameter_tuple : tuple of floats
+            Estimates for any shape parameters (if applicable), followed by
+            those for location and scale. For most random variables, shape
+            statistics will be returned, but there are exceptions (e.g.
+            ``norm``).
+
+        Notes
+        -----
+        With ``method="MLE"`` (default), the fit is computed by minimizing
+        the negative log-likelihood function. A large, finite penalty
+        (rather than infinite negative log-likelihood) is applied for
+        observations beyond the support of the distribution.
+
+        With ``method="MM"``, the fit is computed by minimizing the L2 norm
+        of the relative errors between the first *k* raw (about zero) data
+        moments and the corresponding distribution moments, where *k* is the
+        number of non-fixed parameters.
+        More precisely, the objective function is::
+
+            (((data_moments - dist_moments)
+              / np.maximum(np.abs(data_moments), 1e-8))**2).sum()
+
+        where the constant ``1e-8`` avoids division by zero in case of
+        vanishing data moments. Typically, this error norm can be reduced to
+        zero.
+        Note that the standard method of moments can produce parameters for
+        which some data are outside the support of the fitted distribution;
+        this implementation does nothing to prevent this.
+
+        For either method,
+        the returned answer is not guaranteed to be globally optimal; it
+        may only be locally optimal, or the optimization may fail altogether.
+        If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``,
+        the `fit` method will raise a ``RuntimeError``.
+
+        When passing a ``CensoredData`` instance to ``data``, the log-likelihood
+        function is defined as:
+
+        .. math::
+
+            l(\pmb{\theta}; k) & = \sum
+                                    \log(f(k_u; \pmb{\theta}))
+                                + \sum
+                                    \log(F(k_l; \pmb{\theta})) \\
+                                & + \sum
+                                    \log(1 - F(k_r; \pmb{\theta})) \\
+                                & + \sum
+                                    \log(F(k_{\text{high}, i}; \pmb{\theta})
+                                    - F(k_{\text{low}, i}; \pmb{\theta}))
+
+        where :math:`f` and :math:`F` are the pdf and cdf, respectively, of the
+        function being fitted, :math:`\pmb{\theta}` is the parameter vector,
+        :math:`u` are the indices of uncensored observations,
+        :math:`l` are the indices of left-censored observations,
+        :math:`r` are the indices of right-censored observations,
+        subscripts "low"/"high" denote endpoints of interval-censored observations, and
+        :math:`i` are the indices of interval-censored observations.
+
+        Examples
+        --------
+
+        Generate some data to fit: draw random variates from the `beta`
+        distribution
+
+        >>> import numpy as np
+        >>> from scipy.stats import beta
+        >>> a, b = 1., 2.
+        >>> rng = np.random.default_rng(172786373191770012695001057628748821561)
+        >>> x = beta.rvs(a, b, size=1000, random_state=rng)
+
+        Now we can fit all four parameters (``a``, ``b``, ``loc`` and
+        ``scale``):
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x)
+        >>> a1, b1, loc1, scale1
+        (1.0198945204435628, 1.9484708982737828, 4.372241314917588e-05, 0.9979078845964814)
+
+        The fit can be done also using a custom optimizer:
+
+        >>> from scipy.optimize import minimize
+        >>> def custom_optimizer(func, x0, args=(), disp=0):
+        ...     res = minimize(func, x0, args, method="slsqp", options={"disp": disp})
+        ...     if res.success:
+        ...         return res.x
+        ...     raise RuntimeError('optimization routine failed')
+        >>> a1, b1, loc1, scale1 = beta.fit(x, method="MLE", optimizer=custom_optimizer)
+        >>> a1, b1, loc1, scale1
+        (1.0198821087258905, 1.948484145914738, 4.3705304486881485e-05, 0.9979104663953395)
+
+        We can also use some prior knowledge about the dataset: let's keep
+        ``loc`` and ``scale`` fixed:
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
+        >>> loc1, scale1
+        (0, 1)
+
+        We can also keep shape parameters fixed by using ``f``-keywords. To
+        keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
+        equivalently, ``fa=1``:
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
+        >>> a1
+        1
+
+        Not all distributions return estimates for the shape parameters.
+        ``norm`` for example just returns estimates for location and scale:
+
+        >>> from scipy.stats import norm
+        >>> x = norm.rvs(a, b, size=1000, random_state=123)
+        >>> loc1, scale1 = norm.fit(x)
+        >>> loc1, scale1
+        (0.92087172783841631, 2.0015750750324668)
+        """ # noqa: E501
+        method = kwds.get('method', "mle").lower()
+
+        censored = isinstance(data, CensoredData)
+        if censored:
+            if method != 'mle':
+                raise ValueError('For censored data, the method must'
+                                 ' be "MLE".')
+            if data.num_censored() == 0:
+                # There are no censored values in data, so replace the
+                # CensoredData instance with a regular array.
+                data = data._uncensored
+                censored = False
+
+        Narg = len(args)
+        if Narg > self.numargs:
+            raise TypeError("Too many input arguments.")
+
+        # Check the finiteness of data only if data is not an instance of
+        # CensoredData.  The arrays in a CensoredData instance have already
+        # been validated.
+        if not censored:
+            # Note: `ravel()` is called for backwards compatibility.
+            data = np.asarray(data).ravel()
+            if not np.isfinite(data).all():
+                raise ValueError("The data contains non-finite values.")
+
+        start = [None]*2
+        if (Narg < self.numargs) or not ('loc' in kwds and
+                                         'scale' in kwds):
+            # get distribution specific starting locations
+            start = self._fitstart(data)
+            args += start[Narg:-2]
+        loc = kwds.pop('loc', start[-2])
+        scale = kwds.pop('scale', start[-1])
+        args += (loc, scale)
+        x0, func, restore, args = self._reduce_func(args, kwds, data=data)
+        optimizer = kwds.pop('optimizer', optimize.fmin)
+        # convert string to function in scipy.optimize
+        optimizer = _fit_determine_optimizer(optimizer)
+        # by now kwds must be empty, since everybody took what they needed
+        if kwds:
+            raise TypeError(f"Unknown arguments: {kwds}.")
+
+        # In some cases, method of moments can be done with fsolve/root
+        # instead of an optimizer, but sometimes no solution exists,
+        # especially when the user fixes parameters. Minimizing the sum
+        # of squares of the error generalizes to these cases.
+        vals = optimizer(func, x0, args=(data,), disp=0)
+        obj = func(vals, data)
+
+        if restore is not None:
+            vals = restore(args, vals)
+        vals = tuple(vals)
+
+        loc, scale, shapes = self._unpack_loc_scale(vals)
+        if not (np.all(self._argcheck(*shapes)) and scale > 0):
+            raise FitError("Optimization converged to parameters that are "
+                           "outside the range allowed by the distribution.")
+
+        if method == 'mm':
+            if not np.isfinite(obj):
+                raise FitError("Optimization failed: either a data moment "
+                               "or fitted distribution moment is "
+                               "non-finite.")
+
+        return vals
+
+    def _fit_loc_scale_support(self, data, *args):
+        """Estimate loc and scale parameters from data accounting for support.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to fit.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        Lhat : float
+            Estimated location parameter for the data.
+        Shat : float
+            Estimated scale parameter for the data.
+
+        """
+        if isinstance(data, CensoredData):
+            # For this estimate, "uncensor" the data by taking the
+            # given endpoints as the data for the left- or right-censored
+            # data, and the mean for the interval-censored data.
+            data = data._uncensor()
+        else:
+            data = np.asarray(data)
+
+        # Estimate location and scale according to the method of moments.
+        loc_hat, scale_hat = self.fit_loc_scale(data, *args)
+
+        # Compute the support according to the shape parameters.
+        self._argcheck(*args)
+        _a, _b = self._get_support(*args)
+        a, b = _a, _b
+        support_width = b - a
+
+        # If the support is empty then return the moment-based estimates.
+        if support_width <= 0:
+            return loc_hat, scale_hat
+
+        # Compute the proposed support according to the loc and scale
+        # estimates.
+        a_hat = loc_hat + a * scale_hat
+        b_hat = loc_hat + b * scale_hat
+
+        # Use the moment-based estimates if they are compatible with the data.
+        data_a = np.min(data)
+        data_b = np.max(data)
+        if a_hat < data_a and data_b < b_hat:
+            return loc_hat, scale_hat
+
+        # Otherwise find other estimates that are compatible with the data.
+        data_width = data_b - data_a
+        rel_margin = 0.1
+        margin = data_width * rel_margin
+
+        # For a finite interval, both the location and scale
+        # should have interesting values.
+        if support_width < np.inf:
+            loc_hat = (data_a - a) - margin
+            scale_hat = (data_width + 2 * margin) / support_width
+            return loc_hat, scale_hat
+
+        # For a one-sided interval, use only an interesting location parameter.
+        if a > -np.inf:
+            return (data_a - a) - margin, 1
+        elif b < np.inf:
+            return (data_b - b) + margin, 1
+        else:
+            raise RuntimeError
+
+    def fit_loc_scale(self, data, *args):
+        """
+        Estimate loc and scale parameters from data using 1st and 2nd moments.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to fit.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        Lhat : float
+            Estimated location parameter for the data.
+        Shat : float
+            Estimated scale parameter for the data.
+
+        """
+        mu, mu2 = self.stats(*args, **{'moments': 'mv'})
+        tmp = asarray(data)
+        muhat = tmp.mean()
+        mu2hat = tmp.var()
+        Shat = sqrt(mu2hat / mu2)
+        with np.errstate(invalid='ignore'):
+            Lhat = muhat - Shat*mu
+        if not np.isfinite(Lhat):
+            Lhat = 0
+        if not (np.isfinite(Shat) and (0 < Shat)):
+            Shat = 1
+        return Lhat, Shat
+
+    def _entropy(self, *args):
+        def integ(x):
+            val = self._pdf(x, *args)
+            return entr(val)
+
+        # upper limit is often inf, so suppress warnings when integrating
+        _a, _b = self._get_support(*args)
+        with np.errstate(over='ignore'):
+            h = integrate.quad(integ, _a, _b)[0]
+
+        if not np.isnan(h):
+            return h
+        else:
+            # try with different limits if integration problems
+            low, upp = self.ppf([1e-10, 1. - 1e-10], *args)
+            if np.isinf(_b):
+                upper = upp
+            else:
+                upper = _b
+            if np.isinf(_a):
+                lower = low
+            else:
+                lower = _a
+            return integrate.quad(integ, lower, upper)[0]
+
+    def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,
+               conditional=False, **kwds):
+        """Calculate expected value of a function with respect to the
+        distribution by numerical integration.
+
+        The expected value of a function ``f(x)`` with respect to a
+        distribution ``dist`` is defined as::
+
+                    ub
+            E[f(x)] = Integral(f(x) * dist.pdf(x)),
+                    lb
+
+        where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``
+        distribution. If the bounds ``lb`` and ``ub`` correspond to the
+        support of the distribution, e.g. ``[-inf, inf]`` in the default
+        case, then the integral is the unrestricted expectation of ``f(x)``.
+        Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``
+        outside a finite interval in which case the expectation is
+        calculated within the finite range ``[lb, ub]``.
+
+        Parameters
+        ----------
+        func : callable, optional
+            Function for which integral is calculated. Takes only one argument.
+            The default is the identity mapping f(x) = x.
+        args : tuple, optional
+            Shape parameters of the distribution.
+        loc : float, optional
+            Location parameter (default=0).
+        scale : float, optional
+            Scale parameter (default=1).
+        lb, ub : scalar, optional
+            Lower and upper bound for integration. Default is set to the
+            support of the distribution.
+        conditional : bool, optional
+            If True, the integral is corrected by the conditional probability
+            of the integration interval.  The return value is the expectation
+            of the function, conditional on being in the given interval.
+            Default is False.
+
+        Additional keyword arguments are passed to the integration routine.
+
+        Returns
+        -------
+        expect : float
+            The calculated expected value.
+
+        Notes
+        -----
+        The integration behavior of this function is inherited from
+        `scipy.integrate.quad`. Neither this function nor
+        `scipy.integrate.quad` can verify whether the integral exists or is
+        finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and
+        ``cauchy(0).expect()`` returns ``0.0``.
+
+        Likewise, the accuracy of results is not verified by the function.
+        `scipy.integrate.quad` is typically reliable for integrals that are
+        numerically favorable, but it is not guaranteed to converge
+        to a correct value for all possible intervals and integrands. This
+        function is provided for convenience; for critical applications,
+        check results against other integration methods.
+
+        The function is not vectorized.
+
+        Examples
+        --------
+
+        To understand the effect of the bounds of integration consider
+
+        >>> from scipy.stats import expon
+        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)
+        0.6321205588285578
+
+        This is close to
+
+        >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)
+        0.6321205588285577
+
+        If ``conditional=True``
+
+        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)
+        1.0000000000000002
+
+        The slight deviation from 1 is due to numerical integration.
+
+        The integrand can be treated as a complex-valued function
+        by passing ``complex_func=True`` to `scipy.integrate.quad` .
+
+        >>> import numpy as np
+        >>> from scipy.stats import vonmises
+        >>> res = vonmises(loc=2, kappa=1).expect(lambda x: np.exp(1j*x),
+        ...                                       complex_func=True)
+        >>> res
+        (-0.18576377217422957+0.40590124735052263j)
+
+        >>> np.angle(res)  # location of the (circular) distribution
+        2.0
+
+        """
+        lockwds = {'loc': loc,
+                   'scale': scale}
+        self._argcheck(*args)
+        _a, _b = self._get_support(*args)
+        if func is None:
+            def fun(x, *args):
+                return x * self.pdf(x, *args, **lockwds)
+        else:
+            def fun(x, *args):
+                return func(x) * self.pdf(x, *args, **lockwds)
+        if lb is None:
+            lb = loc + _a * scale
+        if ub is None:
+            ub = loc + _b * scale
+
+        cdf_bounds = self.cdf([lb, ub], *args, **lockwds)
+        invfac = cdf_bounds[1] - cdf_bounds[0]
+
+        kwds['args'] = args
+
+        # split interval to help integrator w/ infinite support; see gh-8928
+        alpha = 0.05  # split body from tails at probability mass `alpha`
+        inner_bounds = np.array([alpha, 1-alpha])
+        cdf_inner_bounds = cdf_bounds[0] + invfac * inner_bounds
+        c, d = loc + self._ppf(cdf_inner_bounds, *args) * scale
+
+        # Do not silence warnings from integration.
+        lbc = integrate.quad(fun, lb, c, **kwds)[0]
+        cd = integrate.quad(fun, c, d, **kwds)[0]
+        dub = integrate.quad(fun, d, ub, **kwds)[0]
+        vals = (lbc + cd + dub)
+
+        if conditional:
+            vals /= invfac
+        return np.array(vals)[()]  # make it a numpy scalar like other methods
+
+    def _param_info(self):
+        shape_info = self._shape_info()
+        loc_info = _ShapeInfo("loc", False, (-np.inf, np.inf), (False, False))
+        scale_info = _ShapeInfo("scale", False, (0, np.inf), (False, False))
+        param_info = shape_info + [loc_info, scale_info]
+        return param_info
+
+    # For now, _delta_cdf is a private method.
+    def _delta_cdf(self, x1, x2, *args, loc=0, scale=1):
+        """
+        Compute CDF(x2) - CDF(x1).
+
+        Where x1 is greater than the median, compute SF(x1) - SF(x2),
+        otherwise compute CDF(x2) - CDF(x1).
+
+        This function is only useful if `dist.sf(x, ...)` has an implementation
+        that is numerically more accurate than `1 - dist.cdf(x, ...)`.
+        """
+        cdf1 = self.cdf(x1, *args, loc=loc, scale=scale)
+        # Possible optimizations (needs investigation-these might not be
+        # better):
+        # * Use _lazywhere instead of np.where
+        # * Instead of cdf1 > 0.5, compare x1 to the median.
+        result = np.where(cdf1 > 0.5,
+                          (self.sf(x1, *args, loc=loc, scale=scale)
+                           - self.sf(x2, *args, loc=loc, scale=scale)),
+                          self.cdf(x2, *args, loc=loc, scale=scale) - cdf1)
+        if result.ndim == 0:
+            result = result[()]
+        return result
+
+
+# Helpers for the discrete distributions
+def _drv2_moment(self, n, *args):
+    """Non-central moment of discrete distribution."""
+    def fun(x):
+        return np.power(x, n) * self._pmf(x, *args)
+
+    _a, _b = self._get_support(*args)
+    return _expect(fun, _a, _b, self._ppf(0.5, *args), self.inc)
+
+
+def _drv2_ppfsingle(self, q, *args):  # Use basic bisection algorithm
+    _a, _b = self._get_support(*args)
+    b = _b
+    a = _a
+
+    step = 10
+    if isinf(b):            # Be sure ending point is > q
+        b = float(max(100*q, 10))
+        while 1:
+            if b >= _b:
+                qb = 1.0
+                break
+            qb = self._cdf(b, *args)
+            if (qb < q):
+                b += step
+                step *= 2
+            else:
+                break
+    else:
+        qb = 1.0
+
+    step = 10
+    if isinf(a):    # be sure starting point < q
+        a = float(min(-100*q, -10))
+        while 1:
+            if a <= _a:
+                qb = 0.0
+                break
+            qa = self._cdf(a, *args)
+            if (qa > q):
+                a -= step
+                step *= 2
+            else:
+                break
+    else:
+        qa = self._cdf(a, *args)
+
+    if np.isinf(a) or np.isinf(b):
+        message = "Arguments that bracket the requested quantile could not be found."
+        raise RuntimeError(message)
+
+    # maximum number of bisections within the normal float64s
+    # maxiter = int(np.log2(finfo.max) - np.log2(finfo.smallest_normal))
+    maxiter = 2046
+    for i in range(maxiter):
+        if (qa == q):
+            return a
+        if (qb == q):
+            return b
+        if b <= a+1:
+            if qa > q:
+                return a
+            else:
+                return b
+        c = int((a+b)/2.0)
+        qc = self._cdf(c, *args)
+        if (qc < q):
+            if a != c:
+                a = c
+            else:
+                raise RuntimeError('updating stopped, endless loop')
+            qa = qc
+        elif (qc > q):
+            if b != c:
+                b = c
+            else:
+                raise RuntimeError('updating stopped, endless loop')
+            qb = qc
+        else:
+            return c
+
+
+# Must over-ride one of _pmf or _cdf or pass in
+#  x_k, p(x_k) lists in initialization
+
+
+class rv_discrete(rv_generic):
+    """A generic discrete random variable class meant for subclassing.
+
+    `rv_discrete` is a base class to construct specific distribution classes
+    and instances for discrete random variables. It can also be used
+    to construct an arbitrary distribution defined by a list of support
+    points and corresponding probabilities.
+
+    Parameters
+    ----------
+    a : float, optional
+        Lower bound of the support of the distribution, default: 0
+    b : float, optional
+        Upper bound of the support of the distribution, default: plus infinity
+    moment_tol : float, optional
+        The tolerance for the generic calculation of moments.
+    values : tuple of two array_like, optional
+        ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero
+        probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk``
+        and ``pk`` must have the same shape, and ``xk`` must be unique.
+    inc : integer, optional
+        Increment for the support of the distribution.
+        Default is 1. (other values have not been tested)
+    badvalue : float, optional
+        The value in a result arrays that indicates a value that for which
+        some argument restriction is violated, default is np.nan.
+    name : str, optional
+        The name of the instance. This string is used to construct the default
+        example for distributions.
+    longname : str, optional
+        This string is used as part of the first line of the docstring returned
+        when a subclass has no docstring of its own. Note: `longname` exists
+        for backwards compatibility, do not use for new subclasses.
+    shapes : str, optional
+        The shape of the distribution. For example "m, n" for a distribution
+        that takes two integers as the two shape arguments for all its methods
+        If not provided, shape parameters will be inferred from
+        the signatures of the private methods, ``_pmf`` and ``_cdf`` of
+        the instance.
+    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.
+
+    Methods
+    -------
+    rvs
+    pmf
+    logpmf
+    cdf
+    logcdf
+    sf
+    logsf
+    ppf
+    isf
+    moment
+    stats
+    entropy
+    expect
+    median
+    mean
+    std
+    var
+    interval
+    __call__
+    support
+
+    Notes
+    -----
+    This class is similar to `rv_continuous`. Whether a shape parameter is
+    valid is decided by an ``_argcheck`` method (which defaults to checking
+    that its arguments are strictly positive.)
+    The main differences are as follows.
+
+    - The support of the distribution is a set of integers.
+    - Instead of the probability density function, ``pdf`` (and the
+      corresponding private ``_pdf``), this class defines the
+      *probability mass function*, `pmf` (and the corresponding
+      private ``_pmf``.)
+    - There is no ``scale`` parameter.
+    - The default implementations of methods (e.g. ``_cdf``) are not designed
+      for distributions with support that is unbounded below (i.e.
+      ``a=-np.inf``), so they must be overridden.
+
+    To create a new discrete distribution, we would do the following:
+
+    >>> from scipy.stats import rv_discrete
+    >>> class poisson_gen(rv_discrete):
+    ...     "Poisson distribution"
+    ...     def _pmf(self, k, mu):
+    ...         return exp(-mu) * mu**k / factorial(k)
+
+    and create an instance::
+
+    >>> poisson = poisson_gen(name="poisson")
+
+    Note that above we defined the Poisson distribution in the standard form.
+    Shifting the distribution can be done by providing the ``loc`` parameter
+    to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``
+    delegates the work to ``poisson._pmf(x-loc, mu)``.
+
+    **Discrete distributions from a list of probabilities**
+
+    Alternatively, you can construct an arbitrary discrete rv defined
+    on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the
+    ``values`` keyword argument to the `rv_discrete` constructor.
+
+    **Deepcopying / Pickling**
+
+    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
+    etc.), any underlying random number generator is deepcopied with it. An
+    implication is that if a distribution relies on the singleton RandomState
+    before copying, it will rely on a copy of that random state after copying,
+    and ``np.random.seed`` will no longer control the state.
+
+    Examples
+    --------
+    Custom made discrete distribution:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> xk = np.arange(7)
+    >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
+    >>> custm = stats.rv_discrete(name='custm', values=(xk, pk))
+    >>>
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')
+    >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)
+    >>> plt.show()
+
+    Random number generation:
+
+    >>> R = custm.rvs(size=100)
+
+    """
+    def __new__(cls, a=0, b=inf, name=None, badvalue=None,
+                moment_tol=1e-8, values=None, inc=1, longname=None,
+                shapes=None, seed=None):
+
+        if values is not None:
+            # dispatch to a subclass
+            return super().__new__(rv_sample)
+        else:
+            # business as usual
+            return super().__new__(cls)
+
+    def __init__(self, a=0, b=inf, name=None, badvalue=None,
+                 moment_tol=1e-8, values=None, inc=1, longname=None,
+                 shapes=None, seed=None):
+
+        super().__init__(seed)
+
+        # cf generic freeze
+        self._ctor_param = dict(
+            a=a, b=b, name=name, badvalue=badvalue,
+            moment_tol=moment_tol, values=values, inc=inc,
+            longname=longname, shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        self.badvalue = badvalue
+        self.a = a
+        self.b = b
+        self.moment_tol = moment_tol
+        self.inc = inc
+        self.shapes = shapes
+
+        if values is not None:
+            raise ValueError("rv_discrete.__init__(..., values != None, ...)")
+
+        self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf],
+                                  locscale_in='loc=0',
+                                  # scale=1 for discrete RVs
+                                  locscale_out='loc, 1')
+        self._attach_methods()
+        self._construct_docstrings(name, longname)
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+        # these methods will be remade in __setstate__
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs",
+                 "_cdfvec", "_ppfvec", "generic_moment"]
+        [dct.pop(attr, None) for attr in attrs]
+        return dct
+
+    def _attach_methods(self):
+        """Attaches dynamically created methods to the rv_discrete instance."""
+        self._cdfvec = vectorize(self._cdf_single, otypes='d')
+        self.vecentropy = vectorize(self._entropy)
+
+        # _attach_methods is responsible for calling _attach_argparser_methods
+        self._attach_argparser_methods()
+
+        # nin correction needs to be after we know numargs
+        # correct nin for generic moment vectorization
+        _vec_generic_moment = vectorize(_drv2_moment, otypes='d')
+        _vec_generic_moment.nin = self.numargs + 2
+        self.generic_moment = types.MethodType(_vec_generic_moment, self)
+
+        # correct nin for ppf vectorization
+        _vppf = vectorize(_drv2_ppfsingle, otypes='d')
+        _vppf.nin = self.numargs + 2
+        self._ppfvec = types.MethodType(_vppf, self)
+
+        # now that self.numargs is defined, we can adjust nin
+        self._cdfvec.nin = self.numargs + 1
+
+    def _construct_docstrings(self, name, longname):
+        if name is None:
+            name = 'Distribution'
+        self.name = name
+
+        # generate docstring for subclass instances
+        if longname is None:
+            if name[0] in ['aeiouAEIOU']:
+                hstr = "An "
+            else:
+                hstr = "A "
+            longname = hstr + name
+
+        if sys.flags.optimize < 2:
+            # Skip adding docstrings if interpreter is run with -OO
+            if self.__doc__ is None:
+                self._construct_default_doc(longname=longname,
+                                            docdict=docdict_discrete,
+                                            discrete='discrete')
+            else:
+                dct = dict(distdiscrete)
+                self._construct_doc(docdict_discrete, dct.get(self.name))
+
+            # discrete RV do not have the scale parameter, remove it
+            self.__doc__ = self.__doc__.replace(
+                '\n    scale : array_like, '
+                'optional\n        scale parameter (default=1)', '')
+
+    def _updated_ctor_param(self):
+        """Return the current version of _ctor_param, possibly updated by user.
+
+        Used by freezing.
+        Keep this in sync with the signature of __init__.
+        """
+        dct = self._ctor_param.copy()
+        dct['a'] = self.a
+        dct['b'] = self.b
+        dct['badvalue'] = self.badvalue
+        dct['moment_tol'] = self.moment_tol
+        dct['inc'] = self.inc
+        dct['name'] = self.name
+        dct['shapes'] = self.shapes
+        return dct
+
+    def _nonzero(self, k, *args):
+        return floor(k) == k
+
+    def _pmf(self, k, *args):
+        return self._cdf(k, *args) - self._cdf(k-1, *args)
+
+    def _logpmf(self, k, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._pmf(k, *args))
+
+    def _logpxf(self, k, *args):
+        # continuous distributions have PDF, discrete have PMF, but sometimes
+        # the distinction doesn't matter. This lets us use `_logpxf` for both
+        # discrete and continuous distributions.
+        return self._logpmf(k, *args)
+
+    def _unpack_loc_scale(self, theta):
+        try:
+            loc = theta[-1]
+            scale = 1
+            args = tuple(theta[:-1])
+        except IndexError as e:
+            raise ValueError("Not enough input arguments.") from e
+        return loc, scale, args
+
+    def _cdf_single(self, k, *args):
+        _a, _b = self._get_support(*args)
+        m = arange(int(_a), k+1)
+        return np.sum(self._pmf(m, *args), axis=0)
+
+    def _cdf(self, x, *args):
+        k = floor(x).astype(np.float64)
+        return self._cdfvec(k, *args)
+
+    # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic
+
+    def rvs(self, *args, **kwargs):
+        """Random variates of given type.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        size : int or tuple of ints, optional
+            Defining number of random variates (Default is 1). Note that `size`
+            has to be given as keyword, not as positional argument.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `random_state` is None (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance, that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of given `size`.
+
+        """
+        kwargs['discrete'] = True
+        return super().rvs(*args, **kwargs)
+
+    def pmf(self, k, *args, **kwds):
+        """Probability mass function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        pmf : array_like
+            Probability mass function evaluated at k
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k <= _b)
+        if not isinstance(self, rv_sample):
+            cond1 = cond1 & self._nonzero(k, *args)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), 'd')
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._pmf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logpmf(self, k, *args, **kwds):
+        """Log of the probability mass function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter. Default is 0.
+
+        Returns
+        -------
+        logpmf : array_like
+            Log of the probability mass function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k <= _b)
+        if not isinstance(self, rv_sample):
+            cond1 = cond1 & self._nonzero(k, *args)
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logpmf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def cdf(self, k, *args, **kwds):
+        """Cumulative distribution function of the given RV.
+
+        Parameters
+        ----------
+        k : array_like, int
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        cdf : ndarray
+            Cumulative distribution function evaluated at `k`.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k >= _b)
+        cond3 = np.isneginf(k)
+        cond = cond0 & cond1 & np.isfinite(k)
+
+        output = zeros(shape(cond), 'd')
+        place(output, cond2*(cond0 == cond0), 1.0)
+        place(output, cond3*(cond0 == cond0), 0.0)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._cdf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logcdf(self, k, *args, **kwds):
+        """Log of the cumulative distribution function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like, int
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        logcdf : array_like
+            Log of the cumulative distribution function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k >= _b)
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2*(cond0 == cond0), 0.0)
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logcdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def sf(self, k, *args, **kwds):
+        """Survival function (1 - `cdf`) at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        sf : array_like
+            Survival function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = ((k < _a) | np.isneginf(k)) & cond0
+        cond = cond0 & cond1 & np.isfinite(k)
+        output = zeros(shape(cond), 'd')
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._sf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logsf(self, k, *args, **kwds):
+        """Log of the survival function of the given RV.
+
+        Returns the log of the "survival function," defined as 1 - `cdf`,
+        evaluated at `k`.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        logsf : ndarray
+            Log of the survival function evaluated at `k`.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k < _a) & cond0
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logsf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def ppf(self, q, *args, **kwds):
+        """Percent point function (inverse of `cdf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            Lower tail probability.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        k : array_like
+            Quantile corresponding to the lower tail probability, q.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        q, loc = map(asarray, (q, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (loc == loc)
+        cond1 = (q > 0) & (q < 1)
+        cond2 = (q == 1) & cond0
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')
+        # output type 'd' to handle nin and inf
+        place(output, (q == 0)*(cond == cond), _a-1 + loc)
+        place(output, cond2, _b + loc)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(loc,)))
+            loc, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._ppf(*goodargs) + loc)
+
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def isf(self, q, *args, **kwds):
+        """Inverse survival function (inverse of `sf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            Upper tail probability.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        k : ndarray or scalar
+            Quantile corresponding to the upper tail probability, q.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        q, loc = map(asarray, (q, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (loc == loc)
+        cond1 = (q > 0) & (q < 1)
+        cond2 = (q == 1) & cond0
+        cond3 = (q == 0) & cond0
+        cond = cond0 & cond1
+
+        # same problem as with ppf; copied from ppf and changed
+        output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')
+        # output type 'd' to handle nin and inf
+        lower_bound = _a - 1 + loc
+        upper_bound = _b + loc
+        place(output, cond2*(cond == cond), lower_bound)
+        place(output, cond3*(cond == cond), upper_bound)
+
+        # call place only if at least 1 valid argument
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(loc,)))
+            loc, goodargs = goodargs[-1], goodargs[:-1]
+            # PB same as ticket 766
+            place(output, cond, self._isf(*goodargs) + loc)
+
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _entropy(self, *args):
+        if hasattr(self, 'pk'):
+            return stats.entropy(self.pk)
+        else:
+            _a, _b = self._get_support(*args)
+            return _expect(lambda x: entr(self._pmf(x, *args)),
+                           _a, _b, self._ppf(0.5, *args), self.inc)
+
+    def expect(self, func=None, args=(), loc=0, lb=None, ub=None,
+               conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32):
+        """
+        Calculate expected value of a function with respect to the distribution
+        for discrete distribution by numerical summation.
+
+        Parameters
+        ----------
+        func : callable, optional
+            Function for which the expectation value is calculated.
+            Takes only one argument.
+            The default is the identity mapping f(k) = k.
+        args : tuple, optional
+            Shape parameters of the distribution.
+        loc : float, optional
+            Location parameter.
+            Default is 0.
+        lb, ub : int, optional
+            Lower and upper bound for the summation, default is set to the
+            support of the distribution, inclusive (``lb <= k <= ub``).
+        conditional : bool, optional
+            If true then the expectation is corrected by the conditional
+            probability of the summation interval. The return value is the
+            expectation of the function, `func`, conditional on being in
+            the given interval (k such that ``lb <= k <= ub``).
+            Default is False.
+        maxcount : int, optional
+            Maximal number of terms to evaluate (to avoid an endless loop for
+            an infinite sum). Default is 1000.
+        tolerance : float, optional
+            Absolute tolerance for the summation. Default is 1e-10.
+        chunksize : int, optional
+            Iterate over the support of a distributions in chunks of this size.
+            Default is 32.
+
+        Returns
+        -------
+        expect : float
+            Expected value.
+
+        Notes
+        -----
+        For heavy-tailed distributions, the expected value may or
+        may not exist,
+        depending on the function, `func`. If it does exist, but the
+        sum converges
+        slowly, the accuracy of the result may be rather low. For instance, for
+        ``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
+        increasing `maxcount` and/or `chunksize` may improve the result,
+        but may also make zipf very slow.
+
+        The function is not vectorized.
+
+        """
+        # Although `args` is just the shape parameters, `poisson_binom` needs this
+        # to split the vector-valued shape into a tuple of separate shapes
+        args, _, _ = self._parse_args(*args)
+
+        if func is None:
+            def fun(x):
+                # loc and args from outer scope
+                return (x+loc)*self._pmf(x, *args)
+        else:
+            def fun(x):
+                # loc and args from outer scope
+                return func(x+loc)*self._pmf(x, *args)
+        # used pmf because _pmf does not check support in randint and there
+        # might be problems(?) with correct self.a, self.b at this stage maybe
+        # not anymore, seems to work now with _pmf
+
+        _a, _b = self._get_support(*args)
+        if lb is None:
+            lb = _a
+        else:
+            lb = lb - loc   # convert bound for standardized distribution
+        if ub is None:
+            ub = _b
+        else:
+            ub = ub - loc   # convert bound for standardized distribution
+        if conditional:
+            invfac = self.sf(lb-1, *args) - self.sf(ub, *args)
+        else:
+            invfac = 1.0
+
+        if isinstance(self, rv_sample):
+            res = self._expect(fun, lb, ub)
+            return res / invfac
+
+        # iterate over the support, starting from the median
+        x0 = self._ppf(0.5, *args)
+        res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize)
+        return res / invfac
+
+    def _param_info(self):
+        shape_info = self._shape_info()
+        loc_info = _ShapeInfo("loc", True, (-np.inf, np.inf), (False, False))
+        param_info = shape_info + [loc_info]
+        return param_info
+
+
+def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10,
+            chunksize=32):
+    """Helper for computing the expectation value of `fun`."""
+    # short-circuit if the support size is small enough
+    if (ub - lb) <= chunksize:
+        supp = np.arange(lb, ub+1, inc)
+        vals = fun(supp)
+        return np.sum(vals)
+
+    # otherwise, iterate starting from x0
+    if x0 < lb:
+        x0 = lb
+    if x0 > ub:
+        x0 = ub
+
+    count, tot = 0, 0.
+    # iterate over [x0, ub] inclusive
+    for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc):
+        count += x.size
+        delta = np.sum(fun(x))
+        tot += delta
+        if abs(delta) < tolerance * x.size:
+            break
+        if count > maxcount:
+            warnings.warn('expect(): sum did not converge',
+                          RuntimeWarning, stacklevel=3)
+            return tot
+
+    # iterate over [lb, x0)
+    for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc):
+        count += x.size
+        delta = np.sum(fun(x))
+        tot += delta
+        if abs(delta) < tolerance * x.size:
+            break
+        if count > maxcount:
+            warnings.warn('expect(): sum did not converge',
+                          RuntimeWarning, stacklevel=3)
+            break
+
+    return tot
+
+
+def _iter_chunked(x0, x1, chunksize=4, inc=1):
+    """Iterate from x0 to x1 in chunks of chunksize and steps inc.
+
+    x0 must be finite, x1 need not be. In the latter case, the iterator is
+    infinite.
+    Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards
+    (make sure to set inc < 0.)
+
+    >>> from scipy.stats._distn_infrastructure import _iter_chunked
+    >>> [x for x in _iter_chunked(2, 5, inc=2)]
+    [array([2, 4])]
+    >>> [x for x in _iter_chunked(2, 11, inc=2)]
+    [array([2, 4, 6, 8]), array([10])]
+    >>> [x for x in _iter_chunked(2, -5, inc=-2)]
+    [array([ 2,  0, -2, -4])]
+    >>> [x for x in _iter_chunked(2, -9, inc=-2)]
+    [array([ 2,  0, -2, -4]), array([-6, -8])]
+
+    """
+    if inc == 0:
+        raise ValueError('Cannot increment by zero.')
+    if chunksize <= 0:
+        raise ValueError(f'Chunk size must be positive; got {chunksize}.')
+
+    s = 1 if inc > 0 else -1
+    stepsize = abs(chunksize * inc)
+
+    x = np.copy(x0)
+    while (x - x1) * inc < 0:
+        delta = min(stepsize, abs(x - x1))
+        step = delta * s
+        supp = np.arange(x, x + step, inc)
+        x += step
+        yield supp
+
+
+class rv_sample(rv_discrete):
+    """A 'sample' discrete distribution defined by the support and values.
+
+    The ctor ignores most of the arguments, only needs the `values` argument.
+    """
+
+    def __init__(self, a=0, b=inf, name=None, badvalue=None,
+                 moment_tol=1e-8, values=None, inc=1, longname=None,
+                 shapes=None, seed=None):
+
+        super(rv_discrete, self).__init__(seed)
+
+        if values is None:
+            raise ValueError("rv_sample.__init__(..., values=None,...)")
+
+        # cf generic freeze
+        self._ctor_param = dict(
+            a=a, b=b, name=name, badvalue=badvalue,
+            moment_tol=moment_tol, values=values, inc=inc,
+            longname=longname, shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        self.badvalue = badvalue
+        self.moment_tol = moment_tol
+        self.inc = inc
+        self.shapes = shapes
+        self.vecentropy = self._entropy
+
+        xk, pk = values
+
+        if np.shape(xk) != np.shape(pk):
+            raise ValueError("xk and pk must have the same shape.")
+        if np.less(pk, 0.0).any():
+            raise ValueError("All elements of pk must be non-negative.")
+        if not np.allclose(np.sum(pk), 1):
+            raise ValueError("The sum of provided pk is not 1.")
+        if not len(set(np.ravel(xk))) == np.size(xk):
+            raise ValueError("xk may not contain duplicate values.")
+
+        indx = np.argsort(np.ravel(xk))
+        self.xk = np.take(np.ravel(xk), indx, 0)
+        self.pk = np.take(np.ravel(pk), indx, 0)
+        self.a = self.xk[0]
+        self.b = self.xk[-1]
+
+        self.qvals = np.cumsum(self.pk, axis=0)
+
+        self.shapes = ' '   # bypass inspection
+
+        self._construct_argparser(meths_to_inspect=[self._pmf],
+                                  locscale_in='loc=0',
+                                  # scale=1 for discrete RVs
+                                  locscale_out='loc, 1')
+
+        self._attach_methods()
+
+        self._construct_docstrings(name, longname)
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+
+        # these methods will be remade in rv_generic.__setstate__,
+        # which calls rv_generic._attach_methods
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs"]
+        [dct.pop(attr, None) for attr in attrs]
+
+        return dct
+
+    def _attach_methods(self):
+        """Attaches dynamically created argparser methods."""
+        self._attach_argparser_methods()
+
+    def _get_support(self, *args):
+        """Return the support of the (unscaled, unshifted) distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        a, b : numeric (float, or int or +/-np.inf)
+            end-points of the distribution's support.
+        """
+        return self.a, self.b
+
+    def _pmf(self, x):
+        return np.select([x == k for k in self.xk],
+                         [np.broadcast_arrays(p, x)[0] for p in self.pk], 0)
+
+    def _cdf(self, x):
+        xx, xxk = np.broadcast_arrays(x[:, None], self.xk)
+        indx = np.argmax(xxk > xx, axis=-1) - 1
+        return self.qvals[indx]
+
+    def _ppf(self, q):
+        qq, sqq = np.broadcast_arrays(q[..., None], self.qvals)
+        indx = argmax(sqq >= qq, axis=-1)
+        return self.xk[indx]
+
+    def _rvs(self, size=None, random_state=None):
+        # Need to define it explicitly, otherwise .rvs() with size=None
+        # fails due to explicit broadcasting in _ppf
+        U = random_state.uniform(size=size)
+        if size is None:
+            U = np.array(U, ndmin=1)
+            Y = self._ppf(U)[0]
+        else:
+            Y = self._ppf(U)
+        return Y
+
+    def _entropy(self):
+        return stats.entropy(self.pk)
+
+    def generic_moment(self, n):
+        n = asarray(n)
+        return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0)
+
+    def _expect(self, fun, lb, ub, *args, **kwds):
+        # ignore all args, just do a brute force summation
+        supp = self.xk[(lb <= self.xk) & (self.xk <= ub)]
+        vals = fun(supp)
+        return np.sum(vals)
+
+
+def _check_shape(argshape, size):
+    """
+    This is a utility function used by `_rvs()` in the class geninvgauss_gen.
+    It compares the tuple argshape to the tuple size.
+
+    Parameters
+    ----------
+    argshape : tuple of integers
+        Shape of the arguments.
+    size : tuple of integers or integer
+        Size argument of rvs().
+
+    Returns
+    -------
+    The function returns two tuples, scalar_shape and bc.
+
+    scalar_shape : tuple
+        Shape to which the 1-d array of random variates returned by
+        _rvs_scalar() is converted when it is copied into the
+        output array of _rvs().
+
+    bc : tuple of booleans
+        bc is an tuple the same length as size. bc[j] is True if the data
+        associated with that index is generated in one call of _rvs_scalar().
+
+    """
+    scalar_shape = []
+    bc = []
+    for argdim, sizedim in zip_longest(argshape[::-1], size[::-1],
+                                       fillvalue=1):
+        if sizedim > argdim or (argdim == sizedim == 1):
+            scalar_shape.append(sizedim)
+            bc.append(True)
+        else:
+            bc.append(False)
+    return tuple(scalar_shape[::-1]), tuple(bc[::-1])
+
+
+def get_distribution_names(namespace_pairs, rv_base_class):
+    """Collect names of statistical distributions and their generators.
+
+    Parameters
+    ----------
+    namespace_pairs : sequence
+        A snapshot of (name, value) pairs in the namespace of a module.
+    rv_base_class : class
+        The base class of random variable generator classes in a module.
+
+    Returns
+    -------
+    distn_names : list of strings
+        Names of the statistical distributions.
+    distn_gen_names : list of strings
+        Names of the generators of the statistical distributions.
+        Note that these are not simply the names of the statistical
+        distributions, with a _gen suffix added.
+
+    """
+    distn_names = []
+    distn_gen_names = []
+    for name, value in namespace_pairs:
+        if name.startswith('_'):
+            continue
+        if name.endswith('_gen') and issubclass(value, rv_base_class):
+            distn_gen_names.append(name)
+        if isinstance(value, rv_base_class):
+            distn_names.append(name)
+    return distn_names, distn_gen_names
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_distr_params.py b/python_embeded/Lib/site-packages/scipy/stats/_distr_params.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad67e8dc9dbd24eba935e0eaa09849e4936d6557
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_distr_params.py
@@ -0,0 +1,299 @@
+"""
+Sane parameters for stats.distributions.
+"""
+import numpy as np
+
+distcont = [
+    ['alpha', (3.5704770516650459,)],
+    ['anglit', ()],
+    ['arcsine', ()],
+    ['argus', (1.0,)],
+    ['beta', (2.3098496451481823, 0.62687954300963677)],
+    ['betaprime', (5, 6)],
+    ['bradford', (0.29891359763170633,)],
+    ['burr', (10.5, 4.3)],
+    ['burr12', (10, 4)],
+    ['cauchy', ()],
+    ['chi', (78,)],
+    ['chi2', (55,)],
+    ['cosine', ()],
+    ['crystalball', (2.0, 3.0)],
+    ['dgamma', (1.1023326088288166,)],
+    ['dpareto_lognorm', (3, 1.2, 1.5, 2)],
+    ['dweibull', (2.0685080649914673,)],
+    ['erlang', (10,)],
+    ['expon', ()],
+    ['exponnorm', (1.5,)],
+    ['exponpow', (2.697119160358469,)],
+    ['exponweib', (2.8923945291034436, 1.9505288745913174)],
+    ['f', (29, 18)],
+    ['fatiguelife', (29,)],   # correction numargs = 1
+    ['fisk', (3.0857548622253179,)],
+    ['foldcauchy', (4.7164673455831894,)],
+    ['foldnorm', (1.9521253373555869,)],
+    ['gamma', (1.9932305483800778,)],
+    ['gausshyper', (13.763771604130699, 3.1189636648681431,
+                    2.5145980350183019, 5.1811649903971615)],  # veryslow
+    ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)],
+    ['genextreme', (-0.1,)],
+    ['gengamma', (4.4162385429431925, 3.1193091679242761)],
+    ['gengamma', (4.4162385429431925, -3.1193091679242761)],
+    ['genhalflogistic', (0.77274727809929322,)],
+    ['genhyperbolic', (0.5, 1.5, -0.5,)],
+    ['geninvgauss', (2.3, 1.5)],
+    ['genlogistic', (0.41192440799679475,)],
+    ['gennorm', (1.2988442399460265,)],
+    ['halfgennorm', (0.6748054997000371,)],
+    ['genpareto', (0.1,)],   # use case with finite moments
+    ['gibrat', ()],
+    ['gompertz', (0.94743713075105251,)],
+    ['gumbel_l', ()],
+    ['gumbel_r', ()],
+    ['halfcauchy', ()],
+    ['halflogistic', ()],
+    ['halfnorm', ()],
+    ['hypsecant', ()],
+    ['invgamma', (4.0668996136993067,)],
+    ['invgauss', (0.14546264555347513,)],
+    ['invweibull', (10.58,)],
+    ['irwinhall', (10,)],
+    ['jf_skew_t', (8, 4)],
+    ['johnsonsb', (4.3172675099141058, 3.1837781130785063)],
+    ['johnsonsu', (2.554395574161155, 2.2482281679651965)],
+    ['kappa4', (0.0, 0.0)],
+    ['kappa4', (-0.1, 0.1)],
+    ['kappa4', (0.0, 0.1)],
+    ['kappa4', (0.1, 0.0)],
+    ['kappa3', (1.0,)],
+    ['ksone', (1000,)],  # replace 22 by 100 to avoid failing range, ticket 956
+    ['kstwo', (10,)],
+    ['kstwobign', ()],
+    ['landau', ()],
+    ['laplace', ()],
+    ['laplace_asymmetric', (2,)],
+    ['levy', ()],
+    ['levy_l', ()],
+    ['levy_stable', (1.8, -0.5)],
+    ['loggamma', (0.41411931826052117,)],
+    ['logistic', ()],
+    ['loglaplace', (3.2505926592051435,)],
+    ['lognorm', (0.95368226960575331,)],
+    ['loguniform', (0.01, 1.25)],
+    ['lomax', (1.8771398388773268,)],
+    ['maxwell', ()],
+    ['mielke', (10.4, 4.6)],
+    ['moyal', ()],
+    ['nakagami', (4.9673794866666237,)],
+    ['ncf', (27, 27, 0.41578441799226107)],
+    ['nct', (14, 0.24045031331198066)],
+    ['ncx2', (21, 1.0560465975116415)],
+    ['norm', ()],
+    ['norminvgauss', (1.25, 0.5)],
+    ['pareto', (2.621716532144454,)],
+    ['pearson3', (0.1,)],
+    ['pearson3', (-2,)],
+    ['powerlaw', (1.6591133289905851,)],
+    ['powerlaw', (0.6591133289905851,)],
+    ['powerlognorm', (2.1413923530064087, 0.44639540782048337)],
+    ['powernorm', (4.4453652254590779,)],
+    ['rayleigh', ()],
+    ['rdist', (1.6,)],
+    ['recipinvgauss', (0.63004267809369119,)],
+    ['reciprocal', (0.01, 1.25)],
+    ['rel_breitwigner', (36.545206797050334, )],
+    ['rice', (0.7749725210111873,)],
+    ['semicircular', ()],
+    ['skewcauchy', (0.5,)],
+    ['skewnorm', (4.0,)],
+    ['studentized_range', (3.0, 10.0)],
+    ['t', (2.7433514990818093,)],
+    ['trapezoid', (0.2, 0.8)],
+    ['triang', (0.15785029824528218,)],
+    ['truncexpon', (4.6907725456810478,)],
+    ['truncnorm', (-1.0978730080013919, 2.7306754109031979)],
+    ['truncnorm', (0.1, 2.)],
+    ['truncpareto', (1.8, 5.3)],
+    ['truncpareto', (2, 5)],
+    ['truncweibull_min', (2.5, 0.25, 1.75)],
+    ['tukeylambda', (3.1321477856738267,)],
+    ['uniform', ()],
+    ['vonmises', (3.9939042581071398,)],
+    ['vonmises_line', (3.9939042581071398,)],
+    ['wald', ()],
+    ['weibull_max', (2.8687961709100187,)],
+    ['weibull_min', (1.7866166930421596,)],
+    ['wrapcauchy', (0.031071279018614728,)]
+]
+
+
+distdiscrete = [
+    ['bernoulli',(0.3,)],
+    ['betabinom', (5, 2.3, 0.63)],
+    ['betanbinom', (5, 9.3, 1)],
+    ['binom', (5, 0.4)],
+    ['boltzmann',(1.4, 19)],
+    ['dlaplace', (0.8,)],  # 0.5
+    ['geom', (0.5,)],
+    ['hypergeom',(30, 12, 6)],
+    ['hypergeom',(21,3,12)],  # numpy.random (3,18,12) numpy ticket:921
+    ['hypergeom',(21,18,11)],  # numpy.random (18,3,11) numpy ticket:921
+    ['nchypergeom_fisher', (140, 80, 60, 0.5)],
+    ['nchypergeom_wallenius', (140, 80, 60, 0.5)],
+    ['logser', (0.6,)],  # re-enabled, numpy ticket:921
+    ['nbinom', (0.4, 0.4)],  # from tickets: 583
+    ['nbinom', (5, 0.5)],
+    ['planck', (0.51,)],   # 4.1
+    ['poisson', (0.6,)],
+    ['poisson_binom', ([0.1, 0.6, 0.7, 0.8],)],
+    ['randint', (7, 31)],
+    ['skellam', (15, 8)],
+    ['zipf', (6.6,)],
+    ['zipfian', (0.75, 15)],
+    ['zipfian', (1.25, 10)],
+    ['yulesimon', (11.0,)],
+    ['nhypergeom', (20, 7, 1)]
+]
+
+
+invdistdiscrete = [
+    # In each of the following, at least one shape parameter is invalid
+    ['hypergeom', (3, 3, 4)],
+    ['nhypergeom', (5, 2, 8)],
+    ['nchypergeom_fisher', (3, 3, 4, 1)],
+    ['nchypergeom_wallenius', (3, 3, 4, 1)],
+    ['bernoulli', (1.5, )],
+    ['binom', (10, 1.5)],
+    ['betabinom', (10, -0.4, -0.5)],
+    ['betanbinom', (10, -0.4, -0.5)],
+    ['boltzmann', (-1, 4)],
+    ['dlaplace', (-0.5, )],
+    ['geom', (1.5, )],
+    ['logser', (1.5, )],
+    ['nbinom', (10, 1.5)],
+    ['planck', (-0.5, )],
+    ['poisson', (-0.5, )],
+    ['poisson_binom', ([-1, 2, 0.5],)],
+    ['randint', (5, 2)],
+    ['skellam', (-5, -2)],
+    ['zipf', (-2, )],
+    ['yulesimon', (-2, )],
+    ['zipfian', (-0.75, 15)]
+]
+
+
+invdistcont = [
+    # In each of the following, at least one shape parameter is invalid
+    ['alpha', (-1, )],
+    ['anglit', ()],
+    ['arcsine', ()],
+    ['argus', (-1, )],
+    ['beta', (-2, 2)],
+    ['betaprime', (-2, 2)],
+    ['bradford', (-1, )],
+    ['burr', (-1, 1)],
+    ['burr12', (-1, 1)],
+    ['cauchy', ()],
+    ['chi', (-1, )],
+    ['chi2', (-1, )],
+    ['cosine', ()],
+    ['crystalball', (-1, 2)],
+    ['dgamma', (-1, )],
+    ['dpareto_lognorm', (3, -1.2, 1.5, 2)],
+    ['dweibull', (-1, )],
+    ['erlang', (-1, )],
+    ['expon', ()],
+    ['exponnorm', (-1, )],
+    ['exponweib', (1, -1)],
+    ['exponpow', (-1, )],
+    ['f', (10, -10)],
+    ['fatiguelife', (-1, )],
+    ['fisk', (-1, )],
+    ['foldcauchy', (-1, )],
+    ['foldnorm', (-1, )],
+    ['genlogistic', (-1, )],
+    ['gennorm', (-1, )],
+    ['genpareto', (np.inf, )],
+    ['genexpon', (1, 2, -3)],
+    ['genextreme', (np.inf, )],
+    ['genhyperbolic', (0.5, -0.5, -1.5,)],
+    ['gausshyper', (1, 2, 3, -4)],
+    ['gamma', (-1, )],
+    ['gengamma', (-1, 0)],
+    ['genhalflogistic', (-1, )],
+    ['geninvgauss', (1, 0)],
+    ['gibrat', ()],
+    ['gompertz', (-1, )],
+    ['gumbel_r', ()],
+    ['gumbel_l', ()],
+    ['halfcauchy', ()],
+    ['halflogistic', ()],
+    ['halfnorm', ()],
+    ['halfgennorm', (-1, )],
+    ['hypsecant', ()],
+    ['invgamma', (-1, )],
+    ['invgauss', (-1, )],
+    ['invweibull', (-1, )],
+    ['irwinhall', (-1,)],
+    ['irwinhall', (0,)],
+    ['irwinhall', (2.5,)],
+    ['jf_skew_t', (-1, 0)],
+    ['johnsonsb', (1, -2)],
+    ['johnsonsu', (1, -2)],
+    ['kappa4', (np.nan, 0)],
+    ['kappa3', (-1, )],
+    ['ksone', (-1, )],
+    ['kstwo', (-1, )],
+    ['kstwobign', ()],
+    ['landau', ()],
+    ['laplace', ()],
+    ['laplace_asymmetric', (-1, )],
+    ['levy', ()],
+    ['levy_l', ()],
+    ['levy_stable', (-1, 1)],
+    ['logistic', ()],
+    ['loggamma', (-1, )],
+    ['loglaplace', (-1, )],
+    ['lognorm', (-1, )],
+    ['loguniform', (10, 5)],
+    ['lomax', (-1, )],
+    ['maxwell', ()],
+    ['mielke', (1, -2)],
+    ['moyal', ()],
+    ['nakagami', (-1, )],
+    ['ncx2', (-1, 2)],
+    ['ncf', (10, 20, -1)],
+    ['nct', (-1, 2)],
+    ['norm', ()],
+    ['norminvgauss', (5, -10)],
+    ['pareto', (-1, )],
+    ['pearson3', (np.nan, )],
+    ['powerlaw', (-1, )],
+    ['powerlognorm', (1, -2)],
+    ['powernorm', (-1, )],
+    ['rdist', (-1, )],
+    ['rayleigh', ()],
+    ['rice', (-1, )],
+    ['recipinvgauss', (-1, )],
+    ['semicircular', ()],
+    ['skewnorm', (np.inf, )],
+    ['studentized_range', (-1, 1)],
+    ['rel_breitwigner', (-2, )],
+    ['t', (-1, )],
+    ['trapezoid', (0, 2)],
+    ['triang', (2, )],
+    ['truncexpon', (-1, )],
+    ['truncnorm', (10, 5)],
+    ['truncpareto', (-1, 5)],
+    ['truncpareto', (1.8, .5)],
+    ['truncweibull_min', (-2.5, 0.25, 1.75)],
+    ['tukeylambda', (np.nan, )],
+    ['uniform', ()],
+    ['vonmises', (-1, )],
+    ['vonmises_line', (-1, )],
+    ['wald', ()],
+    ['weibull_min', (-1, )],
+    ['weibull_max', (-1, )],
+    ['wrapcauchy', (2, )],
+    ['reciprocal', (15, 10)],
+    ['skewcauchy', (2, )]
+]
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_distribution_infrastructure.py b/python_embeded/Lib/site-packages/scipy/stats/_distribution_infrastructure.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5f356d4470157d6e82146ebb4f2f3d70f9ffaec
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_distribution_infrastructure.py
@@ -0,0 +1,5068 @@
+import functools
+from abc import ABC, abstractmethod
+from functools import cached_property
+import math
+
+import numpy as np
+from numpy import inf
+
+from scipy._lib._util import _lazywhere, _rng_spawn
+from scipy._lib._docscrape import ClassDoc, NumpyDocString
+from scipy import special, stats
+from scipy.integrate import tanhsinh as _tanhsinh
+from scipy.optimize._bracket import _bracket_root, _bracket_minimum
+from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize
+from scipy.stats._probability_distribution import _ProbabilityDistribution
+from scipy.stats import qmc
+
+# in case we need to distinguish between None and not specified
+# Typically this is used to determine whether the tolerance has been set by the
+# user and make a decision about which method to use to evaluate a distribution
+# function. Sometimes, the logic does not consider the value of the tolerance,
+# only whether this has been defined or not. This is not intended to be the
+# best possible logic; the intent is to establish the structure, which can
+# be refined in follow-up work.
+# See https://github.com/scipy/scipy/pull/21050#discussion_r1714195433.
+_null = object()
+def _isnull(x):
+    return type(x) is object or x is None
+
+__all__ = ['make_distribution', 'Mixture', 'order_statistic',
+           'truncate', 'abs', 'exp', 'log']
+
+# Could add other policies for broadcasting and edge/out-of-bounds case handling
+# For instance, when edge case handling is known not to be needed, it's much
+# faster to turn it off, but it might still be nice to have array conversion
+# and shaping done so the user doesn't need to be so careful.
+_SKIP_ALL = "skip_all"
+# Other cache policies would be useful, too.
+_NO_CACHE = "no_cache"
+
+# TODO:
+#  Test sample dtypes
+#  Add dtype kwarg (especially for distributions with no parameters)
+#  When drawing endpoint/out-of-bounds values of a parameter, draw them from
+#   the endpoints/out-of-bounds region of the full `domain`, not `typical`.
+#  Distributions without shape parameters probably need to accept a `dtype` parameter;
+#    right now they default to float64. If we have them default to float16, they will
+#    need to determine result_type when input is not float16 (overhead).
+#  Test _solve_bounded bracket logic, and decide what to do about warnings
+#  Get test coverage to 100%
+#  Raise when distribution method returns wrong shape/dtype?
+#  Consider ensuring everything is at least 1D for calculations? Would avoid needing
+#    to sprinkle `np.asarray` throughout due to indescriminate conversion of 0D arrays
+#    to scalars
+#  Break up `test_basic`: test each method separately
+#  Fix `sample` for QMCEngine (implementation does not match documentation)
+#  When a parameter is invalid, set only the offending parameter to NaN (if possible)?
+#  `_tanhsinh` special case when there are no abscissae between the limits
+#    example: cdf of uniform betweeen 1.0 and np.nextafter(1.0, np.inf)
+#  check behavior of moment methods when moments are undefined/infinite -
+#    basically OK but needs tests
+#  investigate use of median
+#  implement symmetric distribution
+#  implement composite distribution
+#  implement wrapped distribution
+#  profile/optimize
+#  general cleanup (choose keyword-only parameters)
+#  compare old/new distribution timing
+#  make video
+#  add array API support
+#  why does dist.ilogcdf(-100) not converge to bound? Check solver response to inf
+#  _chandrupatla_minimize should not report xm = fm = NaN when it fails
+#  integrate `logmoment` into `moment`? (Not hard, but enough time and code
+#   complexity to wait for reviewer feedback before adding.)
+#  Eliminate bracket_root error "`min <= a < b <= max` must be True"
+#  Test repr?
+#  use `median` information to improve integration? In some cases this will
+#   speed things up. If it's not needed, it may be about twice as slow. I think
+#   it should depend on the accuracy setting.
+#  in tests, check reference value against that produced using np.vectorize?
+#  add `axis` to `ks_1samp`
+#  User tips for faster execution:
+#  - pass NumPy arrays
+#  - pass inputs of floating point type (not integers)
+#  - prefer NumPy scalars or 0d arrays over other size 1 arrays
+#  - pass no invalid parameters and disable invalid parameter checks with iv_profile
+#  - provide a Generator if you're going to do sampling
+#  add options for drawing parameters: log-spacing
+#  accuracy benchmark suite
+#  Should caches be attributes so we can more easily ensure that they are not
+#   modified when caching is turned off?
+#  Make ShiftedScaledDistribution more efficient - only process underlying
+#   distribution parameters as necessary.
+#  Reconsider `all_inclusive`
+#  Should process_parameters update kwargs rather than returning? Should we
+#   update parameters rather than setting to what process_parameters returns?
+
+# Questions:
+# 1.  I override `__getattr__` so that distribution parameters can be read as
+#     attributes. We don't want uses to try to change them.
+#     - To prevent replacements (dist.a = b), I could override `__setattr__`.
+#     - To prevent in-place modifications, `__getattr__` could return a copy,
+#       or it could set the WRITEABLE flag of the array to false.
+#     Which should I do?
+# 2.  `cache_policy` is supported in several methods where I imagine it being
+#     useful, but it needs to be tested. Before doing that:
+#     - What should the default value be?
+#     - What should the other values be?
+#     Or should we just eliminate this policy?
+# 3.  `validation_policy` is supported in a few places, but it should be checked for
+#     consistency. I have the same questions as for `cache_policy`.
+# 4.  `tol` is currently notional. I think there needs to be way to set
+#     separate `atol` and `rtol`. Some ways I imagine it being used:
+#     - Values can be passed to iterative functions (quadrature, root-finder).
+#     - To control which "method" of a distribution function is used. For
+#       example, if `atol` is set to `1e-12`, it may be acceptable to compute
+#       the complementary CDF as 1 - CDF even when CDF is nearly 1; otherwise,
+#       a (potentially more time-consuming) method would need to be used.
+#     I'm looking for unified suggestions for the interface, not ad hoc ideas
+#     for using tolerances. Suppose the user wants to have more control over
+#     the tolerances used for each method - how do they specify it? It would
+#     probably be easiest for the user if they could pass tolerances into each
+#     method, but it's easiest for us if they can only set it as a property of
+#     the class. Perhaps a dictionary of tolerance settings?
+# 5.  I also envision that accuracy estimates should be reported to the user
+#     somehow. I think my preference would be to return a subclass of an array
+#     with an `error` attribute - yes, really. But this is unlikely to be
+#     popular, so what are other ideas? Again, we need a unified vision here,
+#     not just pointing out difficulties (not all errors are known or easy
+#     to estimate, what to do when errors could compound, etc.).
+# 6.  The term "method" is used to refer to public instance functions,
+#     private instance functions, the "method" string argument, and the means
+#     of calculating the desired quantity (represented by the string argument).
+#     For the sake of disambiguation, shall I rename the "method" string to
+#     "strategy" and refer to the means of calculating the quantity as the
+#     "strategy"?
+
+# Originally, I planned to filter out invalid distribution parameters;
+# distribution implementation functions would always work with "compressed",
+# 1D arrays containing only valid distribution parameters. There are two
+# problems with this:
+# - This essentially requires copying all arrays, even if there is only a
+#   single invalid parameter combination. This is expensive. Then, to output
+#   the original size data to the user, we need to "decompress" the arrays
+#   and fill in the NaNs, so more copying. Unless we branch the code when
+#   there are no invalid data, these copies happen even in the normal case,
+#   where there are no invalid parameter combinations. We should not incur
+#   all this overhead in the normal case.
+# - For methods that accept arguments other than distribution parameters, the
+#   user will pass in arrays that are broadcastable with the original arrays,
+#   not the compressed arrays. This means that this same sort of invalid
+#   value detection needs to be repeated every time one of these methods is
+#   called.
+# The much simpler solution is to keep the data uncompressed but to replace
+# the invalid parameters and arguments with NaNs (and only if some are
+# invalid). With this approach, the copying happens only if/when it is
+# needed. Most functions involved in stats distribution calculations don't
+# mind NaNs; they just return NaN. The behavior "If x_i is NaN, the result
+# is NaN" is explicit in the array API. So this should be fine.
+#
+# Currently, I am still leaving the parameters and function arguments
+# in their broadcasted shapes rather than, say, raveling. The intent
+# is to avoid back and forth reshaping. If authors of distributions have
+# trouble dealing with N-D arrays, we can reconsider this.
+#
+# Another important decision is that the *private* methods must accept
+# the distribution parameters as inputs rather than relying on these
+# cached properties directly (although the public methods typically pass
+# the cached values to the private methods). This is because the elementwise
+# algorithms for quadrature, differentiation, root-finding, and minimization
+# prefer that the input functions are strictly elementwise in the sense
+# that the value output for a given input element does not depend on the
+# shape of the input or that element's location within the input array.
+# When the computation has converged for an element, it is removed from
+# the computation entirely. As a result, the shape of the arrays passed to
+# the function will almost never be broadcastable with the shape of the
+# cached parameter arrays.
+#
+# I've sprinkled in some optimizations for scalars and same-shape/type arrays
+# throughout. The biggest time sinks before were:
+# - broadcast_arrays
+# - result_dtype
+# - is_subdtype
+# It is much faster to check whether these are necessary than to do them.
+
+
+class _Domain(ABC):
+    r""" Representation of the applicable domain of a parameter or variable.
+
+    A `_Domain` object is responsible for storing information about the
+    domain of a parameter or variable, determining whether a value is within
+    the domain (`contains`), and providing a text/mathematical representation
+    of itself (`__str__`). Because the domain of a parameter/variable can have
+    a complicated relationship with other parameters and variables of a
+    distribution, `_Domain` itself does not try to represent all possibilities;
+    in fact, it has no implementation and is meant for subclassing.
+
+    Attributes
+    ----------
+    symbols : dict
+        A map from special numerical values to symbols for use in `__str__`
+
+    Methods
+    -------
+    contains(x)
+        Determine whether the argument is contained within the domain (True)
+        or not (False). Used for input validation.
+    get_numerical_endpoints()
+        Gets the numerical values of the domain endpoints, which may have been
+        defined symbolically.
+    __str__()
+        Returns a text representation of the domain (e.g. ``[0, b)``).
+        Used for generating documentation.
+
+    """
+    symbols = {np.inf: r"\infty", -np.inf: r"-\infty", np.pi: r"\pi", -np.pi: r"-\pi"}
+
+    @abstractmethod
+    def contains(self, x):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def draw(self, n):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def get_numerical_endpoints(self, x):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def __str__(self):
+        raise NotImplementedError()
+
+
+class _SimpleDomain(_Domain):
+    r""" Representation of a simply-connected domain defined by two endpoints.
+
+    Each endpoint may be a finite scalar, positive or negative infinity, or
+    be given by a single parameter. The domain may include the endpoints or
+    not.
+
+    This class still does not provide an implementation of the __str__ method,
+    so it is meant for subclassing (e.g. a subclass for domains on the real
+    line).
+
+    Attributes
+    ----------
+    symbols : dict
+        Inherited. A map from special values to symbols for use in `__str__`.
+    endpoints : 2-tuple of float(s) and/or str(s)
+        A tuple with two values. Each may be either a float (the numerical
+        value of the endpoints of the domain) or a string (the name of the
+        parameters that will define the endpoint).
+    inclusive : 2-tuple of bools
+        A tuple with two boolean values; each indicates whether the
+        corresponding endpoint is included within the domain or not.
+
+    Methods
+    -------
+    define_parameters(*parameters)
+        Records any parameters used to define the endpoints of the domain
+    get_numerical_endpoints(parameter_values)
+        Gets the numerical values of the domain endpoints, which may have been
+        defined symbolically.
+    contains(item, parameter_values)
+        Determines whether the argument is contained within the domain
+
+    """
+    def __init__(self, endpoints=(-inf, inf), inclusive=(False, False)):
+        self.symbols = super().symbols.copy()
+        a, b = endpoints
+        self.endpoints = np.asarray(a)[()], np.asarray(b)[()]
+        self.inclusive = inclusive
+
+    def define_parameters(self, *parameters):
+        r""" Records any parameters used to define the endpoints of the domain.
+
+        Adds the keyword name of each parameter and its text representation
+        to the  `symbols` attribute as key:value pairs.
+        For instance, a parameter may be passed into to a distribution's
+        initializer using the keyword `log_a`, and the corresponding
+        string representation may be '\log(a)'. To form the text
+        representation of the domain for use in documentation, the
+        _Domain object needs to map from the keyword name used in the code
+        to the string representation.
+
+        Returns None, but updates the `symbols` attribute.
+
+        Parameters
+        ----------
+        *parameters : _Parameter objects
+            Parameters that may define the endpoints of the domain.
+
+        """
+        new_symbols = {param.name: param.symbol for param in parameters}
+        self.symbols.update(new_symbols)
+
+    def get_numerical_endpoints(self, parameter_values):
+        r""" Get the numerical values of the domain endpoints.
+
+        Domain endpoints may be defined symbolically. This returns numerical
+        values of the endpoints given numerical values for any variables.
+
+        Parameters
+        ----------
+        parameter_values : dict
+            A dictionary that maps between string variable names and numerical
+            values of parameters, which may define the endpoints.
+
+        Returns
+        -------
+        a, b : ndarray
+            Numerical values of the endpoints
+
+        """
+        # TODO: ensure outputs are floats
+        a, b = self.endpoints
+        # If `a` (`b`) is a string - the name of the parameter that defines
+        # the endpoint of the domain - then corresponding numerical values
+        # will be found in the `parameter_values` dictionary. Otherwise, it is
+        # itself the array of numerical values of the endpoint.
+        try:
+            a = np.asarray(parameter_values.get(a, a))
+            b = np.asarray(parameter_values.get(b, b))
+        except TypeError as e:
+            message = ("The endpoints of the distribution are defined by "
+                       "parameters, but their values were not provided. When "
+                       f"using a private method of {self.__class__}, pass "
+                       "all required distribution parameters as keyword "
+                       "arguments.")
+            raise TypeError(message) from e
+
+        return a, b
+
+    def contains(self, item, parameter_values=None):
+        r"""Determine whether the argument is contained within the domain.
+
+        Parameters
+        ----------
+        item : ndarray
+            The argument
+        parameter_values : dict
+            A dictionary that maps between string variable names and numerical
+            values of parameters, which may define the endpoints.
+
+        Returns
+        -------
+        out : bool
+            True if `item` is within the domain; False otherwise.
+
+        """
+        parameter_values = parameter_values or {}
+        # if self.all_inclusive:
+        #     # Returning a 0d value here makes things much faster.
+        #     # I'm not sure if it's safe, though. If it causes a bug someday,
+        #     # I guess it wasn't.
+        #     # Even if there is no bug because of the shape, it is incorrect for
+        #     # `contains` to return True when there are invalid (e.g. NaN)
+        #     # parameters.
+        #     return np.asarray(True)
+
+        a, b = self.get_numerical_endpoints(parameter_values)
+        left_inclusive, right_inclusive = self.inclusive
+
+        in_left = item >= a if left_inclusive else item > a
+        in_right = item <= b if right_inclusive else item < b
+        return in_left & in_right
+
+
+class _RealDomain(_SimpleDomain):
+    r""" Represents a simply-connected subset of the real line; i.e., an interval
+
+    Completes the implementation of the `_SimpleDomain` class for simple
+    domains on the real line.
+
+    Methods
+    -------
+    define_parameters(*parameters)
+        (Inherited) Records any parameters used to define the endpoints of the
+        domain.
+    get_numerical_endpoints(parameter_values)
+        (Inherited) Gets the numerical values of the domain endpoints, which
+        may have been defined symbolically.
+    contains(item, parameter_values)
+        (Inherited) Determines whether the argument is contained within the
+        domain
+    __str__()
+        Returns a string representation of the domain, e.g. "[a, b)".
+    draw(size, rng, proportions, parameter_values)
+        Draws random values based on the domain. Proportions of values within
+        the domain, on the endpoints of the domain, outside the domain,
+        and having value NaN are specified by `proportions`.
+
+    """
+
+    def __str__(self):
+        a, b = self.endpoints
+        left_inclusive, right_inclusive = self.inclusive
+
+        left = "[" if left_inclusive else "("
+        a = self.symbols.get(a, f"{a}")
+        right = "]" if right_inclusive else ")"
+        b = self.symbols.get(b, f"{b}")
+
+        return f"{left}{a}, {b}{right}"
+
+    def draw(self, n, type_, min, max, squeezed_base_shape, rng=None):
+        r""" Draw random values from the domain.
+
+        Parameters
+        ----------
+        n : int
+            The number of values to be drawn from the domain.
+        type_ : str
+            A string indicating whether the values are
+
+            - strictly within the domain ('in'),
+            - at one of the two endpoints ('on'),
+            - strictly outside the domain ('out'), or
+            - NaN ('nan').
+        min, max : ndarray
+            The endpoints of the domain.
+        squeezed_based_shape : tuple of ints
+            See _RealParameter.draw.
+        rng : np.Generator
+            The Generator used for drawing random values.
+
+        """
+        rng = np.random.default_rng(rng)
+
+        # get copies of min and max with no nans so that uniform doesn't fail
+        min_nn, max_nn = min.copy(), max.copy()
+        i = np.isnan(min_nn) | np.isnan(max_nn)
+        min_nn[i] = 0
+        max_nn[i] = 1
+
+        shape = (n,) + squeezed_base_shape
+
+        if type_ == 'in':
+            z = rng.uniform(min_nn, max_nn, size=shape)
+
+        elif type_ == 'on':
+            z_on_shape = shape
+            z = np.ones(z_on_shape)
+            i = rng.random(size=n) < 0.5
+            z[i] = min
+            z[~i] = max
+
+        elif type_ == 'out':
+            # make this work for infinite bounds
+            z = min_nn - rng.uniform(size=shape)
+            zr = max_nn + rng.uniform(size=shape)
+            i = rng.random(size=n) < 0.5
+            z[i] = zr[i]
+
+        elif type_ == 'nan':
+            z = np.full(shape, np.nan)
+
+        return z
+
+
+class _IntegerDomain(_SimpleDomain):
+    r""" Representation of a domain of consecutive integers.
+
+    Completes the implementation of the `_SimpleDomain` class for domains
+    composed of consecutive integer values.
+
+    To be completed when needed.
+    """
+    def __init__(self):
+        raise NotImplementedError
+
+
+class _Parameter(ABC):
+    r""" Representation of a distribution parameter or variable.
+
+    A `_Parameter` object is responsible for storing information about a
+    parameter or variable, providing input validation/standardization of
+    values passed for that parameter, providing a text/mathematical
+    representation of the parameter for the documentation (`__str__`), and
+    drawing random values of itself for testing and benchmarking. It does
+    not provide a complete implementation of this functionality and is meant
+    for subclassing.
+
+    Attributes
+    ----------
+    name : str
+        The keyword used to pass numerical values of the parameter into the
+        initializer of the distribution
+    symbol : str
+        The text representation of the variable in the documentation. May
+        include LaTeX.
+    domain : _Domain
+        The domain of the parameter for which the distribution is valid.
+    typical : 2-tuple of floats or strings (consider making a _Domain)
+        Defines the endpoints of a typical range of values of the parameter.
+        Used for sampling.
+
+    Methods
+    -------
+    __str__():
+        Returns a string description of the variable for use in documentation,
+        including the keyword used to represent it in code, the symbol used to
+        represent it mathemtatically, and a description of the valid domain.
+    draw(size, *, rng, domain, proportions)
+        Draws random values of the parameter. Proportions of values within
+        the valid domain, on the endpoints of the domain, outside the domain,
+        and having value NaN are specified by `proportions`.
+    validate(x):
+        Validates and standardizes the argument for use as numerical values
+        of the parameter.
+
+   """
+    def __init__(self, name, *, domain, symbol=None, typical=None):
+        self.name = name
+        self.symbol = symbol or name
+        self.domain = domain
+        if typical is not None and not isinstance(typical, _Domain):
+            typical = _RealDomain(typical)
+        self.typical = typical or domain
+
+    def __str__(self):
+        r""" String representation of the parameter for use in documentation."""
+        return f"`{self.name}` for :math:`{self.symbol} \\in {str(self.domain)}`"
+
+    def draw(self, size=None, *, rng=None, region='domain', proportions=None,
+             parameter_values=None):
+        r""" Draw random values of the parameter for use in testing.
+
+        Parameters
+        ----------
+        size : tuple of ints
+            The shape of the array of valid values to be drawn.
+        rng : np.Generator
+            The Generator used for drawing random values.
+        region : str
+            The region of the `_Parameter` from which to draw. Default is
+            "domain" (the *full* domain); alternative is "typical". An
+            enhancement would give a way to interpolate between the two.
+        proportions : tuple of numbers
+            A tuple of four non-negative numbers that indicate the expected
+            relative proportion of elements that:
+
+            - are strictly within the domain,
+            - are at one of the two endpoints,
+            - are strictly outside the domain, and
+            - are NaN,
+
+            respectively. Default is (1, 0, 0, 0). The number of elements in
+            each category is drawn from the multinomial distribution with
+            `np.prod(size)` as the number of trials and `proportions` as the
+            event probabilities. The values in `proportions` are automatically
+            normalized to sum to 1.
+        parameter_values : dict
+            Map between the names of parameters (that define the endpoints of
+            `typical`) and numerical values (arrays).
+
+        """
+        parameter_values = parameter_values or {}
+        domain = self.domain
+        proportions = (1, 0, 0, 0) if proportions is None else proportions
+
+        pvals = proportions / np.sum(proportions)
+
+        a, b = domain.get_numerical_endpoints(parameter_values)
+        a, b = np.broadcast_arrays(a, b)
+
+        base_shape = a.shape
+        extended_shape = np.broadcast_shapes(size, base_shape)
+        n_extended = np.prod(extended_shape)
+        n_base = np.prod(base_shape)
+        n = int(n_extended / n_base) if n_extended else 0
+
+        rng = np.random.default_rng(rng)
+        n_in, n_on, n_out, n_nan = rng.multinomial(n, pvals)
+
+        # `min` and `max` can have singleton dimensions that correspond with
+        # non-singleton dimensions in `size`. We need to be careful to avoid
+        # shuffling results (e.g. a value that was generated for the domain
+        # [min[i], max[i]] ends up at index j). To avoid this:
+        # - Squeeze the singleton dimensions out of `min`/`max`. Squeezing is
+        #   often not the right thing to do, but here is equivalent to moving
+        #   all the dimensions that are singleton in `min`/`max` (which may be
+        #   non-singleton in the result) to the left. This is what we want.
+        # - Now all the non-singleton dimensions of the result are on the left.
+        #   Ravel them to a single dimension of length `n`, which is now along
+        #   the 0th axis.
+        # - Reshape the 0th axis back to the required dimensions, and move
+        #   these axes back to their original places.
+        base_shape_padded = ((1,)*(len(extended_shape) - len(base_shape))
+                             + base_shape)
+        base_singletons = np.where(np.asarray(base_shape_padded)==1)[0]
+        new_base_singletons = tuple(range(len(base_singletons)))
+        # Base singleton dimensions are going to get expanded to these lengths
+        shape_expansion = np.asarray(extended_shape)[base_singletons]
+
+        # assert(np.prod(shape_expansion) == n)  # check understanding
+        # min = np.reshape(min, base_shape_padded)
+        # max = np.reshape(max, base_shape_padded)
+        # min = np.moveaxis(min, base_singletons, new_base_singletons)
+        # max = np.moveaxis(max, base_singletons, new_base_singletons)
+        # squeezed_base_shape = max.shape[len(base_singletons):]
+        # assert np.all(min.reshape(squeezed_base_shape) == min.squeeze())
+        # assert np.all(max.reshape(squeezed_base_shape) == max.squeeze())
+
+        # min = np.maximum(a, _fiinfo(a).min/10) if np.any(np.isinf(a)) else a
+        # max = np.minimum(b, _fiinfo(b).max/10) if np.any(np.isinf(b)) else b
+        min = np.asarray(a.squeeze())
+        max = np.asarray(b.squeeze())
+        squeezed_base_shape = max.shape
+
+        if region == 'typical':
+            typical = self.typical
+            a, b = typical.get_numerical_endpoints(parameter_values)
+            a, b = np.broadcast_arrays(a, b)
+            min_here = np.asarray(a.squeeze())
+            max_here = np.asarray(b.squeeze())
+            z_in = typical.draw(n_in, 'in', min_here, max_here, squeezed_base_shape,
+                                rng=rng)
+        else:
+            z_in = domain.draw(n_in, 'in', min, max, squeezed_base_shape, rng=rng)
+        z_on = domain.draw(n_on, 'on', min, max, squeezed_base_shape, rng=rng)
+        z_out = domain.draw(n_out, 'out', min, max, squeezed_base_shape, rng=rng)
+        z_nan= domain.draw(n_nan, 'nan', min, max, squeezed_base_shape, rng=rng)
+
+        z = np.concatenate((z_in, z_on, z_out, z_nan), axis=0)
+        z = rng.permuted(z, axis=0)
+
+        z = np.reshape(z, tuple(shape_expansion) + squeezed_base_shape)
+        z = np.moveaxis(z, new_base_singletons, base_singletons)
+        return z
+
+    @abstractmethod
+    def validate(self, arr):
+        raise NotImplementedError()
+
+
+class _RealParameter(_Parameter):
+    r""" Represents a real-valued parameter.
+
+    Implements the remaining methods of _Parameter for real parameters.
+    All attributes are inherited.
+
+    """
+    def validate(self, arr, parameter_values):
+        r""" Input validation/standardization of numerical values of a parameter.
+
+        Checks whether elements of the argument `arr` are reals, ensuring that
+        the dtype reflects this. Also produces a logical array that indicates
+        which elements meet the requirements.
+
+        Parameters
+        ----------
+        arr : ndarray
+            The argument array to be validated and standardized.
+        parameter_values : dict
+            Map of parameter names to parameter value arrays.
+
+        Returns
+        -------
+        arr : ndarray
+            The argument array that has been validated and standardized
+            (converted to an appropriate dtype, if necessary).
+        dtype : NumPy dtype
+            The appropriate floating point dtype of the parameter.
+        valid : boolean ndarray
+            Logical array indicating which elements are valid (True) and
+            which are not (False). The arrays of all distribution parameters
+            will be broadcasted, and elements for which any parameter value
+            does not meet the requirements will be replaced with NaN.
+
+        """
+        arr = np.asarray(arr)
+
+        valid_dtype = None
+        # minor optimization - fast track the most common types to avoid
+        # overhead of np.issubdtype. Checking for `in {...}` doesn't work : /
+        if arr.dtype == np.float64 or arr.dtype == np.float32:
+            pass
+        elif arr.dtype == np.int32 or arr.dtype == np.int64:
+            arr = np.asarray(arr, dtype=np.float64)
+        elif np.issubdtype(arr.dtype, np.floating):
+            pass
+        elif np.issubdtype(arr.dtype, np.integer):
+            arr = np.asarray(arr, dtype=np.float64)
+        else:
+            message = f"Parameter `{self.name}` must be of real dtype."
+            raise TypeError(message)
+
+        valid = self.domain.contains(arr, parameter_values)
+        valid = valid & valid_dtype if valid_dtype is not None else valid
+
+        return arr[()], arr.dtype, valid
+
+
+class _Parameterization:
+    r""" Represents a parameterization of a distribution.
+
+    Distributions can have multiple parameterizations. A `_Parameterization`
+    object is responsible for recording the parameters used by the
+    parameterization, checking whether keyword arguments passed to the
+    distribution match the parameterization, and performing input validation
+    of the numerical values of these parameters.
+
+    Attributes
+    ----------
+    parameters : dict
+        String names (of keyword arguments) and the corresponding _Parameters.
+
+    Methods
+    -------
+    __len__()
+        Returns the number of parameters in the parameterization.
+    __str__()
+        Returns a string representation of the parameterization.
+    copy
+        Returns a copy of the parameterization. This is needed for transformed
+        distributions that add parameters to the parameterization.
+    matches(parameters)
+        Checks whether the keyword arguments match the parameterization.
+    validation(parameter_values)
+        Input validation / standardization of parameterization. Validates the
+        numerical values of all parameters.
+    draw(sizes, rng, proportions)
+        Draw random values of all parameters of the parameterization for use
+        in testing.
+    """
+    def __init__(self, *parameters):
+        self.parameters = {param.name: param for param in parameters}
+
+    def __len__(self):
+        return len(self.parameters)
+
+    def copy(self):
+        return _Parameterization(*self.parameters.values())
+
+    def matches(self, parameters):
+        r""" Checks whether the keyword arguments match the parameterization.
+
+        Parameters
+        ----------
+        parameters : set
+            Set of names of parameters passed into the distribution as keyword
+            arguments.
+
+        Returns
+        -------
+        out : bool
+            True if the keyword arguments names match the names of the
+            parameters of this parameterization.
+        """
+        return parameters == set(self.parameters.keys())
+
+    def validation(self, parameter_values):
+        r""" Input validation / standardization of parameterization.
+
+        Parameters
+        ----------
+        parameter_values : dict
+            The keyword arguments passed as parameter values to the
+            distribution.
+
+        Returns
+        -------
+        all_valid : ndarray
+            Logical array indicating the elements of the broadcasted arrays
+            for which all parameter values are valid.
+        dtype : dtype
+            The common dtype of the parameter arrays. This will determine
+            the dtype of the output of distribution methods.
+        """
+        all_valid = True
+        dtypes = set()  # avoid np.result_type if there's only one type
+        for name, arr in parameter_values.items():
+            parameter = self.parameters[name]
+            arr, dtype, valid = parameter.validate(arr, parameter_values)
+            dtypes.add(dtype)
+            all_valid = all_valid & valid
+            parameter_values[name] = arr
+        dtype = arr.dtype if len(dtypes)==1 else np.result_type(*list(dtypes))
+
+        return all_valid, dtype
+
+    def __str__(self):
+        r"""Returns a string representation of the parameterization."""
+        messages = [str(param) for name, param in self.parameters.items()]
+        return ", ".join(messages)
+
+    def draw(self, sizes=None, rng=None, proportions=None, region='domain'):
+        r"""Draw random values of all parameters for use in testing.
+
+        Parameters
+        ----------
+        sizes : iterable of shape tuples
+            The size of the array to be generated for each parameter in the
+            parameterization. Note that the order of sizes is arbitary; the
+            size of the array generated for a specific parameter is not
+            controlled individually as written.
+        rng : NumPy Generator
+            The generator used to draw random values.
+        proportions : tuple
+            A tuple of four non-negative numbers that indicate the expected
+            relative proportion of elements that are within the parameter's
+            domain, are on the boundary of the parameter's domain, are outside
+            the parameter's domain, and have value NaN. For more information,
+            see the `draw` method of the _Parameter subclasses.
+        domain : str
+            The domain of the `_Parameter` from which to draw. Default is
+            "domain" (the *full* domain); alternative is "typical".
+
+        Returns
+        -------
+        parameter_values : dict (string: array)
+            A dictionary of parameter name/value pairs.
+        """
+        # ENH: be smart about the order. The domains of some parameters
+        # depend on others. If the relationshp is simple (e.g. a < b < c),
+        # we can draw values in order a, b, c.
+        parameter_values = {}
+
+        if not len(sizes) or not np.iterable(sizes[0]):
+            sizes = [sizes]*len(self.parameters)
+
+        for size, param in zip(sizes, self.parameters.values()):
+            parameter_values[param.name] = param.draw(
+                size, rng=rng, proportions=proportions,
+                parameter_values=parameter_values,
+                region=region
+            )
+
+        return parameter_values
+
+
+def _set_invalid_nan(f):
+    # Wrapper for input / output validation and standardization of distribution
+    # functions that accept either the quantile or percentile as an argument:
+    # logpdf, pdf
+    # logcdf, cdf
+    # logccdf, ccdf
+    # ilogcdf, icdf
+    # ilogccdf, iccdf
+    # Arguments that are outside the required range are replaced by NaN before
+    # passing them into the underlying function. The corresponding outputs
+    # are replaced by the appropriate value before being returned to the user.
+    # For example, when the argument of `cdf` exceeds the right end of the
+    # distribution's support, the wrapper replaces the argument with NaN,
+    # ignores the output of the underlying function, and returns 1.0. It also
+    # ensures that output is of the appropriate shape and dtype.
+
+    endpoints = {'icdf': (0, 1), 'iccdf': (0, 1),
+                 'ilogcdf': (-np.inf, 0), 'ilogccdf': (-np.inf, 0)}
+    replacements = {'logpdf': (-inf, -inf), 'pdf': (0, 0),
+                    '_logcdf1': (-inf, 0), '_logccdf1': (0, -inf),
+                    '_cdf1': (0, 1), '_ccdf1': (1, 0)}
+    replace_strict = {'pdf', 'logpdf'}
+    replace_exact = {'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'}
+    clip = {'_cdf1', '_ccdf1'}
+    clip_log = {'_logcdf1', '_logccdf1'}
+
+    @functools.wraps(f)
+    def filtered(self, x, *args, **kwargs):
+        if self.validation_policy == _SKIP_ALL:
+            return f(self, x, *args, **kwargs)
+
+        method_name = f.__name__
+        x = np.asarray(x)
+        dtype = self._dtype
+        shape = self._shape
+
+        # Ensure that argument is at least as precise as distribution
+        # parameters, which are already at least floats. This will avoid issues
+        # with raising integers to negative integer powers and failure to replace
+        # invalid integers with NaNs.
+        if x.dtype != dtype:
+            dtype = np.result_type(x.dtype, dtype)
+            x = np.asarray(x, dtype=dtype)
+
+        # Broadcasting is slow. Do it only if necessary.
+        if not x.shape == shape:
+            try:
+                shape = np.broadcast_shapes(x.shape, shape)
+                x = np.broadcast_to(x, shape)
+                # Should we broadcast the distribution parameters to this shape, too?
+            except ValueError as e:
+                message = (
+                    f"The argument provided to `{self.__class__.__name__}"
+                    f".{method_name}` cannot be be broadcast to the same "
+                    "shape as the distribution parameters.")
+                raise ValueError(message) from e
+
+        low, high = endpoints.get(method_name, self.support())
+
+        # Check for arguments outside of domain. They'll be replaced with NaNs,
+        # and the result will be set to the appropriate value.
+        left_inc, right_inc = self._variable.domain.inclusive
+        mask_low = (x < low if (method_name in replace_strict and left_inc)
+                    else x <= low)
+        mask_high = (x > high if (method_name in replace_strict and right_inc)
+                     else x >= high)
+        mask_invalid = (mask_low | mask_high)
+        any_invalid = (mask_invalid if mask_invalid.shape == ()
+                       else np.any(mask_invalid))
+
+        # Check for arguments at domain endpoints, whether they
+        # are part of the domain or not.
+        any_endpoint = False
+        if method_name in replace_exact:
+            mask_low_endpoint = (x == low)
+            mask_high_endpoint = (x == high)
+            mask_endpoint = (mask_low_endpoint | mask_high_endpoint)
+            any_endpoint = (mask_endpoint if mask_endpoint.shape == ()
+                            else np.any(mask_endpoint))
+
+        # Set out-of-domain arguments to NaN. The result will be set to the
+        # appropriate value later.
+        if any_invalid:
+            x = np.array(x, dtype=dtype, copy=True)
+            x[mask_invalid] = np.nan
+
+        res = np.asarray(f(self, x, *args, **kwargs))
+
+        # Ensure that the result is the correct dtype and shape,
+        # copying (only once) if necessary.
+        res_needs_copy = False
+        if res.dtype != dtype:
+            dtype = np.result_type(dtype, self._dtype)
+            res_needs_copy = True
+
+        if res.shape != shape:  # faster to check first
+            res = np.broadcast_to(res, self._shape)
+            res_needs_copy = res_needs_copy or any_invalid or any_endpoint
+
+        if res_needs_copy:
+            res = np.array(res, dtype=dtype, copy=True)
+
+        #  For arguments outside the function domain, replace results
+        if any_invalid:
+            replace_low, replace_high = (
+                replacements.get(method_name, (np.nan, np.nan)))
+            res[mask_low] = replace_low
+            res[mask_high] = replace_high
+
+        # For arguments at the endpoints of the domain, replace results
+        if any_endpoint:
+            a, b = self.support()
+            if a.shape != shape:
+                a = np.array(np.broadcast_to(a, shape), copy=True)
+                b = np.array(np.broadcast_to(b, shape), copy=True)
+
+            replace_low_endpoint = (
+                b[mask_low_endpoint] if method_name.endswith('ccdf')
+                else a[mask_low_endpoint])
+            replace_high_endpoint = (
+                a[mask_high_endpoint] if method_name.endswith('ccdf')
+                else b[mask_high_endpoint])
+
+            res[mask_low_endpoint] = replace_low_endpoint
+            res[mask_high_endpoint] = replace_high_endpoint
+
+        # Clip probabilities to [0, 1]
+        if method_name in clip:
+            res = np.clip(res, 0., 1.)
+        elif method_name in clip_log:
+            res = res.real  # exp(res) > 0
+            res = np.clip(res, None, 0.)  # exp(res) < 1
+
+        return res[()]
+
+    return filtered
+
+
+def _set_invalid_nan_property(f):
+    # Wrapper for input / output validation and standardization of distribution
+    # functions that represent properties of the distribution itself:
+    # logentropy, entropy
+    # median, mode
+    # moment
+    # It ensures that the output is of the correct shape and dtype and that
+    # there are NaNs wherever the distribution parameters were invalid.
+
+    @functools.wraps(f)
+    def filtered(self, *args, **kwargs):
+        if self.validation_policy == _SKIP_ALL:
+            return f(self, *args, **kwargs)
+
+        res = f(self, *args, **kwargs)
+        if res is None:
+            # message could be more appropriate
+            raise NotImplementedError(self._not_implemented)
+
+        res = np.asarray(res)
+        needs_copy = False
+        dtype = res.dtype
+
+        if dtype != self._dtype:  # this won't work for logmoments (complex)
+            dtype = np.result_type(dtype, self._dtype)
+            needs_copy = True
+
+        if res.shape != self._shape:  # faster to check first
+            res = np.broadcast_to(res, self._shape)
+            needs_copy = needs_copy or self._any_invalid
+
+        if needs_copy:
+            res = res.astype(dtype=dtype, copy=True)
+
+        if self._any_invalid:
+            # may be redundant when quadrature is used, but not necessarily
+            # when formulas are used.
+            res[self._invalid] = np.nan
+
+        return res[()]
+
+    return filtered
+
+
+def _dispatch(f):
+    # For each public method (instance function) of a distribution (e.g. ccdf),
+    # there may be several ways ("method"s) that it can be computed (e.g. a
+    # formula, as the complement of the CDF, or via numerical integration).
+    # Each "method" is implemented by a different private method (instance
+    # function).
+    # This wrapper calls the appropriate private method based on the public
+    # method and any specified `method` keyword option.
+    # - If `method` is specified as a string (by the user), the appropriate
+    #   private method is called.
+    # - If `method` is None:
+    #   - The appropriate private method for the public method is looked up
+    #     in a cache.
+    #   - If the cache does not have an entry for the public method, the
+    #     appropriate "dispatch " function is called to determine which method
+    #     is most appropriate given the available private methods and
+    #     settings (e.g. tolerance).
+
+    @functools.wraps(f)
+    def wrapped(self, *args, method=None, **kwargs):
+        func_name = f.__name__
+        method = method or self._method_cache.get(func_name, None)
+        if callable(method):
+            pass
+        elif method is not None:
+            method = 'logexp' if method == 'log/exp' else method
+            method_name = func_name.replace('dispatch', method)
+            method = getattr(self, method_name)
+        else:
+            method = f(self, *args, method=method, **kwargs)
+            if func_name != '_sample_dispatch' and self.cache_policy != _NO_CACHE:
+                self._method_cache[func_name] = method
+
+        try:
+            return method(*args, **kwargs)
+        except KeyError as e:
+            raise NotImplementedError(self._not_implemented) from e
+
+    return wrapped
+
+
+def _cdf2_input_validation(f):
+    # Wrapper that does the job of `_set_invalid_nan` when `cdf` or `logcdf`
+    # is called with two quantile arguments.
+    # Let's keep it simple; no special cases for speed right now.
+    # The strategy is a bit different than for 1-arg `cdf` (and other methods
+    # covered by `_set_invalid_nan`). For 1-arg `cdf`, elements of `x` that
+    # are outside (or at the edge of) the support get replaced by `nan`,
+    # and then the results get replaced by the appropriate value (0 or 1).
+    # We *could* do something similar, dispatching to `_cdf1` in these
+    # cases. That would be a bit more robust, but it would also be quite
+    # a bit more complex, since we'd have to do different things when
+    # `x` and `y` are both out of bounds, when just `x` is out of bounds,
+    # when just `y` is out of bounds, and when both are out of bounds.
+    # I'm not going to do that right now. Instead, simply replace values
+    # outside the support by those at the edge of the support. Here, we also
+    # omit some of the optimizations that make `_set_invalid_nan` faster for
+    # simple arguments (e.g. float64 scalars).
+
+    @functools.wraps(f)
+    def wrapped(self, x, y, *args, **kwargs):
+        func_name = f.__name__
+
+        low, high = self.support()
+        x, y, low, high = np.broadcast_arrays(x, y, low, high)
+        dtype = np.result_type(x.dtype, y.dtype, self._dtype)
+        # yes, copy to avoid modifying input arrays
+        x, y = x.astype(dtype, copy=True), y.astype(dtype, copy=True)
+
+        # Swap arguments to ensure that x < y, and replace
+        # out-of domain arguments with domain endpoints. We'll
+        # transform the result later.
+        i_swap = y < x
+        x[i_swap], y[i_swap] = y[i_swap], x[i_swap]
+        i = x < low
+        x[i] = low[i]
+        i = y < low
+        y[i] = low[i]
+        i = x > high
+        x[i] = high[i]
+        i = y > high
+        y[i] = high[i]
+
+        res = f(self, x, y, *args, **kwargs)
+
+        # Clipping probability to [0, 1]
+        if func_name in {'_cdf2', '_ccdf2'}:
+            res = np.clip(res, 0., 1.)
+        else:
+            res = np.clip(res, None, 0.)  # exp(res) < 1
+
+        # Transform the result to account for swapped argument order
+        res = np.asarray(res)
+        if func_name == '_cdf2':
+            res[i_swap] *= -1.
+        elif func_name == '_ccdf2':
+            res[i_swap] *= -1
+            res[i_swap] += 2.
+        elif func_name == '_logcdf2':
+            res = np.asarray(res + 0j) if np.any(i_swap) else res
+            res[i_swap] = res[i_swap] + np.pi*1j
+        else:
+            # res[i_swap] is always positive and less than 1, so it's
+            # safe to ensure that the result is real
+            res[i_swap] = _logexpxmexpy(np.log(2), res[i_swap]).real
+        return res[()]
+
+    return wrapped
+
+
+def _fiinfo(x):
+    if np.issubdtype(x.dtype, np.inexact):
+        return np.finfo(x.dtype)
+    else:
+        return np.iinfo(x)
+
+
+def _kwargs2args(f, args=None, kwargs=None):
+    # Wraps a function that accepts a primary argument `x`, secondary
+    # arguments `args`, and secondary keyward arguments `kwargs` such that the
+    # wrapper accepts only `x` and `args`. The keyword arguments are extracted
+    # from `args` passed into the wrapper, and these are passed to the
+    # underlying function as `kwargs`.
+    # This is a temporary workaround until the scalar algorithms `_tanhsinh`,
+    # `_chandrupatla`, etc., support `kwargs` or can operate with compressing
+    # arguments to the callable.
+    args = args or []
+    kwargs = kwargs or {}
+    names = list(kwargs.keys())
+    n_args = len(args)
+
+    def wrapped(x, *args):
+        return f(x, *args[:n_args], **dict(zip(names, args[n_args:])))
+
+    args = list(args) + list(kwargs.values())
+
+    return wrapped, args
+
+
+def _log1mexp(x):
+    r"""Compute the log of the complement of the exponential.
+
+    This function is equivalent to::
+
+        log1mexp(x) = np.log(1-np.exp(x))
+
+    but avoids loss of precision when ``np.exp(x)`` is nearly 0 or 1.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+
+    Returns
+    -------
+    y : ndarray
+        An array of the same shape as `x`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distribution_infrastructure import _log1mexp
+    >>> x = 1e-300  # log of a number very close to 1
+    >>> _log1mexp(x)  # log of the complement of a number very close to 1
+    -690.7755278982137
+    >>> # np.log1p(-np.exp(x))  # -inf; emits warning
+
+    """
+    def f1(x):
+        # good for exp(x) close to 0
+        return np.log1p(-np.exp(x))
+
+    def f2(x):
+        # good for exp(x) close to 1
+        with np.errstate(divide='ignore'):
+            return np.real(np.log(-special.expm1(x + 0j)))
+
+    return _lazywhere(x < -1, (x,), f=f1, f2=f2)[()]
+
+
+def _logexpxmexpy(x, y):
+    """ Compute the log of the difference of the exponentials of two arguments.
+
+    Avoids over/underflow, but does not prevent loss of precision otherwise.
+    """
+    # TODO: properly avoid NaN when y is negative infinity
+    # TODO: silence warning with taking log of complex nan
+    # TODO: deal with x == y better
+    i = np.isneginf(np.real(y))
+    if np.any(i):
+        y = np.asarray(y.copy())
+        y[i] = np.finfo(y.dtype).min
+    x, y = np.broadcast_arrays(x, y)
+    res = np.asarray(special.logsumexp([x, y+np.pi*1j], axis=0))
+    i = (x == y)
+    res[i] = -np.inf
+    return res
+
+
+def _guess_bracket(xmin, xmax):
+    a = np.full_like(xmin, -1.0)
+    b = np.ones_like(xmax)
+
+    i = np.isfinite(xmin) & np.isfinite(xmax)
+    a[i] = xmin[i]
+    b[i] = xmax[i]
+
+    i = np.isfinite(xmin) & ~np.isfinite(xmax)
+    a[i] = xmin[i]
+    b[i] = xmin[i] + 1
+
+    i = np.isfinite(xmax) & ~np.isfinite(xmin)
+    a[i] = xmax[i] - 1
+    b[i] = xmax[i]
+
+    return a, b
+
+
+def _log_real_standardize(x):
+    """Standardizes the (complex) logarithm of a real number.
+
+    The logarithm of a real number may be represented by a complex number with
+    imaginary part that is a multiple of pi*1j. Even multiples correspond with
+    a positive real and odd multiples correspond with a negative real.
+
+    Given a logarithm of a real number `x`, this function returns an equivalent
+    representation in a standard form: the log of a positive real has imaginary
+    part `0` and the log of a negative real has imaginary part `pi`.
+
+    """
+    shape = x.shape
+    x = np.atleast_1d(x)
+    real = np.real(x).astype(x.dtype)
+    complex = np.imag(x)
+    y = real
+    negative = np.exp(complex*1j) < 0.5
+    y[negative] = y[negative] + np.pi * 1j
+    return y.reshape(shape)[()]
+
+
+def _combine_docs(dist_family, *, include_examples=True):
+    fields = set(NumpyDocString.sections)
+    fields.remove('index')
+    if not include_examples:
+        fields.remove('Examples')
+
+    doc = ClassDoc(dist_family)
+    superdoc = ClassDoc(ContinuousDistribution)
+    for field in fields:
+        if field in {"Methods", "Attributes"}:
+            doc[field] = superdoc[field]
+        elif field in {"Summary"}:
+            pass
+        elif field == "Extended Summary":
+            doc[field].append(_generate_domain_support(dist_family))
+        elif field == 'Examples':
+            doc[field] = [_generate_example(dist_family)]
+        else:
+            doc[field] += superdoc[field]
+    return str(doc)
+
+
+def _generate_domain_support(dist_family):
+    n_parameterizations = len(dist_family._parameterizations)
+
+    domain = f"\nfor :math:`x` in {dist_family._variable.domain}.\n"
+
+    if n_parameterizations == 0:
+        support = """
+        This class accepts no distribution parameters.
+        """
+    elif n_parameterizations == 1:
+        support = f"""
+        This class accepts one parameterization:
+        {str(dist_family._parameterizations[0])}.
+        """
+    else:
+        number = {2: 'two', 3: 'three', 4: 'four', 5: 'five'}[
+            n_parameterizations]
+        parameterizations = [f"- {str(p)}" for p in
+                             dist_family._parameterizations]
+        parameterizations = "\n".join(parameterizations)
+        support = f"""
+        This class accepts {number} parameterizations:
+
+        {parameterizations}
+        """
+    support = "\n".join([line.lstrip() for line in support.split("\n")][1:])
+    return domain + support
+
+
+def _generate_example(dist_family):
+    n_parameters = dist_family._num_parameters(0)
+    shapes = [()] * n_parameters
+    rng = np.random.default_rng(615681484984984)
+    i = 0
+    dist = dist_family._draw(shapes, rng=rng, i_parameterization=i)
+
+    rng = np.random.default_rng(2354873452)
+    name = dist_family.__name__
+    if n_parameters:
+        parameter_names = list(dist._parameterizations[i].parameters)
+        parameter_values = [round(getattr(dist, name), 2) for name in
+                            parameter_names]
+        name_values = [f"{name}={value}" for name, value in
+                       zip(parameter_names, parameter_values)]
+        instantiation = f"{name}({', '.join(name_values)})"
+        attributes = ", ".join([f"X.{param}" for param in dist._parameters])
+        X = dist_family(**dict(zip(parameter_names, parameter_values)))
+    else:
+        instantiation = f"{name}()"
+        X = dist
+
+    p = 0.32
+    x = round(X.icdf(p), 2)
+    y = round(X.icdf(2 * p), 2)
+
+    example = f"""
+    To use the distribution class, it must be instantiated using keyword
+    parameters corresponding with one of the accepted parameterizations.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> from scipy.stats import {name}
+    >>> X = {instantiation}
+
+    For convenience, the ``plot`` method can be used to visualize the density
+    and other functions of the distribution.
+
+    >>> X.plot()
+    >>> plt.show()
+
+    The support of the underlying distribution is available using the ``support``
+    method.
+
+    >>> X.support()
+    {X.support()}
+    """
+
+    if n_parameters:
+        example += f"""
+        The numerical values of parameters associated with all parameterizations
+        are available as attributes.
+
+        >>> {attributes}
+        {tuple(X._parameters.values())}
+        """
+
+    example += f"""
+    To evaluate the probability density function of the underlying distribution
+    at argument ``x={x}``:
+
+    >>> x = {x}
+    >>> X.pdf(x)
+    {X.pdf(x)}
+
+    The cumulative distribution function, its complement, and the logarithm
+    of these functions are evaluated similarly.
+
+    >>> np.allclose(np.exp(X.logccdf(x)), 1 - X.cdf(x))
+    True
+
+    The inverse of these functions with respect to the argument ``x`` is also
+    available.
+
+    >>> logp = np.log(1 - X.ccdf(x))
+    >>> np.allclose(X.ilogcdf(logp), x)
+    True
+
+    Note that distribution functions and their logarithms also have two-argument
+    versions for working with the probability mass between two arguments. The
+    result tends to be more accurate than the naive implementation because it avoids
+    subtractive cancellation.
+
+    >>> y = {y}
+    >>> np.allclose(X.ccdf(x, y), 1 - (X.cdf(y) - X.cdf(x)))
+    True
+
+    There are methods for computing measures of central tendency,
+    dispersion, higher moments, and entropy.
+
+    >>> X.mean(), X.median(), X.mode()
+    {X.mean(), X.median(), X.mode()}
+    >>> X.variance(), X.standard_deviation()
+    {X.variance(), X.standard_deviation()}
+    >>> X.skewness(), X.kurtosis()
+    {X.skewness(), X.kurtosis()}
+    >>> np.allclose(X.moment(order=6, kind='standardized'),
+    ...             X.moment(order=6, kind='central') / X.variance()**3)
+    True
+    >>> np.allclose(np.exp(X.logentropy()), X.entropy())
+    True
+
+    Pseudo-random samples can be drawn from
+    the underlying distribution using ``sample``.
+
+    >>> X.sample(shape=(4,))
+    {repr(X.sample(shape=(4,)))}  # may vary
+    """
+    # remove the indentation due to use of block quote within function;
+    # eliminate blank first line
+    example = "\n".join([line.lstrip() for line in example.split("\n")][1:])
+    return example
+
+
+class ContinuousDistribution(_ProbabilityDistribution):
+    r""" Class that represents a continuous statistical distribution.
+
+    Parameters
+    ----------
+    tol : positive float, optional
+        The desired relative tolerance of calculations. Left unspecified,
+        calculations may be faster; when provided, calculations may be
+        more likely to meet the desired accuracy.
+    validation_policy : {None, "skip_all"}
+        Specifies the level of input validation to perform. Left unspecified,
+        input validation is performed to ensure appropriate behavior in edge
+        case (e.g. parameters out of domain, argument outside of distribution
+        support, etc.) and improve consistency of output dtype, shape, etc.
+        Pass ``'skip_all'`` to avoid the computational overhead of these
+        checks when rough edges are acceptable.
+    cache_policy : {None, "no_cache"}
+        Specifies the extent to which intermediate results are cached. Left
+        unspecified, intermediate results of some calculations (e.g. distribution
+        support, moments, etc.) are cached to improve performance of future
+        calculations. Pass ``'no_cache'`` to reduce memory reserved by the class
+        instance.
+
+    Attributes
+    ----------
+    All parameters are available as attributes.
+
+    Methods
+    -------
+    support
+
+    plot
+
+    sample
+
+    moment
+
+    mean
+    median
+    mode
+
+    variance
+    standard_deviation
+
+    skewness
+    kurtosis
+
+    pdf
+    logpdf
+
+    cdf
+    icdf
+    ccdf
+    iccdf
+
+    logcdf
+    ilogcdf
+    logccdf
+    ilogccdf
+
+    entropy
+    logentropy
+
+    See Also
+    --------
+    :ref:`rv_infrastructure` : Tutorial
+
+    Notes
+    -----
+    The following abbreviations are used throughout the documentation.
+
+    - PDF: probability density function
+    - CDF: cumulative distribution function
+    - CCDF: complementary CDF
+    - entropy: differential entropy
+    - log-*F*: logarithm of *F* (e.g. log-CDF)
+    - inverse *F*: inverse function of *F* (e.g. inverse CDF)
+
+    The API documentation is written to describe the API, not to serve as
+    a statistical reference. Effort is made to be correct at the level
+    required to use the functionality, not to be mathematically rigorous.
+    For example, continuity and differentiability may be implicitly assumed.
+    For precise mathematical definitions, consult your preferred mathematical
+    text.
+
+    """
+    __array_priority__ = 1
+    _parameterizations = []  # type: ignore[var-annotated]
+
+    ### Initialization
+
+    def __init__(self, *, tol=_null, validation_policy=None, cache_policy=None,
+                 **parameters):
+        self.tol = tol
+        self.validation_policy = validation_policy
+        self.cache_policy = cache_policy
+        self._not_implemented = (
+            f"`{self.__class__.__name__}` does not provide an accurate "
+            "implementation of the required method. Consider leaving "
+            "`method` and `tol` unspecified to use another implementation."
+        )
+        self._original_parameters = {}
+        # We may want to override the `__init__` method with parameters so
+        # IDEs can suggest parameter names. If there are multiple parameterizations,
+        # we'll need the default values of parameters to be None; this will
+        # filter out the parameters that were not actually specified by the user.
+        parameters = {key: val for key, val in
+                      sorted(parameters.items()) if val is not None}
+        self._update_parameters(**parameters)
+
+    def _update_parameters(self, *, validation_policy=None, **params):
+        r""" Update the numerical values of distribution parameters.
+
+        Parameters
+        ----------
+        **params : array_like
+            Desired numerical values of the distribution parameters. Any or all
+            of the parameters initially used to instantiate the distribution
+            may be modified. Parameters used in alternative parameterizations
+            are not accepted.
+
+        validation_policy : str
+            To be documented. See Question 3 at the top.
+        """
+
+        parameters = original_parameters = self._original_parameters.copy()
+        parameters.update(**params)
+        parameterization = None
+        self._invalid = np.asarray(False)
+        self._any_invalid = False
+        self._shape = tuple()
+        self._ndim = 0
+        self._size = 1
+        self._dtype = np.float64
+
+        if (validation_policy or self.validation_policy) == _SKIP_ALL:
+            parameters = self._process_parameters(**parameters)
+        elif not len(self._parameterizations):
+            if parameters:
+                message = (f"The `{self.__class__.__name__}` distribution "
+                           "family does not accept parameters, but parameters "
+                           f"`{set(parameters)}` were provided.")
+                raise ValueError(message)
+        else:
+            # This is default behavior, which re-runs all parameter validations
+            # even when only a single parameter is modified. For many
+            # distributions, the domain of a parameter doesn't depend on other
+            # parameters, so parameters could safely be modified without
+            # re-validating all other parameters. To handle these cases more
+            # efficiently, we could allow the developer  to override this
+            # behavior.
+
+            # Currently the user can only update the original parameterization.
+            # Even though that parameterization is already known,
+            # `_identify_parameterization` is called to produce a nice error
+            # message if the user passes other values. To be a little more
+            # efficient, we could detect whether the values passed are
+            # consistent with the original parameterization rather than finding
+            # it from scratch. However, we might want other parameterizations
+            # to be accepted, which would require other changes, so I didn't
+            # optimize this.
+
+            parameterization = self._identify_parameterization(parameters)
+            parameters, shape, size, ndim = self._broadcast(parameters)
+            parameters, invalid, any_invalid, dtype = (
+                self._validate(parameterization, parameters))
+            parameters = self._process_parameters(**parameters)
+
+            self._invalid = invalid
+            self._any_invalid = any_invalid
+            self._shape = shape
+            self._size = size
+            self._ndim = ndim
+            self._dtype = dtype
+
+        self.reset_cache()
+        self._parameters = parameters
+        self._parameterization = parameterization
+        self._original_parameters = original_parameters
+        for name in self._parameters.keys():
+            # Make parameters properties of the class; return values from the instance
+            if hasattr(self.__class__, name):
+                continue
+            setattr(self.__class__, name, property(lambda self_, name_=name:
+                                                   self_._parameters[name_].copy()[()]))
+
+    def reset_cache(self):
+        r""" Clear all cached values.
+
+        To improve the speed of some calculations, the distribution's support
+        and moments are cached.
+
+        This function is called automatically whenever the distribution
+        parameters are updated.
+
+        """
+        # We could offer finer control over what is cleared.
+        # For simplicity, these will still exist even if cache_policy is
+        # NO_CACHE; they just won't be populated. This allows caching to be
+        # turned on and off easily.
+        self._moment_raw_cache = {}
+        self._moment_central_cache = {}
+        self._moment_standardized_cache = {}
+        self._support_cache = None
+        self._method_cache = {}
+        self._constant_cache = None
+
+    def _identify_parameterization(self, parameters):
+        # Determine whether a `parameters` dictionary matches is consistent
+        # with one of the parameterizations of the distribution. If so,
+        # return that parameterization object; if not, raise an error.
+        #
+        # I've come back to this a few times wanting to avoid this explicit
+        # loop. I've considered several possibilities, but they've all been a
+        # little unusual. For example, we could override `_eq_` so we can
+        # use _parameterizations.index() to retrieve the parameterization,
+        # or the user could put the parameterizations in a dictionary so we
+        # could look them up with a key (e.g. frozenset of parameter names).
+        # I haven't been sure enough of these approaches to implement them.
+        parameter_names_set = set(parameters)
+
+        for parameterization in self._parameterizations:
+            if parameterization.matches(parameter_names_set):
+                break
+        else:
+            if not parameter_names_set:
+                message = (f"The `{self.__class__.__name__}` distribution "
+                           "family requires parameters, but none were "
+                           "provided.")
+            else:
+                parameter_names = self._get_parameter_str(parameters)
+                message = (f"The provided parameters `{parameter_names}` "
+                           "do not match a supported parameterization of the "
+                           f"`{self.__class__.__name__}` distribution family.")
+            raise ValueError(message)
+
+        return parameterization
+
+    def _broadcast(self, parameters):
+        # Broadcast the distribution parameters to the same shape. If the
+        # arrays are not broadcastable, raise a meaningful error.
+        #
+        # We always make sure that the parameters *are* the same shape
+        # and not just broadcastable. Users can access parameters as
+        # attributes, and I think they should see the arrays as the same shape.
+        # More importantly, arrays should be the same shape before logical
+        # indexing operations, which are needed in infrastructure code when
+        # there are invalid parameters, and may be needed in
+        # distribution-specific code. We don't want developers to need to
+        # broadcast in implementation functions.
+
+        # It's much faster to check whether broadcasting is necessary than to
+        # broadcast when it's not necessary.
+        parameter_vals = [np.asarray(parameter)
+                          for parameter in parameters.values()]
+        parameter_shapes = set(parameter.shape for parameter in parameter_vals)
+        if len(parameter_shapes) == 1:
+            return (parameters, parameter_vals[0].shape,
+                    parameter_vals[0].size, parameter_vals[0].ndim)
+
+        try:
+            parameter_vals = np.broadcast_arrays(*parameter_vals)
+        except ValueError as e:
+            parameter_names = self._get_parameter_str(parameters)
+            message = (f"The parameters `{parameter_names}` provided to the "
+                       f"`{self.__class__.__name__}` distribution family "
+                       "cannot be broadcast to the same shape.")
+            raise ValueError(message) from e
+        return (dict(zip(parameters.keys(), parameter_vals)),
+                parameter_vals[0].shape,
+                parameter_vals[0].size,
+                parameter_vals[0].ndim)
+
+    def _validate(self, parameterization, parameters):
+        # Broadcasts distribution parameter arrays and converts them to a
+        # consistent dtype. Replaces invalid parameters with `np.nan`.
+        # Returns the validated parameters, a boolean mask indicated *which*
+        # elements are invalid, a boolean scalar indicating whether *any*
+        # are invalid (to skip special treatments if none are invalid), and
+        # the common dtype.
+        valid, dtype = parameterization.validation(parameters)
+        invalid = ~valid
+        any_invalid = invalid if invalid.shape == () else np.any(invalid)
+        # If necessary, make the arrays contiguous and replace invalid with NaN
+        if any_invalid:
+            for parameter_name in parameters:
+                parameters[parameter_name] = np.copy(
+                    parameters[parameter_name])
+                parameters[parameter_name][invalid] = np.nan
+
+        return parameters, invalid, any_invalid, dtype
+
+    def _process_parameters(self, **params):
+        r""" Process and cache distribution parameters for reuse.
+
+        This is intended to be overridden by subclasses. It allows distribution
+        authors to pre-process parameters for re-use. For instance, when a user
+        parameterizes a LogUniform distribution with `a` and `b`, it makes
+        sense to calculate `log(a)` and `log(b)` because these values will be
+        used in almost all distribution methods. The dictionary returned by
+        this method is passed to all private methods that calculate functions
+        of the distribution.
+        """
+        return params
+
+    def _get_parameter_str(self, parameters):
+        # Get a string representation of the parameters like "{a, b, c}".
+        return f"{{{', '.join(parameters.keys())}}}"
+
+    def _copy_parameterization(self):
+        self._parameterizations = self._parameterizations.copy()
+        for i in range(len(self._parameterizations)):
+            self._parameterizations[i] = self._parameterizations[i].copy()
+
+    ### Attributes
+
+    # `tol` attribute is just notional right now. See Question 4 above.
+    @property
+    def tol(self):
+        r"""positive float:
+        The desired relative tolerance of calculations. Left unspecified,
+        calculations may be faster; when provided, calculations may be
+        more likely to meet the desired accuracy.
+        """
+        return self._tol
+
+    @tol.setter
+    def tol(self, tol):
+        if _isnull(tol):
+            self._tol = tol
+            return
+
+        tol = np.asarray(tol)
+        if (tol.shape != () or not tol > 0 or  # catches NaNs
+                not np.issubdtype(tol.dtype, np.floating)):
+            message = (f"Attribute `tol` of `{self.__class__.__name__}` must "
+                       "be a positive float, if specified.")
+            raise ValueError(message)
+        self._tol = tol[()]
+
+    @property
+    def cache_policy(self):
+        r"""{None, "no_cache"}:
+        Specifies the extent to which intermediate results are cached. Left
+        unspecified, intermediate results of some calculations (e.g. distribution
+        support, moments, etc.) are cached to improve performance of future
+        calculations. Pass ``'no_cache'`` to reduce memory reserved by the class
+        instance.
+        """
+        return self._cache_policy
+
+    @cache_policy.setter
+    def cache_policy(self, cache_policy):
+        cache_policy = str(cache_policy).lower() if cache_policy is not None else None
+        cache_policies = {None, 'no_cache'}
+        if cache_policy not in cache_policies:
+            message = (f"Attribute `cache_policy` of `{self.__class__.__name__}` "
+                       f"must be one of {cache_policies}, if specified.")
+            raise ValueError(message)
+        self._cache_policy = cache_policy
+
+    @property
+    def validation_policy(self):
+        r"""{None, "skip_all"}:
+        Specifies the level of input validation to perform. Left unspecified,
+        input validation is performed to ensure appropriate behavior in edge
+        case (e.g. parameters out of domain, argument outside of distribution
+        support, etc.) and improve consistency of output dtype, shape, etc.
+        Use ``'skip_all'`` to avoid the computational overhead of these
+        checks when rough edges are acceptable.
+        """
+        return self._validation_policy
+
+    @validation_policy.setter
+    def validation_policy(self, validation_policy):
+        validation_policy = (str(validation_policy).lower()
+                             if validation_policy is not None else None)
+        iv_policies = {None, 'skip_all'}
+        if validation_policy not in iv_policies:
+            message = (f"Attribute `validation_policy` of `{self.__class__.__name__}` "
+                       f"must be one of {iv_policies}, if specified.")
+            raise ValueError(message)
+        self._validation_policy = validation_policy
+
+    ### Other magic methods
+
+    def __repr__(self):
+        r""" Returns a string representation of the distribution.
+
+        Includes the name of the distribution family, the names of the
+        parameters and the `repr` of each of their values.
+
+
+        """
+        class_name = self.__class__.__name__
+        parameters = list(self._original_parameters.items())
+        info = []
+        with np.printoptions(threshold=10):
+            str_parameters = [f"{symbol}={repr(value)}" for symbol, value in parameters]
+        str_parameters = f"{', '.join(str_parameters)}"
+        info.append(str_parameters)
+        return f"{class_name}({', '.join(info)})"
+
+    def __str__(self):
+        class_name = self.__class__.__name__
+        parameters = list(self._original_parameters.items())
+        info = []
+        with np.printoptions(threshold=10):
+            str_parameters = [f"{symbol}={str(value)}" for symbol, value in parameters]
+        str_parameters = f"{', '.join(str_parameters)}"
+        info.append(str_parameters)
+        return f"{class_name}({', '.join(info)})"
+
+    def __add__(self, loc):
+        return ShiftedScaledDistribution(self, loc=loc)
+
+    def __sub__(self, loc):
+        return ShiftedScaledDistribution(self, loc=-loc)
+
+    def __mul__(self, scale):
+        return ShiftedScaledDistribution(self, scale=scale)
+
+    def __truediv__(self, scale):
+        return ShiftedScaledDistribution(self, scale=1/scale)
+
+    def __pow__(self, other):
+        if not np.isscalar(other) or other <= 0 or other != int(other):
+            message = ("Raising a random variable to the power of an argument is only "
+                       "implemented when the argument is a positive integer.")
+            raise NotImplementedError(message)
+
+        # Fill in repr_pattern with the repr of self before taking abs.
+        # Avoids having unnecessary abs in the repr.
+        with np.printoptions(threshold=10):
+            repr_pattern = f"({repr(self)})**{repr(other)}"
+            str_pattern = f"({str(self)})**{str(other)}"
+        X = abs(self) if other % 2 == 0 else self
+
+        funcs = dict(g=lambda u: u**other, repr_pattern=repr_pattern,
+                     str_pattern=str_pattern,
+                     h=lambda u: np.sign(u) * np.abs(u)**(1 / other),
+                     dh=lambda u: 1/other * np.abs(u)**(1/other - 1))
+
+        return MonotonicTransformedDistribution(X, **funcs, increasing=True)
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+    def __rsub__(self, other):
+        return self.__neg__().__add__(other)
+
+    def __rmul__(self, other):
+        return self.__mul__(other)
+
+    def __rtruediv__(self, other):
+        a, b = self.support()
+        with np.printoptions(threshold=10):
+            funcs = dict(g=lambda u: 1 / u,
+                         repr_pattern=f"{repr(other)}/({repr(self)})",
+                         str_pattern=f"{str(other)}/({str(self)})",
+                         h=lambda u: 1 / u, dh=lambda u: 1 / u ** 2)
+        if np.all(a >= 0) or np.all(b <= 0):
+            out = MonotonicTransformedDistribution(self, **funcs, increasing=False)
+        else:
+            message = ("Division by a random variable is only implemented "
+                       "when the support is either non-negative or non-positive.")
+            raise NotImplementedError(message)
+        if np.all(other == 1):
+            return out
+        else:
+            return out * other
+
+    def __rpow__(self, other):
+        with np.printoptions(threshold=10):
+            funcs = dict(g=lambda u: other**u,
+                         h=lambda u: np.log(u) / np.log(other),
+                         dh=lambda u: 1 / np.abs(u * np.log(other)),
+                         repr_pattern=f"{repr(other)}**({repr(self)})",
+                         str_pattern=f"{str(other)}**({str(self)})",)
+
+        if not np.isscalar(other) or other <= 0 or other == 1:
+            message = ("Raising an argument to the power of a random variable is only "
+                       "implemented when the argument is a positive scalar other than "
+                       "1.")
+            raise NotImplementedError(message)
+
+        if other > 1:
+            return MonotonicTransformedDistribution(self, **funcs, increasing=True)
+        else:
+            return MonotonicTransformedDistribution(self, **funcs, increasing=False)
+
+    def __neg__(self):
+        return self * -1
+
+    def __abs__(self):
+        return FoldedDistribution(self)
+
+    ### Utilities
+
+    ## Input validation
+
+    def _validate_order_kind(self, order, kind, kinds):
+        # Yet another integer validating function. Unlike others in SciPy, it
+        # Is quite flexible about what is allowed as an integer, and it
+        # raises a distribution-specific error message to facilitate
+        # identification of the source of the error.
+        if self.validation_policy == _SKIP_ALL:
+            return order
+
+        order = np.asarray(order, dtype=self._dtype)[()]
+        message = (f"Argument `order` of `{self.__class__.__name__}.moment` "
+                   "must be a finite, positive integer.")
+        try:
+            order_int = round(order.item())
+            # If this fails for any reason (e.g. it's an array, it's infinite)
+            # it's not a valid `order`.
+        except Exception as e:
+            raise ValueError(message) from e
+
+        if order_int <0 or order_int != order:
+            raise ValueError(message)
+
+        message = (f"Argument `kind` of `{self.__class__.__name__}.moment` "
+                   f"must be one of {set(kinds)}.")
+        if kind.lower() not in kinds:
+            raise ValueError(message)
+
+        return order
+
+    def _preserve_type(self, x):
+        x = np.asarray(x)
+        if x.dtype != self._dtype:
+            x = x.astype(self._dtype)
+        return x[()]
+
+    ## Testing
+
+    @classmethod
+    def _draw(cls, sizes=None, rng=None, i_parameterization=None,
+              proportions=None):
+        r""" Draw a specific (fully-defined) distribution from the family.
+
+        See _Parameterization.draw for documentation details.
+        """
+        rng = np.random.default_rng(rng)
+        if len(cls._parameterizations) == 0:
+            return cls()
+        if i_parameterization is None:
+            n = cls._num_parameterizations()
+            i_parameterization = rng.integers(0, max(0, n - 1), endpoint=True)
+
+        parameterization = cls._parameterizations[i_parameterization]
+        parameters = parameterization.draw(sizes, rng, proportions=proportions,
+                                           region='typical')
+        return cls(**parameters)
+
+    @classmethod
+    def _num_parameterizations(cls):
+        # Returns the number of parameterizations accepted by the family.
+        return len(cls._parameterizations)
+
+    @classmethod
+    def _num_parameters(cls, i_parameterization=0):
+        # Returns the number of parameters used in the specified
+        # parameterization.
+        return (0 if not cls._num_parameterizations()
+                else len(cls._parameterizations[i_parameterization]))
+
+    ## Algorithms
+
+    def _quadrature(self, integrand, limits=None, args=None,
+                    params=None, log=False):
+        # Performs numerical integration of an integrand between limits.
+        # Much of this should be added to `_tanhsinh`.
+        a, b = self._support(**params) if limits is None else limits
+        a, b = np.broadcast_arrays(a, b)
+        if not a.size:
+            # maybe need to figure out result type from a, b
+            return np.empty(a.shape, dtype=self._dtype)
+        args = [] if args is None else args
+        params = {} if params is None else params
+        f, args = _kwargs2args(integrand, args=args, kwargs=params)
+        args = np.broadcast_arrays(*args)
+        # If we know the median or mean, consider breaking up the interval
+        rtol = None if _isnull(self.tol) else self.tol
+        res = _tanhsinh(f, a, b, args=args, log=log, rtol=rtol)
+        # For now, we ignore the status, but I want to return the error
+        # estimate - see question 5 at the top.
+        return res.integral
+
+    def _solve_bounded(self, f, p, *, bounds=None, params=None):
+        # Finds the argument of a function that produces the desired output.
+        # Much of this should be added to _bracket_root / _chandrupatla.
+        xmin, xmax = self._support(**params) if bounds is None else bounds
+        params = {} if params is None else params
+
+        p, xmin, xmax = np.broadcast_arrays(p, xmin, xmax)
+        if not p.size:
+            # might need to figure out result type based on p
+            return np.empty(p.shape, dtype=self._dtype)
+
+        def f2(x, _p, **kwargs):  # named `_p` to avoid conflict with shape `p`
+            return f(x, **kwargs) - _p
+
+        f3, args = _kwargs2args(f2, args=[p], kwargs=params)
+        # If we know the median or mean, should use it
+
+        # Any operations between 0d array and a scalar produces a scalar, so...
+        shape = xmin.shape
+        xmin, xmax = np.atleast_1d(xmin, xmax)
+
+        xl0, xr0 = _guess_bracket(xmin, xmax)
+        xmin = xmin.reshape(shape)
+        xmax = xmax.reshape(shape)
+        xl0 = xl0.reshape(shape)
+        xr0 = xr0.reshape(shape)
+
+        res = _bracket_root(f3, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=args)
+        # For now, we ignore the status, but I want to use the bracket width
+        # as an error estimate - see question 5 at the top.
+        xrtol = None if _isnull(self.tol) else self.tol
+        return _chandrupatla(f3, a=res.xl, b=res.xr, args=args, xrtol=xrtol).x
+
+    ## Other
+
+    def _overrides(self, method_name):
+        # Determines whether a class overrides a specified method.
+        # Returns True if the method implementation exists and is the same as
+        # that of the `ContinuousDistribution` class; otherwise returns False.
+
+        # Sometimes we use `_overrides` to check whether a certain method is overridden
+        # and if so, call it. This begs the questions of why we don't do the more
+        # obvious thing: restructure so that if the private method is overridden,
+        # Python will call it instead of the inherited version automatically. The short
+        # answer is that there are multiple ways a use might wish to evaluate a method,
+        # and simply overriding the method with a formula is not always the best option.
+        # For more complete discussion of the considerations, see:
+        # https://github.com/scipy/scipy/pull/21050#discussion_r1707798901
+        method = getattr(self.__class__, method_name, None)
+        super_method = getattr(ContinuousDistribution, method_name, None)
+        return method is not super_method
+
+    ### Distribution properties
+    # The following "distribution properties" are exposed via a public method
+    # that accepts only options (not distribution parameters or quantile/
+    # percentile argument).
+    # support
+    # logentropy, entropy,
+    # median, mode, mean,
+    # variance, standard_deviation
+    # skewness, kurtosis
+    # Common options are:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Input/output validation is provided by the `_set_invalid_nan_property`
+    # decorator. These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Dispatch methods always accept:
+    # method - as passed from the public method
+    # params - a dictionary of distribution shape parameters passed by
+    #          the public method.
+    # Dispatch methods accept `params` rather than relying on the state of the
+    # object because iterative algorithms like `_tanhsinh` and `_chandrupatla`
+    # need their callable to follow a strict elementwise protocol: each element
+    # of the output is determined solely by the values of the inputs at the
+    # corresponding location. The public methods do not satisfy this protocol
+    # because they do not accept the parameters as arguments, producing an
+    # output that generally has a different shape than that of the input. Also,
+    # by calling "dispatch" methods rather than the public methods, the
+    # iterative algorithms avoid the overhead of input validation.
+    #
+    # Each dispatch method can designate the responsibility of computing
+    # the required value to any of several "implementation" methods. These
+    # methods accept only `**params`, the parameter dictionary passed from
+    # the public method via the dispatch method. We separate the implementation
+    # methods from the dispatch methods for the sake of simplicity (via
+    # compartmentalization) and to allow subclasses to override certain
+    # implementation methods (typically only the "formula" methods). The names
+    # of implementation methods are combinations of the public method name and
+    # the name of the "method" (strategy for calculating the desired quantity)
+    # string. (In fact, the name of the implementation method is calculated
+    # from these two strings in the `_dispatch` decorator.) Common method
+    # strings are:
+    # formula - distribution-specific analytical expressions to be implemented
+    #           by subclasses.
+    # log/exp - Compute the log of a number and then exponentiate it or vice
+    #           versa.
+    # quadrature - Compute the value via numerical integration.
+    #
+    # The default method (strategy) is determined based on what implementation
+    # methods are available and the error tolerance of the user. Typically,
+    # a formula is always used if available. We fall back to "log/exp" if a
+    # formula for the logarithm or exponential of the quantity is available,
+    # and we use quadrature otherwise.
+
+    def support(self):
+        # If this were a `cached_property`, we couldn't update the value
+        # when the distribution parameters change.
+        # Caching is important, though, because calls to _support take a few
+        # microseconds even when `a` and `b` are already the same shape.
+        if self._support_cache is not None:
+            return self._support_cache
+
+        a, b = self._support(**self._parameters)
+        if a.shape != self._shape:
+            a = np.broadcast_to(a, self._shape)
+        if b.shape != self._shape:
+            b = np.broadcast_to(b, self._shape)
+
+        if self._any_invalid:
+            a, b = np.asarray(a).copy(), np.asarray(b).copy()
+            a[self._invalid], b[self._invalid] = np.nan, np.nan
+            a, b = a[()], b[()]
+
+        support = (a, b)
+
+        if self.cache_policy != _NO_CACHE:
+            self._support_cache = support
+
+        return support
+
+    def _support(self, **params):
+        # Computes the support given distribution parameters
+        a, b = self._variable.domain.get_numerical_endpoints(params)
+        if len(params):
+            # the parameters should all be of the same dtype and shape at this point
+            vals = list(params.values())
+            shape = vals[0].shape
+            a = np.broadcast_to(a, shape) if a.shape != shape else a
+            b = np.broadcast_to(b, shape) if b.shape != shape else b
+        return self._preserve_type(a), self._preserve_type(b)
+
+    @_set_invalid_nan_property
+    def logentropy(self, *, method=None):
+        return self._logentropy_dispatch(method=method, **self._parameters) + 0j
+
+    @_dispatch
+    def _logentropy_dispatch(self, method=None, **params):
+        if self._overrides('_logentropy_formula'):
+            method = self._logentropy_formula
+        elif self._overrides('_entropy_formula'):
+            method = self._logentropy_logexp_safe
+        else:
+            method = self._logentropy_quadrature
+        return method
+
+    def _logentropy_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logentropy_logexp(self, **params):
+        res = np.log(self._entropy_dispatch(**params)+0j)
+        return _log_real_standardize(res)
+
+    def _logentropy_logexp_safe(self, **params):
+        out = self._logentropy_logexp(**params)
+        mask = np.isinf(out.real)
+        if np.any(mask):
+            params_mask = {key:val[mask] for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logentropy_quadrature(**params_mask)
+        return out[()]
+
+    def _logentropy_quadrature(self, **params):
+        def logintegrand(x, **params):
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf + np.log(0j+logpdf)
+        res = self._quadrature(logintegrand, params=params, log=True)
+        return _log_real_standardize(res + np.pi*1j)
+
+    @_set_invalid_nan_property
+    def entropy(self, *, method=None):
+        return self._entropy_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _entropy_dispatch(self, method=None, **params):
+        if self._overrides('_entropy_formula'):
+            method = self._entropy_formula
+        elif self._overrides('_logentropy_formula'):
+            method = self._entropy_logexp
+        else:
+            method = self._entropy_quadrature
+        return method
+
+    def _entropy_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _entropy_logexp(self, **params):
+        return np.real(np.exp(self._logentropy_dispatch(**params)))
+
+    def _entropy_quadrature(self, **params):
+        def integrand(x, **params):
+            pdf = self._pdf_dispatch(x, **params)
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf * pdf
+        return -self._quadrature(integrand, params=params)
+
+    @_set_invalid_nan_property
+    def median(self, *, method=None):
+        return self._median_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _median_dispatch(self, method=None, **params):
+        if self._overrides('_median_formula'):
+            method = self._median_formula
+        else:
+            method = self._median_icdf
+        return method
+
+    def _median_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _median_icdf(self, **params):
+        return self._icdf_dispatch(0.5, **params)
+
+    @_set_invalid_nan_property
+    def mode(self, *, method=None):
+        return self._mode_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _mode_dispatch(self, method=None, **params):
+        # We could add a method that looks for a critical point with
+        # differentiation and the root finder
+        if self._overrides('_mode_formula'):
+            method = self._mode_formula
+        else:
+            method = self._mode_optimization
+        return method
+
+    def _mode_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _mode_optimization(self, **params):
+        if not self._size:
+            return np.empty(self._shape, dtype=self._dtype)
+
+        a, b = self._support(**params)
+        m = self._median_dispatch(**params)
+
+        f, args = _kwargs2args(lambda x, **params: -self._pdf_dispatch(x, **params),
+                               args=(), kwargs=params)
+        res_b = _bracket_minimum(f, m, xmin=a, xmax=b, args=args)
+        res = _chandrupatla_minimize(f, res_b.xl, res_b.xm, res_b.xr, args=args)
+        mode = np.asarray(res.x)
+        mode_at_boundary = res_b.status == -1
+        mode_at_left = mode_at_boundary & (res_b.fl <= res_b.fm)
+        mode_at_right = mode_at_boundary & (res_b.fr < res_b.fm)
+        mode[mode_at_left] = a[mode_at_left]
+        mode[mode_at_right] = b[mode_at_right]
+        return mode[()]
+
+    def mean(self, *, method=None):
+        return self.moment(1, kind='raw', method=method)
+
+    def variance(self, *, method=None):
+        return self.moment(2, kind='central', method=method)
+
+    def standard_deviation(self, *, method=None):
+        return np.sqrt(self.variance(method=method))
+
+    def skewness(self, *, method=None):
+        return self.moment(3, kind='standardized', method=method)
+
+    def kurtosis(self, *, method=None, convention='non-excess'):
+        conventions = {'non-excess', 'excess'}
+        message = (f'Parameter `convention` of `{self.__class__.__name__}.kurtosis` '
+                   f"must be one of {conventions}.")
+        convention = convention.lower()
+        if convention not in conventions:
+            raise ValueError(message)
+        k = self.moment(4, kind='standardized', method=method)
+        return k - 3 if convention == 'excess' else k
+
+    ### Distribution functions
+    # The following functions related to the distribution PDF and CDF are
+    # exposed via a public method that accepts one positional argument - the
+    # quantile - and keyword options (but not distribution parameters).
+    # logpdf, pdf
+    # logcdf, cdf
+    # logccdf, ccdf
+    # The `logcdf` and `cdf` functions can also be called with two positional
+    # arguments - lower and upper quantiles - and they return the probability
+    # mass (integral of the PDF) between them. The 2-arg versions of `logccdf`
+    # and `ccdf` return the complement of this quantity.
+    # All the (1-arg) cumulative distribution functions have inverse
+    # functions, which accept one positional argument - the percentile.
+    # ilogcdf, icdf
+    # ilogccdf, iccdf
+    # Common keyword options include:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Tolerance options should be added.
+    # Input/output validation is provided by the `_set_invalid_nan`
+    # decorator. These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Each dispatch method can designate the responsibility of computing
+    # the required value to any of several "implementation" methods. These
+    # methods accept only `**params`, the parameter dictionary passed from
+    # the public method via the dispatch method.
+    # See the note corresponding with the "Distribution Parameters" for more
+    # information.
+
+    ## Probability Density Functions
+
+    @_set_invalid_nan
+    def logpdf(self, x, /, *, method=None):
+        return self._logpdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logpdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_logpdf_formula'):
+            method = self._logpdf_formula
+        elif _isnull(self.tol):  # ensure that developers override _logpdf
+            method = self._logpdf_logexp
+        return method
+
+    def _logpdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logpdf_logexp(self, x, **params):
+        return np.log(self._pdf_dispatch(x, **params))
+
+    @_set_invalid_nan
+    def pdf(self, x, /, *, method=None):
+        return self._pdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _pdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_pdf_formula'):
+            method = self._pdf_formula
+        else:
+            method = self._pdf_logexp
+        return method
+
+    def _pdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _pdf_logexp(self, x, **params):
+        return np.exp(self._logpdf_dispatch(x, **params))
+
+    ## Cumulative Distribution Functions
+
+    def logcdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._logcdf1(x, method=method)
+        else:
+            return self._logcdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _logcdf2(self, x, y, *, method):
+        out = self._logcdf2_dispatch(x, y, method=method, **self._parameters)
+        return (out + 0j) if not np.issubdtype(out.dtype, np.complexfloating) else out
+
+    @_dispatch
+    def _logcdf2_dispatch(self, x, y, *, method=None, **params):
+        # dtype is complex if any x > y, else real
+        # Should revisit this logic.
+        if self._overrides('_logcdf2_formula'):
+            method = self._logcdf2_formula
+        elif (self._overrides('_logcdf_formula')
+              or self._overrides('_logccdf_formula')):
+            method = self._logcdf2_subtraction
+        elif (self._overrides('_cdf_formula')
+              or self._overrides('_ccdf_formula')):
+            method = self._logcdf2_logexp_safe
+        else:
+            method = self._logcdf2_quadrature
+        return method
+
+    def _logcdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logcdf2_subtraction(self, x, y, **params):
+        flip_sign = x > y  # some results will be negative
+        x, y = np.minimum(x, y), np.maximum(x, y)
+        logcdf_x = self._logcdf_dispatch(x, **params)
+        logcdf_y = self._logcdf_dispatch(y, **params)
+        logccdf_x = self._logccdf_dispatch(x, **params)
+        logccdf_y = self._logccdf_dispatch(y, **params)
+        case_left = (logcdf_x < -1) & (logcdf_y < -1)
+        case_right = (logccdf_x < -1) & (logccdf_y < -1)
+        case_central = ~(case_left | case_right)
+        log_mass = _logexpxmexpy(logcdf_y, logcdf_x)
+        log_mass[case_right] = _logexpxmexpy(logccdf_x, logccdf_y)[case_right]
+        log_tail = np.logaddexp(logcdf_x, logccdf_y)[case_central]
+        log_mass[case_central] = _log1mexp(log_tail)
+        log_mass[flip_sign] += np.pi * 1j
+        return log_mass[()] if np.any(flip_sign) else log_mass.real[()]
+
+    def _logcdf2_logexp(self, x, y, **params):
+        expres = self._cdf2_dispatch(x, y, **params)
+        expres = expres + 0j if np.any(x > y) else expres
+        return np.log(expres)
+
+    def _logcdf2_logexp_safe(self, x, y, **params):
+        out = self._logcdf2_logexp(x, y, **params)
+        mask = np.isinf(out.real)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logcdf2_quadrature(x[mask], y[mask], **params_mask)
+        return out[()]
+
+    def _logcdf2_quadrature(self, x, y, **params):
+        logres = self._quadrature(self._logpdf_dispatch, limits=(x, y),
+                                  log=True, params=params)
+        return logres
+
+    @_set_invalid_nan
+    def _logcdf1(self, x, *, method=None):
+        return self._logcdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logcdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_logcdf_formula'):
+            method = self._logcdf_formula
+        elif self._overrides('_logccdf_formula'):
+            method = self._logcdf_complement
+        elif self._overrides('_cdf_formula'):
+            method = self._logcdf_logexp_safe
+        else:
+            method = self._logcdf_quadrature
+        return method
+
+    def _logcdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logcdf_complement(self, x, **params):
+        return _log1mexp(self._logccdf_dispatch(x, **params))
+
+    def _logcdf_logexp(self, x, **params):
+        return np.log(self._cdf_dispatch(x, **params))
+
+    def _logcdf_logexp_safe(self, x, **params):
+        out = self._logcdf_logexp(x, **params)
+        mask = np.isinf(out)
+        if np.any(mask):
+            params_mask = {key:np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logcdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _logcdf_quadrature(self, x, **params):
+        a, _ = self._support(**params)
+        return self._quadrature(self._logpdf_dispatch, limits=(a, x),
+                                params=params, log=True)
+
+    def cdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._cdf1(x, method=method)
+        else:
+            return self._cdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _cdf2(self, x, y, *, method):
+        return self._cdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _cdf2_dispatch(self, x, y, *, method=None, **params):
+        # Should revisit this logic.
+        if self._overrides('_cdf2_formula'):
+            method = self._cdf2_formula
+        elif (self._overrides('_logcdf_formula')
+              or self._overrides('_logccdf_formula')):
+            method = self._cdf2_logexp
+        elif self._overrides('_cdf_formula') or self._overrides('_ccdf_formula'):
+            method = self._cdf2_subtraction_safe
+        else:
+            method = self._cdf2_quadrature
+        return method
+
+    def _cdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _cdf2_logexp(self, x, y, **params):
+        return np.real(np.exp(self._logcdf2_dispatch(x, y, **params)))
+
+    def _cdf2_subtraction(self, x, y, **params):
+        # Improvements:
+        # Lazy evaluation of cdf/ccdf only where needed
+        # Stack x and y to reduce function calls?
+        cdf_x = self._cdf_dispatch(x, **params)
+        cdf_y = self._cdf_dispatch(y, **params)
+        ccdf_x = self._ccdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        i = (ccdf_x < 0.5) & (ccdf_y < 0.5)
+        return np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x)
+
+    def _cdf2_subtraction_safe(self, x, y, **params):
+        cdf_x = self._cdf_dispatch(x, **params)
+        cdf_y = self._cdf_dispatch(y, **params)
+        ccdf_x = self._ccdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        i = (ccdf_x < 0.5) & (ccdf_y < 0.5)
+        out = np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x)
+
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+
+        cdf_max = np.maximum(cdf_x, cdf_y)
+        ccdf_max = np.maximum(ccdf_x, ccdf_y)
+        spacing = np.spacing(np.where(i, ccdf_max, cdf_max))
+        mask = np.abs(tol * out) < spacing
+
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._cdf2_quadrature(x[mask], y[mask], *params_mask)
+        return out[()]
+
+    def _cdf2_quadrature(self, x, y, **params):
+        return self._quadrature(self._pdf_dispatch, limits=(x, y), params=params)
+
+    @_set_invalid_nan
+    def _cdf1(self, x, *, method):
+        return self._cdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _cdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_cdf_formula'):
+            method = self._cdf_formula
+        elif self._overrides('_logcdf_formula'):
+            method = self._cdf_logexp
+        elif self._overrides('_ccdf_formula'):
+            method = self._cdf_complement_safe
+        else:
+            method = self._cdf_quadrature
+        return method
+
+    def _cdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _cdf_logexp(self, x, **params):
+        return np.exp(self._logcdf_dispatch(x, **params))
+
+    def _cdf_complement(self, x, **params):
+        return 1 - self._ccdf_dispatch(x, **params)
+
+    def _cdf_complement_safe(self, x, **params):
+        ccdf = self._ccdf_dispatch(x, **params)
+        out = 1 - ccdf
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * out < np.spacing(ccdf)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._cdf_quadrature(x[mask], *params_mask)
+        return out[()]
+
+    def _cdf_quadrature(self, x, **params):
+        a, _ = self._support(**params)
+        return self._quadrature(self._pdf_dispatch, limits=(a, x),
+                                params=params)
+
+    def logccdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._logccdf1(x, method=method)
+        else:
+            return self._logccdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _logccdf2(self, x, y, *, method):
+        return self._logccdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _logccdf2_dispatch(self, x, y, *, method=None, **params):
+        # if _logccdf2_formula exists, we could use the complement
+        # if _ccdf2_formula exists, we could use log/exp
+        if self._overrides('_logccdf2_formula'):
+            method = self._logccdf2_formula
+        else:
+            method = self._logccdf2_addition
+        return method
+
+    def _logccdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logccdf2_addition(self, x, y, **params):
+        logcdf_x = self._logcdf_dispatch(x, **params)
+        logccdf_y = self._logccdf_dispatch(y, **params)
+        return special.logsumexp([logcdf_x, logccdf_y], axis=0)
+
+    @_set_invalid_nan
+    def _logccdf1(self, x, *, method=None):
+        return self._logccdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_logccdf_formula'):
+            method = self._logccdf_formula
+        elif self._overrides('_logcdf_formula'):
+            method = self._logccdf_complement
+        elif self._overrides('_ccdf_formula'):
+            method = self._logccdf_logexp_safe
+        else:
+            method = self._logccdf_quadrature
+        return method
+
+    def _logccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logccdf_complement(self, x, **params):
+        return _log1mexp(self._logcdf_dispatch(x, **params))
+
+    def _logccdf_logexp(self, x, **params):
+        return np.log(self._ccdf_dispatch(x, **params))
+
+    def _logccdf_logexp_safe(self, x, **params):
+        out = self._logccdf_logexp(x, **params)
+        mask = np.isinf(out)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logccdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _logccdf_quadrature(self, x, **params):
+        _, b = self._support(**params)
+        return self._quadrature(self._logpdf_dispatch, limits=(x, b),
+                                params=params, log=True)
+
+    def ccdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._ccdf1(x, method=method)
+        else:
+            return self._ccdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _ccdf2(self, x, y, *, method):
+        return self._ccdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _ccdf2_dispatch(self, x, y, *, method=None, **params):
+        if self._overrides('_ccdf2_formula'):
+            method = self._ccdf2_formula
+        else:
+            method = self._ccdf2_addition
+        return method
+
+    def _ccdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ccdf2_addition(self, x, y, **params):
+        cdf_x = self._cdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        # even if x > y, cdf(x, y) + ccdf(x,y) sums to 1
+        return cdf_x + ccdf_y
+
+    @_set_invalid_nan
+    def _ccdf1(self, x, *, method):
+        return self._ccdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _ccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ccdf_formula'):
+            method = self._ccdf_formula
+        elif self._overrides('_logccdf_formula'):
+            method = self._ccdf_logexp
+        elif self._overrides('_cdf_formula'):
+            method = self._ccdf_complement_safe
+        else:
+            method = self._ccdf_quadrature
+        return method
+
+    def _ccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ccdf_logexp(self, x, **params):
+        return np.exp(self._logccdf_dispatch(x, **params))
+
+    def _ccdf_complement(self, x, **params):
+        return 1 - self._cdf_dispatch(x, **params)
+
+    def _ccdf_complement_safe(self, x, **params):
+        cdf = self._cdf_dispatch(x, **params)
+        out = 1 - cdf
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * out < np.spacing(cdf)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._ccdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _ccdf_quadrature(self, x, **params):
+        _, b = self._support(**params)
+        return self._quadrature(self._pdf_dispatch, limits=(x, b),
+                                params=params)
+
+    ## Inverse cumulative distribution functions
+
+    @_set_invalid_nan
+    def ilogcdf(self, logp, /, *, method=None):
+        return self._ilogcdf_dispatch(logp, method=method, **self._parameters)
+
+    @_dispatch
+    def _ilogcdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ilogcdf_formula'):
+            method = self._ilogcdf_formula
+        elif self._overrides('_ilogccdf_formula'):
+            method = self._ilogcdf_complement
+        else:
+            method = self._ilogcdf_inversion
+        return method
+
+    def _ilogcdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ilogcdf_complement(self, x, **params):
+        return self._ilogccdf_dispatch(_log1mexp(x), **params)
+
+    def _ilogcdf_inversion(self, x, **params):
+        return self._solve_bounded(self._logcdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def icdf(self, p, /, *, method=None):
+        return self._icdf_dispatch(p, method=method, **self._parameters)
+
+    @_dispatch
+    def _icdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_icdf_formula'):
+            method = self._icdf_formula
+        elif self._overrides('_iccdf_formula'):
+            method = self._icdf_complement_safe
+        else:
+            method = self._icdf_inversion
+        return method
+
+    def _icdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _icdf_complement(self, x, **params):
+        return self._iccdf_dispatch(1 - x, **params)
+
+    def _icdf_complement_safe(self, x, **params):
+        out = self._icdf_complement(x, **params)
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * x < np.spacing(1 - x)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._icdf_inversion(x[mask], *params_mask)
+        return out[()]
+
+    def _icdf_inversion(self, x, **params):
+        return self._solve_bounded(self._cdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def ilogccdf(self, logp, /, *, method=None):
+        return self._ilogccdf_dispatch(logp, method=method, **self._parameters)
+
+    @_dispatch
+    def _ilogccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ilogccdf_formula'):
+            method = self._ilogccdf_formula
+        elif self._overrides('_ilogcdf_formula'):
+            method = self._ilogccdf_complement
+        else:
+            method = self._ilogccdf_inversion
+        return method
+
+    def _ilogccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ilogccdf_complement(self, x, **params):
+        return self._ilogcdf_dispatch(_log1mexp(x), **params)
+
+    def _ilogccdf_inversion(self, x, **params):
+        return self._solve_bounded(self._logccdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def iccdf(self, p, /, *, method=None):
+        return self._iccdf_dispatch(p, method=method, **self._parameters)
+
+    @_dispatch
+    def _iccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_iccdf_formula'):
+            method = self._iccdf_formula
+        elif self._overrides('_icdf_formula'):
+            method = self._iccdf_complement_safe
+        else:
+            method = self._iccdf_inversion
+        return method
+
+    def _iccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _iccdf_complement(self, x, **params):
+        return self._icdf_dispatch(1 - x, **params)
+
+    def _iccdf_complement_safe(self, x, **params):
+        out = self._iccdf_complement(x, **params)
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * x < np.spacing(1 - x)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._iccdf_inversion(x[mask], *params_mask)
+        return out[()]
+
+    def _iccdf_inversion(self, x, **params):
+        return self._solve_bounded(self._ccdf_dispatch, x, params=params)
+
+    ### Sampling Functions
+    # The following functions for drawing samples from the distribution are
+    # exposed via a public method that accepts one positional argument - the
+    # shape of the sample - and keyword options (but not distribution
+    # parameters).
+    # sample
+    # ~~qmc_sample~~ built into sample now
+    #
+    # Common keyword options include:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # rng - the NumPy Generator/SciPy QMCEngine object to used for drawing numbers.
+    #
+    # Input/output validation is included in each function, since there is
+    # little code to be shared.
+    # These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Each dispatch method can designate the responsibility of sampling to any
+    # of several "implementation" methods. These methods accept only
+    # `**params`, the parameter dictionary passed from the public method via
+    # the "dispatch" method.
+    # See the note corresponding with the "Distribution Parameters" for more
+    # information.
+
+    # TODO:
+    #  - should we accept a QRNG with `d != 1`?
+    def sample(self, shape=(), *, method=None, rng=None):
+        # needs output validation to ensure that developer returns correct
+        # dtype and shape
+        sample_shape = (shape,) if not np.iterable(shape) else tuple(shape)
+        full_shape = sample_shape + self._shape
+        rng = np.random.default_rng(rng) if not isinstance(rng, qmc.QMCEngine) else rng
+        res = self._sample_dispatch(sample_shape, full_shape, method=method,
+                                    rng=rng, **self._parameters)
+
+        return res.astype(self._dtype, copy=False)
+
+    @_dispatch
+    def _sample_dispatch(self, sample_shape, full_shape, *, method, rng, **params):
+        # make sure that tests catch if sample is 0d array
+        if self._overrides('_sample_formula') and not isinstance(rng, qmc.QMCEngine):
+            method = self._sample_formula
+        else:
+            method = self._sample_inverse_transform
+        return method
+
+    def _sample_formula(self, sample_shape, full_shape, *, rng, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _sample_inverse_transform(self, sample_shape, full_shape, *, rng, **params):
+        if isinstance(rng, qmc.QMCEngine):
+            uniform = self._qmc_uniform(sample_shape, full_shape, qrng=rng, **params)
+        else:
+            uniform = rng.random(size=full_shape, dtype=self._dtype)
+        return self._icdf_dispatch(uniform, **params)
+
+    def _qmc_uniform(self, sample_shape, full_shape, *, qrng, **params):
+        # Generate QMC uniform sample(s) on unit interval with specified shape;
+        # if `sample_shape != ()`, then each slice along axis 0 is independent.
+
+        # Determine the number of independent sequences and the length of each.
+        n_low_discrepancy = sample_shape[0] if sample_shape else 1
+        n_independent = math.prod(full_shape[1:] if sample_shape else full_shape)
+
+        # For each independent sequence, we'll need a new QRNG of the appropriate class
+        # with its own RNG. (If scramble=False, we don't really need all the separate
+        # rngs, but I'm not going to add a special code path right now.)
+        rngs = _rng_spawn(qrng.rng, n_independent)
+        qrng_class = qrng.__class__
+        kwargs = dict(d=1, scramble=qrng.scramble, optimization=qrng._optimization)
+        if isinstance(qrng, qmc.Sobol):
+            kwargs['bits'] = qrng.bits
+
+        # Draw uniform low-discrepancy sequences scrambled with each RNG
+        uniforms = []
+        for rng in rngs:
+            qrng = qrng_class(seed=rng, **kwargs)
+            uniform = qrng.random(n_low_discrepancy)
+            uniform = uniform.reshape(n_low_discrepancy if sample_shape else ())[()]
+            uniforms.append(uniform)
+
+        # Reorder the axes and ensure that the shape is correct
+        uniform = np.moveaxis(np.stack(uniforms), -1, 0) if uniforms else np.asarray([])
+        return uniform.reshape(full_shape)
+
+    ### Moments
+    # The `moment` method accepts two positional arguments - the order and kind
+    # (raw, central, or standard) of the moment - and a keyword option:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Like the distribution properties, input/output validation is provided by
+    # the `_set_invalid_nan_property` decorator.
+    #
+    # Unlike most public methods above, `moment` dispatches to one of three
+    # private methods - one for each 'kind'. Like most *public* methods above,
+    # each of these private methods calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use. Also, each dispatch method can designate the responsibility
+    # computing the moment to one of several "implementation" methods.
+    # Unlike the dispatch methods above, however, the `@_dispatch` decorator
+    # is not used, and both logic and method calls are included in the function
+    # itself.
+    # Instead of determining which method will be used based solely on the
+    # implementation methods available and calling only the corresponding
+    # implementation method, *all* the implementation methods are called
+    # in sequence until one returns the desired information. When an
+    # implementation methods cannot provide the requested information, it
+    # returns the object None (which is distinct from arrays with NaNs or infs,
+    # which are valid values of moments).
+    # The reason for this approach is that although formulae for the first
+    # few moments of a distribution may be found, general formulae that work
+    # for all orders are not always easy to find. This approach allows the
+    # developer to write "formula" implementation functions that return the
+    # desired moment when it is available and None otherwise.
+    #
+    # Note that the first implementation method called is a cache. This is
+    # important because lower-order moments are often needed to compute
+    # higher moments from formulae, so we eliminate redundant calculations
+    # when moments of several orders are needed.
+
+    @cached_property
+    def _moment_methods(self):
+        return {'cache', 'formula', 'transform',
+                'normalize', 'general', 'quadrature'}
+
+    @property
+    def _zero(self):
+        return self._constants()[0]
+
+    @property
+    def _one(self):
+        return self._constants()[1]
+
+    def _constants(self):
+        if self._constant_cache is not None:
+            return self._constant_cache
+
+        constants = self._preserve_type([0, 1])
+
+        if self.cache_policy != _NO_CACHE:
+            self._constant_cache = constants
+
+        return constants
+
+    @_set_invalid_nan_property
+    def moment(self, order=1, kind='raw', *, method=None):
+        kinds = {'raw': self._moment_raw,
+                 'central': self._moment_central,
+                 'standardized': self._moment_standardized}
+        order = self._validate_order_kind(order, kind, kinds)
+        moment_kind = kinds[kind]
+        return moment_kind(order, method=method)
+
+    def _moment_raw(self, order=1, *, method=None):
+        """Raw distribution moment about the origin."""
+        # Consider exposing the point about which moments are taken as an
+        # option. This is easy to support, since `_moment_transform_center`
+        # does all the work.
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_raw_dispatch(order, methods=methods, **self._parameters)
+
+    def _moment_raw_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_raw_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_raw_formula(order, **params)
+
+        if moment is None and 'transform' in methods and order > 1:
+            moment = self._moment_raw_transform(order, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_raw_general(order, **params)
+
+        if moment is None and 'quadrature' in methods:
+            moment = self._moment_integrate_pdf(order, center=self._zero, **params)
+
+        if moment is None and 'quadrature_icdf' in methods:
+            moment = self._moment_integrate_icdf(order, center=self._zero, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_raw_cache[order] = moment
+
+        return moment
+
+    def _moment_raw_formula(self, order, **params):
+        return None
+
+    def _moment_raw_transform(self, order, **params):
+        central_moments = []
+        for i in range(int(order) + 1):
+            methods = {'cache', 'formula', 'normalize', 'general'}
+            moment_i = self._moment_central_dispatch(order=i, methods=methods, **params)
+            if moment_i is None:
+                return None
+            central_moments.append(moment_i)
+
+        # Doesn't make sense to get the mean by "transform", since that's
+        # how we got here. Questionable whether 'quadrature' should be here.
+        mean_methods = {'cache', 'formula', 'quadrature'}
+        mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params)
+        if mean is None:
+            return None
+
+        moment = self._moment_transform_center(order, central_moments, mean, self._zero)
+        return moment
+
+    def _moment_raw_general(self, order, **params):
+        # This is the only general formula for a raw moment of a probability
+        # distribution
+        return self._one if order == 0 else None
+
+    def _moment_central(self, order=1, *, method=None):
+        """Distribution moment about the mean."""
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_central_dispatch(order, methods=methods, **self._parameters)
+
+    def _moment_central_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_central_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_central_formula(order, **params)
+
+        if moment is None and 'transform' in methods:
+            moment = self._moment_central_transform(order, **params)
+
+        if moment is None and 'normalize' in methods and order > 2:
+            moment = self._moment_central_normalize(order, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_central_general(order, **params)
+
+        if moment is None and 'quadrature' in methods:
+            mean = self._moment_raw_dispatch(self._one, **params,
+                                             methods=self._moment_methods)
+            moment = self._moment_integrate_pdf(order, center=mean, **params)
+
+        if moment is None and 'quadrature_icdf' in methods:
+            mean = self._moment_raw_dispatch(self._one, **params,
+                                             methods=self._moment_methods)
+            moment = self._moment_integrate_icdf(order, center=mean, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_central_cache[order] = moment
+
+        return moment
+
+    def _moment_central_formula(self, order, **params):
+        return None
+
+    def _moment_central_transform(self, order, **params):
+
+        raw_moments = []
+        for i in range(int(order) + 1):
+            methods = {'cache', 'formula', 'general'}
+            moment_i = self._moment_raw_dispatch(order=i, methods=methods, **params)
+            if moment_i is None:
+                return None
+            raw_moments.append(moment_i)
+
+        mean_methods = self._moment_methods
+        mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params)
+
+        moment = self._moment_transform_center(order, raw_moments, self._zero, mean)
+        return moment
+
+    def _moment_central_normalize(self, order, **params):
+        methods = {'cache', 'formula', 'general'}
+        standard_moment = self._moment_standardized_dispatch(order, **params,
+                                                             methods=methods)
+        if standard_moment is None:
+            return None
+        var = self._moment_central_dispatch(2, methods=self._moment_methods, **params)
+        return standard_moment*var**(order/2)
+
+    def _moment_central_general(self, order, **params):
+        general_central_moments = {0: self._one, 1: self._zero}
+        return general_central_moments.get(order, None)
+
+    def _moment_standardized(self, order=1, *, method=None):
+        """Standardized distribution moment."""
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_standardized_dispatch(order, methods=methods,
+                                                  **self._parameters)
+
+    def _moment_standardized_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_standardized_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_standardized_formula(order, **params)
+
+        if moment is None and 'normalize' in methods:
+            moment = self._moment_standardized_normalize(order, False, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_standardized_general(order, **params)
+
+        if moment is None and 'normalize' in methods:
+            moment = self._moment_standardized_normalize(order, True, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_standardized_cache[order] = moment
+
+        return moment
+
+    def _moment_standardized_formula(self, order, **params):
+        return None
+
+    def _moment_standardized_normalize(self, order, use_quadrature, **params):
+        methods = ({'quadrature'} if use_quadrature
+                   else {'cache', 'formula', 'transform'})
+        central_moment = self._moment_central_dispatch(order, **params,
+                                                       methods=methods)
+        if central_moment is None:
+            return None
+        var = self._moment_central_dispatch(2, methods=self._moment_methods,
+                                            **params)
+        return central_moment/var**(order/2)
+
+    def _moment_standardized_general(self, order, **params):
+        general_standard_moments = {0: self._one, 1: self._zero, 2: self._one}
+        return general_standard_moments.get(order, None)
+
+    def _moment_integrate_pdf(self, order, center, **params):
+        def integrand(x, order, center, **params):
+            pdf = self._pdf_dispatch(x, **params)
+            return pdf*(x-center)**order
+        return self._quadrature(integrand, args=(order, center), params=params)
+
+    def _moment_integrate_icdf(self, order, center, **params):
+        def integrand(x, order, center, **params):
+            x = self._icdf_dispatch(x, **params)
+            return (x-center)**order
+        return self._quadrature(integrand, limits=(0., 1.),
+                                args=(order, center), params=params)
+
+    def _moment_transform_center(self, order, moment_as, a, b):
+        a, b, *moment_as = np.broadcast_arrays(a, b, *moment_as)
+        n = order
+        i = np.arange(n+1).reshape([-1]+[1]*a.ndim)  # orthogonal to other axes
+        i = self._preserve_type(i)
+        n_choose_i = special.binom(n, i)
+        with np.errstate(invalid='ignore'):  # can happen with infinite moment
+            moment_b = np.sum(n_choose_i*moment_as*(a-b)**(n-i), axis=0)
+        return moment_b
+
+    def _logmoment(self, order=1, *, logcenter=None, standardized=False):
+        # make this private until it is worked into moment
+        if logcenter is None or standardized is True:
+            logmean = self._logmoment_quad(self._one, -np.inf, **self._parameters)
+        else:
+            logmean = None
+
+        logcenter = logmean if logcenter is None else logcenter
+        res = self._logmoment_quad(order, logcenter, **self._parameters)
+        if standardized:
+            logvar = self._logmoment_quad(2, logmean, **self._parameters)
+            res = res - logvar * (order/2)
+        return res
+
+    def _logmoment_quad(self, order, logcenter, **params):
+        def logintegrand(x, order, logcenter, **params):
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf + order * _logexpxmexpy(np.log(x + 0j), logcenter)
+            ## if logx == logcenter, `_logexpxmexpy` returns (-inf + 0j)
+            ## multiplying by order produces (-inf + nan j) - bad
+            ## We're skipping logmoment tests, so we might don't need to fix
+            ## now, but if we ever do use run them, this might help:
+            # logx = np.log(x+0j)
+            # out = np.asarray(logpdf + order*_logexpxmexpy(logx, logcenter))
+            # i = (logx == logcenter)
+            # out[i] = logpdf[i]
+            # return out
+        return self._quadrature(logintegrand, args=(order, logcenter),
+                                params=params, log=True)
+
+    ### Convenience
+
+    def plot(self, x='x', y='pdf', *, t=('cdf', 0.0005, 0.9995), ax=None):
+        r"""Plot a function of the distribution.
+
+        Convenience function for quick visualization of the distribution
+        underlying the random variable.
+
+        Parameters
+        ----------
+        x, y : str, optional
+            String indicating the quantities to be used as the abscissa and
+            ordinate (horizontal and vertical coordinates), respectively.
+            Defaults are ``'x'`` (the domain of the random variable) and
+            ``'pdf'`` (the probability density function). Valid values are:
+            'x', 'pdf', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logpdf', 'logcdf',
+            'logccdf', 'ilogcdf', 'ilogccdf'.
+        t : 3-tuple of (str, float, float), optional
+            Tuple indicating the limits within which the quantities are plotted.
+            Default is ``('cdf', 0.001, 0.999)`` indicating that the central
+            99.9% of the distribution is to be shown. Valid values are:
+            'x', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logcdf', 'logccdf',
+            'ilogcdf', 'ilogccdf'.
+        ax : `matplotlib.axes`, optional
+            Axes on which to generate the plot. If not provided, use the
+            current axes.
+
+        Returns
+        -------
+        ax : `matplotlib.axes`
+            Axes on which the plot was generated.
+            The plot can be customized by manipulating this object.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> import matplotlib.pyplot as plt
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Plot the PDF over the central 99.9% of the distribution.
+        Compare against a histogram of a random sample.
+
+        >>> ax = X.plot()
+        >>> sample = X.sample(10000)
+        >>> ax.hist(sample, density=True, bins=50, alpha=0.5)
+        >>> plt.show()
+
+        Plot ``logpdf(x)`` as a function of ``x`` in the left tail,
+        where the log of the CDF is between -10 and ``np.log(0.5)``.
+
+        >>> X.plot('x', 'logpdf', t=('logcdf', -10, np.log(0.5)))
+        >>> plt.show()
+
+        Plot the PDF of the normal distribution as a function of the
+        CDF for various values of the scale parameter.
+
+        >>> X = stats.Normal(mu=0., sigma=[0.5, 1., 2])
+        >>> X.plot('cdf', 'pdf')
+        >>> plt.show()
+
+        """
+
+        # Strategy: given t limits, get quantile limits. Form grid of
+        # quantiles, compute requested x and y at quantiles, and plot.
+        # Currently, the grid of quantiles is always linearly spaced.
+        # Instead of always computing linearly-spaced quantiles, it
+        # would be better to choose:
+        # a) quantiles or probabilities
+        # b) linearly or logarithmically spaced
+        # based on the specified `t`.
+        # TODO:
+        # - smart spacing of points
+        # - when the parameters of the distribution are an array,
+        #   use the full range of abscissae for all curves
+
+        t_is_quantile = {'x', 'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'}
+        t_is_probability = {'cdf', 'ccdf', 'logcdf', 'logccdf'}
+        valid_t = t_is_quantile.union(t_is_probability)
+        valid_xy =  valid_t.union({'pdf', 'logpdf'})
+
+        ndim = self._ndim
+        x_name, y_name = x, y
+        t_name, tlim = t[0], np.asarray(t[1:])
+        tlim = tlim[:, np.newaxis] if ndim else tlim
+
+        # pdf/logpdf are not valid for `t` because we can't easily invert them
+        message = (f'Argument `t` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_t}')
+        if t_name not in valid_t:
+            raise ValueError(message)
+
+        message = (f'Argument `x` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_xy}')
+        if x_name not in valid_xy:
+            raise ValueError(message)
+
+        message = (f'Argument `y` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_xy}')
+        if t_name not in valid_xy:
+            raise ValueError(message)
+
+        # This could just be a warning
+        message = (f'`{self.__class__.__name__}.plot` was called on a random '
+                   'variable with at least one invalid shape parameters. When '
+                   'a parameter is invalid, no plot can be shown.')
+        if self._any_invalid:
+            raise ValueError(message)
+
+        # We could automatically ravel, but do we want to? For now, raise.
+        message = ("To use `plot`, distribution parameters must be "
+                   "scalars or arrays with one or fewer dimensions.")
+        if ndim > 1:
+            raise ValueError(message)
+
+        try:
+            import matplotlib.pyplot as plt  # noqa: F401, E402
+        except ModuleNotFoundError as exc:
+            message = ("`matplotlib` must be installed to use "
+                       f"`{self.__class__.__name__}.plot`.")
+            raise ModuleNotFoundError(message) from exc
+        ax = plt.gca() if ax is None else ax
+
+        # get quantile limits given t limits
+        qlim = tlim if t_name in t_is_quantile else getattr(self, 'i'+t_name)(tlim)
+
+        message = (f"`{self.__class__.__name__}.plot` received invalid input for `t`: "
+                   f"calling {'i'+t_name}({tlim}) produced {qlim}.")
+        if not np.all(np.isfinite(qlim)):
+            raise ValueError(message)
+
+        # form quantile grid
+        grid = np.linspace(0, 1, 300)
+        grid = grid[:, np.newaxis] if ndim else grid
+        q = qlim[0] + (qlim[1] - qlim[0]) * grid
+
+        # compute requested x and y at quantile grid
+        x = q if x_name in t_is_quantile else getattr(self, x_name)(q)
+        y = q if y_name in t_is_quantile else getattr(self, y_name)(q)
+
+        # make plot
+        ax.plot(x, y)
+        ax.set_xlabel(f"${x_name}$")
+        ax.set_ylabel(f"${y_name}$")
+        ax.set_title(str(self))
+
+        # only need a legend if distribution has parameters
+        if len(self._parameters):
+            label = []
+            parameters = self._parameterization.parameters
+            param_names = list(parameters)
+            param_arrays = [np.atleast_1d(self._parameters[pname])
+                            for pname in param_names]
+            for param_vals in zip(*param_arrays):
+                assignments = [f"${parameters[name].symbol}$ = {val:.4g}"
+                               for name, val in zip(param_names, param_vals)]
+                label.append(", ".join(assignments))
+            ax.legend(label)
+
+        return ax
+
+
+    ### Fitting
+    # All methods above treat the distribution parameters as fixed, and the
+    # variable argument may be a quantile or probability. The fitting functions
+    # are fundamentally different because the quantiles (often observations)
+    # are considered to be fixed, and the distribution parameters are the
+    # variables. In a sense, they are like an inverse of the sampling
+    # functions.
+    #
+    # At first glance, it would seem ideal for `fit` to be a classmethod,
+    # called like `LogUniform.fit(sample=sample)`.
+    # I tried this. I insisted on it for a while. But if `fit` is a
+    # classmethod, it cannot call instance methods. If we want to support MLE,
+    # MPS, MoM, MoLM, then we end up with most of the distribution functions
+    # above needing to be classmethods, too. All state information, such as
+    # tolerances and the underlying distribution of `ShiftedScaledDistribution`
+    # and `OrderStatisticDistribution`, would need to be passed into all
+    # methods. And I'm not really sure how we would call `fit` as a
+    # classmethod of a transformed distribution - maybe
+    # ShiftedScaledDistribution.fit would accept the class of the
+    # shifted/scaled distribution as an argument?
+    #
+    # In any case, it was a conscious decision for the infrastructure to
+    # treat the parameters as "fixed" and the quantile/percentile arguments
+    # as "variable". There are a lot of advantages to this structure, and I
+    # don't think the fact that a few methods reverse the fixed and variable
+    # quantities should make us question that choice. It can still accomodate
+    # these methods reasonably efficiently.
+
+
+# Special case the names of some new-style distributions in `make_distribution`
+_distribution_names = {
+    'argus': 'ARGUS',
+    'betaprime': 'BetaPrime',
+    'chi2': 'ChiSquared',
+    'crystalball': 'CrystalBall',
+    'dgamma': 'DoubleGamma',
+    'dweibull': 'DoubleWeibull',
+    'expon': 'Exponential',
+    'exponnorm': 'ExponentiallyModifiedNormal',
+    'exponweib': 'ExponentialWeibull',
+    'exponpow': 'ExponentialPower',
+    'fatiguelife': 'FatigueLife',
+    'foldcauchy': 'FoldedCauchy',
+    'foldnorm': 'FoldedNormal',
+    'genlogistic': 'GeneralizedLogistic',
+    'gennorm': 'GeneralizedNormal',
+    'genpareto': 'GeneralizedPareto',
+    'genexpon': 'GeneralizedExponential',
+    'genextreme': 'GeneralizedExtremeValue',
+    'gausshyper': 'GaussHypergeometric',
+    'gengamma': 'GeneralizedGamma',
+    'genhalflogistic': 'GeneralizedHalfLogistic',
+    'geninvgauss': 'GeneralizedInverseGaussian',
+    'gumbel_r': 'Gumbel',
+    'gumbel_l': 'ReflectedGumbel',
+    'halfcauchy': 'HalfCauchy',
+    'halflogistic': 'HalfLogistic',
+    'halfnorm': 'HalfNormal',
+    'halfgennorm': 'HalfGeneralizedNormal',
+    'hypsecant': 'HyperbolicSecant',
+    'invgamma': 'InverseGammma',
+    'invgauss': 'InverseGaussian',
+    'invweibull': 'InverseWeibull',
+    'irwinhall': 'IrwinHall',
+    'jf_skew_t': 'JonesFaddySkewT',
+    'johnsonsb': 'JohnsonSB',
+    'johnsonsu': 'JohnsonSU',
+    'ksone': 'KSOneSided',
+    'kstwo': 'KSTwoSided',
+    'kstwobign': 'KSTwoSidedAsymptotic',
+    'laplace_asymmetric': 'LaplaceAsymmetric',
+    'levy_l': 'LevyLeft',
+    'levy_stable': 'LevyStable',
+    'loggamma': 'ExpGamma',  # really the Exponential Gamma Distribution
+    'loglaplace': 'LogLaplace',
+    'lognorm': 'LogNormal',
+    'loguniform': 'LogUniform',
+    'ncx2': 'NoncentralChiSquared',
+    'nct': 'NoncentralT',
+    'norm': 'Normal',
+    'norminvgauss': 'NormalInverseGaussian',
+    'powerlaw': 'PowerLaw',
+    'powernorm': 'PowerNormal',
+    'rdist': 'R',
+    'rel_breitwigner': 'RelativisticBreitWigner',
+    'recipinvgauss': 'ReciprocalInverseGaussian',
+    'reciprocal': 'LogUniform',
+    'semicircular': 'SemiCircular',
+    'skewcauchy': 'SkewCauchy',
+    'skewnorm': 'SkewNormal',
+    'studentized_range': 'StudentizedRange',
+    't': 'StudentT',
+    'trapezoid': 'Trapezoidal',
+    'triang': 'Triangular',
+    'truncexpon': 'TruncatedExponential',
+    'truncnorm': 'TruncatedNormal',
+    'truncpareto': 'TruncatedPareto',
+    'truncweibull_min': 'TruncatedWeibull',
+    'tukeylambda': 'TukeyLambda',
+    'vonmises_line': 'VonMisesLine',
+    'weibull_min': 'Weibull',
+    'weibull_max': 'ReflectedWeibull',
+    'wrapcauchy': 'WrappedCauchyLine',
+}
+
+
+# beta, genextreme, gengamma, t, tukeylambda need work for 1D arrays
+def make_distribution(dist):
+    """Generate a `ContinuousDistribution` from an instance of `rv_continuous`
+
+    The returned value is a `ContinuousDistribution` subclass. Like any subclass
+    of `ContinuousDistribution`, it must be instantiated (i.e. by passing all shape
+    parameters as keyword arguments) before use. Once instantiated, the resulting
+    object will have the same interface as any other instance of
+    `ContinuousDistribution`; e.g., `scipy.stats.Normal`.
+
+    .. note::
+
+        `make_distribution` does not work perfectly with all instances of
+        `rv_continuous`. Known failures include `levy_stable` and `vonmises`,
+        and some methods of some distributions will not support array shape
+        parameters.
+
+    Parameters
+    ----------
+    dist : `rv_continuous`
+        Instance of `rv_continuous`.
+
+    Returns
+    -------
+    CustomDistribution : `ContinuousDistribution`
+        A subclass of `ContinuousDistribution` corresponding with `dist`. The
+        initializer requires all shape parameters to be passed as keyword arguments
+        (using the same names as the instance of `rv_continuous`).
+
+    Notes
+    -----
+    The documentation of `ContinuousDistribution` is not rendered. See below for
+    an example of how to instantiate the class (i.e. pass all shape parameters of
+    `dist` to the initializer as keyword arguments). Documentation of all methods
+    is identical to that of `scipy.stats.Normal`. Use ``help`` on the returned
+    class or its methods for more information.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> LogU = stats.make_distribution(stats.loguniform)
+    >>> X = LogU(a=1.0, b=3.0)
+    >>> np.isclose((X + 0.25).median(), stats.loguniform.ppf(0.5, 1, 3, loc=0.25))
+    np.True_
+    >>> X.plot()
+    >>> sample = X.sample(10000, rng=np.random.default_rng())
+    >>> plt.hist(sample, density=True, bins=30)
+    >>> plt.legend(('pdf', 'histogram'))
+    >>> plt.show()
+
+    """
+    if dist in {stats.levy_stable, stats.vonmises}:
+        raise NotImplementedError(f"`{dist.name}` is not supported.")
+
+    if not isinstance(dist, stats.rv_continuous):
+        message = "The argument must be an instance of `rv_continuous`."
+        raise ValueError(message)
+
+    parameters = []
+    names = []
+    support = getattr(dist, '_support', (dist.a, dist.b))
+    for shape_info in dist._shape_info():
+        domain = _RealDomain(endpoints=shape_info.endpoints,
+                             inclusive=shape_info.inclusive)
+        param = _RealParameter(shape_info.name, domain=domain)
+        parameters.append(param)
+        names.append(shape_info.name)
+
+    _x_support = _RealDomain(endpoints=support, inclusive=(True, True))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1))
+
+    repr_str = _distribution_names.get(dist.name, dist.name.capitalize())
+
+    class CustomDistribution(ContinuousDistribution):
+        _parameterizations = ([_Parameterization(*parameters)] if parameters
+                              else [])
+        _variable = _x_param
+
+        def __repr__(self):
+            s = super().__repr__()
+            return s.replace('CustomDistribution', repr_str)
+
+        def __str__(self):
+            s = super().__str__()
+            return s.replace('CustomDistribution', repr_str)
+
+    # override the domain's `get_numerical_endpoints` rather than the
+    # distribution's `_support` to ensure that `_support` takes care
+    # of any required broadcasting, etc.
+    def get_numerical_endpoints(parameter_values):
+        a, b = dist._get_support(**parameter_values)
+        return np.asarray(a)[()], np.asarray(b)[()]
+
+    def _sample_formula(self, _, full_shape=(), *, rng=None, **kwargs):
+        return dist._rvs(size=full_shape, random_state=rng, **kwargs)
+
+    def _moment_raw_formula(self, order, **kwargs):
+        return dist._munp(int(order), **kwargs)
+
+    def _moment_raw_formula_1(self, order, **kwargs):
+        if order != 1:
+            return None
+        return dist._stats(**kwargs)[0]
+
+    def _moment_central_formula(self, order, **kwargs):
+        if order != 2:
+            return None
+        return dist._stats(**kwargs)[1]
+
+    def _moment_standard_formula(self, order, **kwargs):
+        if order == 3:
+            if dist._stats_has_moments:
+                kwargs['moments'] = 's'
+            return dist._stats(**kwargs)[int(order - 1)]
+        elif order == 4:
+            if dist._stats_has_moments:
+                kwargs['moments'] = 'k'
+            k = dist._stats(**kwargs)[int(order - 1)]
+            return k if k is None else k + 3
+        else:
+            return None
+
+    methods = {'_logpdf': '_logpdf_formula',
+               '_pdf': '_pdf_formula',
+               '_logcdf': '_logcdf_formula',
+               '_cdf': '_cdf_formula',
+               '_logsf': '_logccdf_formula',
+               '_sf': '_ccdf_formula',
+               '_ppf': '_icdf_formula',
+               '_isf': '_iccdf_formula',
+               '_entropy': '_entropy_formula',
+               '_median': '_median_formula'}
+
+    # These are not desirable overrides for the new infrastructure
+    skip_override = {'norminvgauss': {'_sf', '_isf'}}
+
+    for old_method, new_method in methods.items():
+        if dist.name in skip_override and old_method in skip_override[dist.name]:
+            continue
+        # If method of old distribution overrides generic implementation...
+        method = getattr(dist.__class__, old_method, None)
+        super_method = getattr(stats.rv_continuous, old_method, None)
+        if method is not super_method:
+            # Make it an attribute of the new object with the new name
+            setattr(CustomDistribution, new_method, getattr(dist, old_method))
+
+    def _overrides(method_name):
+        return (getattr(dist.__class__, method_name, None)
+                is not getattr(stats.rv_continuous, method_name, None))
+
+    if _overrides('_get_support'):
+        domain = CustomDistribution._variable.domain
+        domain.get_numerical_endpoints = get_numerical_endpoints
+
+    if _overrides('_munp'):
+        CustomDistribution._moment_raw_formula = _moment_raw_formula
+
+    if _overrides('_rvs'):
+        CustomDistribution._sample_formula = _sample_formula
+
+    if _overrides('_stats'):
+        CustomDistribution._moment_standardized_formula = _moment_standard_formula
+        if not _overrides('_munp'):
+            CustomDistribution._moment_raw_formula = _moment_raw_formula_1
+            CustomDistribution._moment_central_formula = _moment_central_formula
+
+    support_etc = _combine_docs(CustomDistribution, include_examples=False).lstrip()
+    docs = [
+        f"This class represents `scipy.stats.{dist.name}` as a subclass of "
+        "`ContinuousDistribution`.",
+        f"The `repr`/`str` of class instances is `{repr_str}`.",
+        f"The PDF of the distribution is defined {support_etc}"
+    ]
+    CustomDistribution.__doc__ = ("\n".join(docs))
+
+    return CustomDistribution
+
+
+# Rough sketch of how we might shift/scale distributions. The purpose of
+# making it a separate class is for
+# a) simplicity of the ContinuousDistribution class and
+# b) avoiding the requirement that every distribution accept loc/scale.
+# The simplicity of ContinuousDistribution is important, because there are
+# several other distribution transformations to be supported; e.g., truncation,
+# wrapping, folding, and doubling. We wouldn't want to cram all of this
+# into the `ContinuousDistribution` class. Also, the order of the composition
+# matters (e.g. truncate then shift/scale or vice versa). It's easier to
+# accommodate different orders if the transformation is built up from
+# components rather than all built into `ContinuousDistribution`.
+
+def _shift_scale_distribution_function_2arg(func):
+    def wrapped(self, x, y, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        xt = self._transform(x, loc, scale)
+        yt = self._transform(y, loc, scale)
+        fxy = f(xt, yt, *args, **kwargs)
+        fyx = f(yt, xt, *args, **kwargs)
+        return np.real_if_close(np.where(sign, fxy, fyx))[()]
+
+    return wrapped
+
+def _shift_scale_distribution_function(func):
+    # c is for complementary
+    citem = {'_logcdf_dispatch': '_logccdf_dispatch',
+             '_cdf_dispatch': '_ccdf_dispatch',
+             '_logccdf_dispatch': '_logcdf_dispatch',
+             '_ccdf_dispatch': '_cdf_dispatch'}
+    def wrapped(self, x, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+        cf = getattr(self._dist, citem[item])
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        xt = self._transform(x, loc, scale)
+        fx = f(xt, *args, **kwargs)
+        cfx = cf(xt, *args, **kwargs)
+        return np.where(sign, fx, cfx)[()]
+
+    return wrapped
+
+def _shift_scale_inverse_function(func):
+    citem = {'_ilogcdf_dispatch': '_ilogccdf_dispatch',
+             '_icdf_dispatch': '_iccdf_dispatch',
+             '_ilogccdf_dispatch': '_ilogcdf_dispatch',
+             '_iccdf_dispatch': '_icdf_dispatch'}
+    def wrapped(self, p, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+        cf = getattr(self._dist, citem[item])
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        fx =  self._itransform(f(p, *args, **kwargs), loc, scale)
+        cfx = self._itransform(cf(p, *args, **kwargs), loc, scale)
+        return np.where(sign, fx, cfx)[()]
+
+    return wrapped
+
+
+class TransformedDistribution(ContinuousDistribution):
+    def __init__(self, X, /, *args, **kwargs):
+        self._copy_parameterization()
+        self._variable = X._variable
+        self._dist = X
+        if X._parameterization:
+            # Add standard distribution parameters to our parameterization
+            dist_parameters = X._parameterization.parameters
+            set_params = set(dist_parameters)
+            if not self._parameterizations:
+                self._parameterizations.append(_Parameterization())
+            for parameterization in self._parameterizations:
+                if set_params.intersection(parameterization.parameters):
+                    message = (f"One or more of the parameters of {X} has "
+                               "the same name as a parameter of "
+                               f"{self.__class__.__name__}. Name collisions "
+                               "create ambiguities and are not supported.")
+                    raise ValueError(message)
+                parameterization.parameters.update(dist_parameters)
+        super().__init__(*args, **kwargs)
+
+    def _overrides(self, method_name):
+        return (self._dist._overrides(method_name)
+                or super()._overrides(method_name))
+
+    def reset_cache(self):
+        self._dist.reset_cache()
+        super().reset_cache()
+
+    def _update_parameters(self, *, validation_policy=None, **params):
+        # maybe broadcast everything before processing?
+        parameters = {}
+        # There may be some issues with _original_parameters
+        # We only want to update with _dist._original_parameters during
+        # initialization. Afterward that, we want to start with
+        # self._original_parameters.
+        parameters.update(self._dist._original_parameters)
+        parameters.update(params)
+        super()._update_parameters(validation_policy=validation_policy, **parameters)
+
+    def _process_parameters(self, **params):
+        return self._dist._process_parameters(**params)
+
+    def __repr__(self):
+        raise NotImplementedError()
+
+    def __str__(self):
+        raise NotImplementedError()
+
+
+class TruncatedDistribution(TransformedDistribution):
+    """Truncated distribution."""
+    # TODO:
+    # - consider avoiding catastropic cancellation by using appropriate tail
+    # - if the mode of `_dist` is within the support, it's still the mode
+    # - rejection sampling might be more efficient than inverse transform
+
+    _lb_domain = _RealDomain(endpoints=(-inf, 'ub'), inclusive=(True, False))
+    _lb_param = _RealParameter('lb', symbol=r'b_l',
+                                domain=_lb_domain, typical=(0.1, 0.2))
+
+    _ub_domain = _RealDomain(endpoints=('lb', inf), inclusive=(False, True))
+    _ub_param = _RealParameter('ub', symbol=r'b_u',
+                                  domain=_ub_domain, typical=(0.8, 0.9))
+
+    _parameterizations = [_Parameterization(_lb_param, _ub_param),
+                          _Parameterization(_lb_param),
+                          _Parameterization(_ub_param)]
+
+    def __init__(self, X, /, *args, lb=-np.inf, ub=np.inf, **kwargs):
+        return super().__init__(X, *args, lb=lb, ub=ub, **kwargs)
+
+    def _process_parameters(self, lb=None, ub=None, **params):
+        lb = lb if lb is not None else np.full_like(lb, -np.inf)[()]
+        ub = ub if ub is not None else np.full_like(ub, np.inf)[()]
+        parameters = self._dist._process_parameters(**params)
+        a, b = self._support(lb=lb, ub=ub, **parameters)
+        logmass = self._dist._logcdf2_dispatch(a, b, **parameters)
+        parameters.update(dict(lb=lb, ub=ub, _a=a, _b=b, logmass=logmass))
+        return parameters
+
+    def _support(self, lb, ub, **params):
+        a, b = self._dist._support(**params)
+        return np.maximum(a, lb), np.minimum(b, ub)
+
+    def _overrides(self, method_name):
+        return False
+
+    def _logpdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logpdf = self._dist._logpdf_dispatch(x, *args, **params)
+        return logpdf - logmass
+
+    def _logcdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logcdf = self._dist._logcdf2_dispatch(_a, x, *args, **params)
+        # of course, if this result is small we could compute with the other tail
+        return logcdf - logmass
+
+    def _logccdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logccdf = self._dist._logcdf2_dispatch(x, _b, *args, **params)
+        return logccdf - logmass
+
+    def _logcdf2_dispatch(self, x, y, *args, lb, ub, _a, _b, logmass, **params):
+        logcdf2 = self._dist._logcdf2_dispatch(x, y, *args, **params)
+        return logcdf2 - logmass
+
+    def _ilogcdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
+        log_Fa = self._dist._logcdf_dispatch(_a, *args, **params)
+        logp_adjusted = np.logaddexp(log_Fa, logp + logmass)
+        return self._dist._ilogcdf_dispatch(logp_adjusted, *args, **params)
+
+    def _ilogccdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
+        log_cFb = self._dist._logccdf_dispatch(_b, *args, **params)
+        logp_adjusted = np.logaddexp(log_cFb, logp + logmass)
+        return self._dist._ilogccdf_dispatch(logp_adjusted, *args, **params)
+
+    def _icdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
+        Fa = self._dist._cdf_dispatch(_a, *args, **params)
+        p_adjusted = Fa + p*np.exp(logmass)
+        return self._dist._icdf_dispatch(p_adjusted, *args, **params)
+
+    def _iccdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
+        cFb = self._dist._ccdf_dispatch(_b, *args, **params)
+        p_adjusted = cFb + p*np.exp(logmass)
+        return self._dist._iccdf_dispatch(p_adjusted, *args, **params)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return (f"truncate({repr(self._dist)}, "
+                    f"lb={repr(self.lb)}, ub={repr(self.ub)})")
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return (f"truncate({str(self._dist)}, "
+                    f"lb={str(self.lb)}, ub={str(self.ub)})")
+
+
+def truncate(X, lb=-np.inf, ub=np.inf):
+    """Truncate the support of a random variable.
+
+    Given a random variable `X`, `truncate` returns a random variable with
+    support truncated to the interval between `lb` and `ub`. The underlying
+    probability density function is normalized accordingly.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable to be truncated.
+    lb, ub : float array-like
+        The lower and upper truncation points, respectively. Must be
+        broadcastable with one another and the shape of `X`.
+
+    Returns
+    -------
+    X : `ContinuousDistribution`
+        The truncated random variable.
+
+    References
+    ----------
+    .. [1] "Truncated Distribution". *Wikipedia*.
+           https://en.wikipedia.org/wiki/Truncated_distribution
+
+    Examples
+    --------
+    Compare against `scipy.stats.truncnorm`, which truncates a standard normal,
+    *then* shifts and scales it.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> loc, scale, lb, ub = 1, 2, -2, 2
+    >>> X = stats.truncnorm(lb, ub, loc, scale)
+    >>> Y = scale * stats.truncate(stats.Normal(), lb, ub) + loc
+    >>> x = np.linspace(-3, 5, 300)
+    >>> plt.plot(x, X.pdf(x), '-', label='X')
+    >>> plt.plot(x, Y.pdf(x), '--', label='Y')
+    >>> plt.xlabel('x')
+    >>> plt.ylabel('PDF')
+    >>> plt.title('Truncated, then Shifted/Scaled Normal')
+    >>> plt.legend()
+    >>> plt.show()
+
+    However, suppose we wish to shift and scale a normal random variable,
+    then truncate its support to given values. This is straightforward with
+    `truncate`.
+
+    >>> Z = stats.truncate(scale * stats.Normal() + loc, lb, ub)
+    >>> Z.plot()
+    >>> plt.show()
+
+    Furthermore, `truncate` can be applied to any random variable:
+
+    >>> Rayleigh = stats.make_distribution(stats.rayleigh)
+    >>> W = stats.truncate(Rayleigh(), lb=0, ub=3)
+    >>> W.plot()
+    >>> plt.show()
+
+    """
+    return TruncatedDistribution(X, lb=lb, ub=ub)
+
+
+class ShiftedScaledDistribution(TransformedDistribution):
+    """Distribution with a standard shift/scale transformation."""
+    # Unclear whether infinite loc/scale will work reasonably in all cases
+    _loc_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True))
+    _loc_param = _RealParameter('loc', symbol=r'\mu',
+                                domain=_loc_domain, typical=(1, 2))
+
+    _scale_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True))
+    _scale_param = _RealParameter('scale', symbol=r'\sigma',
+                                  domain=_scale_domain, typical=(0.1, 10))
+
+    _parameterizations = [_Parameterization(_loc_param, _scale_param),
+                          _Parameterization(_loc_param),
+                          _Parameterization(_scale_param)]
+
+    def _process_parameters(self, loc=None, scale=None, **params):
+        loc = loc if loc is not None else np.zeros_like(scale)[()]
+        scale = scale if scale is not None else np.ones_like(loc)[()]
+        sign = scale > 0
+        parameters = self._dist._process_parameters(**params)
+        parameters.update(dict(loc=loc, scale=scale, sign=sign))
+        return parameters
+
+    def _transform(self, x, loc, scale, **kwargs):
+        return (x - loc)/scale
+
+    def _itransform(self, x, loc, scale, **kwargs):
+        return x * scale + loc
+
+    def _support(self, loc, scale, sign, **params):
+        # Add shortcut for infinite support?
+        a, b = self._dist._support(**params)
+        a, b = self._itransform(a, loc, scale), self._itransform(b, loc, scale)
+        return np.where(sign, a, b)[()], np.where(sign, b, a)[()]
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            result =  f"{repr(self.scale)}*{repr(self._dist)}"
+            if not self.loc.ndim and self.loc < 0:
+                result += f" - {repr(-self.loc)}"
+            elif (np.any(self.loc != 0)
+                  or not np.can_cast(self.loc.dtype, self.scale.dtype)):
+                # We don't want to hide a zero array loc if it can cause
+                # a type promotion.
+                result += f" + {repr(self.loc)}"
+        return result
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            result =  f"{str(self.scale)}*{str(self._dist)}"
+            if not self.loc.ndim and self.loc < 0:
+                result += f" - {str(-self.loc)}"
+            elif (np.any(self.loc != 0)
+                  or not np.can_cast(self.loc.dtype, self.scale.dtype)):
+                # We don't want to hide a zero array loc if it can cause
+                # a type promotion.
+                result += f" + {str(self.loc)}"
+        return result
+
+    # Here, we override all the `_dispatch` methods rather than the public
+    # methods or _function methods. Why not the public methods?
+    # If we were to override the public methods, then other
+    # TransformedDistribution classes (which could transform a
+    # ShiftedScaledDistribution) would need to call the public methods of
+    # ShiftedScaledDistribution, which would run the input validation again.
+    # Why not the _function methods? For distributions that rely on the
+    # default implementation of methods (e.g. `quadrature`, `inversion`),
+    # the implementation would "see" the location and scale like other
+    # distribution parameters, so they could affect the accuracy of the
+    # calculations. I think it is cleaner if `loc` and `scale` do not affect
+    # the underlying calculations at all.
+
+    def _entropy_dispatch(self, *args, loc, scale, sign, **params):
+        return (self._dist._entropy_dispatch(*args, **params)
+                + np.log(np.abs(scale)))
+
+    def _logentropy_dispatch(self, *args, loc, scale, sign, **params):
+        lH0 = self._dist._logentropy_dispatch(*args, **params)
+        lls = np.log(np.log(np.abs(scale))+0j)
+        return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0)
+
+    def _median_dispatch(self, *, method, loc, scale, sign, **params):
+        raw = self._dist._median_dispatch(method=method, **params)
+        return self._itransform(raw, loc, scale)
+
+    def _mode_dispatch(self, *, method, loc, scale, sign, **params):
+        raw = self._dist._mode_dispatch(method=method, **params)
+        return self._itransform(raw, loc, scale)
+
+    def _logpdf_dispatch(self, x, *args, loc, scale, sign, **params):
+        x = self._transform(x, loc, scale)
+        logpdf = self._dist._logpdf_dispatch(x, *args, **params)
+        return logpdf - np.log(np.abs(scale))
+
+    def _pdf_dispatch(self, x, *args, loc, scale, sign, **params):
+        x = self._transform(x, loc, scale)
+        pdf = self._dist._pdf_dispatch(x, *args, **params)
+        return pdf / np.abs(scale)
+
+    # Sorry about the magic. This is just a draft to show the behavior.
+    @_shift_scale_distribution_function
+    def _logcdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _cdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _logccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _ccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _logcdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _cdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _logccdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _ccdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _ilogcdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _icdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _ilogccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _iccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    def _moment_standardized_dispatch(self, order, *, loc, scale, sign, methods,
+                                      **params):
+        res = (self._dist._moment_standardized_dispatch(
+            order, methods=methods, **params))
+        return None if res is None else res * np.sign(scale)**order
+
+    def _moment_central_dispatch(self, order, *, loc, scale, sign, methods,
+                                 **params):
+        res = (self._dist._moment_central_dispatch(
+            order, methods=methods, **params))
+        return None if res is None else res * scale**order
+
+    def _moment_raw_dispatch(self, order, *, loc, scale, sign, methods,
+                             **params):
+        raw_moments = []
+        methods_highest_order = methods
+        for i in range(int(order) + 1):
+            methods = (self._moment_methods if i < order
+                       else methods_highest_order)
+            raw = self._dist._moment_raw_dispatch(i, methods=methods, **params)
+            if raw is None:
+                return None
+            moment_i = raw * scale**i
+            raw_moments.append(moment_i)
+
+        return self._moment_transform_center(
+            order, raw_moments, loc, self._zero)
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         rng, loc, scale, sign, method, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return self._itransform(rvs, loc=loc, scale=scale, sign=sign, **params)
+
+    def __add__(self, loc):
+        return ShiftedScaledDistribution(self._dist, loc=self.loc + loc,
+                                         scale=self.scale)
+
+    def __sub__(self, loc):
+        return ShiftedScaledDistribution(self._dist, loc=self.loc - loc,
+                                         scale=self.scale)
+
+    def __mul__(self, scale):
+        return ShiftedScaledDistribution(self._dist,
+                                         loc=self.loc * scale,
+                                         scale=self.scale * scale)
+
+    def __truediv__(self, scale):
+        return ShiftedScaledDistribution(self._dist,
+                                         loc=self.loc / scale,
+                                         scale=self.scale / scale)
+
+
+class OrderStatisticDistribution(TransformedDistribution):
+    r"""Probability distribution of an order statistic
+
+    An instance of this class represents a random variable that follows the
+    distribution underlying the :math:`r^{\text{th}}` order statistic of a
+    sample of :math:`n` observations of a random variable :math:`X`.
+
+    Parameters
+    ----------
+    dist : `ContinuousDistribution`
+        The random variable :math:`X`
+    n : array_like
+        The (integer) sample size :math:`n`
+    r : array_like
+        The (integer) rank of the order statistic :math:`r`
+
+
+    Notes
+    -----
+    If we make :math:`n` observations of a continuous random variable
+    :math:`X` and sort them in increasing order
+    :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`,
+    :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic.
+
+    If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`,
+    :math:`F`, and :math:`F'`, respectively, then the PDF underlying
+    math:`X_{(r)}` is given by:
+
+    .. math::
+
+        f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r}
+
+    The CDF and other methods of the distribution underlying :math:`X_{(r)}`
+    are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is
+    a standard uniform random variable, and that the order statistics of
+    observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`.
+
+    References
+    ----------
+    .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic
+
+    Examples
+    --------
+    Suppose we are interested in order statistics of samples of size five drawn
+    from the standard normal distribution. Plot the PDF underlying the fourth
+    order statistic and compare with a normalized histogram from simulation.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> from scipy.stats._distribution_infrastructure import OrderStatisticDistribution
+    >>>
+    >>> X = stats.Normal()
+    >>> data = X.sample(shape=(10000, 5))
+    >>> ranks = np.sort(data, axis=1)
+    >>> Y = OrderStatisticDistribution(X, r=4, n=5)
+    >>>
+    >>> ax = plt.gca()
+    >>> Y.plot(ax=ax)
+    >>> ax.hist(ranks[:, 3], density=True, bins=30)
+    >>> plt.show()
+
+    """
+
+    # These can be restricted to _IntegerDomain/_IntegerParameter in a separate
+    # PR if desired.
+    _r_domain = _RealDomain(endpoints=(1, 'n'), inclusive=(True, True))
+    _r_param = _RealParameter('r', domain=_r_domain, typical=(1, 2))
+
+    _n_domain = _RealDomain(endpoints=(1, np.inf), inclusive=(True, True))
+    _n_param = _RealParameter('n', domain=_n_domain, typical=(1, 4))
+
+    _r_domain.define_parameters(_n_param)
+
+    _parameterizations = [_Parameterization(_r_param, _n_param)]
+
+    def __init__(self, dist, /, *args, r, n, **kwargs):
+        super().__init__(dist, *args, r=r, n=n, **kwargs)
+
+    def _support(self, *args, r, n, **kwargs):
+        return self._dist._support(*args, **kwargs)
+
+    def _process_parameters(self, r=None, n=None, **params):
+        parameters = self._dist._process_parameters(**params)
+        parameters.update(dict(r=r, n=n))
+        return parameters
+
+    def _overrides(self, method_name):
+        return method_name in {'_logpdf_formula', '_pdf_formula',
+                               '_cdf_formula', '_ccdf_formula',
+                               '_icdf_formula', '_iccdf_formula'}
+
+    def _logpdf_formula(self, x, r, n, **kwargs):
+        log_factor = special.betaln(r, n - r + 1)
+        log_fX = self._dist._logpdf_dispatch(x, **kwargs)
+        # log-methods sometimes use complex dtype with 0 imaginary component,
+        # but `_tanhsinh` doesn't accept complex limits of integration; take `real`.
+        log_FX = self._dist._logcdf_dispatch(x.real, **kwargs)
+        log_cFX = self._dist._logccdf_dispatch(x.real, **kwargs)
+        # This can be problematic when (r - 1)|(n-r) = 0 and `log_FX`|log_cFX = -inf
+        # The PDF in these cases is 0^0, so these should be replaced with log(1)=0
+        # return log_fX + (r-1)*log_FX + (n-r)*log_cFX - log_factor
+        rm1_log_FX = np.where((r - 1 == 0) & np.isneginf(log_FX), 0, (r-1)*log_FX)
+        nmr_log_cFX = np.where((n - r == 0) & np.isneginf(log_cFX), 0, (n-r)*log_cFX)
+        return log_fX + rm1_log_FX + nmr_log_cFX - log_factor
+
+    def _pdf_formula(self, x, r, n, **kwargs):
+        # 1 / factor = factorial(n) / (factorial(r-1) * factorial(n-r))
+        factor = special.beta(r, n - r + 1)
+        fX = self._dist._pdf_dispatch(x, **kwargs)
+        FX = self._dist._cdf_dispatch(x, **kwargs)
+        cFX = self._dist._ccdf_dispatch(x, **kwargs)
+        return fX * FX**(r-1) * cFX**(n-r) / factor
+
+    def _cdf_formula(self, x, r, n, **kwargs):
+        x_ = self._dist._cdf_dispatch(x, **kwargs)
+        return special.betainc(r, n-r+1, x_)
+
+    def _ccdf_formula(self, x, r, n, **kwargs):
+        x_ = self._dist._cdf_dispatch(x, **kwargs)
+        return special.betaincc(r, n-r+1, x_)
+
+    def _icdf_formula(self, p, r, n, **kwargs):
+        p_ = special.betaincinv(r, n-r+1, p)
+        return self._dist._icdf_dispatch(p_, **kwargs)
+
+    def _iccdf_formula(self, p, r, n, **kwargs):
+        p_ = special.betainccinv(r, n-r+1, p)
+        return self._dist._icdf_dispatch(p_, **kwargs)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return (f"order_statistic({repr(self._dist)}, r={repr(self.r)}, "
+                    f"n={repr(self.n)})")
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return (f"order_statistic({str(self._dist)}, r={str(self.r)}, "
+                    f"n={str(self.n)})")
+
+
+def order_statistic(X, /, *, r, n):
+    r"""Probability distribution of an order statistic
+
+    Returns a random variable that follows the distribution underlying the
+    :math:`r^{\text{th}}` order statistic of a sample of :math:`n`
+    observations of a random variable :math:`X`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`
+    r : array_like
+        The (positive integer) rank of the order statistic :math:`r`
+    n : array_like
+        The (positive integer) sample size :math:`n`
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable that follows the distribution of the prescribed
+        order statistic.
+
+    Notes
+    -----
+    If we make :math:`n` observations of a continuous random variable
+    :math:`X` and sort them in increasing order
+    :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`,
+    :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic.
+
+    If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`,
+    :math:`F`, and :math:`F'`, respectively, then the PDF underlying
+    math:`X_{(r)}` is given by:
+
+    .. math::
+
+        f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r}
+
+    The CDF and other methods of the distribution underlying :math:`X_{(r)}`
+    are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is
+    a standard uniform random variable, and that the order statistics of
+    observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`.
+
+    References
+    ----------
+    .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic
+
+    Examples
+    --------
+    Suppose we are interested in order statistics of samples of size five drawn
+    from the standard normal distribution. Plot the PDF underlying each
+    order statistic and compare with a normalized histogram from simulation.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>>
+    >>> X = stats.Normal()
+    >>> data = X.sample(shape=(10000, 5))
+    >>> sorted = np.sort(data, axis=1)
+    >>> Y = stats.order_statistic(X, r=[1, 2, 3, 4, 5], n=5)
+    >>>
+    >>> ax = plt.gca()
+    >>> colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
+    >>> for i in range(5):
+    ...     y = sorted[:, i]
+    ...     ax.hist(y, density=True, bins=30, alpha=0.1, color=colors[i])
+    >>> Y.plot(ax=ax)
+    >>> plt.show()
+
+    """
+    r, n = np.asarray(r), np.asarray(n)
+    if np.any((r != np.floor(r)) | (r < 0)) or np.any((n != np.floor(n)) | (n < 0)):
+        message = "`r` and `n` must contain only positive integers."
+        raise ValueError(message)
+    return OrderStatisticDistribution(X, r=r, n=n)
+
+
+class Mixture(_ProbabilityDistribution):
+    r"""Representation of a mixture distribution.
+
+    A mixture distribution is the distribution of a random variable
+    defined in the following way: first, a random variable is selected
+    from `components` according to the probabilities given by `weights`, then
+    the selected random variable is realized.
+
+    Parameters
+    ----------
+    components : sequence of `ContinuousDistribution`
+        The underlying instances of `ContinuousDistribution`.
+        All must have scalar shape parameters (if any); e.g., the `pdf` evaluated
+        at a scalar argument must return a scalar.
+    weights : sequence of floats, optional
+        The corresponding probabilities of selecting each random variable.
+        Must be non-negative and sum to one. The default behavior is to weight
+        all components equally.
+
+    Attributes
+    ----------
+    components : sequence of `ContinuousDistribution`
+        The underlying instances of `ContinuousDistribution`.
+    weights : ndarray
+        The corresponding probabilities of selecting each random variable.
+
+    Methods
+    -------
+    support
+
+    sample
+
+    moment
+
+    mean
+    median
+    mode
+
+    variance
+    standard_deviation
+
+    skewness
+    kurtosis
+
+    pdf
+    logpdf
+
+    cdf
+    icdf
+    ccdf
+    iccdf
+
+    logcdf
+    ilogcdf
+    logccdf
+    ilogccdf
+
+    entropy
+
+    Notes
+    -----
+    The following abbreviations are used throughout the documentation.
+
+    - PDF: probability density function
+    - CDF: cumulative distribution function
+    - CCDF: complementary CDF
+    - entropy: differential entropy
+    - log-*F*: logarithm of *F* (e.g. log-CDF)
+    - inverse *F*: inverse function of *F* (e.g. inverse CDF)
+
+    References
+    ----------
+    .. [1] Mixture distribution, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Mixture_distribution
+
+    """
+    # Todo:
+    # Add support for array shapes, weights
+
+    def _input_validation(self, components, weights):
+        if len(components) == 0:
+            message = ("`components` must contain at least one random variable.")
+            raise ValueError(message)
+
+        for var in components:
+            # will generalize to other kinds of distributions when there
+            # *are* other kinds of distributions
+            if not isinstance(var, ContinuousDistribution):
+                message = ("Each element of `components` must be an instance of "
+                           "`ContinuousDistribution`.")
+                raise ValueError(message)
+            if not var._shape == ():
+                message = "All elements of `components` must have scalar shapes."
+                raise ValueError(message)
+
+        if weights is None:
+            return components, weights
+
+        weights = np.asarray(weights)
+        if weights.shape != (len(components),):
+            message = "`components` and `weights` must have the same length."
+            raise ValueError(message)
+
+        if not np.issubdtype(weights.dtype, np.inexact):
+            message = "`weights` must have floating point dtype."
+            raise ValueError(message)
+
+        if not np.isclose(np.sum(weights), 1.0):
+            message = "`weights` must sum to 1.0."
+            raise ValueError(message)
+
+        if not np.all(weights >= 0):
+            message = "All `weights` must be non-negative."
+            raise ValueError(message)
+
+        return components, weights
+
+    def __init__(self, components, *, weights=None):
+        components, weights = self._input_validation(components, weights)
+        n = len(components)
+        dtype = np.result_type(*(var._dtype for var in components))
+        self._shape = np.broadcast_shapes(*(var._shape for var in components))
+        self._dtype, self._components = dtype, components
+        self._weights = np.full(n, 1/n, dtype=dtype) if weights is None else weights
+        self.validation_policy = None
+
+    @property
+    def components(self):
+        return list(self._components)
+
+    @property
+    def weights(self):
+        return self._weights.copy()
+
+    def _full(self, val, *args):
+        args = [np.asarray(arg) for arg in args]
+        dtype = np.result_type(self._dtype, *(arg.dtype for arg in args))
+        shape = np.broadcast_shapes(self._shape, *(arg.shape for arg in args))
+        return np.full(shape, val, dtype=dtype)
+
+    def _sum(self, fun, *args):
+        out = self._full(0, *args)
+        for var, weight in zip(self._components, self._weights):
+            out += getattr(var, fun)(*args) * weight
+        return out[()]
+
+    def _logsum(self, fun, *args):
+        out = self._full(-np.inf, *args)
+        for var, log_weight in zip(self._components, np.log(self._weights)):
+            np.logaddexp(out, getattr(var, fun)(*args) + log_weight, out=out)
+        return out[()]
+
+    def support(self):
+        a = self._full(np.inf)
+        b = self._full(-np.inf)
+        for var in self._components:
+            a = np.minimum(a, var.support()[0])
+            b = np.maximum(b, var.support()[1])
+        return a, b
+
+    def _raise_if_method(self, method):
+        if method is not None:
+            raise NotImplementedError("`method` not implemented for this distribution.")
+
+    def logentropy(self, *, method=None):
+        self._raise_if_method(method)
+        def log_integrand(x):
+            # `x` passed by `_tanhsinh` will be of complex dtype because
+            # `log_integrand` returns complex values, but the imaginary
+            # component is always zero. Extract the real part because
+            # `logpdf` uses `logaddexp`, which fails for complex input.
+            return self.logpdf(x.real) + np.log(self.logpdf(x.real) + 0j)
+
+        res = _tanhsinh(log_integrand, *self.support(), log=True).integral
+        return _log_real_standardize(res + np.pi*1j)
+
+    def entropy(self, *, method=None):
+        self._raise_if_method(method)
+        return _tanhsinh(lambda x: -self.pdf(x) * self.logpdf(x),
+                         *self.support()).integral
+
+    def mode(self, *, method=None):
+        self._raise_if_method(method)
+        a, b = self.support()
+        def f(x): return -self.pdf(x)
+        res = _bracket_minimum(f, 1., xmin=a, xmax=b)
+        res = _chandrupatla_minimize(f, res.xl, res.xm, res.xr)
+        return res.x
+
+    def median(self, *, method=None):
+        self._raise_if_method(method)
+        return self.icdf(0.5)
+
+    def mean(self, *, method=None):
+        self._raise_if_method(method)
+        return self._sum('mean')
+
+    def variance(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_central(2)
+
+    def standard_deviation(self, *, method=None):
+        self._raise_if_method(method)
+        return self.variance()**0.5
+
+    def skewness(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_standardized(3)
+
+    def kurtosis(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_standardized(4)
+
+    def moment(self, order=1, kind='raw', *, method=None):
+        self._raise_if_method(method)
+        kinds = {'raw': self._moment_raw,
+                 'central': self._moment_central,
+                 'standardized': self._moment_standardized}
+        order = ContinuousDistribution._validate_order_kind(self, order, kind, kinds)
+        moment_kind = kinds[kind]
+        return moment_kind(order)
+
+    def _moment_raw(self, order):
+        out = self._full(0)
+        for var, weight in zip(self._components, self._weights):
+            out += var.moment(order, kind='raw') * weight
+        return out[()]
+
+    def _moment_central(self, order):
+        order = int(order)
+        out = self._full(0)
+        for var, weight in zip(self._components, self._weights):
+            moment_as = [var.moment(order, kind='central')
+                         for order in range(order + 1)]
+            a, b = var.mean(), self.mean()
+            moment = var._moment_transform_center(order, moment_as, a, b)
+            out += moment * weight
+        return out[()]
+
+    def _moment_standardized(self, order):
+        return self._moment_central(order) / self.standard_deviation()**order
+
+    def pdf(self, x, /, *, method=None):
+        self._raise_if_method(method)
+        return self._sum('pdf', x)
+
+    def logpdf(self, x, /, *, method=None):
+        self._raise_if_method(method)
+        return self._logsum('logpdf', x)
+
+    def cdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._sum('cdf', *args)
+
+    def logcdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._logsum('logcdf', *args)
+
+    def ccdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._sum('ccdf', *args)
+
+    def logccdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._logsum('logccdf', *args)
+
+    def _invert(self, fun, p):
+        xmin, xmax = self.support()
+        fun = getattr(self, fun)
+        f = lambda x, p: fun(x) - p  # noqa: E731 is silly
+        xl0, xr0 = _guess_bracket(xmin, xmax)
+        res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p,))
+        return _chandrupatla(f, a=res.xl, b=res.xr, args=(p,)).x
+
+    def icdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('cdf', p)
+
+    def iccdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('ccdf', p)
+
+    def ilogcdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('logcdf', p)
+
+    def ilogccdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('logccdf', p)
+
+    def sample(self, shape=(), *, rng=None, method=None):
+        self._raise_if_method(method)
+        rng = np.random.default_rng(rng)
+        size = np.prod(np.atleast_1d(shape))
+        ns = rng.multinomial(size, self._weights)
+        x = [var.sample(shape=n, rng=rng) for n, var in zip(ns, self._components)]
+        x = np.reshape(rng.permuted(np.concatenate(x)), shape)
+        return x[()]
+
+    def __repr__(self):
+        result = "Mixture(\n"
+        result += "    [\n"
+        with np.printoptions(threshold=10):
+            for component in self.components:
+                result += f"        {repr(component)},\n"
+            result += "    ],\n"
+            result += f"    weights={repr(self.weights)},\n"
+        result += ")"
+        return result
+
+    def __str__(self):
+        result = "Mixture(\n"
+        result += "    [\n"
+        with np.printoptions(threshold=10):
+            for component in self.components:
+                result += f"        {str(component)},\n"
+            result += "    ],\n"
+            result += f"    weights={str(self.weights)},\n"
+        result += ")"
+        return result
+
+
+class MonotonicTransformedDistribution(TransformedDistribution):
+    r"""Distribution underlying a strictly monotonic function of a random variable
+
+    Given a random variable :math:`X`; a strictly monotonic function
+    :math:`g(u)`, its inverse :math:`h(u) = g^{-1}(u)`, and the derivative magnitude
+    :math: `|h'(u)| = \left| \frac{dh(u)}{du} \right|`, define the distribution
+    underlying the random variable :math:`Y = g(X)`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+    g, h, dh : callable
+        Elementwise functions representing the mathematical functions
+        :math:`g(u)`, :math:`h(u)`, and :math:`|h'(u)|`
+    logdh : callable, optional
+        Elementwise function representing :math:`\log(h'(u))`.
+        The default is ``lambda u: np.log(dh(u))``, but providing
+        a custom implementation may avoid over/underflow.
+    increasing : bool, optional
+        Whether the function is strictly increasing (True, default)
+        or strictly decreasing (False).
+    repr_pattern : str, optional
+        A string pattern for determining the __repr__. The __repr__
+        for X will be substituted into the position where `***` appears.
+        For example:
+            ``"exp(***)"`` for the repr of an exponentially transformed
+            distribution
+        The default is ``f"{g.__name__}(***)"``.
+    str_pattern : str, optional
+        A string pattern for determining `__str__`. The `__str__`
+        for X will be substituted into the position where `***` appears.
+        For example:
+            ``"exp(***)"`` for the repr of an exponentially transformed
+            distribution
+        The default is the value `repr_pattern` takes.
+    """
+
+    def __init__(self, X, /, *args, g, h, dh, logdh=None,
+                 increasing=True, repr_pattern=None,
+                 str_pattern=None, **kwargs):
+        super().__init__(X, *args, **kwargs)
+        self._g = g
+        self._h = h
+        self._dh = dh
+        self._logdh = (logdh if logdh is not None
+                       else lambda u: np.log(dh(u)))
+        if increasing:
+            self._xdf = self._dist._cdf_dispatch
+            self._cxdf = self._dist._ccdf_dispatch
+            self._ixdf = self._dist._icdf_dispatch
+            self._icxdf = self._dist._iccdf_dispatch
+            self._logxdf = self._dist._logcdf_dispatch
+            self._logcxdf = self._dist._logccdf_dispatch
+            self._ilogxdf = self._dist._ilogcdf_dispatch
+            self._ilogcxdf = self._dist._ilogccdf_dispatch
+        else:
+            self._xdf = self._dist._ccdf_dispatch
+            self._cxdf = self._dist._cdf_dispatch
+            self._ixdf = self._dist._iccdf_dispatch
+            self._icxdf = self._dist._icdf_dispatch
+            self._logxdf = self._dist._logccdf_dispatch
+            self._logcxdf = self._dist._logcdf_dispatch
+            self._ilogxdf = self._dist._ilogccdf_dispatch
+            self._ilogcxdf = self._dist._ilogcdf_dispatch
+        self._increasing = increasing
+        self._repr_pattern = repr_pattern or f"{g.__name__}(***)"
+        self._str_pattern = str_pattern or self._repr_pattern
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return self._repr_pattern.replace("***", repr(self._dist))
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return self._str_pattern.replace("***", str(self._dist))
+
+    def _overrides(self, method_name):
+        # Do not use the generic overrides of TransformedDistribution
+        return False
+
+    def _support(self, **params):
+        a, b = self._dist._support(**params)
+        # For reciprocal transformation, we want this zero to become -inf
+        b = np.where(b==0, np.asarray("-0", dtype=b.dtype), b)
+        with np.errstate(divide='ignore'):
+            if self._increasing:
+                return self._g(a), self._g(b)
+            else:
+                return self._g(b), self._g(a)
+
+    def _logpdf_dispatch(self, x, *args, **params):
+        return self._dist._logpdf_dispatch(self._h(x), *args, **params) + self._logdh(x)
+
+    def _pdf_dispatch(self, x, *args, **params):
+        return self._dist._pdf_dispatch(self._h(x), *args, **params) * self._dh(x)
+
+    def _logcdf_dispatch(self, x, *args, **params):
+        return self._logxdf(self._h(x), *args, **params)
+
+    def _cdf_dispatch(self, x, *args, **params):
+        return self._xdf(self._h(x), *args, **params)
+
+    def _logccdf_dispatch(self, x, *args, **params):
+        return self._logcxdf(self._h(x), *args, **params)
+
+    def _ccdf_dispatch(self, x, *args, **params):
+        return self._cxdf(self._h(x), *args, **params)
+
+    def _ilogcdf_dispatch(self, p, *args, **params):
+        return self._g(self._ilogxdf(p, *args, **params))
+
+    def _icdf_dispatch(self, p, *args, **params):
+        return self._g(self._ixdf(p, *args, **params))
+
+    def _ilogccdf_dispatch(self, p, *args, **params):
+        return self._g(self._ilogcxdf(p, *args, **params))
+
+    def _iccdf_dispatch(self, p, *args, **params):
+        return self._g(self._icxdf(p, *args, **params))
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         method, rng, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return self._g(rvs)
+
+
+class FoldedDistribution(TransformedDistribution):
+    r"""Distribution underlying the absolute value of a random variable
+
+    Given a random variable :math:`X`; define the distribution
+    underlying the random variable :math:`Y = |X|`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        The random variable :math:`Y = |X|`
+
+    """
+    # Many enhancements are possible if distribution is symmetric. Start
+    # with the general case; enhance later.
+
+    def __init__(self, X, /, *args, **kwargs):
+        super().__init__(X, *args, **kwargs)
+        # I think we need to allow `_support` to define whether the endpoints
+        # are inclusive or not. In the meantime, it's best to ensure that the lower
+        # endpoint (typically 0 for folded distribution) is inclusive so PDF evaluates
+        # correctly at that point.
+        self._variable.domain.inclusive = (True, self._variable.domain.inclusive[1])
+
+    def _overrides(self, method_name):
+        # Do not use the generic overrides of TransformedDistribution
+        return False
+
+    def _support(self, **params):
+        a, b = self._dist._support(**params)
+        a_, b_ = np.abs(a), np.abs(b)
+        a_, b_ = np.minimum(a_, b_), np.maximum(a_, b_)
+        i = (a < 0) & (b > 0)
+        a_ = np.asarray(a_)
+        a_[i] = 0
+        return a_[()], b_[()]
+
+    def _logpdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        right = self._dist._logpdf_dispatch(x, *args, method=method, **params)
+        left = self._dist._logpdf_dispatch(-x, *args, method=method, **params)
+        left = np.asarray(left)
+        right = np.asarray(right)
+        a, b = self._dist._support(**params)
+        left[-x < a] = -np.inf
+        right[x > b] = -np.inf
+        logpdfs = np.stack([left, right])
+        return special.logsumexp(logpdfs, axis=0)
+
+    def _pdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        right = self._dist._pdf_dispatch(x, *args, method=method, **params)
+        left = self._dist._pdf_dispatch(-x, *args, method=method, **params)
+        left = np.asarray(left)
+        right = np.asarray(right)
+        a, b = self._dist._support(**params)
+        left[-x < a] = 0
+        right[x > b] = 0
+        return left + right
+
+    def _logcdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._logcdf2_dispatch(xl, xr, *args, method=method, **params).real
+
+    def _cdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._cdf2_dispatch(xl, xr, *args, **params)
+
+    def _logccdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._logccdf2_dispatch(xl, xr, *args, method=method, 
+                                             **params).real
+
+    def _ccdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._ccdf2_dispatch(xl, xr, *args, method=method, **params)
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         method, rng, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return np.abs(rvs)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return f"abs({repr(self._dist)})"
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return f"abs({str(self._dist)})"
+
+
+def abs(X, /):
+    r"""Absolute value of a random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = |X|`.
+
+    Examples
+    --------
+    Suppose we have a normally distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> X = stats.Normal()
+
+    We wish to have a random variable :math:`Y` distributed according to
+    the folded normal distribution; that is, a random variable :math:`|X|`.
+
+    >>> Y = stats.abs(X)
+
+    The PDF of the distribution in the left half plane is "folded" over to
+    the right half plane. Because the normal PDF is symmetric, the resulting
+    PDF is zero for negative arguments and doubled for positive arguments.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 300)
+    >>> ax = plt.gca()
+    >>> Y.plot(x='x', y='pdf', t=('x', -1, 5), ax=ax)
+    >>> plt.plot(x, 2 * X.pdf(x), '--')
+    >>> plt.legend(('PDF of `Y`', 'Doubled PDF of `X`'))
+    >>> plt.show()
+
+    """
+    return FoldedDistribution(X)
+
+
+def exp(X, /):
+    r"""Natural exponential of a random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = \exp(X)`.
+
+    Examples
+    --------
+    Suppose we have a normally distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> X = stats.Normal()
+
+    We wish to have a lognormally distributed random variable :math:`Y`,
+    a random variable whose natural logarithm is :math:`X`.
+    If :math:`X` is to be the natural logarithm of :math:`Y`, then we
+    must take :math:`Y` to be the natural exponential of :math:`X`.
+
+    >>> Y = stats.exp(X)
+
+    To demonstrate that ``X`` represents the logarithm of ``Y``,
+    we plot a normalized histogram of the logarithm of observations of
+    ``Y`` against the PDF underlying ``X``.
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(435383595582522)
+    >>> y = Y.sample(shape=10000, rng=rng)
+    >>> ax = plt.gca()
+    >>> ax.hist(np.log(y), bins=50, density=True)
+    >>> X.plot(ax=ax)
+    >>> plt.legend(('PDF of `X`', 'histogram of `log(y)`'))
+    >>> plt.show()
+
+    """
+    return MonotonicTransformedDistribution(X, g=np.exp, h=np.log, dh=lambda u: 1 / u,
+                                            logdh=lambda u: -np.log(u))
+
+
+def log(X, /):
+    r"""Natural logarithm of a non-negative random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X` with positive support.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = \exp(X)`.
+
+    Examples
+    --------
+    Suppose we have a gamma distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> Gamma = stats.make_distribution(stats.gamma)
+    >>> X = Gamma(a=1.0)
+
+    We wish to have a exp-gamma distributed random variable :math:`Y`,
+    a random variable whose natural exponential is :math:`X`.
+    If :math:`X` is to be the natural exponential of :math:`Y`, then we
+    must take :math:`Y` to be the natural logarithm of :math:`X`.
+
+    >>> Y = stats.log(X)
+
+    To demonstrate that ``X`` represents the exponential of ``Y``,
+    we plot a normalized histogram of the exponential of observations of
+    ``Y`` against the PDF underlying ``X``.
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(435383595582522)
+    >>> y = Y.sample(shape=10000, rng=rng)
+    >>> ax = plt.gca()
+    >>> ax.hist(np.exp(y), bins=50, density=True)
+    >>> X.plot(ax=ax)
+    >>> plt.legend(('PDF of `X`', 'histogram of `exp(y)`'))
+    >>> plt.show()
+
+    """
+    if np.any(X.support()[0] < 0):
+        message = ("The logarithm of a random variable is only implemented when the "
+                   "support is non-negative.")
+        raise NotImplementedError(message)
+    return MonotonicTransformedDistribution(X, g=np.log, h=np.exp, dh=np.exp,
+                                            logdh=lambda u: u)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_entropy.py b/python_embeded/Lib/site-packages/scipy/stats/_entropy.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b77b705da09ea608cfcb77d984d842f0a561444
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_entropy.py
@@ -0,0 +1,429 @@
+"""
+Created on Fri Apr  2 09:06:05 2021
+
+@author: matth
+"""
+
+import math
+import numpy as np
+from scipy import special
+from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays
+from scipy._lib._array_api import array_namespace, xp_moveaxis_to_end
+
+__all__ = ['entropy', 'differential_entropy']
+
+
+@_axis_nan_policy_factory(
+    lambda x: x,
+    n_samples=lambda kwgs: (
+        2 if ("qk" in kwgs and kwgs["qk"] is not None)
+        else 1
+    ),
+    n_outputs=1, result_to_tuple=lambda x: (x,), paired=True,
+    too_small=-1  # entropy doesn't have too small inputs
+)
+def entropy(pk: np.typing.ArrayLike,
+            qk: np.typing.ArrayLike | None = None,
+            base: float | None = None,
+            axis: int = 0
+            ) -> np.number | np.ndarray:
+    """
+    Calculate the Shannon entropy/relative entropy of given distribution(s).
+
+    If only probabilities `pk` are given, the Shannon entropy is calculated as
+    ``H = -sum(pk * log(pk))``.
+
+    If `qk` is not None, then compute the relative entropy
+    ``D = sum(pk * log(pk / qk))``. This quantity is also known
+    as the Kullback-Leibler divergence.
+
+    This routine will normalize `pk` and `qk` if they don't sum to 1.
+
+    Parameters
+    ----------
+    pk : array_like
+        Defines the (discrete) distribution. Along each axis-slice of ``pk``,
+        element ``i`` is the  (possibly unnormalized) probability of event
+        ``i``.
+    qk : array_like, optional
+        Sequence against which the relative entropy is computed. Should be in
+        the same format as `pk`.
+    base : float, optional
+        The logarithmic base to use, defaults to ``e`` (natural logarithm).
+    axis : int, optional
+        The axis along which the entropy is calculated. Default is 0.
+
+    Returns
+    -------
+    S : {float, array_like}
+        The calculated entropy.
+
+    Notes
+    -----
+    Informally, the Shannon entropy quantifies the expected uncertainty
+    inherent in the possible outcomes of a discrete random variable.
+    For example,
+    if messages consisting of sequences of symbols from a set are to be
+    encoded and transmitted over a noiseless channel, then the Shannon entropy
+    ``H(pk)`` gives a tight lower bound for the average number of units of
+    information needed per symbol if the symbols occur with frequencies
+    governed by the discrete distribution `pk` [1]_. The choice of base
+    determines the choice of units; e.g., ``e`` for nats, ``2`` for bits, etc.
+
+    The relative entropy, ``D(pk|qk)``, quantifies the increase in the average
+    number of units of information needed per symbol if the encoding is
+    optimized for the probability distribution `qk` instead of the true
+    distribution `pk`. Informally, the relative entropy quantifies the expected
+    excess in surprise experienced if one believes the true distribution is
+    `qk` when it is actually `pk`.
+
+    A related quantity, the cross entropy ``CE(pk, qk)``, satisfies the
+    equation ``CE(pk, qk) = H(pk) + D(pk|qk)`` and can also be calculated with
+    the formula ``CE = -sum(pk * log(qk))``. It gives the average
+    number of units of information needed per symbol if an encoding is
+    optimized for the probability distribution `qk` when the true distribution
+    is `pk`. It is not computed directly by `entropy`, but it can be computed
+    using two calls to the function (see Examples).
+
+    See [2]_ for more information.
+
+    References
+    ----------
+    .. [1] Shannon, C.E. (1948), A Mathematical Theory of Communication.
+           Bell System Technical Journal, 27: 379-423.
+           https://doi.org/10.1002/j.1538-7305.1948.tb01338.x
+    .. [2] Thomas M. Cover and Joy A. Thomas. 2006. Elements of Information
+           Theory (Wiley Series in Telecommunications and Signal Processing).
+           Wiley-Interscience, USA.
+
+
+    Examples
+    --------
+    The outcome of a fair coin is the most uncertain:
+
+    >>> import numpy as np
+    >>> from scipy.stats import entropy
+    >>> base = 2  # work in units of bits
+    >>> pk = np.array([1/2, 1/2])  # fair coin
+    >>> H = entropy(pk, base=base)
+    >>> H
+    1.0
+    >>> H == -np.sum(pk * np.log(pk)) / np.log(base)
+    True
+
+    The outcome of a biased coin is less uncertain:
+
+    >>> qk = np.array([9/10, 1/10])  # biased coin
+    >>> entropy(qk, base=base)
+    0.46899559358928117
+
+    The relative entropy between the fair coin and biased coin is calculated
+    as:
+
+    >>> D = entropy(pk, qk, base=base)
+    >>> D
+    0.7369655941662062
+    >>> np.isclose(D, np.sum(pk * np.log(pk/qk)) / np.log(base), rtol=4e-16, atol=0)
+    True
+
+    The cross entropy can be calculated as the sum of the entropy and
+    relative entropy`:
+
+    >>> CE = entropy(pk, base=base) + entropy(pk, qk, base=base)
+    >>> CE
+    1.736965594166206
+    >>> CE == -np.sum(pk * np.log(qk)) / np.log(base)
+    True
+
+    """
+    if base is not None and base <= 0:
+        raise ValueError("`base` must be a positive number or `None`.")
+
+    xp = array_namespace(pk) if qk is None else array_namespace(pk, qk)
+
+    pk = xp.asarray(pk)
+    with np.errstate(invalid='ignore'):
+        pk = 1.0*pk / xp.sum(pk, axis=axis, keepdims=True)  # type: ignore[operator]
+    if qk is None:
+        vec = special.entr(pk)
+    else:
+        qk = xp.asarray(qk)
+        pk, qk = _broadcast_arrays((pk, qk), axis=None, xp=xp)  # don't ignore any axes
+        sum_kwargs = dict(axis=axis, keepdims=True)
+        qk = 1.0*qk / xp.sum(qk, **sum_kwargs)  # type: ignore[operator, call-overload]
+        vec = special.rel_entr(pk, qk)
+    S = xp.sum(vec, axis=axis)
+    if base is not None:
+        S /= math.log(base)
+    return S
+
+
+def _differential_entropy_is_too_small(samples, kwargs, axis=-1):
+    values = samples[0]
+    n = values.shape[axis]
+    window_length = kwargs.get("window_length",
+                               math.floor(math.sqrt(n) + 0.5))
+    if not 2 <= 2 * window_length < n:
+        return True
+    return False
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,),
+    too_small=_differential_entropy_is_too_small
+)
+def differential_entropy(
+    values: np.typing.ArrayLike,
+    *,
+    window_length: int | None = None,
+    base: float | None = None,
+    axis: int = 0,
+    method: str = "auto",
+) -> np.number | np.ndarray:
+    r"""Given a sample of a distribution, estimate the differential entropy.
+
+    Several estimation methods are available using the `method` parameter. By
+    default, a method is selected based the size of the sample.
+
+    Parameters
+    ----------
+    values : sequence
+        Sample from a continuous distribution.
+    window_length : int, optional
+        Window length for computing Vasicek estimate. Must be an integer
+        between 1 and half of the sample size. If ``None`` (the default), it
+        uses the heuristic value
+
+        .. math::
+            \left \lfloor \sqrt{n} + 0.5 \right \rfloor
+
+        where :math:`n` is the sample size. This heuristic was originally
+        proposed in [2]_ and has become common in the literature.
+    base : float, optional
+        The logarithmic base to use, defaults to ``e`` (natural logarithm).
+    axis : int, optional
+        The axis along which the differential entropy is calculated.
+        Default is 0.
+    method : {'vasicek', 'van es', 'ebrahimi', 'correa', 'auto'}, optional
+        The method used to estimate the differential entropy from the sample.
+        Default is ``'auto'``.  See Notes for more information.
+
+    Returns
+    -------
+    entropy : float
+        The calculated differential entropy.
+
+    Notes
+    -----
+    This function will converge to the true differential entropy in the limit
+
+    .. math::
+        n \to \infty, \quad m \to \infty, \quad \frac{m}{n} \to 0
+
+    The optimal choice of ``window_length`` for a given sample size depends on
+    the (unknown) distribution. Typically, the smoother the density of the
+    distribution, the larger the optimal value of ``window_length`` [1]_.
+
+    The following options are available for the `method` parameter.
+
+    * ``'vasicek'`` uses the estimator presented in [1]_. This is
+      one of the first and most influential estimators of differential entropy.
+    * ``'van es'`` uses the bias-corrected estimator presented in [3]_, which
+      is not only consistent but, under some conditions, asymptotically normal.
+    * ``'ebrahimi'`` uses an estimator presented in [4]_, which was shown
+      in simulation to have smaller bias and mean squared error than
+      the Vasicek estimator.
+    * ``'correa'`` uses the estimator presented in [5]_ based on local linear
+      regression. In a simulation study, it had consistently smaller mean
+      square error than the Vasiceck estimator, but it is more expensive to
+      compute.
+    * ``'auto'`` selects the method automatically (default). Currently,
+      this selects ``'van es'`` for very small samples (<10), ``'ebrahimi'``
+      for moderate sample sizes (11-1000), and ``'vasicek'`` for larger
+      samples, but this behavior is subject to change in future versions.
+
+    All estimators are implemented as described in [6]_.
+
+    References
+    ----------
+    .. [1] Vasicek, O. (1976). A test for normality based on sample entropy.
+           Journal of the Royal Statistical Society:
+           Series B (Methodological), 38(1), 54-59.
+    .. [2] Crzcgorzewski, P., & Wirczorkowski, R. (1999). Entropy-based
+           goodness-of-fit test for exponentiality. Communications in
+           Statistics-Theory and Methods, 28(5), 1183-1202.
+    .. [3] Van Es, B. (1992). Estimating functionals related to a density by a
+           class of statistics based on spacings. Scandinavian Journal of
+           Statistics, 61-72.
+    .. [4] Ebrahimi, N., Pflughoeft, K., & Soofi, E. S. (1994). Two measures
+           of sample entropy. Statistics & Probability Letters, 20(3), 225-234.
+    .. [5] Correa, J. C. (1995). A new estimator of entropy. Communications
+           in Statistics-Theory and Methods, 24(10), 2439-2449.
+    .. [6] Noughabi, H. A. (2015). Entropy Estimation Using Numerical Methods.
+           Annals of Data Science, 2(2), 231-241.
+           https://link.springer.com/article/10.1007/s40745-015-0045-9
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import differential_entropy, norm
+
+    Entropy of a standard normal distribution:
+
+    >>> rng = np.random.default_rng()
+    >>> values = rng.standard_normal(100)
+    >>> differential_entropy(values)
+    1.3407817436640392
+
+    Compare with the true entropy:
+
+    >>> float(norm.entropy())
+    1.4189385332046727
+
+    For several sample sizes between 5 and 1000, compare the accuracy of
+    the ``'vasicek'``, ``'van es'``, and ``'ebrahimi'`` methods. Specifically,
+    compare the root mean squared error (over 1000 trials) between the estimate
+    and the true differential entropy of the distribution.
+
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>>
+    >>>
+    >>> def rmse(res, expected):
+    ...     '''Root mean squared error'''
+    ...     return np.sqrt(np.mean((res - expected)**2))
+    >>>
+    >>>
+    >>> a, b = np.log10(5), np.log10(1000)
+    >>> ns = np.round(np.logspace(a, b, 10)).astype(int)
+    >>> reps = 1000  # number of repetitions for each sample size
+    >>> expected = stats.expon.entropy()
+    >>>
+    >>> method_errors = {'vasicek': [], 'van es': [], 'ebrahimi': []}
+    >>> for method in method_errors:
+    ...     for n in ns:
+    ...        rvs = stats.expon.rvs(size=(reps, n), random_state=rng)
+    ...        res = stats.differential_entropy(rvs, method=method, axis=-1)
+    ...        error = rmse(res, expected)
+    ...        method_errors[method].append(error)
+    >>>
+    >>> for method, errors in method_errors.items():
+    ...     plt.loglog(ns, errors, label=method)
+    >>>
+    >>> plt.legend()
+    >>> plt.xlabel('sample size')
+    >>> plt.ylabel('RMSE (1000 trials)')
+    >>> plt.title('Entropy Estimator Error (Exponential Distribution)')
+
+    """
+    xp = array_namespace(values)
+    values = xp.asarray(values)
+    if xp.isdtype(values.dtype, "integral"):  # type: ignore[union-attr]
+        values = xp.astype(values, xp.asarray(1.).dtype)
+    values = xp_moveaxis_to_end(values, axis, xp=xp)
+    n = values.shape[-1]  # type: ignore[union-attr]
+
+    if window_length is None:
+        window_length = math.floor(math.sqrt(n) + 0.5)
+
+    if not 2 <= 2 * window_length < n:
+        raise ValueError(
+            f"Window length ({window_length}) must be positive and less "
+            f"than half the sample size ({n}).",
+        )
+
+    if base is not None and base <= 0:
+        raise ValueError("`base` must be a positive number or `None`.")
+
+    sorted_data = xp.sort(values, axis=-1)
+
+    methods = {"vasicek": _vasicek_entropy,
+               "van es": _van_es_entropy,
+               "correa": _correa_entropy,
+               "ebrahimi": _ebrahimi_entropy,
+               "auto": _vasicek_entropy}
+    method = method.lower()
+    if method not in methods:
+        message = f"`method` must be one of {set(methods)}"
+        raise ValueError(message)
+
+    if method == "auto":
+        if n <= 10:
+            method = 'van es'
+        elif n <= 1000:
+            method = 'ebrahimi'
+        else:
+            method = 'vasicek'
+
+    res = methods[method](sorted_data, window_length, xp=xp)
+
+    if base is not None:
+        res /= math.log(base)
+
+    # avoid dtype changes due to data-apis/array-api-compat#152
+    # can be removed when data-apis/array-api-compat#152 is resolved
+    return xp.astype(res, values.dtype)  # type: ignore[union-attr]
+
+
+def _pad_along_last_axis(X, m, *, xp):
+    """Pad the data for computing the rolling window difference."""
+    # scales a  bit better than method in _vasicek_like_entropy
+    shape = X.shape[:-1] + (m,)
+    Xl = xp.broadcast_to(X[..., :1], shape)  # :1 vs 0 to maintain shape
+    Xr = xp.broadcast_to(X[..., -1:], shape)
+    return xp.concat((Xl, X, Xr), axis=-1)
+
+
+def _vasicek_entropy(X, m, *, xp):
+    """Compute the Vasicek estimator as described in [6] Eq. 1.3."""
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+    differences = X[..., 2 * m:] - X[..., : -2 * m:]
+    logs = xp.log(n/(2*m) * differences)
+    return xp.mean(logs, axis=-1)
+
+
+def _van_es_entropy(X, m, *, xp):
+    """Compute the van Es estimator as described in [6]."""
+    # No equation number, but referred to as HVE_mn.
+    # Typo: there should be a log within the summation.
+    n = X.shape[-1]
+    difference = X[..., m:] - X[..., :-m]
+    term1 = 1/(n-m) * xp.sum(xp.log((n+1)/m * difference), axis=-1)
+    k = xp.arange(m, n+1, dtype=term1.dtype)
+    return term1 + xp.sum(1/k) + math.log(m) - math.log(n+1)
+
+
+def _ebrahimi_entropy(X, m, *, xp):
+    """Compute the Ebrahimi estimator as described in [6]."""
+    # No equation number, but referred to as HE_mn
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+
+    differences = X[..., 2 * m:] - X[..., : -2 * m:]
+
+    i = xp.arange(1, n+1, dtype=X.dtype)
+    ci = xp.ones_like(i)*2
+    ci[i <= m] = 1 + (i[i <= m] - 1)/m
+    ci[i >= n - m + 1] = 1 + (n - i[i >= n-m+1])/m
+
+    logs = xp.log(n * differences / (ci * m))
+    return xp.mean(logs, axis=-1)
+
+
+def _correa_entropy(X, m, *, xp):
+    """Compute the Correa estimator as described in [6]."""
+    # No equation number, but referred to as HC_mn
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+
+    i = xp.arange(1, n+1)
+    dj = xp.arange(-m, m+1)[:, None]
+    j = i + dj
+    j0 = j + m - 1  # 0-indexed version of j
+
+    Xibar = xp.mean(X[..., j0], axis=-2, keepdims=True)
+    difference = X[..., j0] - Xibar
+    num = xp.sum(difference*dj, axis=-2)  # dj is d-i
+    den = n*xp.sum(difference**2, axis=-2)
+    return -xp.mean(xp.log(num/den), axis=-1)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_fit.py b/python_embeded/Lib/site-packages/scipy/stats/_fit.py
new file mode 100644
index 0000000000000000000000000000000000000000..894bcafc1a5c7bb868696c1ae212c319a86bdff1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_fit.py
@@ -0,0 +1,1351 @@
+import warnings
+from collections import namedtuple
+import numpy as np
+from scipy import optimize, stats
+from scipy._lib._util import check_random_state, _transition_to_rng
+
+
+def _combine_bounds(name, user_bounds, shape_domain, integral):
+    """Intersection of user-defined bounds and distribution PDF/PMF domain"""
+
+    user_bounds = np.atleast_1d(user_bounds)
+
+    if user_bounds[0] > user_bounds[1]:
+        message = (f"There are no values for `{name}` on the interval "
+                   f"{list(user_bounds)}.")
+        raise ValueError(message)
+
+    bounds = (max(user_bounds[0], shape_domain[0]),
+              min(user_bounds[1], shape_domain[1]))
+
+    if integral and (np.ceil(bounds[0]) > np.floor(bounds[1])):
+        message = (f"There are no integer values for `{name}` on the interval "
+                   f"defined by the user-provided bounds and the domain "
+                   "of the distribution.")
+        raise ValueError(message)
+    elif not integral and (bounds[0] > bounds[1]):
+        message = (f"There are no values for `{name}` on the interval "
+                   f"defined by the user-provided bounds and the domain "
+                   "of the distribution.")
+        raise ValueError(message)
+
+    if not np.all(np.isfinite(bounds)):
+        message = (f"The intersection of user-provided bounds for `{name}` "
+                   f"and the domain of the distribution is not finite. Please "
+                   f"provide finite bounds for shape `{name}` in `bounds`.")
+        raise ValueError(message)
+
+    return bounds
+
+
+class FitResult:
+    r"""Result of fitting a discrete or continuous distribution to data
+
+    Attributes
+    ----------
+    params : namedtuple
+        A namedtuple containing the maximum likelihood estimates of the
+        shape parameters, location, and (if applicable) scale of the
+        distribution.
+    success : bool or None
+        Whether the optimizer considered the optimization to terminate
+        successfully or not.
+    message : str or None
+        Any status message provided by the optimizer.
+
+    """
+
+    def __init__(self, dist, data, discrete, res):
+        self._dist = dist
+        self._data = data
+        self.discrete = discrete
+        self.pxf = getattr(dist, "pmf", None) or getattr(dist, "pdf", None)
+
+        shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
+        if not discrete:
+            FitParams = namedtuple('FitParams', shape_names + ['loc', 'scale'])
+        else:
+            FitParams = namedtuple('FitParams', shape_names + ['loc'])
+
+        self.params = FitParams(*res.x)
+
+        # Optimizer can report success even when nllf is infinite
+        if res.success and not np.isfinite(self.nllf()):
+            res.success = False
+            res.message = ("Optimization converged to parameter values that "
+                           "are inconsistent with the data.")
+        self.success = getattr(res, "success", None)
+        self.message = getattr(res, "message", None)
+
+    def __repr__(self):
+        keys = ["params", "success", "message"]
+        m = max(map(len, keys)) + 1
+        return '\n'.join([key.rjust(m) + ': ' + repr(getattr(self, key))
+                          for key in keys if getattr(self, key) is not None])
+
+    def nllf(self, params=None, data=None):
+        """Negative log-likelihood function
+
+        Evaluates the negative of the log-likelihood function of the provided
+        data at the provided parameters.
+
+        Parameters
+        ----------
+        params : tuple, optional
+            The shape parameters, location, and (if applicable) scale of the
+            distribution as a single tuple. Default is the maximum likelihood
+            estimates (``self.params``).
+        data : array_like, optional
+            The data for which the log-likelihood function is to be evaluated.
+            Default is the data to which the distribution was fit.
+
+        Returns
+        -------
+        nllf : float
+            The negative of the log-likelihood function.
+
+        """
+        params = params if params is not None else self.params
+        data = data if data is not None else self._data
+        return self._dist.nnlf(theta=params, x=data)
+
+    def plot(self, ax=None, *, plot_type="hist"):
+        """Visually compare the data against the fitted distribution.
+
+        Available only if `matplotlib` is installed.
+
+        Parameters
+        ----------
+        ax : `matplotlib.axes.Axes`
+            Axes object to draw the plot onto, otherwise uses the current Axes.
+        plot_type : {"hist", "qq", "pp", "cdf"}
+            Type of plot to draw. Options include:
+
+            - "hist": Superposes the PDF/PMF of the fitted distribution
+              over a normalized histogram of the data.
+            - "qq": Scatter plot of theoretical quantiles against the
+              empirical quantiles. Specifically, the x-coordinates are the
+              values of the fitted distribution PPF evaluated at the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is the
+              number of data points, and the y-coordinates are the sorted
+              data points.
+            - "pp": Scatter plot of theoretical percentiles against the
+              observed percentiles. Specifically, the x-coordinates are the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
+              the number of data points, and the y-coordinates are the values
+              of the fitted distribution CDF evaluated at the sorted
+              data points.
+            - "cdf": Superposes the CDF of the fitted distribution over the
+              empirical CDF. Specifically, the x-coordinates of the empirical
+              CDF are the sorted data points, and the y-coordinates are the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
+              the number of data points.
+
+        Returns
+        -------
+        ax : `matplotlib.axes.Axes`
+            The matplotlib Axes object on which the plot was drawn.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> import matplotlib.pyplot as plt  # matplotlib must be installed
+        >>> rng = np.random.default_rng()
+        >>> data = stats.nbinom(5, 0.5).rvs(size=1000, random_state=rng)
+        >>> bounds = [(0, 30), (0, 1)]
+        >>> res = stats.fit(stats.nbinom, data, bounds)
+        >>> ax = res.plot()  # save matplotlib Axes object
+
+        The `matplotlib.axes.Axes` object can be used to customize the plot.
+        See `matplotlib.axes.Axes` documentation for details.
+
+        >>> ax.set_xlabel('number of trials')  # customize axis label
+        >>> ax.get_children()[0].set_linewidth(5)  # customize line widths
+        >>> ax.legend()
+        >>> plt.show()
+        """
+        try:
+            import matplotlib  # noqa: F401
+        except ModuleNotFoundError as exc:
+            message = "matplotlib must be installed to use method `plot`."
+            raise ModuleNotFoundError(message) from exc
+
+        plots = {'histogram': self._hist_plot, 'qq': self._qq_plot,
+                 'pp': self._pp_plot, 'cdf': self._cdf_plot,
+                 'hist': self._hist_plot}
+        if plot_type.lower() not in plots:
+            message = f"`plot_type` must be one of {set(plots.keys())}"
+            raise ValueError(message)
+        plot = plots[plot_type.lower()]
+
+        if ax is None:
+            import matplotlib.pyplot as plt
+            ax = plt.gca()
+
+        fit_params = np.atleast_1d(self.params)
+
+        return plot(ax=ax, fit_params=fit_params)
+
+    def _hist_plot(self, ax, fit_params):
+        from matplotlib.ticker import MaxNLocator
+
+        support = self._dist.support(*fit_params)
+        lb = support[0] if np.isfinite(support[0]) else min(self._data)
+        ub = support[1] if np.isfinite(support[1]) else max(self._data)
+        pxf = "PMF" if self.discrete else "PDF"
+
+        if self.discrete:
+            x = np.arange(lb, ub + 2)
+            y = self.pxf(x, *fit_params)
+            ax.vlines(x[:-1], 0, y[:-1], label='Fitted Distribution PMF',
+                      color='C0')
+            options = dict(density=True, bins=x, align='left', color='C1')
+            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
+            ax.set_xlabel('k')
+            ax.set_ylabel('PMF')
+        else:
+            x = np.linspace(lb, ub, 200)
+            y = self.pxf(x, *fit_params)
+            ax.plot(x, y, '--', label='Fitted Distribution PDF', color='C0')
+            options = dict(density=True, bins=50, align='mid', color='C1')
+            ax.set_xlabel('x')
+            ax.set_ylabel('PDF')
+
+        if len(self._data) > 50 or self.discrete:
+            ax.hist(self._data, label="Histogram of Data", **options)
+        else:
+            ax.plot(self._data, np.zeros_like(self._data), "*",
+                    label='Data', color='C1')
+
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ {pxf} and Histogram")
+        ax.legend(*ax.get_legend_handles_labels())
+        return ax
+
+    def _qp_plot(self, ax, fit_params, qq):
+        data = np.sort(self._data)
+        ps = self._plotting_positions(len(self._data))
+
+        if qq:
+            qp = "Quantiles"
+            plot_type = 'Q-Q'
+            x = self._dist.ppf(ps, *fit_params)
+            y = data
+        else:
+            qp = "Percentiles"
+            plot_type = 'P-P'
+            x = ps
+            y = self._dist.cdf(data, *fit_params)
+
+        ax.plot(x, y, '.', label=f'Fitted Distribution {plot_type}',
+                color='C0', zorder=1)
+        xlim = ax.get_xlim()
+        ylim = ax.get_ylim()
+        lim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])]
+        if not qq:
+            lim = max(lim[0], 0), min(lim[1], 1)
+
+        if self.discrete and qq:
+            q_min, q_max = int(lim[0]), int(lim[1]+1)
+            q_ideal = np.arange(q_min, q_max)
+            # q_ideal = np.unique(self._dist.ppf(ps, *fit_params))
+            ax.plot(q_ideal, q_ideal, 'o', label='Reference', color='k',
+                    alpha=0.25, markerfacecolor='none', clip_on=True)
+        elif self.discrete and not qq:
+            # The intent of this is to match the plot that would be produced
+            # if x were continuous on [0, 1] and y were cdf(ppf(x)).
+            # It can be approximated by letting x = np.linspace(0, 1, 1000),
+            # but this might not look great when zooming in. The vertical
+            # portions are included to indicate where the transition occurs
+            # where the data completely obscures the horizontal portions.
+            p_min, p_max = lim
+            a, b = self._dist.support(*fit_params)
+            p_min = max(p_min, 0 if np.isfinite(a) else 1e-3)
+            p_max = min(p_max, 1 if np.isfinite(b) else 1-1e-3)
+            q_min, q_max = self._dist.ppf([p_min, p_max], *fit_params)
+            qs = np.arange(q_min-1, q_max+1)
+            ps = self._dist.cdf(qs, *fit_params)
+            ax.step(ps, ps, '-', label='Reference', color='k', alpha=0.25,
+                    clip_on=True)
+        else:
+            ax.plot(lim, lim, '-', label='Reference', color='k', alpha=0.25,
+                    clip_on=True)
+
+        ax.set_xlim(lim)
+        ax.set_ylim(lim)
+        ax.set_xlabel(rf"Fitted $\tt {self._dist.name}$ Theoretical {qp}")
+        ax.set_ylabel(f"Data {qp}")
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ {plot_type} Plot")
+        ax.legend(*ax.get_legend_handles_labels())
+        ax.set_aspect('equal')
+        return ax
+
+    def _qq_plot(self, **kwargs):
+        return self._qp_plot(qq=True, **kwargs)
+
+    def _pp_plot(self, **kwargs):
+        return self._qp_plot(qq=False, **kwargs)
+
+    def _plotting_positions(self, n, a=.5):
+        # See https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot#Plotting_positions
+        k = np.arange(1, n+1)
+        return (k-a) / (n + 1 - 2*a)
+
+    def _cdf_plot(self, ax, fit_params):
+        data = np.sort(self._data)
+        ecdf = self._plotting_positions(len(self._data))
+        ls = '--' if len(np.unique(data)) < 30 else '.'
+        xlabel = 'k' if self.discrete else 'x'
+        ax.step(data, ecdf, ls, label='Empirical CDF', color='C1', zorder=0)
+
+        xlim = ax.get_xlim()
+        q = np.linspace(*xlim, 300)
+        tcdf = self._dist.cdf(q, *fit_params)
+
+        ax.plot(q, tcdf, label='Fitted Distribution CDF', color='C0', zorder=1)
+        ax.set_xlim(xlim)
+        ax.set_ylim(0, 1)
+        ax.set_xlabel(xlabel)
+        ax.set_ylabel("CDF")
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ and Empirical CDF")
+        handles, labels = ax.get_legend_handles_labels()
+        ax.legend(handles[::-1], labels[::-1])
+        return ax
+
+
+def fit(dist, data, bounds=None, *, guess=None, method='mle',
+        optimizer=optimize.differential_evolution):
+    r"""Fit a discrete or continuous distribution to data
+
+    Given a distribution, data, and bounds on the parameters of the
+    distribution, return maximum likelihood estimates of the parameters.
+
+    Parameters
+    ----------
+    dist : `scipy.stats.rv_continuous` or `scipy.stats.rv_discrete`
+        The object representing the distribution to be fit to the data.
+    data : 1D array_like
+        The data to which the distribution is to be fit. If the data contain
+        any of ``np.nan``, ``np.inf``, or -``np.inf``, the fit method will
+        raise a ``ValueError``.
+    bounds : dict or sequence of tuples, optional
+        If a dictionary, each key is the name of a parameter of the
+        distribution, and the corresponding value is a tuple containing the
+        lower and upper bound on that parameter.  If the distribution is
+        defined only for a finite range of values of that parameter, no entry
+        for that parameter is required; e.g., some distributions have
+        parameters which must be on the interval [0, 1]. Bounds for parameters
+        location (``loc``) and scale (``scale``) are optional; by default,
+        they are fixed to 0 and 1, respectively.
+
+        If a sequence, element *i* is a tuple containing the lower and upper
+        bound on the *i*\ th parameter of the distribution. In this case,
+        bounds for *all* distribution shape parameters must be provided.
+        Optionally, bounds for location and scale may follow the
+        distribution shape parameters.
+
+        If a shape is to be held fixed (e.g. if it is known), the
+        lower and upper bounds may be equal. If a user-provided lower or upper
+        bound is beyond a bound of the domain for which the distribution is
+        defined, the bound of the distribution's domain will replace the
+        user-provided value. Similarly, parameters which must be integral
+        will be constrained to integral values within the user-provided bounds.
+    guess : dict or array_like, optional
+        If a dictionary, each key is the name of a parameter of the
+        distribution, and the corresponding value is a guess for the value
+        of the parameter.
+
+        If a sequence, element *i* is a guess for the *i*\ th parameter of the
+        distribution. In this case, guesses for *all* distribution shape
+        parameters must be provided.
+
+        If `guess` is not provided, guesses for the decision variables will
+        not be passed to the optimizer. If `guess` is provided, guesses for
+        any missing parameters will be set at the mean of the lower and
+        upper bounds. Guesses for parameters which must be integral will be
+        rounded to integral values, and guesses that lie outside the
+        intersection of the user-provided bounds and the domain of the
+        distribution will be clipped.
+    method : {'mle', 'mse'}
+        With ``method="mle"`` (default), the fit is computed by minimizing
+        the negative log-likelihood function. A large, finite penalty
+        (rather than infinite negative log-likelihood) is applied for
+        observations beyond the support of the distribution.
+        With ``method="mse"``, the fit is computed by minimizing
+        the negative log-product spacing function. The same penalty is applied
+        for observations beyond the support. We follow the approach of [1]_,
+        which is generalized for samples with repeated observations.
+    optimizer : callable, optional
+        `optimizer` is a callable that accepts the following positional
+        argument.
+
+        fun : callable
+            The objective function to be optimized. `fun` accepts one argument
+            ``x``, candidate shape parameters of the distribution, and returns
+            the objective function value given ``x``, `dist`, and the provided
+            `data`.
+            The job of `optimizer` is to find values of the decision variables
+            that minimizes `fun`.
+
+        `optimizer` must also accept the following keyword argument.
+
+        bounds : sequence of tuples
+            The bounds on values of the decision variables; each element will
+            be a tuple containing the lower and upper bound on a decision
+            variable.
+
+        If `guess` is provided, `optimizer` must also accept the following
+        keyword argument.
+
+        x0 : array_like
+            The guesses for each decision variable.
+
+        If the distribution has any shape parameters that must be integral or
+        if the distribution is discrete and the location parameter is not
+        fixed, `optimizer` must also accept the following keyword argument.
+
+        integrality : array_like of bools
+            For each decision variable, True if the decision variable
+            must be constrained to integer values and False if the decision
+            variable is continuous.
+
+        `optimizer` must return an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal values of
+        the decision variables in an attribute ``x``. If attributes
+        ``fun``, ``status``, or ``message`` are provided, they will be
+        included in the result object returned by `fit`.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.FitResult`
+        An object with the following fields.
+
+        params : namedtuple
+            A namedtuple containing the maximum likelihood estimates of the
+            shape parameters, location, and (if applicable) scale of the
+            distribution.
+        success : bool or None
+            Whether the optimizer considered the optimization to terminate
+            successfully or not.
+        message : str or None
+            Any status message provided by the optimizer.
+
+        The object has the following method:
+
+        nllf(params=None, data=None)
+            By default, the negative log-likelihood function at the fitted
+            `params` for the given `data`. Accepts a tuple containing
+            alternative shapes, location, and scale of the distribution and
+            an array of alternative data.
+
+        plot(ax=None)
+            Superposes the PDF/PMF of the fitted distribution over a normalized
+            histogram of the data.
+
+    See Also
+    --------
+    rv_continuous,  rv_discrete
+
+    Notes
+    -----
+    Optimization is more likely to converge to the maximum likelihood estimate
+    when the user provides tight bounds containing the maximum likelihood
+    estimate. For example, when fitting a binomial distribution to data, the
+    number of experiments underlying each sample may be known, in which case
+    the corresponding shape parameter ``n`` can be fixed.
+
+    References
+    ----------
+    .. [1] Shao, Yongzhao, and Marjorie G. Hahn. "Maximum product of spacings
+           method: a unified formulation with illustration of strong
+           consistency." Illinois Journal of Mathematics 43.3 (1999): 489-499.
+
+    Examples
+    --------
+    Suppose we wish to fit a distribution to the following data.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> dist = stats.nbinom
+    >>> shapes = (5, 0.5)
+    >>> data = dist.rvs(*shapes, size=1000, random_state=rng)
+
+    Suppose we do not know how the data were generated, but we suspect that
+    it follows a negative binomial distribution with parameters *n* and *p*\.
+    (See `scipy.stats.nbinom`.) We believe that the parameter *n* was fewer
+    than 30, and we know that the parameter *p* must lie on the interval
+    [0, 1]. We record this information in a variable `bounds` and pass
+    this information to `fit`.
+
+    >>> bounds = [(0, 30), (0, 1)]
+    >>> res = stats.fit(dist, data, bounds)
+
+    `fit` searches within the user-specified `bounds` for the
+    values that best match the data (in the sense of maximum likelihood
+    estimation). In this case, it found shape values similar to those
+    from which the data were actually generated.
+
+    >>> res.params
+    FitParams(n=5.0, p=0.5028157644634368, loc=0.0)  # may vary
+
+    We can visualize the results by superposing the probability mass function
+    of the distribution (with the shapes fit to the data) over a normalized
+    histogram of the data.
+
+    >>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
+    >>> res.plot()
+    >>> plt.show()
+
+    Note that the estimate for *n* was exactly integral; this is because
+    the domain of the `nbinom` PMF includes only integral *n*, and the `nbinom`
+    object "knows" that. `nbinom` also knows that the shape *p* must be a
+    value between 0 and 1. In such a case - when the domain of the distribution
+    with respect to a parameter is finite - we are not required to specify
+    bounds for the parameter.
+
+    >>> bounds = {'n': (0, 30)}  # omit parameter p using a `dict`
+    >>> res2 = stats.fit(dist, data, bounds)
+    >>> res2.params
+    FitParams(n=5.0, p=0.5016492009232932, loc=0.0)  # may vary
+
+    If we wish to force the distribution to be fit with *n* fixed at 6, we can
+    set both the lower and upper bounds on *n* to 6. Note, however, that the
+    value of the objective function being optimized is typically worse (higher)
+    in this case.
+
+    >>> bounds = {'n': (6, 6)}  # fix parameter `n`
+    >>> res3 = stats.fit(dist, data, bounds)
+    >>> res3.params
+    FitParams(n=6.0, p=0.5486556076755706, loc=0.0)  # may vary
+    >>> res3.nllf() > res.nllf()
+    True  # may vary
+
+    Note that the numerical results of the previous examples are typical, but
+    they may vary because the default optimizer used by `fit`,
+    `scipy.optimize.differential_evolution`, is stochastic. However, we can
+    customize the settings used by the optimizer to ensure reproducibility -
+    or even use a different optimizer entirely - using the `optimizer`
+    parameter.
+
+    >>> from scipy.optimize import differential_evolution
+    >>> rng = np.random.default_rng(767585560716548)
+    >>> def optimizer(fun, bounds, *, integrality):
+    ...     return differential_evolution(fun, bounds, strategy='best2bin',
+    ...                                   rng=rng, integrality=integrality)
+    >>> bounds = [(0, 30), (0, 1)]
+    >>> res4 = stats.fit(dist, data, bounds, optimizer=optimizer)
+    >>> res4.params
+    FitParams(n=5.0, p=0.5015183149259951, loc=0.0)
+
+    """
+    # --- Input Validation / Standardization --- #
+    user_bounds = bounds
+    user_guess = guess
+
+    # distribution input validation and information collection
+    if hasattr(dist, "pdf"):  # can't use isinstance for types
+        default_bounds = {'loc': (0, 0), 'scale': (1, 1)}
+        discrete = False
+    elif hasattr(dist, "pmf"):
+        default_bounds = {'loc': (0, 0)}
+        discrete = True
+    else:
+        message = ("`dist` must be an instance of `rv_continuous` "
+                   "or `rv_discrete.`")
+        raise ValueError(message)
+
+    try:
+        param_info = dist._param_info()
+    except AttributeError as e:
+        message = (f"Distribution `{dist.name}` is not yet supported by "
+                   "`scipy.stats.fit` because shape information has "
+                   "not been defined.")
+        raise ValueError(message) from e
+
+    # data input validation
+    data = np.asarray(data)
+    if data.ndim != 1:
+        message = "`data` must be exactly one-dimensional."
+        raise ValueError(message)
+    if not (np.issubdtype(data.dtype, np.number)
+            and np.all(np.isfinite(data))):
+        message = "All elements of `data` must be finite numbers."
+        raise ValueError(message)
+
+    # bounds input validation and information collection
+    n_params = len(param_info)
+    n_shapes = n_params - (1 if discrete else 2)
+    param_list = [param.name for param in param_info]
+    param_names = ", ".join(param_list)
+    shape_names = ", ".join(param_list[:n_shapes])
+
+    if user_bounds is None:
+        user_bounds = {}
+
+    if isinstance(user_bounds, dict):
+        default_bounds.update(user_bounds)
+        user_bounds = default_bounds
+        user_bounds_array = np.empty((n_params, 2))
+        for i in range(n_params):
+            param_name = param_info[i].name
+            user_bound = user_bounds.pop(param_name, None)
+            if user_bound is None:
+                user_bound = param_info[i].domain
+            user_bounds_array[i] = user_bound
+        if user_bounds:
+            message = ("Bounds provided for the following unrecognized "
+                       f"parameters will be ignored: {set(user_bounds)}")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    else:
+        try:
+            user_bounds = np.asarray(user_bounds, dtype=float)
+            if user_bounds.size == 0:
+                user_bounds = np.empty((0, 2))
+        except ValueError as e:
+            message = ("Each element of a `bounds` sequence must be a tuple "
+                       "containing two elements: the lower and upper bound of "
+                       "a distribution parameter.")
+            raise ValueError(message) from e
+        if (user_bounds.ndim != 2 or user_bounds.shape[1] != 2):
+            message = ("Each element of `bounds` must be a tuple specifying "
+                       "the lower and upper bounds of a shape parameter")
+            raise ValueError(message)
+        if user_bounds.shape[0] < n_shapes:
+            message = (f"A `bounds` sequence must contain at least {n_shapes} "
+                       "elements: tuples specifying the lower and upper "
+                       f"bounds of all shape parameters {shape_names}.")
+            raise ValueError(message)
+        if user_bounds.shape[0] > n_params:
+            message = ("A `bounds` sequence may not contain more than "
+                       f"{n_params} elements: tuples specifying the lower and "
+                       "upper bounds of distribution parameters "
+                       f"{param_names}.")
+            raise ValueError(message)
+
+        user_bounds_array = np.empty((n_params, 2))
+        user_bounds_array[n_shapes:] = list(default_bounds.values())
+        user_bounds_array[:len(user_bounds)] = user_bounds
+
+    user_bounds = user_bounds_array
+    validated_bounds = []
+    for i in range(n_params):
+        name = param_info[i].name
+        user_bound = user_bounds_array[i]
+        param_domain = param_info[i].domain
+        integral = param_info[i].integrality
+        combined = _combine_bounds(name, user_bound, param_domain, integral)
+        validated_bounds.append(combined)
+
+    bounds = np.asarray(validated_bounds)
+    integrality = [param.integrality for param in param_info]
+
+    # guess input validation
+
+    if user_guess is None:
+        guess_array = None
+    elif isinstance(user_guess, dict):
+        default_guess = {param.name: np.mean(bound)
+                         for param, bound in zip(param_info, bounds)}
+        unrecognized = set(user_guess) - set(default_guess)
+        if unrecognized:
+            message = ("Guesses provided for the following unrecognized "
+                       f"parameters will be ignored: {unrecognized}")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+        default_guess.update(user_guess)
+
+        message = ("Each element of `guess` must be a scalar "
+                   "guess for a distribution parameter.")
+        try:
+            guess_array = np.asarray([default_guess[param.name]
+                                      for param in param_info], dtype=float)
+        except ValueError as e:
+            raise ValueError(message) from e
+
+    else:
+        message = ("Each element of `guess` must be a scalar "
+                   "guess for a distribution parameter.")
+        try:
+            user_guess = np.asarray(user_guess, dtype=float)
+        except ValueError as e:
+            raise ValueError(message) from e
+        if user_guess.ndim != 1:
+            raise ValueError(message)
+        if user_guess.shape[0] < n_shapes:
+            message = (f"A `guess` sequence must contain at least {n_shapes} "
+                       "elements: scalar guesses for the distribution shape "
+                       f"parameters {shape_names}.")
+            raise ValueError(message)
+        if user_guess.shape[0] > n_params:
+            message = ("A `guess` sequence may not contain more than "
+                       f"{n_params} elements: scalar guesses for the "
+                       f"distribution parameters {param_names}.")
+            raise ValueError(message)
+
+        guess_array = np.mean(bounds, axis=1)
+        guess_array[:len(user_guess)] = user_guess
+
+    if guess_array is not None:
+        guess_rounded = guess_array.copy()
+
+        guess_rounded[integrality] = np.round(guess_rounded[integrality])
+        rounded = np.where(guess_rounded != guess_array)[0]
+        for i in rounded:
+            message = (f"Guess for parameter `{param_info[i].name}` "
+                       f"rounded from {guess_array[i]} to {guess_rounded[i]}.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        guess_clipped = np.clip(guess_rounded, bounds[:, 0], bounds[:, 1])
+        clipped = np.where(guess_clipped != guess_rounded)[0]
+        for i in clipped:
+            message = (f"Guess for parameter `{param_info[i].name}` "
+                       f"clipped from {guess_rounded[i]} to "
+                       f"{guess_clipped[i]}.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        guess = guess_clipped
+    else:
+        guess = None
+
+    # --- Fitting --- #
+    def nllf(free_params, data=data):  # bind data NOW
+        with np.errstate(invalid='ignore', divide='ignore'):
+            return dist._penalized_nnlf(free_params, data)
+
+    def nlpsf(free_params, data=data):  # bind data NOW
+        with np.errstate(invalid='ignore', divide='ignore'):
+            return dist._penalized_nlpsf(free_params, data)
+
+    methods = {'mle': nllf, 'mse': nlpsf}
+    objective = methods[method.lower()]
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        kwds = {}
+        if bounds is not None:
+            kwds['bounds'] = bounds
+        if np.any(integrality):
+            kwds['integrality'] = integrality
+        if guess is not None:
+            kwds['x0'] = guess
+        res = optimizer(objective, **kwds)
+
+    return FitResult(dist, data, discrete, res)
+
+
+GoodnessOfFitResult = namedtuple('GoodnessOfFitResult',
+                                 ('fit_result', 'statistic', 'pvalue',
+                                  'null_distribution'))
+
+
+@_transition_to_rng('random_state')
+def goodness_of_fit(dist, data, *, known_params=None, fit_params=None,
+                    guessed_params=None, statistic='ad', n_mc_samples=9999,
+                    rng=None):
+    r"""
+    Perform a goodness of fit test comparing data to a distribution family.
+
+    Given a distribution family and data, perform a test of the null hypothesis
+    that the data were drawn from a distribution in that family. Any known
+    parameters of the distribution may be specified. Remaining parameters of
+    the distribution will be fit to the data, and the p-value of the test
+    is computed accordingly. Several statistics for comparing the distribution
+    to data are available.
+
+    Parameters
+    ----------
+    dist : `scipy.stats.rv_continuous`
+        The object representing the distribution family under the null
+        hypothesis.
+    data : 1D array_like
+        Finite, uncensored data to be tested.
+    known_params : dict, optional
+        A dictionary containing name-value pairs of known distribution
+        parameters. Monte Carlo samples are randomly drawn from the
+        null-hypothesized distribution with these values of the parameters.
+        Before the statistic is evaluated for the observed `data` and each
+        Monte Carlo sample, only remaining unknown parameters of the
+        null-hypothesized distribution family are fit to the samples; the
+        known parameters are held fixed. If all parameters of the distribution
+        family are known, then the step of fitting the distribution family to
+        each sample is omitted.
+    fit_params : dict, optional
+        A dictionary containing name-value pairs of distribution parameters
+        that have already been fit to the data, e.g. using `scipy.stats.fit`
+        or the ``fit`` method of `dist`. Monte Carlo samples are drawn from the
+        null-hypothesized distribution with these specified values of the
+        parameter. However, these and all other unknown parameters of the
+        null-hypothesized distribution family are always fit to the sample,
+        whether that is the observed `data` or a Monte Carlo sample, before
+        the statistic is evaluated.
+    guessed_params : dict, optional
+        A dictionary containing name-value pairs of distribution parameters
+        which have been guessed. These parameters are always considered as
+        free parameters and are fit both to the provided `data` as well as
+        to the Monte Carlo samples drawn from the null-hypothesized
+        distribution. The purpose of these `guessed_params` is to be used as
+        initial values for the numerical fitting procedure.
+    statistic : {"ad", "ks", "cvm", "filliben"} or callable, optional
+        The statistic used to compare data to a distribution after fitting
+        unknown parameters of the distribution family to the data. The
+        Anderson-Darling ("ad") [1]_, Kolmogorov-Smirnov ("ks") [1]_,
+        Cramer-von Mises ("cvm") [1]_, and Filliben ("filliben") [7]_
+        statistics are available.  Alternatively, a callable with signature
+        ``(dist, data, axis)`` may be supplied to compute the statistic. Here
+        ``dist`` is a frozen distribution object (potentially with array
+        parameters), ``data`` is an array of Monte Carlo samples (of
+        compatible shape), and ``axis`` is the axis of ``data`` along which
+        the statistic must be computed.
+    n_mc_samples : int, default: 9999
+        The number of Monte Carlo samples drawn from the null hypothesized
+        distribution to form the null distribution of the statistic. The
+        sample size of each is the same as the given `data`.
+    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 : GoodnessOfFitResult
+        An object with the following attributes.
+
+        fit_result : `~scipy.stats._result_classes.FitResult`
+            An object representing the fit of the provided `dist` to `data`.
+            This  object includes the values of distribution family parameters
+            that fully define the null-hypothesized distribution, that is,
+            the distribution from which Monte Carlo samples are drawn.
+        statistic : float
+            The value of the statistic comparing provided `data` to the
+            null-hypothesized distribution.
+        pvalue : float
+            The proportion of elements in the null distribution with
+            statistic values at least as extreme as the statistic value of the
+            provided `data`.
+        null_distribution : ndarray
+            The value of the statistic for each Monte Carlo sample
+            drawn from the null-hypothesized distribution.
+
+    Notes
+    -----
+    This is a generalized Monte Carlo goodness-of-fit procedure, special cases
+    of which correspond with various Anderson-Darling tests, Lilliefors' test,
+    etc. The test is described in [2]_, [3]_, and [4]_ as a parametric
+    bootstrap test. This is a Monte Carlo test in which parameters that
+    specify the distribution from which samples are drawn have been estimated
+    from the data. We describe the test using "Monte Carlo" rather than
+    "parametric bootstrap" throughout to avoid confusion with the more familiar
+    nonparametric bootstrap, and describe how the test is performed below.
+
+    *Traditional goodness of fit tests*
+
+    Traditionally, critical values corresponding with a fixed set of
+    significance levels are pre-calculated using Monte Carlo methods. Users
+    perform the test by calculating the value of the test statistic only for
+    their observed `data` and comparing this value to tabulated critical
+    values. This practice is not very flexible, as tables are not available for
+    all distributions and combinations of known and unknown parameter values.
+    Also, results can be inaccurate when critical values are interpolated from
+    limited tabulated data to correspond with the user's sample size and
+    fitted parameter values. To overcome these shortcomings, this function
+    allows the user to perform the Monte Carlo trials adapted to their
+    particular data.
+
+    *Algorithmic overview*
+
+    In brief, this routine executes the following steps:
+
+      1. Fit unknown parameters to the given `data`, thereby forming the
+         "null-hypothesized" distribution, and compute the statistic of
+         this pair of data and distribution.
+      2. Draw random samples from this null-hypothesized distribution.
+      3. Fit the unknown parameters to each random sample.
+      4. Calculate the statistic between each sample and the distribution that
+         has been fit to the sample.
+      5. Compare the value of the statistic corresponding with `data` from (1)
+         against the values of the statistic corresponding with the random
+         samples from (4). The p-value is the proportion of samples with a
+         statistic value greater than or equal to the statistic of the observed
+         data.
+
+    In more detail, the steps are as follows.
+
+    First, any unknown parameters of the distribution family specified by
+    `dist` are fit to the provided `data` using maximum likelihood estimation.
+    (One exception is the normal distribution with unknown location and scale:
+    we use the bias-corrected standard deviation ``np.std(data, ddof=1)`` for
+    the scale as recommended in [1]_.)
+    These values of the parameters specify a particular member of the
+    distribution family referred to as the "null-hypothesized distribution",
+    that is, the distribution from which the data were sampled under the null
+    hypothesis. The `statistic`, which compares data to a distribution, is
+    computed between `data` and the null-hypothesized distribution.
+
+    Next, many (specifically `n_mc_samples`) new samples, each containing the
+    same number of observations as `data`, are drawn from the
+    null-hypothesized distribution. All unknown parameters of the distribution
+    family `dist` are fit to *each resample*, and the `statistic` is computed
+    between each sample and its corresponding fitted distribution. These
+    values of the statistic form the Monte Carlo null distribution (not to be
+    confused with the "null-hypothesized distribution" above).
+
+    The p-value of the test is the proportion of statistic values in the Monte
+    Carlo null distribution that are at least as extreme as the statistic value
+    of the provided `data`. More precisely, the p-value is given by
+
+    .. math::
+
+        p = \frac{b + 1}
+                 {m + 1}
+
+    where :math:`b` is the number of statistic values in the Monte Carlo null
+    distribution that are greater than or equal to the statistic value
+    calculated for `data`, and :math:`m` is the number of elements in the
+    Monte Carlo null distribution (`n_mc_samples`). The addition of :math:`1`
+    to the numerator and denominator can be thought of as including the
+    value of the statistic corresponding with `data` in the null distribution,
+    but a more formal explanation is given in [5]_.
+
+    *Limitations*
+
+    The test can be very slow for some distribution families because unknown
+    parameters of the distribution family must be fit to each of the Monte
+    Carlo samples, and for most distributions in SciPy, distribution fitting
+    performed via numerical optimization.
+
+    *Anti-Pattern*
+
+    For this reason, it may be tempting
+    to treat parameters of the distribution pre-fit to `data` (by the user)
+    as though they were `known_params`, as specification of all parameters of
+    the distribution precludes the need to fit the distribution to each Monte
+    Carlo sample. (This is essentially how the original Kilmogorov-Smirnov
+    test is performed.) Although such a test can provide evidence against the
+    null hypothesis, the test is conservative in the sense that small p-values
+    will tend to (greatly) *overestimate* the probability of making a type I
+    error (that is, rejecting the null hypothesis although it is true), and the
+    power of the test is low (that is, it is less likely to reject the null
+    hypothesis even when the null hypothesis is false).
+    This is because the Monte Carlo samples are less likely to agree with the
+    null-hypothesized distribution as well as `data`. This tends to increase
+    the values of the statistic recorded in the null distribution, so that a
+    larger number of them exceed the value of statistic for `data`, thereby
+    inflating the p-value.
+
+    References
+    ----------
+    .. [1] M. A. Stephens (1974). "EDF Statistics for Goodness of Fit and
+           Some Comparisons." Journal of the American Statistical Association,
+           Vol. 69, pp. 730-737.
+    .. [2] W. Stute, W. G. Manteiga, and M. P. Quindimil (1993).
+           "Bootstrap based goodness-of-fit-tests." Metrika 40.1: 243-256.
+    .. [3] C. Genest, & B Rémillard. (2008). "Validity of the parametric
+           bootstrap for goodness-of-fit testing in semiparametric models."
+           Annales de l'IHP Probabilités et statistiques. Vol. 44. No. 6.
+    .. [4] I. Kojadinovic and J. Yan (2012). "Goodness-of-fit testing based on
+           a weighted bootstrap: A fast large-sample alternative to the
+           parametric bootstrap." Canadian Journal of Statistics 40.3: 480-500.
+    .. [5] B. Phipson and G. K. Smyth (2010). "Permutation P-values Should
+           Never Be Zero: Calculating Exact P-values When Permutations Are
+           Randomly Drawn." Statistical Applications in Genetics and Molecular
+           Biology 9.1.
+    .. [6] H. W. Lilliefors (1967). "On the Kolmogorov-Smirnov test for
+           normality with mean and variance unknown." Journal of the American
+           statistical Association 62.318: 399-402.
+    .. [7] Filliben, James J. "The probability plot correlation coefficient
+           test for normality." Technometrics 17.1 (1975): 111-117.
+
+    Examples
+    --------
+    A well-known test of the null hypothesis that data were drawn from a
+    given distribution is the Kolmogorov-Smirnov (KS) test, available in SciPy
+    as `scipy.stats.ks_1samp`. Suppose we wish to test whether the following
+    data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.uniform.rvs(size=75, random_state=rng)
+
+    were sampled from a normal distribution. To perform a KS test, the
+    empirical distribution function of the observed data will be compared
+    against the (theoretical) cumulative distribution function of a normal
+    distribution. Of course, to do this, the normal distribution under the null
+    hypothesis must be fully specified. This is commonly done by first fitting
+    the ``loc`` and ``scale`` parameters of the distribution to the observed
+    data, then performing the test.
+
+    >>> loc, scale = np.mean(x), np.std(x, ddof=1)
+    >>> cdf = stats.norm(loc, scale).cdf
+    >>> stats.ks_1samp(x, cdf)
+    KstestResult(statistic=0.1119257570456813,
+                 pvalue=0.2827756409939257,
+                 statistic_location=0.7751845155861765,
+                 statistic_sign=-1)
+
+    An advantage of the KS-test is that the p-value - the probability of
+    obtaining a value of the test statistic under the null hypothesis as
+    extreme as the value obtained from the observed data - can be calculated
+    exactly and efficiently. `goodness_of_fit` can only approximate these
+    results.
+
+    >>> known_params = {'loc': loc, 'scale': scale}
+    >>> res = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
+    ...                             statistic='ks', rng=rng)
+    >>> res.statistic, res.pvalue
+    (0.1119257570456813, 0.2788)
+
+    The statistic matches exactly, but the p-value is estimated by forming
+    a "Monte Carlo null distribution", that is, by explicitly drawing random
+    samples from `scipy.stats.norm` with the provided parameters and
+    calculating the stastic for each. The fraction of these statistic values
+    at least as extreme as ``res.statistic`` approximates the exact p-value
+    calculated by `scipy.stats.ks_1samp`.
+
+    However, in many cases, we would prefer to test only that the data were
+    sampled from one of *any* member of the normal distribution family, not
+    specifically from the normal distribution with the location and scale
+    fitted to the observed sample. In this case, Lilliefors [6]_ argued that
+    the KS test is far too conservative (that is, the p-value overstates
+    the actual probability of rejecting a true null hypothesis) and thus lacks
+    power - the ability to reject the null hypothesis when the null hypothesis
+    is actually false.
+    Indeed, our p-value above is approximately 0.28, which is far too large
+    to reject the null hypothesis at any common significance level.
+
+    Consider why this might be. Note that in the KS test above, the statistic
+    always compares data against the CDF of a normal distribution fitted to the
+    *observed data*. This tends to reduce the value of the statistic for the
+    observed data, but it is "unfair" when computing the statistic for other
+    samples, such as those we randomly draw to form the Monte Carlo null
+    distribution. It is easy to correct for this: whenever we compute the KS
+    statistic of a sample, we use the CDF of a normal distribution fitted
+    to *that sample*. The null distribution in this case has not been
+    calculated exactly and is tyically approximated using Monte Carlo methods
+    as described above. This is where `goodness_of_fit` excels.
+
+    >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ks',
+    ...                             rng=rng)
+    >>> res.statistic, res.pvalue
+    (0.1119257570456813, 0.0196)
+
+    Indeed, this p-value is much smaller, and small enough to (correctly)
+    reject the null hypothesis at common significance levels, including 5% and
+    2.5%.
+
+    However, the KS statistic is not very sensitive to all deviations from
+    normality. The original advantage of the KS statistic was the ability
+    to compute the null distribution theoretically, but a more sensitive
+    statistic - resulting in a higher test power - can be used now that we can
+    approximate the null distribution
+    computationally. The Anderson-Darling statistic [1]_ tends to be more
+    sensitive, and critical values of the this statistic have been tabulated
+    for various significance levels and sample sizes using Monte Carlo methods.
+
+    >>> res = stats.anderson(x, 'norm')
+    >>> print(res.statistic)
+    1.2139573337497467
+    >>> print(res.critical_values)
+    [0.549 0.625 0.75  0.875 1.041]
+    >>> print(res.significance_level)
+    [15.  10.   5.   2.5  1. ]
+
+    Here, the observed value of the statistic exceeds the critical value
+    corresponding with a 1% significance level. This tells us that the p-value
+    of the observed data is less than 1%, but what is it? We could interpolate
+    from these (already-interpolated) values, but `goodness_of_fit` can
+    estimate it directly.
+
+    >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ad',
+    ...                             rng=rng)
+    >>> res.statistic, res.pvalue
+    (1.2139573337497467, 0.0034)
+
+    A further advantage is that use of `goodness_of_fit` is not limited to
+    a particular set of distributions or conditions on which parameters
+    are known versus which must be estimated from data. Instead,
+    `goodness_of_fit` can estimate p-values relatively quickly for any
+    distribution with a sufficiently fast and reliable ``fit`` method. For
+    instance, here we perform a goodness of fit test using the Cramer-von Mises
+    statistic against the Rayleigh distribution with known location and unknown
+    scale.
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.chi(df=2.2, loc=0, scale=2).rvs(size=1000, random_state=rng)
+    >>> res = stats.goodness_of_fit(stats.rayleigh, x, statistic='cvm',
+    ...                             known_params={'loc': 0}, rng=rng)
+
+    This executes fairly quickly, but to check the reliability of the ``fit``
+    method, we should inspect the fit result.
+
+    >>> res.fit_result  # location is as specified, and scale is reasonable
+      params: FitParams(loc=0.0, scale=2.1026719844231243)
+     success: True
+     message: 'The fit was performed successfully.'
+    >>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
+    >>> res.fit_result.plot()
+    >>> plt.show()
+
+    If the distribution is not fit to the observed data as well as possible,
+    the test may not control the type I error rate, that is, the chance of
+    rejecting the null hypothesis even when it is true.
+
+    We should also look for extreme outliers in the null distribution that
+    may be caused by unreliable fitting. These do not necessarily invalidate
+    the result, but they tend to reduce the test's power.
+
+    >>> _, ax = plt.subplots()
+    >>> ax.hist(np.log10(res.null_distribution))
+    >>> ax.set_xlabel("log10 of CVM statistic under the null hypothesis")
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_title("Histogram of the Monte Carlo null distribution")
+    >>> plt.show()
+
+    This plot seems reassuring.
+
+    If ``fit`` method is working reliably, and if the distribution of the test
+    statistic is not particularly sensitive to the values of the fitted
+    parameters, then the p-value provided by `goodness_of_fit` is expected to
+    be a good approximation.
+
+    >>> res.statistic, res.pvalue
+    (0.2231991510248692, 0.0525)
+
+    """
+    args = _gof_iv(dist, data, known_params, fit_params, guessed_params,
+                   statistic, n_mc_samples, rng)
+    (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
+     guessed_rfd_params, statistic, n_mc_samples_int, rng) = args
+
+    # Fit null hypothesis distribution to data
+    nhd_fit_fun = _get_fit_fun(dist, data, guessed_nhd_params,
+                               fixed_nhd_params)
+    nhd_vals = nhd_fit_fun(data)
+    nhd_dist = dist(*nhd_vals)
+
+    def rvs(size):
+        return nhd_dist.rvs(size=size, random_state=rng)
+
+    # Define statistic
+    fit_fun = _get_fit_fun(dist, data, guessed_rfd_params, fixed_rfd_params)
+    if callable(statistic):
+        compare_fun = statistic
+    else:
+        compare_fun = _compare_dict[statistic]
+    alternative = getattr(compare_fun, 'alternative', 'greater')
+
+    def statistic_fun(data, axis):
+        # Make things simple by always working along the last axis.
+        data = np.moveaxis(data, axis, -1)
+        rfd_vals = fit_fun(data)
+        rfd_dist = dist(*rfd_vals)
+        return compare_fun(rfd_dist, data, axis=-1)
+
+    res = stats.monte_carlo_test(data, rvs, statistic_fun, vectorized=True,
+                                 n_resamples=n_mc_samples, axis=-1,
+                                 alternative=alternative)
+    opt_res = optimize.OptimizeResult()
+    opt_res.success = True
+    opt_res.message = "The fit was performed successfully."
+    opt_res.x = nhd_vals
+    # Only continuous distributions for now, hence discrete=False
+    # There's no fundamental limitation; it's just that we're not using
+    # stats.fit, discrete distributions don't have `fit` method, and
+    # we haven't written any vectorized fit functions for a discrete
+    # distribution yet.
+    return GoodnessOfFitResult(FitResult(dist, data, False, opt_res),
+                               res.statistic, res.pvalue,
+                               res.null_distribution)
+
+
+def _get_fit_fun(dist, data, guessed_params, fixed_params):
+
+    shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
+    param_names = shape_names + ['loc', 'scale']
+    fparam_names = ['f'+name for name in param_names]
+    all_fixed = not set(fparam_names).difference(fixed_params)
+    guessed_shapes = [guessed_params.pop(x, None)
+                      for x in shape_names if x in guessed_params]
+
+    if all_fixed:
+        def fit_fun(data):
+            return [fixed_params[name] for name in fparam_names]
+    # Define statistic, including fitting distribution to data
+    elif dist in _fit_funs:
+        def fit_fun(data):
+            params = _fit_funs[dist](data, **fixed_params)
+            params = np.asarray(np.broadcast_arrays(*params))
+            if params.ndim > 1:
+                params = params[..., np.newaxis]
+            return params
+    else:
+        def fit_fun_1d(data):
+            return dist.fit(data, *guessed_shapes, **guessed_params,
+                            **fixed_params)
+
+        def fit_fun(data):
+            params = np.apply_along_axis(fit_fun_1d, axis=-1, arr=data)
+            if params.ndim > 1:
+                params = params.T[..., np.newaxis]
+            return params
+
+    return fit_fun
+
+
+# Vectorized fitting functions. These are to accept ND `data` in which each
+# row (slice along last axis) is a sample to fit and scalar fixed parameters.
+# They return a tuple of shape parameter arrays, each of shape data.shape[:-1].
+def _fit_norm(data, floc=None, fscale=None):
+    loc = floc
+    scale = fscale
+    if loc is None and scale is None:
+        loc = np.mean(data, axis=-1)
+        scale = np.std(data, ddof=1, axis=-1)
+    elif loc is None:
+        loc = np.mean(data, axis=-1)
+    elif scale is None:
+        scale = np.sqrt(((data - loc)**2).mean(axis=-1))
+    return loc, scale
+
+
+_fit_funs = {stats.norm: _fit_norm}  # type: ignore[attr-defined]
+
+
+# Vectorized goodness of fit statistic functions. These accept a frozen
+# distribution object and `data` in which each row (slice along last axis) is
+# a sample.
+
+
+def _anderson_darling(dist, data, axis):
+    x = np.sort(data, axis=-1)
+    n = data.shape[-1]
+    i = np.arange(1, n+1)
+    Si = (2*i - 1)/n * (dist.logcdf(x) + dist.logsf(x[..., ::-1]))
+    S = np.sum(Si, axis=-1)
+    return -n - S
+
+
+def _compute_dplus(cdfvals):  # adapted from _stats_py before gh-17062
+    n = cdfvals.shape[-1]
+    return (np.arange(1.0, n + 1) / n - cdfvals).max(axis=-1)
+
+
+def _compute_dminus(cdfvals):
+    n = cdfvals.shape[-1]
+    return (cdfvals - np.arange(0.0, n)/n).max(axis=-1)
+
+
+def _kolmogorov_smirnov(dist, data, axis=-1):
+    x = np.sort(data, axis=axis)
+    cdfvals = dist.cdf(x)
+    cdfvals = np.moveaxis(cdfvals, axis, -1)
+    Dplus = _compute_dplus(cdfvals)  # always works along last axis
+    Dminus = _compute_dminus(cdfvals)
+    return np.maximum(Dplus, Dminus)
+
+
+def _corr(X, M):
+    # Correlation coefficient r, simplified and vectorized as we need it.
+    # See [7] Equation (2). Lemma 1/2 are only for distributions symmetric
+    # about 0.
+    Xm = X.mean(axis=-1, keepdims=True)
+    Mm = M.mean(axis=-1, keepdims=True)
+    num = np.sum((X - Xm) * (M - Mm), axis=-1)
+    den = np.sqrt(np.sum((X - Xm)**2, axis=-1) * np.sum((M - Mm)**2, axis=-1))
+    return num/den
+
+
+def _filliben(dist, data, axis):
+    # [7] Section 8 # 1
+    X = np.sort(data, axis=-1)
+
+    # [7] Section 8 # 2
+    n = data.shape[-1]
+    k = np.arange(1, n+1)
+    # Filliben used an approximation for the uniform distribution order
+    # statistic medians.
+    # m = (k - .3175)/(n + 0.365)
+    # m[-1] = 0.5**(1/n)
+    # m[0] = 1 - m[-1]
+    # We can just as easily use the (theoretically) exact values. See e.g.
+    # https://en.wikipedia.org/wiki/Order_statistic
+    # "Order statistics sampled from a uniform distribution"
+    m = stats.beta(k, n + 1 - k).median()
+
+    # [7] Section 8 # 3
+    M = dist.ppf(m)
+
+    # [7] Section 8 # 4
+    return _corr(X, M)
+_filliben.alternative = 'less'  # type: ignore[attr-defined]
+
+
+def _cramer_von_mises(dist, data, axis):
+    x = np.sort(data, axis=-1)
+    n = data.shape[-1]
+    cdfvals = dist.cdf(x)
+    u = (2*np.arange(1, n+1) - 1)/(2*n)
+    w = 1 / (12*n) + np.sum((u - cdfvals)**2, axis=-1)
+    return w
+
+
+_compare_dict = {"ad": _anderson_darling, "ks": _kolmogorov_smirnov,
+                 "cvm": _cramer_von_mises, "filliben": _filliben}
+
+
+def _gof_iv(dist, data, known_params, fit_params, guessed_params, statistic,
+            n_mc_samples, rng):
+
+    if not isinstance(dist, stats.rv_continuous):
+        message = ("`dist` must be a (non-frozen) instance of "
+                   "`stats.rv_continuous`.")
+        raise TypeError(message)
+
+    data = np.asarray(data, dtype=float)
+    if not data.ndim == 1:
+        message = "`data` must be a one-dimensional array of numbers."
+        raise ValueError(message)
+
+    # Leave validation of these key/value pairs to the `fit` method,
+    # but collect these into dictionaries that will be used
+    known_params = known_params or dict()
+    fit_params = fit_params or dict()
+    guessed_params = guessed_params or dict()
+
+    known_params_f = {("f"+key): val for key, val in known_params.items()}
+    fit_params_f = {("f"+key): val for key, val in fit_params.items()}
+
+    # These are the values of parameters of the null distribution family
+    # with which resamples are drawn
+    fixed_nhd_params = known_params_f.copy()
+    fixed_nhd_params.update(fit_params_f)
+
+    # These are fixed when fitting the distribution family to resamples
+    fixed_rfd_params = known_params_f.copy()
+
+    # These are used as guesses when fitting the distribution family to
+    # the original data
+    guessed_nhd_params = guessed_params.copy()
+
+    # These are used as guesses when fitting the distribution family to
+    # resamples
+    guessed_rfd_params = fit_params.copy()
+    guessed_rfd_params.update(guessed_params)
+
+    if not callable(statistic):
+        statistic = statistic.lower()
+        statistics = {'ad', 'ks', 'cvm', 'filliben'}
+        if statistic not in statistics:
+            message = f"`statistic` must be one of {statistics}."
+            raise ValueError(message)
+
+    n_mc_samples_int = int(n_mc_samples)
+    if n_mc_samples_int != n_mc_samples:
+        message = "`n_mc_samples` must be an integer."
+        raise TypeError(message)
+
+    rng = check_random_state(rng)
+
+    return (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
+            guessed_rfd_params, statistic, n_mc_samples_int, rng)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_hypotests.py b/python_embeded/Lib/site-packages/scipy/stats/_hypotests.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a461f79e33590d16adff0abe7eeefddc7a049fb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_hypotests.py
@@ -0,0 +1,2027 @@
+from collections import namedtuple
+from dataclasses import dataclass
+from math import comb
+import numpy as np
+import warnings
+from itertools import combinations
+import scipy.stats
+from scipy.optimize import shgo
+from . import distributions
+from ._common import ConfidenceInterval
+from ._continuous_distns import norm
+from scipy.special import gamma, kv, gammaln
+from scipy.fft import ifft
+from ._stats_pythran import _a_ij_Aij_Dij2
+from ._stats_pythran import (
+    _concordant_pairs as _P, _discordant_pairs as _Q
+)
+from ._axis_nan_policy import _axis_nan_policy_factory
+from scipy.stats import _stats_py
+
+__all__ = ['epps_singleton_2samp', 'cramervonmises', 'somersd',
+           'barnard_exact', 'boschloo_exact', 'cramervonmises_2samp',
+           'tukey_hsd', 'poisson_means_test']
+
+Epps_Singleton_2sampResult = namedtuple('Epps_Singleton_2sampResult',
+                                        ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(Epps_Singleton_2sampResult, n_samples=2, too_small=4)
+def epps_singleton_2samp(x, y, t=(0.4, 0.8)):
+    """Compute the Epps-Singleton (ES) test statistic.
+
+    Test the null hypothesis that two samples have the same underlying
+    probability distribution.
+
+    Parameters
+    ----------
+    x, y : array-like
+        The two samples of observations to be tested. Input must not have more
+        than one dimension. Samples can have different lengths, but both
+        must have at least five observations.
+    t : array-like, optional
+        The points (t1, ..., tn) where the empirical characteristic function is
+        to be evaluated. It should be positive distinct numbers. The default
+        value (0.4, 0.8) is proposed in [1]_. Input must not have more than
+        one dimension.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The associated p-value based on the asymptotic chi2-distribution.
+
+    See Also
+    --------
+    ks_2samp, anderson_ksamp
+
+    Notes
+    -----
+    Testing whether two samples are generated by the same underlying
+    distribution is a classical question in statistics. A widely used test is
+    the Kolmogorov-Smirnov (KS) test which relies on the empirical
+    distribution function. Epps and Singleton introduce a test based on the
+    empirical characteristic function in [1]_.
+
+    One advantage of the ES test compared to the KS test is that is does
+    not assume a continuous distribution. In [1]_, the authors conclude
+    that the test also has a higher power than the KS test in many
+    examples. They recommend the use of the ES test for discrete samples as
+    well as continuous samples with at least 25 observations each, whereas
+    `anderson_ksamp` is recommended for smaller sample sizes in the
+    continuous case.
+
+    The p-value is computed from the asymptotic distribution of the test
+    statistic which follows a `chi2` distribution. If the sample size of both
+    `x` and `y` is below 25, the small sample correction proposed in [1]_ is
+    applied to the test statistic.
+
+    The default values of `t` are determined in [1]_ by considering
+    various distributions and finding good values that lead to a high power
+    of the test in general. Table III in [1]_ gives the optimal values for
+    the distributions tested in that study. The values of `t` are scaled by
+    the semi-interquartile range in the implementation, see [1]_.
+
+    References
+    ----------
+    .. [1] T. W. Epps and K. J. Singleton, "An omnibus test for the two-sample
+       problem using the empirical characteristic function", Journal of
+       Statistical Computation and Simulation 26, p. 177--203, 1986.
+
+    .. [2] S. J. Goerg and J. Kaiser, "Nonparametric testing of distributions
+       - the Epps-Singleton two-sample test using the empirical characteristic
+       function", The Stata Journal 9(3), p. 454--465, 2009.
+
+    """
+    # x and y are converted to arrays by the decorator
+    t = np.asarray(t)
+    # check if x and y are valid inputs
+    nx, ny = len(x), len(y)
+    if (nx < 5) or (ny < 5):
+        raise ValueError('x and y should have at least 5 elements, but len(x) '
+                         f'= {nx} and len(y) = {ny}.')
+    if not np.isfinite(x).all():
+        raise ValueError('x must not contain nonfinite values.')
+    if not np.isfinite(y).all():
+        raise ValueError('y must not contain nonfinite values.')
+    n = nx + ny
+
+    # check if t is valid
+    if t.ndim > 1:
+        raise ValueError(f't must be 1d, but t.ndim equals {t.ndim}.')
+    if np.less_equal(t, 0).any():
+        raise ValueError('t must contain positive elements only.')
+
+    # rescale t with semi-iqr as proposed in [1]; import iqr here to avoid
+    # circular import
+    from scipy.stats import iqr
+    sigma = iqr(np.hstack((x, y))) / 2
+    ts = np.reshape(t, (-1, 1)) / sigma
+
+    # covariance estimation of ES test
+    gx = np.vstack((np.cos(ts*x), np.sin(ts*x))).T  # shape = (nx, 2*len(t))
+    gy = np.vstack((np.cos(ts*y), np.sin(ts*y))).T
+    cov_x = np.cov(gx.T, bias=True)  # the test uses biased cov-estimate
+    cov_y = np.cov(gy.T, bias=True)
+    est_cov = (n/nx)*cov_x + (n/ny)*cov_y
+    est_cov_inv = np.linalg.pinv(est_cov)
+    r = np.linalg.matrix_rank(est_cov_inv)
+    if r < 2*len(t):
+        warnings.warn('Estimated covariance matrix does not have full rank. '
+                      'This indicates a bad choice of the input t and the '
+                      'test might not be consistent.', # see p. 183 in [1]_
+                      stacklevel=2)
+
+    # compute test statistic w distributed asympt. as chisquare with df=r
+    g_diff = np.mean(gx, axis=0) - np.mean(gy, axis=0)
+    w = n*np.dot(g_diff.T, np.dot(est_cov_inv, g_diff))
+
+    # apply small-sample correction
+    if (max(nx, ny) < 25):
+        corr = 1.0/(1.0 + n**(-0.45) + 10.1*(nx**(-1.7) + ny**(-1.7)))
+        w = corr * w
+
+    chi2 = _stats_py._SimpleChi2(r)
+    p = _stats_py._get_pvalue(w, chi2, alternative='greater', symmetric=False, xp=np)
+
+    return Epps_Singleton_2sampResult(w, p)
+
+
+def poisson_means_test(k1, n1, k2, n2, *, diff=0, alternative='two-sided'):
+    r"""
+    Performs the Poisson means test, AKA the "E-test".
+
+    This is a test of the null hypothesis that the difference between means of
+    two Poisson distributions is `diff`. The samples are provided as the
+    number of events `k1` and `k2` observed within measurement intervals
+    (e.g. of time, space, number of observations) of sizes `n1` and `n2`.
+
+    Parameters
+    ----------
+    k1 : int
+        Number of events observed from distribution 1.
+    n1: float
+        Size of sample from distribution 1.
+    k2 : int
+        Number of events observed from distribution 2.
+    n2 : float
+        Size of sample from distribution 2.
+    diff : float, default=0
+        The hypothesized difference in means between the distributions
+        underlying the samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+          * 'two-sided': the difference between distribution means is not
+            equal to `diff`
+          * 'less': the difference between distribution means is less than
+            `diff`
+          * 'greater': the difference between distribution means is greater
+            than `diff`
+
+    Returns
+    -------
+    statistic : float
+        The test statistic (see [1]_ equation 3.3).
+    pvalue : float
+        The probability of achieving such an extreme value of the test
+        statistic under the null hypothesis.
+
+    Notes
+    -----
+
+    Let:
+
+    .. math:: X_1 \sim \mbox{Poisson}(\mathtt{n1}\lambda_1)
+
+    be a random variable independent of
+
+    .. math:: X_2  \sim \mbox{Poisson}(\mathtt{n2}\lambda_2)
+
+    and let ``k1`` and ``k2`` be the observed values of :math:`X_1`
+    and :math:`X_2`, respectively. Then `poisson_means_test` uses the number
+    of observed events ``k1`` and ``k2`` from samples of size ``n1`` and
+    ``n2``, respectively, to test the null hypothesis that
+
+    .. math::
+       H_0: \lambda_1 - \lambda_2 = \mathtt{diff}
+
+    A benefit of the E-test is that it has good power for small sample sizes,
+    which can reduce sampling costs [1]_. It has been evaluated and determined
+    to be more powerful than the comparable C-test, sometimes referred to as
+    the Poisson exact test.
+
+    References
+    ----------
+    .. [1]  Krishnamoorthy, K., & Thomson, J. (2004). A more powerful test for
+       comparing two Poisson means. Journal of Statistical Planning and
+       Inference, 119(1), 23-35.
+
+    .. [2]  Przyborowski, J., & Wilenski, H. (1940). Homogeneity of results in
+       testing samples from Poisson series: With an application to testing
+       clover seed for dodder. Biometrika, 31(3/4), 313-323.
+
+    Examples
+    --------
+
+    Suppose that a gardener wishes to test the number of dodder (weed) seeds
+    in a sack of clover seeds that they buy from a seed company. It has
+    previously been established that the number of dodder seeds in clover
+    follows the Poisson distribution.
+
+    A 100 gram sample is drawn from the sack before being shipped to the
+    gardener. The sample is analyzed, and it is found to contain no dodder
+    seeds; that is, `k1` is 0. However, upon arrival, the gardener draws
+    another 100 gram sample from the sack. This time, three dodder seeds are
+    found in the sample; that is, `k2` is 3. The gardener would like to
+    know if the difference is significant and not due to chance. The
+    null hypothesis is that the difference between the two samples is merely
+    due to chance, or that :math:`\lambda_1 - \lambda_2 = \mathtt{diff}`
+    where :math:`\mathtt{diff} = 0`. The alternative hypothesis is that the
+    difference is not due to chance, or :math:`\lambda_1 - \lambda_2 \ne 0`.
+    The gardener selects a significance level of 5% to reject the null
+    hypothesis in favor of the alternative [2]_.
+
+    >>> import scipy.stats as stats
+    >>> res = stats.poisson_means_test(0, 100, 3, 100)
+    >>> res.statistic, res.pvalue
+    (-1.7320508075688772, 0.08837900929018157)
+
+    The p-value is .088, indicating a near 9% chance of observing a value of
+    the test statistic under the null hypothesis. This exceeds 5%, so the
+    gardener does not reject the null hypothesis as the difference cannot be
+    regarded as significant at this level.
+    """
+
+    _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative)
+
+    # "for a given k_1 and k_2, an estimate of \lambda_2 is given by" [1] (3.4)
+    lmbd_hat2 = ((k1 + k2) / (n1 + n2) - diff * n1 / (n1 + n2))
+
+    # "\hat{\lambda_{2k}} may be less than or equal to zero ... and in this
+    # case the null hypothesis cannot be rejected ... [and] it is not necessary
+    # to compute the p-value". [1] page 26 below eq. (3.6).
+    if lmbd_hat2 <= 0:
+        return _stats_py.SignificanceResult(0, 1)
+
+    # The unbiased variance estimate [1] (3.2)
+    var = k1 / (n1 ** 2) + k2 / (n2 ** 2)
+
+    # The _observed_ pivot statistic from the input. It follows the
+    # unnumbered equation following equation (3.3) This is used later in
+    # comparison with the computed pivot statistics in an indicator function.
+    t_k1k2 = (k1 / n1 - k2 / n2 - diff) / np.sqrt(var)
+
+    # Equation (3.5) of [1] is lengthy, so it is broken into several parts,
+    # beginning here. Note that the probability mass function of poisson is
+    # exp^(-\mu)*\mu^k/k!, so and this is called with shape \mu, here noted
+    # here as nlmbd_hat*. The strategy for evaluating the double summation in
+    # (3.5) is to create two arrays of the values of the two products inside
+    # the summation and then broadcast them together into a matrix, and then
+    # sum across the entire matrix.
+
+    # Compute constants (as seen in the first and second separated products in
+    # (3.5).). (This is the shape (\mu) parameter of the poisson distribution.)
+    nlmbd_hat1 = n1 * (lmbd_hat2 + diff)
+    nlmbd_hat2 = n2 * lmbd_hat2
+
+    # Determine summation bounds for tail ends of distribution rather than
+    # summing to infinity. `x1*` is for the outer sum and `x2*` is the inner
+    # sum.
+    x1_lb, x1_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat1)
+    x2_lb, x2_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat2)
+
+    # Construct arrays to function as the x_1 and x_2 counters on the summation
+    # in (3.5). `x1` is in columns and `x2` is in rows to allow for
+    # broadcasting.
+    x1 = np.arange(x1_lb, x1_ub + 1)
+    x2 = np.arange(x2_lb, x2_ub + 1)[:, None]
+
+    # These are the two products in equation (3.5) with `prob_x1` being the
+    # first (left side) and `prob_x2` being the second (right side). (To
+    # make as clear as possible: the 1st contains a "+ d" term, the 2nd does
+    # not.)
+    prob_x1 = distributions.poisson.pmf(x1, nlmbd_hat1)
+    prob_x2 = distributions.poisson.pmf(x2, nlmbd_hat2)
+
+    # compute constants for use in the "pivot statistic" per the
+    # unnumbered equation following (3.3).
+    lmbd_x1 = x1 / n1
+    lmbd_x2 = x2 / n2
+    lmbds_diff = lmbd_x1 - lmbd_x2 - diff
+    var_x1x2 = lmbd_x1 / n1 + lmbd_x2 / n2
+
+    # This is the 'pivot statistic' for use in the indicator of the summation
+    # (left side of "I[.]").
+    with np.errstate(invalid='ignore', divide='ignore'):
+        t_x1x2 = lmbds_diff / np.sqrt(var_x1x2)
+
+    # `[indicator]` implements the "I[.] ... the indicator function" per
+    # the paragraph following equation (3.5).
+    if alternative == 'two-sided':
+        indicator = np.abs(t_x1x2) >= np.abs(t_k1k2)
+    elif alternative == 'less':
+        indicator = t_x1x2 <= t_k1k2
+    else:
+        indicator = t_x1x2 >= t_k1k2
+
+    # Multiply all combinations of the products together, exclude terms
+    # based on the `indicator` and then sum. (3.5)
+    pvalue = np.sum((prob_x1 * prob_x2)[indicator])
+    return _stats_py.SignificanceResult(t_k1k2, pvalue)
+
+
+def _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative):
+    # """check for valid types and values of input to `poisson_mean_test`."""
+    if k1 != int(k1) or k2 != int(k2):
+        raise TypeError('`k1` and `k2` must be integers.')
+
+    count_err = '`k1` and `k2` must be greater than or equal to 0.'
+    if k1 < 0 or k2 < 0:
+        raise ValueError(count_err)
+
+    if n1 <= 0 or n2 <= 0:
+        raise ValueError('`n1` and `n2` must be greater than 0.')
+
+    if diff < 0:
+        raise ValueError('diff must be greater than or equal to 0.')
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    if alternative.lower() not in alternatives:
+        raise ValueError(f"Alternative must be one of '{alternatives}'.")
+
+
+class CramerVonMisesResult:
+    def __init__(self, statistic, pvalue):
+        self.statistic = statistic
+        self.pvalue = pvalue
+
+    def __repr__(self):
+        return (f"{self.__class__.__name__}(statistic={self.statistic}, "
+                f"pvalue={self.pvalue})")
+
+
+def _psi1_mod(x):
+    """
+    psi1 is defined in equation 1.10 in Csörgő, S. and Faraway, J. (1996).
+    This implements a modified version by excluding the term V(x) / 12
+    (here: _cdf_cvm_inf(x) / 12) to avoid evaluating _cdf_cvm_inf(x)
+    twice in _cdf_cvm.
+
+    Implementation based on MAPLE code of Julian Faraway and R code of the
+    function pCvM in the package goftest (v1.1.1), permission granted
+    by Adrian Baddeley. Main difference in the implementation: the code
+    here keeps adding terms of the series until the terms are small enough.
+    """
+
+    def _ed2(y):
+        z = y**2 / 4
+        b = kv(1/4, z) + kv(3/4, z)
+        return np.exp(-z) * (y/2)**(3/2) * b / np.sqrt(np.pi)
+
+    def _ed3(y):
+        z = y**2 / 4
+        c = np.exp(-z) / np.sqrt(np.pi)
+        return c * (y/2)**(5/2) * (2*kv(1/4, z) + 3*kv(3/4, z) - kv(5/4, z))
+
+    def _Ak(k, x):
+        m = 2*k + 1
+        sx = 2 * np.sqrt(x)
+        y1 = x**(3/4)
+        y2 = x**(5/4)
+
+        e1 = m * gamma(k + 1/2) * _ed2((4 * k + 3)/sx) / (9 * y1)
+        e2 = gamma(k + 1/2) * _ed3((4 * k + 1) / sx) / (72 * y2)
+        e3 = 2 * (m + 2) * gamma(k + 3/2) * _ed3((4 * k + 5) / sx) / (12 * y2)
+        e4 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 1) / sx) / (144 * y1)
+        e5 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 5) / sx) / (144 * y1)
+
+        return e1 + e2 + e3 + e4 + e5
+
+    x = np.asarray(x)
+    tot = np.zeros_like(x, dtype='float')
+    cond = np.ones_like(x, dtype='bool')
+    k = 0
+    while np.any(cond):
+        z = -_Ak(k, x[cond]) / (np.pi * gamma(k + 1))
+        tot[cond] = tot[cond] + z
+        cond[cond] = np.abs(z) >= 1e-7
+        k += 1
+
+    return tot
+
+
+def _cdf_cvm_inf(x):
+    """
+    Calculate the cdf of the Cramér-von Mises statistic (infinite sample size).
+
+    See equation 1.2 in Csörgő, S. and Faraway, J. (1996).
+
+    Implementation based on MAPLE code of Julian Faraway and R code of the
+    function pCvM in the package goftest (v1.1.1), permission granted
+    by Adrian Baddeley. Main difference in the implementation: the code
+    here keeps adding terms of the series until the terms are small enough.
+
+    The function is not expected to be accurate for large values of x, say
+    x > 4, when the cdf is very close to 1.
+    """
+    x = np.asarray(x)
+
+    def term(x, k):
+        # this expression can be found in [2], second line of (1.3)
+        u = np.exp(gammaln(k + 0.5) - gammaln(k+1)) / (np.pi**1.5 * np.sqrt(x))
+        y = 4*k + 1
+        q = y**2 / (16*x)
+        b = kv(0.25, q)
+        return u * np.sqrt(y) * np.exp(-q) * b
+
+    tot = np.zeros_like(x, dtype='float')
+    cond = np.ones_like(x, dtype='bool')
+    k = 0
+    while np.any(cond):
+        z = term(x[cond], k)
+        tot[cond] = tot[cond] + z
+        cond[cond] = np.abs(z) >= 1e-7
+        k += 1
+
+    return tot
+
+
+def _cdf_cvm(x, n=None):
+    """
+    Calculate the cdf of the Cramér-von Mises statistic for a finite sample
+    size n. If N is None, use the asymptotic cdf (n=inf).
+
+    See equation 1.8 in Csörgő, S. and Faraway, J. (1996) for finite samples,
+    1.2 for the asymptotic cdf.
+
+    The function is not expected to be accurate for large values of x, say
+    x > 2, when the cdf is very close to 1 and it might return values > 1
+    in that case, e.g. _cdf_cvm(2.0, 12) = 1.0000027556716846. Moreover, it
+    is not accurate for small values of n, especially close to the bounds of
+    the distribution's domain, [1/(12*n), n/3], where the value jumps to 0
+    and 1, respectively. These are limitations of the approximation by Csörgő
+    and Faraway (1996) implemented in this function.
+    """
+    x = np.asarray(x)
+    if n is None:
+        y = _cdf_cvm_inf(x)
+    else:
+        # support of the test statistic is [12/n, n/3], see 1.1 in [2]
+        y = np.zeros_like(x, dtype='float')
+        sup = (1./(12*n) < x) & (x < n/3.)
+        # note: _psi1_mod does not include the term _cdf_cvm_inf(x) / 12
+        # therefore, we need to add it here
+        y[sup] = _cdf_cvm_inf(x[sup]) * (1 + 1./(12*n)) + _psi1_mod(x[sup]) / n
+        y[x >= n/3] = 1
+
+    if y.ndim == 0:
+        return y[()]
+    return y
+
+
+def _cvm_result_to_tuple(res):
+    return res.statistic, res.pvalue
+
+
+@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=1, too_small=1,
+                          result_to_tuple=_cvm_result_to_tuple)
+def cramervonmises(rvs, cdf, args=()):
+    """Perform the one-sample Cramér-von Mises test for goodness of fit.
+
+    This performs a test of the goodness of fit of a cumulative distribution
+    function (cdf) :math:`F` compared to the empirical distribution function
+    :math:`F_n` of observed random variates :math:`X_1, ..., X_n` that are
+    assumed to be independent and identically distributed ([1]_).
+    The null hypothesis is that the :math:`X_i` have cumulative distribution
+    :math:`F`.
+
+    Parameters
+    ----------
+    rvs : array_like
+        A 1-D array of observed values of the random variables :math:`X_i`.
+        The sample must contain at least two observations.
+    cdf : str or callable
+        The cumulative distribution function :math:`F` to test the
+        observations against. If a string, it should be the name of a
+        distribution in `scipy.stats`. If a callable, that callable is used
+        to calculate the cdf: ``cdf(x, *args) -> float``.
+    args : tuple, optional
+        Distribution parameters. These are assumed to be known; see Notes.
+
+    Returns
+    -------
+    res : object with attributes
+        statistic : float
+            Cramér-von Mises statistic.
+        pvalue : float
+            The p-value.
+
+    See Also
+    --------
+    kstest, cramervonmises_2samp
+
+    Notes
+    -----
+    .. versionadded:: 1.6.0
+
+    The p-value relies on the approximation given by equation 1.8 in [2]_.
+    It is important to keep in mind that the p-value is only accurate if
+    one tests a simple hypothesis, i.e. the parameters of the reference
+    distribution are known. If the parameters are estimated from the data
+    (composite hypothesis), the computed p-value is not reliable.
+
+    References
+    ----------
+    .. [1] Cramér-von Mises criterion, Wikipedia,
+           https://en.wikipedia.org/wiki/Cram%C3%A9r%E2%80%93von_Mises_criterion
+    .. [2] Csörgő, S. and Faraway, J. (1996). The Exact and Asymptotic
+           Distribution of Cramér-von Mises Statistics. Journal of the
+           Royal Statistical Society, pp. 221-234.
+
+    Examples
+    --------
+
+    Suppose we wish to test whether data generated by ``scipy.stats.norm.rvs``
+    were, in fact, drawn from the standard normal distribution. We choose a
+    significance level of ``alpha=0.05``.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(165417232101553420507139617764912913465)
+    >>> x = stats.norm.rvs(size=500, random_state=rng)
+    >>> res = stats.cramervonmises(x, 'norm')
+    >>> res.statistic, res.pvalue
+    (0.1072085112565724, 0.5508482238203407)
+
+    The p-value exceeds our chosen significance level, so we do not
+    reject the null hypothesis that the observed sample is drawn from the
+    standard normal distribution.
+
+    Now suppose we wish to check whether the same samples shifted by 2.1 is
+    consistent with being drawn from a normal distribution with a mean of 2.
+
+    >>> y = x + 2.1
+    >>> res = stats.cramervonmises(y, 'norm', args=(2,))
+    >>> res.statistic, res.pvalue
+    (0.8364446265294695, 0.00596286797008283)
+
+    Here we have used the `args` keyword to specify the mean (``loc``)
+    of the normal distribution to test the data against. This is equivalent
+    to the following, in which we create a frozen normal distribution with
+    mean 2.1, then pass its ``cdf`` method as an argument.
+
+    >>> frozen_dist = stats.norm(loc=2)
+    >>> res = stats.cramervonmises(y, frozen_dist.cdf)
+    >>> res.statistic, res.pvalue
+    (0.8364446265294695, 0.00596286797008283)
+
+    In either case, we would reject the null hypothesis that the observed
+    sample is drawn from a normal distribution with a mean of 2 (and default
+    variance of 1) because the p-value is less than our chosen
+    significance level.
+
+    """
+    if isinstance(cdf, str):
+        cdf = getattr(distributions, cdf).cdf
+
+    vals = np.sort(np.asarray(rvs))
+
+    if vals.size <= 1:
+        raise ValueError('The sample must contain at least two observations.')
+
+    n = len(vals)
+    cdfvals = cdf(vals, *args)
+
+    u = (2*np.arange(1, n+1) - 1)/(2*n)
+    w = 1/(12*n) + np.sum((u - cdfvals)**2)
+
+    # avoid small negative values that can occur due to the approximation
+    p = np.clip(1. - _cdf_cvm(w, n), 0., None)
+
+    return CramerVonMisesResult(statistic=w, pvalue=p)
+
+
+def _get_wilcoxon_distr(n):
+    """
+    Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum
+    of ranks of positive differences).
+    Returns an array with the probabilities of all the possible ranks
+    r = 0, ..., n*(n+1)/2
+    """
+    c = np.ones(1, dtype=np.float64)
+    for k in range(1, n + 1):
+        prev_c = c
+        c = np.zeros(k * (k + 1) // 2 + 1, dtype=np.float64)
+        m = len(prev_c)
+        c[:m] = prev_c * 0.5
+        c[-m:] += prev_c * 0.5
+    return c
+
+
+def _get_wilcoxon_distr2(n):
+    """
+    Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum
+    of ranks of positive differences).
+    Returns an array with the probabilities of all the possible ranks
+    r = 0, ..., n*(n+1)/2
+    This is a slower reference function
+    References
+    ----------
+    .. [1] 1. Harris T, Hardin JW. Exact Wilcoxon Signed-Rank and Wilcoxon
+        Mann-Whitney Ranksum Tests. The Stata Journal. 2013;13(2):337-343.
+    """
+    ai = np.arange(1, n+1)[:, None]
+    t = n*(n+1)/2
+    q = 2*t
+    j = np.arange(q)
+    theta = 2*np.pi/q*j
+    phi_sp = np.prod(np.cos(theta*ai), axis=0)
+    phi_s = np.exp(1j*theta*t) * phi_sp
+    p = np.real(ifft(phi_s))
+    res = np.zeros(int(t)+1)
+    res[:-1:] = p[::2]
+    res[0] /= 2
+    res[-1] = res[0]
+    return res
+
+
+def _tau_b(A):
+    """Calculate Kendall's tau-b and p-value from contingency table."""
+    # See [2] 2.2 and 4.2
+
+    # contingency table must be truly 2D
+    if A.shape[0] == 1 or A.shape[1] == 1:
+        return np.nan, np.nan
+
+    NA = A.sum()
+    PA = _P(A)
+    QA = _Q(A)
+    Sri2 = (A.sum(axis=1)**2).sum()
+    Scj2 = (A.sum(axis=0)**2).sum()
+    denominator = (NA**2 - Sri2)*(NA**2 - Scj2)
+
+    tau = (PA-QA)/(denominator)**0.5
+
+    numerator = 4*(_a_ij_Aij_Dij2(A) - (PA - QA)**2 / NA)
+    s02_tau_b = numerator/denominator
+    if s02_tau_b == 0:  # Avoid divide by zero
+        return tau, 0
+    Z = tau/s02_tau_b**0.5
+    p = 2*norm.sf(abs(Z))  # 2-sided p-value
+
+    return tau, p
+
+
+def _somers_d(A, alternative='two-sided'):
+    """Calculate Somers' D and p-value from contingency table."""
+    # See [3] page 1740
+
+    # contingency table must be truly 2D
+    if A.shape[0] <= 1 or A.shape[1] <= 1:
+        return np.nan, np.nan
+
+    NA = A.sum()
+    NA2 = NA**2
+    PA = _P(A)
+    QA = _Q(A)
+    Sri2 = (A.sum(axis=1)**2).sum()
+
+    d = (PA - QA)/(NA2 - Sri2)
+
+    S = _a_ij_Aij_Dij2(A) - (PA-QA)**2/NA
+
+    with np.errstate(divide='ignore'):
+        Z = (PA - QA)/(4*(S))**0.5
+
+    norm = _stats_py._SimpleNormal()
+    p = _stats_py._get_pvalue(Z, norm, alternative, xp=np)
+
+    return d, p
+
+
+@dataclass
+class SomersDResult:
+    statistic: float
+    pvalue: float
+    table: np.ndarray
+
+
+def somersd(x, y=None, alternative='two-sided'):
+    r"""Calculates Somers' D, an asymmetric measure of ordinal association.
+
+    Like Kendall's :math:`\tau`, Somers' :math:`D` is a measure of the
+    correspondence between two rankings. Both statistics consider the
+    difference between the number of concordant and discordant pairs in two
+    rankings :math:`X` and :math:`Y`, and both are normalized such that values
+    close  to 1 indicate strong agreement and values close to -1 indicate
+    strong disagreement. They differ in how they are normalized. To show the
+    relationship, Somers' :math:`D` can be defined in terms of Kendall's
+    :math:`\tau_a`:
+
+    .. math::
+        D(Y|X) = \frac{\tau_a(X, Y)}{\tau_a(X, X)}
+
+    Suppose the first ranking :math:`X` has :math:`r` distinct ranks and the
+    second ranking :math:`Y` has :math:`s` distinct ranks. These two lists of
+    :math:`n` rankings can also be viewed as an :math:`r \times s` contingency
+    table in which element :math:`i, j` is the number of rank pairs with rank
+    :math:`i` in ranking :math:`X` and rank :math:`j` in ranking :math:`Y`.
+    Accordingly, `somersd` also allows the input data to be supplied as a
+    single, 2D contingency table instead of as two separate, 1D rankings.
+
+    Note that the definition of Somers' :math:`D` is asymmetric: in general,
+    :math:`D(Y|X) \neq D(X|Y)`. ``somersd(x, y)`` calculates Somers'
+    :math:`D(Y|X)`: the "row" variable :math:`X` is treated as an independent
+    variable, and the "column" variable :math:`Y` is dependent. For Somers'
+    :math:`D(X|Y)`, swap the input lists or transpose the input table.
+
+    Parameters
+    ----------
+    x : array_like
+        1D array of rankings, treated as the (row) independent variable.
+        Alternatively, a 2D contingency table.
+    y : array_like, optional
+        If `x` is a 1D array of rankings, `y` is a 1D array of rankings of the
+        same length, treated as the (column) dependent variable.
+        If `x` is 2D, `y` is ignored.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater':  the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SomersDResult
+        A `SomersDResult` object with the following fields:
+
+            statistic : float
+               The Somers' :math:`D` statistic.
+            pvalue : float
+               The p-value for a hypothesis test whose null
+               hypothesis is an absence of association, :math:`D=0`.
+               See notes for more information.
+            table : 2D array
+               The contingency table formed from rankings `x` and `y` (or the
+               provided contingency table, if `x` is a 2D array)
+
+    See Also
+    --------
+    kendalltau : Calculates Kendall's tau, another correlation measure.
+    weightedtau : Computes a weighted version of Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    pearsonr : Calculates a Pearson correlation coefficient.
+
+    Notes
+    -----
+    This function follows the contingency table approach of [2]_ and
+    [3]_. *p*-values are computed based on an asymptotic approximation of
+    the test statistic distribution under the null hypothesis :math:`D=0`.
+
+    Theoretically, hypothesis tests based on Kendall's :math:`tau` and Somers'
+    :math:`D` should be identical.
+    However, the *p*-values returned by `kendalltau` are based
+    on the null hypothesis of *independence* between :math:`X` and :math:`Y`
+    (i.e. the population from which pairs in :math:`X` and :math:`Y` are
+    sampled contains equal numbers of all possible pairs), which is more
+    specific than the null hypothesis :math:`D=0` used here. If the null
+    hypothesis of independence is desired, it is acceptable to use the
+    *p*-value returned by `kendalltau` with the statistic returned by
+    `somersd` and vice versa. For more information, see [2]_.
+
+    Contingency tables are formatted according to the convention used by
+    SAS and R: the first ranking supplied (``x``) is the "row" variable, and
+    the second ranking supplied (``y``) is the "column" variable. This is
+    opposite the convention of Somers' original paper [1]_.
+
+    References
+    ----------
+    .. [1] Robert H. Somers, "A New Asymmetric Measure of Association for
+           Ordinal Variables", *American Sociological Review*, Vol. 27, No. 6,
+           pp. 799--811, 1962.
+
+    .. [2] Morton B. Brown and Jacqueline K. Benedetti, "Sampling Behavior of
+           Tests for Correlation in Two-Way Contingency Tables", *Journal of
+           the American Statistical Association* Vol. 72, No. 358, pp.
+           309--315, 1977.
+
+    .. [3] SAS Institute, Inc., "The FREQ Procedure (Book Excerpt)",
+           *SAS/STAT 9.2 User's Guide, Second Edition*, SAS Publishing, 2009.
+
+    .. [4] Laerd Statistics, "Somers' d using SPSS Statistics", *SPSS
+           Statistics Tutorials and Statistical Guides*,
+           https://statistics.laerd.com/spss-tutorials/somers-d-using-spss-statistics.php,
+           Accessed July 31, 2020.
+
+    Examples
+    --------
+    We calculate Somers' D for the example given in [4]_, in which a hotel
+    chain owner seeks to determine the association between hotel room
+    cleanliness and customer satisfaction. The independent variable, hotel
+    room cleanliness, is ranked on an ordinal scale: "below average (1)",
+    "average (2)", or "above average (3)". The dependent variable, customer
+    satisfaction, is ranked on a second scale: "very dissatisfied (1)",
+    "moderately dissatisfied (2)", "neither dissatisfied nor satisfied (3)",
+    "moderately satisfied (4)", or "very satisfied (5)". 189 customers
+    respond to the survey, and the results are cast into a contingency table
+    with the hotel room cleanliness as the "row" variable and customer
+    satisfaction as the "column" variable.
+
+    +-----+-----+-----+-----+-----+-----+
+    |     | (1) | (2) | (3) | (4) | (5) |
+    +=====+=====+=====+=====+=====+=====+
+    | (1) | 27  | 25  | 14  | 7   | 0   |
+    +-----+-----+-----+-----+-----+-----+
+    | (2) | 7   | 14  | 18  | 35  | 12  |
+    +-----+-----+-----+-----+-----+-----+
+    | (3) | 1   | 3   | 2   | 7   | 17  |
+    +-----+-----+-----+-----+-----+-----+
+
+    For example, 27 customers assigned their room a cleanliness ranking of
+    "below average (1)" and a corresponding satisfaction of "very
+    dissatisfied (1)". We perform the analysis as follows.
+
+    >>> from scipy.stats import somersd
+    >>> table = [[27, 25, 14, 7, 0], [7, 14, 18, 35, 12], [1, 3, 2, 7, 17]]
+    >>> res = somersd(table)
+    >>> res.statistic
+    0.6032766111513396
+    >>> res.pvalue
+    1.0007091191074533e-27
+
+    The value of the Somers' D statistic is approximately 0.6, indicating
+    a positive correlation between room cleanliness and customer satisfaction
+    in the sample.
+    The *p*-value is very small, indicating a very small probability of
+    observing such an extreme value of the statistic under the null
+    hypothesis that the statistic of the entire population (from which
+    our sample of 189 customers is drawn) is zero. This supports the
+    alternative hypothesis that the true value of Somers' D for the population
+    is nonzero.
+
+    """
+    x, y = np.array(x), np.array(y)
+    if x.ndim == 1:
+        if x.size != y.size:
+            raise ValueError("Rankings must be of equal length.")
+        table = scipy.stats.contingency.crosstab(x, y)[1]
+    elif x.ndim == 2:
+        if np.any(x < 0):
+            raise ValueError("All elements of the contingency table must be "
+                             "non-negative.")
+        if np.any(x != x.astype(int)):
+            raise ValueError("All elements of the contingency table must be "
+                             "integer.")
+        if x.nonzero()[0].size < 2:
+            raise ValueError("At least two elements of the contingency table "
+                             "must be nonzero.")
+        table = x
+    else:
+        raise ValueError("x must be either a 1D or 2D array")
+    # The table type is converted to a float to avoid an integer overflow
+    d, p = _somers_d(table.astype(float), alternative)
+
+    # add alias for consistency with other correlation functions
+    res = SomersDResult(d, p, table)
+    res.correlation = d
+    return res
+
+
+# This could be combined with `_all_partitions` in `_resampling.py`
+def _all_partitions(nx, ny):
+    """
+    Partition a set of indices into two fixed-length sets in all possible ways
+
+    Partition a set of indices 0 ... nx + ny - 1 into two sets of length nx and
+    ny in all possible ways (ignoring order of elements).
+    """
+    z = np.arange(nx+ny)
+    for c in combinations(z, nx):
+        x = np.array(c)
+        mask = np.ones(nx+ny, bool)
+        mask[x] = False
+        y = z[mask]
+        yield x, y
+
+
+def _compute_log_combinations(n):
+    """Compute all log combination of C(n, k)."""
+    gammaln_arr = gammaln(np.arange(n + 1) + 1)
+    return gammaln(n + 1) - gammaln_arr - gammaln_arr[::-1]
+
+
+@dataclass
+class BarnardExactResult:
+    statistic: float
+    pvalue: float
+
+
+def barnard_exact(table, alternative="two-sided", pooled=True, n=32):
+    r"""Perform a Barnard exact test on a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements should be non-negative integers.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes section below.
+
+    pooled : bool, optional
+        Whether to compute score statistic with pooled variance (as in
+        Student's t-test, for example) or unpooled variance (as in Welch's
+        t-test). Default is ``True``.
+
+    n : int, optional
+        Number of sampling points used in the construction of the sampling
+        method. Note that this argument will automatically be converted to
+        the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to
+        select sample points. Default is 32. Must be positive. In most cases,
+        32 points is enough to reach good precision. More points comes at
+        performance cost.
+
+    Returns
+    -------
+    ber : BarnardExactResult
+        A result object with the following attributes.
+
+        statistic : float
+            The Wald statistic with pooled or unpooled variance, depending
+            on the user choice of `pooled`.
+
+        pvalue : float
+            P-value, the probability of obtaining a distribution at least as
+            extreme as the one that was actually observed, assuming that the
+            null hypothesis is true.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.
+    fisher_exact : Fisher exact test on a 2x2 contingency table.
+    boschloo_exact : Boschloo's exact test on a 2x2 contingency table,
+        which is an uniformly more powerful alternative to Fisher's exact test.
+
+    Notes
+    -----
+    Barnard's test is an exact test used in the analysis of contingency
+    tables. It examines the association of two categorical variables, and
+    is a more powerful alternative than Fisher's exact test
+    for 2x2 contingency tables.
+
+    Let's define :math:`X_0` a 2x2 matrix representing the observed sample,
+    where each column stores the binomial experiment, as in the example
+    below. Let's also define :math:`p_1, p_2` the theoretical binomial
+    probabilities for  :math:`x_{11}` and :math:`x_{12}`. When using
+    Barnard exact test, we can assert three different null hypotheses :
+
+    - :math:`H_0 : p_1 \geq p_2` versus :math:`H_1 : p_1 < p_2`,
+      with `alternative` = "less"
+
+    - :math:`H_0 : p_1 \leq p_2` versus :math:`H_1 : p_1 > p_2`,
+      with `alternative` = "greater"
+
+    - :math:`H_0 : p_1 = p_2` versus :math:`H_1 : p_1 \neq p_2`,
+      with `alternative` = "two-sided" (default one)
+
+    In order to compute Barnard's exact test, we are using the Wald
+    statistic [3]_ with pooled or unpooled variance.
+    Under the default assumption that both variances are equal
+    (``pooled = True``), the statistic is computed as:
+
+    .. math::
+
+        T(X) = \frac{
+            \hat{p}_1 - \hat{p}_2
+        }{
+            \sqrt{
+                \hat{p}(1 - \hat{p})
+                (\frac{1}{c_1} +
+                \frac{1}{c_2})
+            }
+        }
+
+    with :math:`\hat{p}_1, \hat{p}_2` and :math:`\hat{p}` the estimator of
+    :math:`p_1, p_2` and :math:`p`, the latter being the combined probability,
+    given the assumption that :math:`p_1 = p_2`.
+
+    If this assumption is invalid (``pooled = False``), the statistic is:
+
+    .. math::
+
+        T(X) = \frac{
+            \hat{p}_1 - \hat{p}_2
+        }{
+            \sqrt{
+                \frac{\hat{p}_1 (1 - \hat{p}_1)}{c_1} +
+                \frac{\hat{p}_2 (1 - \hat{p}_2)}{c_2}
+            }
+        }
+
+    The p-value is then computed as:
+
+    .. math::
+
+        \sum
+            \binom{c_1}{x_{11}}
+            \binom{c_2}{x_{12}}
+            \pi^{x_{11} + x_{12}}
+            (1 - \pi)^{t - x_{11} - x_{12}}
+
+    where the sum is over all  2x2 contingency tables :math:`X` such that:
+    * :math:`T(X) \leq T(X_0)` when `alternative` = "less",
+    * :math:`T(X) \geq T(X_0)` when `alternative` = "greater", or
+    * :math:`T(X) \geq |T(X_0)|` when `alternative` = "two-sided".
+    Above, :math:`c_1, c_2` are the sum of the columns 1 and 2,
+    and :math:`t` the total (sum of the 4 sample's element).
+
+    The returned p-value is the maximum p-value taken over the nuisance
+    parameter :math:`\pi`, where :math:`0 \leq \pi \leq 1`.
+
+    This function's complexity is :math:`O(n c_1 c_2)`, where `n` is the
+    number of sample points.
+
+    References
+    ----------
+    .. [1] Barnard, G. A. "Significance Tests for 2x2 Tables". *Biometrika*.
+           34.1/2 (1947): 123-138. :doi:`dpgkg3`
+
+    .. [2] Mehta, Cyrus R., and Pralay Senchaudhuri. "Conditional versus
+           unconditional exact tests for comparing two binomials."
+           *Cytel Software Corporation* 675 (2003): 1-5.
+
+    .. [3] "Wald Test". *Wikipedia*. https://en.wikipedia.org/wiki/Wald_test
+
+    Examples
+    --------
+    An example use of Barnard's test is presented in [2]_.
+
+        Consider the following example of a vaccine efficacy study
+        (Chan, 1998). In a randomized clinical trial of 30 subjects, 15 were
+        inoculated with a recombinant DNA influenza vaccine and the 15 were
+        inoculated with a placebo. Twelve of the 15 subjects in the placebo
+        group (80%) eventually became infected with influenza whereas for the
+        vaccine group, only 7 of the 15 subjects (47%) became infected. The
+        data are tabulated as a 2 x 2 table::
+
+                Vaccine  Placebo
+            Yes     7        12
+            No      8        3
+
+    When working with statistical hypothesis testing, we usually use a
+    threshold probability or significance level upon which we decide
+    to reject the null hypothesis :math:`H_0`. Suppose we choose the common
+    significance level of 5%.
+
+    Our alternative hypothesis is that the vaccine will lower the chance of
+    becoming infected with the virus; that is, the probability :math:`p_1` of
+    catching the virus with the vaccine will be *less than* the probability
+    :math:`p_2` of catching the virus without the vaccine.  Therefore, we call
+    `barnard_exact` with the ``alternative="less"`` option:
+
+    >>> import scipy.stats as stats
+    >>> res = stats.barnard_exact([[7, 12], [8, 3]], alternative="less")
+    >>> res.statistic
+    -1.894
+    >>> res.pvalue
+    0.03407
+
+    Under the null hypothesis that the vaccine will not lower the chance of
+    becoming infected, the probability of obtaining test results at least as
+    extreme as the observed data is approximately 3.4%. Since this p-value is
+    less than our chosen significance level, we have evidence to reject
+    :math:`H_0` in favor of the alternative.
+
+    Suppose we had used Fisher's exact test instead:
+
+    >>> _, pvalue = stats.fisher_exact([[7, 12], [8, 3]], alternative="less")
+    >>> pvalue
+    0.0640
+
+    With the same threshold significance of 5%, we would not have been able
+    to reject the null hypothesis in favor of the alternative. As stated in
+    [2]_, Barnard's test is uniformly more powerful than Fisher's exact test
+    because Barnard's test does not condition on any margin. Fisher's test
+    should only be used when both sets of marginals are fixed.
+
+    """
+    if n <= 0:
+        raise ValueError(
+            "Number of points `n` must be strictly positive, "
+            f"found {n!r}"
+        )
+
+    table = np.asarray(table, dtype=np.int64)
+
+    if not table.shape == (2, 2):
+        raise ValueError("The input `table` must be of shape (2, 2).")
+
+    if np.any(table < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in table.sum(axis=0):
+        # If both values in column are zero, the p-value is 1 and
+        # the score's statistic is NaN.
+        return BarnardExactResult(np.nan, 1.0)
+
+    total_col_1, total_col_2 = table.sum(axis=0)
+
+    x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(-1, 1)
+    x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(1, -1)
+
+    # We need to calculate the wald statistics for each combination of x1 and
+    # x2.
+    p1, p2 = x1 / total_col_1, x2 / total_col_2
+
+    if pooled:
+        p = (x1 + x2) / (total_col_1 + total_col_2)
+        variances = p * (1 - p) * (1 / total_col_1 + 1 / total_col_2)
+    else:
+        variances = p1 * (1 - p1) / total_col_1 + p2 * (1 - p2) / total_col_2
+
+    # To avoid warning when dividing by 0
+    with np.errstate(divide="ignore", invalid="ignore"):
+        wald_statistic = np.divide((p1 - p2), np.sqrt(variances))
+
+    wald_statistic[p1 == p2] = 0  # Removing NaN values
+
+    wald_stat_obs = wald_statistic[table[0, 0], table[0, 1]]
+
+    if alternative == "two-sided":
+        index_arr = np.abs(wald_statistic) >= abs(wald_stat_obs)
+    elif alternative == "less":
+        index_arr = wald_statistic <= wald_stat_obs
+    elif alternative == "greater":
+        index_arr = wald_statistic >= wald_stat_obs
+    else:
+        msg = (
+            "`alternative` should be one of {'two-sided', 'less', 'greater'},"
+            f" found {alternative!r}"
+        )
+        raise ValueError(msg)
+
+    x1_sum_x2 = x1 + x2
+
+    x1_log_comb = _compute_log_combinations(total_col_1)
+    x2_log_comb = _compute_log_combinations(total_col_2)
+    x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2]
+
+    result = shgo(
+        _get_binomial_log_p_value_with_nuisance_param,
+        args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr),
+        bounds=((0, 1),),
+        n=n,
+        sampling_method="sobol",
+    )
+
+    # result.fun is the negative log pvalue and therefore needs to be
+    # changed before return
+    p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1)
+    return BarnardExactResult(wald_stat_obs, p_value)
+
+
+@dataclass
+class BoschlooExactResult:
+    statistic: float
+    pvalue: float
+
+
+def boschloo_exact(table, alternative="two-sided", n=32):
+    r"""Perform Boschloo's exact test on a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements should be non-negative integers.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes section below.
+
+    n : int, optional
+        Number of sampling points used in the construction of the sampling
+        method. Note that this argument will automatically be converted to
+        the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to
+        select sample points. Default is 32. Must be positive. In most cases,
+        32 points is enough to reach good precision. More points comes at
+        performance cost.
+
+    Returns
+    -------
+    ber : BoschlooExactResult
+        A result object with the following attributes.
+
+        statistic : float
+            The statistic used in Boschloo's test; that is, the p-value
+            from Fisher's exact test.
+
+        pvalue : float
+            P-value, the probability of obtaining a distribution at least as
+            extreme as the one that was actually observed, assuming that the
+            null hypothesis is true.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.
+    fisher_exact : Fisher exact test on a 2x2 contingency table.
+    barnard_exact : Barnard's exact test, which is a more powerful alternative
+        than Fisher's exact test for 2x2 contingency tables.
+
+    Notes
+    -----
+    Boschloo's test is an exact test used in the analysis of contingency
+    tables. It examines the association of two categorical variables, and
+    is a uniformly more powerful alternative to Fisher's exact test
+    for 2x2 contingency tables.
+
+    Boschloo's exact test uses the p-value of Fisher's exact test as a
+    statistic, and Boschloo's p-value is the probability under the null
+    hypothesis of observing such an extreme value of this statistic.
+
+    Let's define :math:`X_0` a 2x2 matrix representing the observed sample,
+    where each column stores the binomial experiment, as in the example
+    below. Let's also define :math:`p_1, p_2` the theoretical binomial
+    probabilities for  :math:`x_{11}` and :math:`x_{12}`. When using
+    Boschloo exact test, we can assert three different alternative hypotheses:
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 < p_2`,
+      with `alternative` = "less"
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 > p_2`,
+      with `alternative` = "greater"
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 \neq p_2`,
+      with `alternative` = "two-sided" (default)
+
+    There are multiple conventions for computing a two-sided p-value when the
+    null distribution is asymmetric. Here, we apply the convention that the
+    p-value of a two-sided test is twice the minimum of the p-values of the
+    one-sided tests (clipped to 1.0). Note that `fisher_exact` follows a
+    different convention, so for a given `table`, the statistic reported by
+    `boschloo_exact` may differ from the p-value reported by `fisher_exact`
+    when ``alternative='two-sided'``.
+
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] R.D. Boschloo. "Raised conditional level of significance for the
+       2 x 2-table when testing the equality of two probabilities",
+       Statistica Neerlandica, 24(1), 1970
+
+    .. [2] "Boschloo's test", Wikipedia,
+       https://en.wikipedia.org/wiki/Boschloo%27s_test
+
+    .. [3] Lise M. Saari et al. "Employee attitudes and job satisfaction",
+       Human Resource Management, 43(4), 395-407, 2004,
+       :doi:`10.1002/hrm.20032`.
+
+    Examples
+    --------
+    In the following example, we consider the article "Employee
+    attitudes and job satisfaction" [3]_
+    which reports the results of a survey from 63 scientists and 117 college
+    professors. Of the 63 scientists, 31 said they were very satisfied with
+    their jobs, whereas 74 of the college professors were very satisfied
+    with their work. Is this significant evidence that college
+    professors are happier with their work than scientists?
+    The following table summarizes the data mentioned above::
+
+                         college professors   scientists
+        Very Satisfied   74                     31
+        Dissatisfied     43                     32
+
+    When working with statistical hypothesis testing, we usually use a
+    threshold probability or significance level upon which we decide
+    to reject the null hypothesis :math:`H_0`. Suppose we choose the common
+    significance level of 5%.
+
+    Our alternative hypothesis is that college professors are truly more
+    satisfied with their work than scientists. Therefore, we expect
+    :math:`p_1` the proportion of very satisfied college professors to be
+    greater than :math:`p_2`, the proportion of very satisfied scientists.
+    We thus call `boschloo_exact` with the ``alternative="greater"`` option:
+
+    >>> import scipy.stats as stats
+    >>> res = stats.boschloo_exact([[74, 31], [43, 32]], alternative="greater")
+    >>> res.statistic
+    0.0483
+    >>> res.pvalue
+    0.0355
+
+    Under the null hypothesis that scientists are happier in their work than
+    college professors, the probability of obtaining test
+    results at least as extreme as the observed data is approximately 3.55%.
+    Since this p-value is less than our chosen significance level, we have
+    evidence to reject :math:`H_0` in favor of the alternative hypothesis.
+
+    """
+    hypergeom = distributions.hypergeom
+
+    if n <= 0:
+        raise ValueError(
+            "Number of points `n` must be strictly positive,"
+            f" found {n!r}"
+        )
+
+    table = np.asarray(table, dtype=np.int64)
+
+    if not table.shape == (2, 2):
+        raise ValueError("The input `table` must be of shape (2, 2).")
+
+    if np.any(table < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in table.sum(axis=0):
+        # If both values in column are zero, the p-value is 1 and
+        # the score's statistic is NaN.
+        return BoschlooExactResult(np.nan, np.nan)
+
+    total_col_1, total_col_2 = table.sum(axis=0)
+    total = total_col_1 + total_col_2
+    x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(1, -1)
+    x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(-1, 1)
+    x1_sum_x2 = x1 + x2
+
+    if alternative == 'less':
+        pvalues = hypergeom.cdf(x1, total, x1_sum_x2, total_col_1).T
+    elif alternative == 'greater':
+        # Same formula as the 'less' case, but with the second column.
+        pvalues = hypergeom.cdf(x2, total, x1_sum_x2, total_col_2).T
+    elif alternative == 'two-sided':
+        boschloo_less = boschloo_exact(table, alternative="less", n=n)
+        boschloo_greater = boschloo_exact(table, alternative="greater", n=n)
+
+        res = (
+            boschloo_less if boschloo_less.pvalue < boschloo_greater.pvalue
+            else boschloo_greater
+        )
+
+        # Two-sided p-value is defined as twice the minimum of the one-sided
+        # p-values
+        pvalue = np.clip(2 * res.pvalue, a_min=0, a_max=1)
+        return BoschlooExactResult(res.statistic, pvalue)
+    else:
+        msg = (
+            f"`alternative` should be one of {'two-sided', 'less', 'greater'},"
+            f" found {alternative!r}"
+        )
+        raise ValueError(msg)
+
+    fisher_stat = pvalues[table[0, 0], table[0, 1]]
+
+    # fisher_stat * (1+1e-13) guards us from small numerical error. It is
+    # equivalent to np.isclose with relative tol of 1e-13 and absolute tol of 0
+    # For more throughout explanations, see gh-14178
+    index_arr = pvalues <= fisher_stat * (1+1e-13)
+
+    x1, x2, x1_sum_x2 = x1.T, x2.T, x1_sum_x2.T
+    x1_log_comb = _compute_log_combinations(total_col_1)
+    x2_log_comb = _compute_log_combinations(total_col_2)
+    x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2]
+
+    result = shgo(
+        _get_binomial_log_p_value_with_nuisance_param,
+        args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr),
+        bounds=((0, 1),),
+        n=n,
+        sampling_method="sobol",
+    )
+
+    # result.fun is the negative log pvalue and therefore needs to be
+    # changed before return
+    p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1)
+    return BoschlooExactResult(fisher_stat, p_value)
+
+
+def _get_binomial_log_p_value_with_nuisance_param(
+    nuisance_param, x1_sum_x2, x1_sum_x2_log_comb, index_arr
+):
+    r"""
+    Compute the log pvalue in respect of a nuisance parameter considering
+    a 2x2 sample space.
+
+    Parameters
+    ----------
+    nuisance_param : float
+        nuisance parameter used in the computation of the maximisation of
+        the p-value. Must be between 0 and 1
+
+    x1_sum_x2 : ndarray
+        Sum of x1 and x2 inside barnard_exact
+
+    x1_sum_x2_log_comb : ndarray
+        sum of the log combination of x1 and x2
+
+    index_arr : ndarray of boolean
+
+    Returns
+    -------
+    p_value : float
+        Return the maximum p-value considering every nuisance parameter
+        between 0 and 1
+
+    Notes
+    -----
+
+    Both Barnard's test and Boschloo's test iterate over a nuisance parameter
+    :math:`\pi \in [0, 1]` to find the maximum p-value. To search this
+    maxima, this function return the negative log pvalue with respect to the
+    nuisance parameter passed in params. This negative log p-value is then
+    used in `shgo` to find the minimum negative pvalue which is our maximum
+    pvalue.
+
+    Also, to compute the different combination used in the
+    p-values' computation formula, this function uses `gammaln` which is
+    more tolerant for large value than `scipy.special.comb`. `gammaln` gives
+    a log combination. For the little precision loss, performances are
+    improved a lot.
+    """
+    t1, t2 = x1_sum_x2.shape
+    n = t1 + t2 - 2
+    with np.errstate(divide="ignore", invalid="ignore"):
+        log_nuisance = np.log(
+            nuisance_param,
+            out=np.zeros_like(nuisance_param),
+            where=nuisance_param >= 0,
+        )
+        log_1_minus_nuisance = np.log(
+            1 - nuisance_param,
+            out=np.zeros_like(nuisance_param),
+            where=1 - nuisance_param >= 0,
+        )
+
+        nuisance_power_x1_x2 = log_nuisance * x1_sum_x2
+        nuisance_power_x1_x2[(x1_sum_x2 == 0)[:, :]] = 0
+
+        nuisance_power_n_minus_x1_x2 = log_1_minus_nuisance * (n - x1_sum_x2)
+        nuisance_power_n_minus_x1_x2[(x1_sum_x2 == n)[:, :]] = 0
+
+        tmp_log_values_arr = (
+            x1_sum_x2_log_comb
+            + nuisance_power_x1_x2
+            + nuisance_power_n_minus_x1_x2
+        )
+
+    tmp_values_from_index = tmp_log_values_arr[index_arr]
+
+    # To avoid dividing by zero in log function and getting inf value,
+    # values are centered according to the max
+    max_value = tmp_values_from_index.max()
+
+    # To have better result's precision, the log pvalue is taken here.
+    # Indeed, pvalue is included inside [0, 1] interval. Passing the
+    # pvalue to log makes the interval a lot bigger ([-inf, 0]), and thus
+    # help us to achieve better precision
+    with np.errstate(divide="ignore", invalid="ignore"):
+        log_probs = np.exp(tmp_values_from_index - max_value).sum()
+        log_pvalue = max_value + np.log(
+            log_probs,
+            out=np.full_like(log_probs, -np.inf),
+            where=log_probs > 0,
+        )
+
+    # Since shgo find the minima, minus log pvalue is returned
+    return -log_pvalue
+
+
+def _pval_cvm_2samp_exact(s, m, n):
+    """
+    Compute the exact p-value of the Cramer-von Mises two-sample test
+    for a given value s of the test statistic.
+    m and n are the sizes of the samples.
+
+    [1] Y. Xiao, A. Gordon, and A. Yakovlev, "A C++ Program for
+        the Cramér-Von Mises Two-Sample Test", J. Stat. Soft.,
+        vol. 17, no. 8, pp. 1-15, Dec. 2006.
+    [2] T. W. Anderson "On the Distribution of the Two-Sample Cramer-von Mises
+        Criterion," The Annals of Mathematical Statistics, Ann. Math. Statist.
+        33(3), 1148-1159, (September, 1962)
+    """
+
+    # [1, p. 3]
+    lcm = np.lcm(m, n)
+    # [1, p. 4], below eq. 3
+    a = lcm // m
+    b = lcm // n
+    # Combine Eq. 9 in [2] with Eq. 2 in [1] and solve for $\zeta$
+    # Hint: `s` is $U$ in [2], and $T_2$ in [1] is $T$ in [2]
+    mn = m * n
+    zeta = lcm ** 2 * (m + n) * (6 * s - mn * (4 * mn - 1)) // (6 * mn ** 2)
+
+    # bound maximum value that may appear in `gs` (remember both rows!)
+    zeta_bound = lcm**2 * (m + n)  # bound elements in row 1
+    combinations = comb(m + n, m)  # sum of row 2
+    max_gs = max(zeta_bound, combinations)
+    dtype = np.min_scalar_type(max_gs)
+
+    # the frequency table of $g_{u, v}^+$ defined in [1, p. 6]
+    gs = ([np.array([[0], [1]], dtype=dtype)]
+          + [np.empty((2, 0), dtype=dtype) for _ in range(m)])
+    for u in range(n + 1):
+        next_gs = []
+        tmp = np.empty((2, 0), dtype=dtype)
+        for v, g in enumerate(gs):
+            # Calculate g recursively with eq. 11 in [1]. Even though it
+            # doesn't look like it, this also does 12/13 (all of Algorithm 1).
+            vi, i0, i1 = np.intersect1d(tmp[0], g[0], return_indices=True)
+            tmp = np.concatenate([
+                np.stack([vi, tmp[1, i0] + g[1, i1]]),
+                np.delete(tmp, i0, 1),
+                np.delete(g, i1, 1)
+            ], 1)
+            res = (a * v - b * u) ** 2
+            tmp[0] += res.astype(dtype)
+            next_gs.append(tmp)
+        gs = next_gs
+    value, freq = gs[m]
+    return np.float64(np.sum(freq[value >= zeta]) / combinations)
+
+
+@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=2, too_small=1,
+                          result_to_tuple=_cvm_result_to_tuple)
+def cramervonmises_2samp(x, y, method='auto'):
+    """Perform the two-sample Cramér-von Mises test for goodness of fit.
+
+    This is the two-sample version of the Cramér-von Mises test ([1]_):
+    for two independent samples :math:`X_1, ..., X_n` and
+    :math:`Y_1, ..., Y_m`, the null hypothesis is that the samples
+    come from the same (unspecified) continuous distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        A 1-D array of observed values of the random variables :math:`X_i`.
+        Must contain at least two observations.
+    y : array_like
+        A 1-D array of observed values of the random variables :math:`Y_i`.
+        Must contain at least two observations.
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        The method used to compute the p-value, see Notes for details.
+        The default is 'auto'.
+
+    Returns
+    -------
+    res : object with attributes
+        statistic : float
+            Cramér-von Mises statistic.
+        pvalue : float
+            The p-value.
+
+    See Also
+    --------
+    cramervonmises, anderson_ksamp, epps_singleton_2samp, ks_2samp
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    The statistic is computed according to equation 9 in [2]_. The
+    calculation of the p-value depends on the keyword `method`:
+
+    - ``asymptotic``: The p-value is approximated by using the limiting
+      distribution of the test statistic.
+    - ``exact``: The exact p-value is computed by enumerating all
+      possible combinations of the test statistic, see [2]_.
+
+    If ``method='auto'``, the exact approach is used
+    if both samples contain equal to or less than 20 observations,
+    otherwise the asymptotic distribution is used.
+
+    If the underlying distribution is not continuous, the p-value is likely to
+    be conservative (Section 6.2 in [3]_). When ranking the data to compute
+    the test statistic, midranks are used if there are ties.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Cramer-von_Mises_criterion
+    .. [2] Anderson, T.W. (1962). On the distribution of the two-sample
+           Cramer-von-Mises criterion. The Annals of Mathematical
+           Statistics, pp. 1148-1159.
+    .. [3] Conover, W.J., Practical Nonparametric Statistics, 1971.
+
+    Examples
+    --------
+
+    Suppose we wish to test whether two samples generated by
+    ``scipy.stats.norm.rvs`` have the same distribution. We choose a
+    significance level of alpha=0.05.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> y = stats.norm.rvs(size=70, random_state=rng)
+    >>> res = stats.cramervonmises_2samp(x, y)
+    >>> res.statistic, res.pvalue
+    (0.29376470588235293, 0.1412873014573014)
+
+    The p-value exceeds our chosen significance level, so we do not
+    reject the null hypothesis that the observed samples are drawn from the
+    same distribution.
+
+    For small sample sizes, one can compute the exact p-values:
+
+    >>> x = stats.norm.rvs(size=7, random_state=rng)
+    >>> y = stats.t.rvs(df=2, size=6, random_state=rng)
+    >>> res = stats.cramervonmises_2samp(x, y, method='exact')
+    >>> res.statistic, res.pvalue
+    (0.197802197802198, 0.31643356643356646)
+
+    The p-value based on the asymptotic distribution is a good approximation
+    even though the sample size is small.
+
+    >>> res = stats.cramervonmises_2samp(x, y, method='asymptotic')
+    >>> res.statistic, res.pvalue
+    (0.197802197802198, 0.2966041181527128)
+
+    Independent of the method, one would not reject the null hypothesis at the
+    chosen significance level in this example.
+
+    """
+    xa = np.sort(np.asarray(x))
+    ya = np.sort(np.asarray(y))
+
+    if xa.size <= 1 or ya.size <= 1:
+        raise ValueError('x and y must contain at least two observations.')
+    if method not in ['auto', 'exact', 'asymptotic']:
+        raise ValueError('method must be either auto, exact or asymptotic.')
+
+    nx = len(xa)
+    ny = len(ya)
+
+    if method == 'auto':
+        if max(nx, ny) > 20:
+            method = 'asymptotic'
+        else:
+            method = 'exact'
+
+    # get ranks of x and y in the pooled sample
+    z = np.concatenate([xa, ya])
+    # in case of ties, use midrank (see [1])
+    r = scipy.stats.rankdata(z, method='average')
+    rx = r[:nx]
+    ry = r[nx:]
+
+    # compute U (eq. 10 in [2])
+    u = nx * np.sum((rx - np.arange(1, nx+1))**2)
+    u += ny * np.sum((ry - np.arange(1, ny+1))**2)
+
+    # compute T (eq. 9 in [2])
+    k, N = nx*ny, nx + ny
+    t = u / (k*N) - (4*k - 1)/(6*N)
+
+    if method == 'exact':
+        p = _pval_cvm_2samp_exact(u, nx, ny)
+    else:
+        # compute expected value and variance of T (eq. 11 and 14 in [2])
+        et = (1 + 1/N)/6
+        vt = (N+1) * (4*k*N - 3*(nx**2 + ny**2) - 2*k)
+        vt = vt / (45 * N**2 * 4 * k)
+
+        # computed the normalized statistic (eq. 15 in [2])
+        tn = 1/6 + (t - et) / np.sqrt(45 * vt)
+
+        # approximate distribution of tn with limiting distribution
+        # of the one-sample test statistic
+        # if tn < 0.003, the _cdf_cvm_inf(tn) < 1.28*1e-18, return 1.0 directly
+        if tn < 0.003:
+            p = 1.0
+        else:
+            p = max(0, 1. - _cdf_cvm_inf(tn))
+
+    return CramerVonMisesResult(statistic=t, pvalue=p)
+
+
+class TukeyHSDResult:
+    """Result of `scipy.stats.tukey_hsd`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic of the test for each comparison. The element
+        at index ``(i, j)`` is the statistic for the comparison between groups
+        ``i`` and ``j``.
+    pvalue : float ndarray
+        The associated p-value from the studentized range distribution. The
+        element at index ``(i, j)`` is the p-value for the comparison
+        between groups ``i`` and ``j``.
+
+    Notes
+    -----
+    The string representation of this object displays the most recently
+    calculated confidence interval, and if none have been previously
+    calculated, it will evaluate ``confidence_interval()``.
+
+    References
+    ----------
+    .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's
+           Method."
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+           28 November 2020.
+    """
+
+    def __init__(self, statistic, pvalue, _nobs, _ntreatments, _stand_err):
+        self.statistic = statistic
+        self.pvalue = pvalue
+        self._ntreatments = _ntreatments
+        self._nobs = _nobs
+        self._stand_err = _stand_err
+        self._ci = None
+        self._ci_cl = None
+
+    def __str__(self):
+        # Note: `__str__` prints the confidence intervals from the most
+        # recent call to `confidence_interval`. If it has not been called,
+        # it will be called with the default CL of .95.
+        if self._ci is None:
+            self.confidence_interval(confidence_level=.95)
+        s = ("Tukey's HSD Pairwise Group Comparisons"
+             f" ({self._ci_cl*100:.1f}% Confidence Interval)\n")
+        s += "Comparison  Statistic  p-value  Lower CI  Upper CI\n"
+        for i in range(self.pvalue.shape[0]):
+            for j in range(self.pvalue.shape[0]):
+                if i != j:
+                    s += (f" ({i} - {j}) {self.statistic[i, j]:>10.3f}"
+                          f"{self.pvalue[i, j]:>10.3f}"
+                          f"{self._ci.low[i, j]:>10.3f}"
+                          f"{self._ci.high[i, j]:>10.3f}\n")
+        return s
+
+    def confidence_interval(self, confidence_level=.95):
+        """Compute the confidence interval for the specified confidence level.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval
+            of the estimated proportion. Default is .95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence intervals for each
+            comparison. The high and low values are accessible for each
+            comparison at index ``(i, j)`` between groups ``i`` and ``j``.
+
+        References
+        ----------
+        .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1.
+               Tukey's Method."
+               https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+               28 November 2020.
+
+        Examples
+        --------
+        >>> from scipy.stats import tukey_hsd
+        >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+        >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+        >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+        >>> result = tukey_hsd(group0, group1, group2)
+        >>> ci = result.confidence_interval()
+        >>> ci.low
+        array([[-3.649159, -8.249159, -3.909159],
+               [ 0.950841, -3.649159,  0.690841],
+               [-3.389159, -7.989159, -3.649159]])
+        >>> ci.high
+        array([[ 3.649159, -0.950841,  3.389159],
+               [ 8.249159,  3.649159,  7.989159],
+               [ 3.909159, -0.690841,  3.649159]])
+        """
+        # check to see if the supplied confidence level matches that of the
+        # previously computed CI.
+        if (self._ci is not None and self._ci_cl is not None and
+                confidence_level == self._ci_cl):
+            return self._ci
+
+        if not 0 < confidence_level < 1:
+            raise ValueError("Confidence level must be between 0 and 1.")
+        # determine the critical value of the studentized range using the
+        # appropriate confidence level, number of treatments, and degrees
+        # of freedom as determined by the number of data less the number of
+        # treatments. ("Confidence limits for Tukey's method")[1]. Note that
+        # in the cases of unequal sample sizes there will be a criterion for
+        # each group comparison.
+        params = (confidence_level, self._nobs, self._ntreatments - self._nobs)
+        srd = distributions.studentized_range.ppf(*params)
+        # also called maximum critical value, the Tukey criterion is the
+        # studentized range critical value * the square root of mean square
+        # error over the sample size.
+        tukey_criterion = srd * self._stand_err
+        # the confidence levels are determined by the
+        # `mean_differences` +- `tukey_criterion`
+        upper_conf = self.statistic + tukey_criterion
+        lower_conf = self.statistic - tukey_criterion
+        self._ci = ConfidenceInterval(low=lower_conf, high=upper_conf)
+        self._ci_cl = confidence_level
+        return self._ci
+
+
+def _tukey_hsd_iv(args):
+    if (len(args)) < 2:
+        raise ValueError("There must be more than 1 treatment.")
+    args = [np.asarray(arg) for arg in args]
+    for arg in args:
+        if arg.ndim != 1:
+            raise ValueError("Input samples must be one-dimensional.")
+        if arg.size <= 1:
+            raise ValueError("Input sample size must be greater than one.")
+        if np.isinf(arg).any():
+            raise ValueError("Input samples must be finite.")
+    return args
+
+
+def tukey_hsd(*args):
+    """Perform Tukey's HSD test for equality of means over multiple treatments.
+
+    Tukey's honestly significant difference (HSD) test performs pairwise
+    comparison of means for a set of samples. Whereas ANOVA (e.g. `f_oneway`)
+    assesses whether the true means underlying each sample are identical,
+    Tukey's HSD is a post hoc test used to compare the mean of each sample
+    to the mean of each other sample.
+
+    The null hypothesis is that the distributions underlying the samples all
+    have the same mean. The test statistic, which is computed for every
+    possible pairing of samples, is simply the difference between the sample
+    means. For each pair, the p-value is the probability under the null
+    hypothesis (and other assumptions; see notes) of observing such an extreme
+    value of the statistic, considering that many pairwise comparisons are
+    being performed. Confidence intervals for the difference between each pair
+    of means are also available.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group. There must be at least
+        two arguments.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TukeyHSDResult` instance
+        The return value is an object with the following attributes:
+
+        statistic : float ndarray
+            The computed statistic of the test for each comparison. The element
+            at index ``(i, j)`` is the statistic for the comparison between
+            groups ``i`` and ``j``.
+        pvalue : float ndarray
+            The computed p-value of the test for each comparison. The element
+            at index ``(i, j)`` is the p-value for the comparison between
+            groups ``i`` and ``j``.
+
+        The object has the following methods:
+
+        confidence_interval(confidence_level=0.95):
+            Compute the confidence interval for the specified confidence level.
+
+    See Also
+    --------
+    dunnett : performs comparison of means against a control group.
+
+    Notes
+    -----
+    The use of this test relies on several assumptions.
+
+    1. The observations are independent within and among groups.
+    2. The observations within each group are normally distributed.
+    3. The distributions from which the samples are drawn have the same finite
+       variance.
+
+    The original formulation of the test was for samples of equal size [6]_.
+    In case of unequal sample sizes, the test uses the Tukey-Kramer method
+    [4]_.
+
+    References
+    ----------
+    .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's
+           Method."
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+           28 November 2020.
+    .. [2] Abdi, Herve & Williams, Lynne. (2021). "Tukey's Honestly Significant
+           Difference (HSD) Test."
+           https://personal.utdallas.edu/~herve/abdi-HSD2010-pretty.pdf
+    .. [3] "One-Way ANOVA Using SAS PROC ANOVA & PROC GLM." SAS
+           Tutorials, 2007, www.stattutorials.com/SAS/TUTORIAL-PROC-GLM.htm.
+    .. [4] Kramer, Clyde Young. "Extension of Multiple Range Tests to Group
+           Means with Unequal Numbers of Replications." Biometrics, vol. 12,
+           no. 3, 1956, pp. 307-310. JSTOR, www.jstor.org/stable/3001469.
+           Accessed 25 May 2021.
+    .. [5] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.3.3.
+           The ANOVA table and tests of hypotheses about means"
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc433.htm,
+           2 June 2021.
+    .. [6] Tukey, John W. "Comparing Individual Means in the Analysis of
+           Variance." Biometrics, vol. 5, no. 2, 1949, pp. 99-114. JSTOR,
+           www.jstor.org/stable/3001913. Accessed 14 June 2021.
+
+
+    Examples
+    --------
+    Here are some data comparing the time to relief of three brands of
+    headache medicine, reported in minutes. Data adapted from [3]_.
+
+    >>> import numpy as np
+    >>> from scipy.stats import tukey_hsd
+    >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+    >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+    >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+
+    We would like to see if the means between any of the groups are
+    significantly different. First, visually examine a box and whisker plot.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.boxplot([group0, group1, group2])
+    >>> ax.set_xticklabels(["group0", "group1", "group2"]) # doctest: +SKIP
+    >>> ax.set_ylabel("mean") # doctest: +SKIP
+    >>> plt.show()
+
+    From the box and whisker plot, we can see overlap in the interquartile
+    ranges group 1 to group 2 and group 3, but we can apply the ``tukey_hsd``
+    test to determine if the difference between means is significant. We
+    set a significance level of .05 to reject the null hypothesis.
+
+    >>> res = tukey_hsd(group0, group1, group2)
+    >>> print(res)
+    Tukey's HSD Pairwise Group Comparisons (95.0% Confidence Interval)
+    Comparison  Statistic  p-value   Lower CI   Upper CI
+    (0 - 1)     -4.600      0.014     -8.249     -0.951
+    (0 - 2)     -0.260      0.980     -3.909      3.389
+    (1 - 0)      4.600      0.014      0.951      8.249
+    (1 - 2)      4.340      0.020      0.691      7.989
+    (2 - 0)      0.260      0.980     -3.389      3.909
+    (2 - 1)     -4.340      0.020     -7.989     -0.691
+
+    The null hypothesis is that each group has the same mean. The p-value for
+    comparisons between ``group0`` and ``group1`` as well as ``group1`` and
+    ``group2`` do not exceed .05, so we reject the null hypothesis that they
+    have the same means. The p-value of the comparison between ``group0``
+    and ``group2`` exceeds .05, so we accept the null hypothesis that there
+    is not a significant difference between their means.
+
+    We can also compute the confidence interval associated with our chosen
+    confidence level.
+
+    >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+    >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+    >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+    >>> result = tukey_hsd(group0, group1, group2)
+    >>> conf = res.confidence_interval(confidence_level=.99)
+    >>> for ((i, j), l) in np.ndenumerate(conf.low):
+    ...     # filter out self comparisons
+    ...     if i != j:
+    ...         h = conf.high[i,j]
+    ...         print(f"({i} - {j}) {l:>6.3f} {h:>6.3f}")
+    (0 - 1) -9.480  0.280
+    (0 - 2) -5.140  4.620
+    (1 - 0) -0.280  9.480
+    (1 - 2) -0.540  9.220
+    (2 - 0) -4.620  5.140
+    (2 - 1) -9.220  0.540
+    """
+    args = _tukey_hsd_iv(args)
+    ntreatments = len(args)
+    means = np.asarray([np.mean(arg) for arg in args])
+    nsamples_treatments = np.asarray([a.size for a in args])
+    nobs = np.sum(nsamples_treatments)
+
+    # determine mean square error [5]. Note that this is sometimes called
+    # mean square error within.
+    mse = (np.sum([np.var(arg, ddof=1) for arg in args] *
+                  (nsamples_treatments - 1)) / (nobs - ntreatments))
+
+    # The calculation of the standard error differs when treatments differ in
+    # size. See ("Unequal sample sizes")[1].
+    if np.unique(nsamples_treatments).size == 1:
+        # all input groups are the same length, so only one value needs to be
+        # calculated [1].
+        normalize = 2 / nsamples_treatments[0]
+    else:
+        # to compare groups of differing sizes, we must compute a variance
+        # value for each individual comparison. Use broadcasting to get the
+        # resulting matrix. [3], verified against [4] (page 308).
+        normalize = 1 / nsamples_treatments + 1 / nsamples_treatments[None].T
+
+    # the standard error is used in the computation of the tukey criterion and
+    # finding the p-values.
+    stand_err = np.sqrt(normalize * mse / 2)
+
+    # the mean difference is the test statistic.
+    mean_differences = means[None].T - means
+
+    # Calculate the t-statistic to use within the survival function of the
+    # studentized range to get the p-value.
+    t_stat = np.abs(mean_differences) / stand_err
+
+    params = t_stat, ntreatments, nobs - ntreatments
+    pvalues = distributions.studentized_range.sf(*params)
+
+    return TukeyHSDResult(mean_differences, pvalues, ntreatments,
+                          nobs, stand_err)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_kde.py b/python_embeded/Lib/site-packages/scipy/stats/_kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..20f652a69fe33361685206aa097a7f5fcbd0d6a8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_kde.py
@@ -0,0 +1,728 @@
+#-------------------------------------------------------------------------------
+#
+#  Define classes for (uni/multi)-variate kernel density estimation.
+#
+#  Currently, only Gaussian kernels are implemented.
+#
+#  Written by: Robert Kern
+#
+#  Date: 2004-08-09
+#
+#  Modified: 2005-02-10 by Robert Kern.
+#              Contributed to SciPy
+#            2005-10-07 by Robert Kern.
+#              Some fixes to match the new scipy_core
+#
+#  Copyright 2004-2005 by Enthought, Inc.
+#
+#-------------------------------------------------------------------------------
+
+# Standard library imports.
+import threading
+import warnings
+
+# SciPy imports.
+from scipy import linalg, special
+from scipy._lib._util import check_random_state
+
+from numpy import (asarray, atleast_2d, reshape, zeros, newaxis, exp, pi,
+                   sqrt, ravel, power, atleast_1d, squeeze, sum, transpose,
+                   ones, cov)
+import numpy as np
+
+# Local imports.
+from . import _mvn
+from ._stats import gaussian_kernel_estimate, gaussian_kernel_estimate_log
+
+
+__all__ = ['gaussian_kde']
+
+MVN_LOCK = threading.Lock()
+
+
+class gaussian_kde:
+    """Representation of a kernel-density estimate using Gaussian kernels.
+
+    Kernel density estimation is a way to estimate the probability density
+    function (PDF) of a random variable in a non-parametric way.
+    `gaussian_kde` works for both uni-variate and multi-variate data.   It
+    includes automatic bandwidth determination.  The estimation works best for
+    a unimodal distribution; bimodal or multi-modal distributions tend to be
+    oversmoothed.
+
+    Parameters
+    ----------
+    dataset : array_like
+        Datapoints to estimate from. In case of univariate data this is a 1-D
+        array, otherwise a 2-D array with shape (# of dims, # of data).
+    bw_method : str, scalar or callable, optional
+        The method used to calculate the estimator bandwidth.  This can be
+        'scott', 'silverman', a scalar constant or a callable.  If a scalar,
+        this will be used directly as `kde.factor`.  If a callable, it should
+        take a `gaussian_kde` instance as only parameter and return a scalar.
+        If None (default), 'scott' is used.  See Notes for more details.
+    weights : array_like, optional
+        weights of datapoints. This must be the same shape as dataset.
+        If None (default), the samples are assumed to be equally weighted
+
+    Attributes
+    ----------
+    dataset : ndarray
+        The dataset with which `gaussian_kde` was initialized.
+    d : int
+        Number of dimensions.
+    n : int
+        Number of datapoints.
+    neff : int
+        Effective number of datapoints.
+
+        .. versionadded:: 1.2.0
+    factor : float
+        The bandwidth factor, obtained from `kde.covariance_factor`. The square
+        of `kde.factor` multiplies the covariance matrix of the data in the kde
+        estimation.
+    covariance : ndarray
+        The covariance matrix of `dataset`, scaled by the calculated bandwidth
+        (`kde.factor`).
+    inv_cov : ndarray
+        The inverse of `covariance`.
+
+    Methods
+    -------
+    evaluate
+    __call__
+    integrate_gaussian
+    integrate_box_1d
+    integrate_box
+    integrate_kde
+    pdf
+    logpdf
+    resample
+    set_bandwidth
+    covariance_factor
+
+    Notes
+    -----
+    Bandwidth selection strongly influences the estimate obtained from the KDE
+    (much more so than the actual shape of the kernel).  Bandwidth selection
+    can be done by a "rule of thumb", by cross-validation, by "plug-in
+    methods" or by other means; see [3]_, [4]_ for reviews.  `gaussian_kde`
+    uses a rule of thumb, the default is Scott's Rule.
+
+    Scott's Rule [1]_, implemented as `scotts_factor`, is::
+
+        n**(-1./(d+4)),
+
+    with ``n`` the number of data points and ``d`` the number of dimensions.
+    In the case of unequally weighted points, `scotts_factor` becomes::
+
+        neff**(-1./(d+4)),
+
+    with ``neff`` the effective number of datapoints.
+    Silverman's Rule [2]_, implemented as `silverman_factor`, is::
+
+        (n * (d + 2) / 4.)**(-1. / (d + 4)).
+
+    or in the case of unequally weighted points::
+
+        (neff * (d + 2) / 4.)**(-1. / (d + 4)).
+
+    Good general descriptions of kernel density estimation can be found in [1]_
+    and [2]_, the mathematics for this multi-dimensional implementation can be
+    found in [1]_.
+
+    With a set of weighted samples, the effective number of datapoints ``neff``
+    is defined by::
+
+        neff = sum(weights)^2 / sum(weights^2)
+
+    as detailed in [5]_.
+
+    `gaussian_kde` does not currently support data that lies in a
+    lower-dimensional subspace of the space in which it is expressed. For such
+    data, consider performing principal component analysis / dimensionality
+    reduction and using `gaussian_kde` with the transformed data.
+
+    References
+    ----------
+    .. [1] D.W. Scott, "Multivariate Density Estimation: Theory, Practice, and
+           Visualization", John Wiley & Sons, New York, Chicester, 1992.
+    .. [2] B.W. Silverman, "Density Estimation for Statistics and Data
+           Analysis", Vol. 26, Monographs on Statistics and Applied Probability,
+           Chapman and Hall, London, 1986.
+    .. [3] B.A. Turlach, "Bandwidth Selection in Kernel Density Estimation: A
+           Review", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993.
+    .. [4] D.M. Bashtannyk and R.J. Hyndman, "Bandwidth selection for kernel
+           conditional density estimation", Computational Statistics & Data
+           Analysis, Vol. 36, pp. 279-298, 2001.
+    .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society.
+           Series A (General), 132, 272
+
+    Examples
+    --------
+    Generate some random two-dimensional data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> def measure(n):
+    ...     "Measurement model, return two coupled measurements."
+    ...     m1 = np.random.normal(size=n)
+    ...     m2 = np.random.normal(scale=0.5, size=n)
+    ...     return m1+m2, m1-m2
+
+    >>> m1, m2 = measure(2000)
+    >>> xmin = m1.min()
+    >>> xmax = m1.max()
+    >>> ymin = m2.min()
+    >>> ymax = m2.max()
+
+    Perform a kernel density estimate on the data:
+
+    >>> X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
+    >>> positions = np.vstack([X.ravel(), Y.ravel()])
+    >>> values = np.vstack([m1, m2])
+    >>> kernel = stats.gaussian_kde(values)
+    >>> Z = np.reshape(kernel(positions).T, X.shape)
+
+    Plot the results:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,
+    ...           extent=[xmin, xmax, ymin, ymax])
+    >>> ax.plot(m1, m2, 'k.', markersize=2)
+    >>> ax.set_xlim([xmin, xmax])
+    >>> ax.set_ylim([ymin, ymax])
+    >>> plt.show()
+
+    """
+    def __init__(self, dataset, bw_method=None, weights=None):
+        self.dataset = atleast_2d(asarray(dataset))
+        if not self.dataset.size > 1:
+            raise ValueError("`dataset` input should have multiple elements.")
+
+        self.d, self.n = self.dataset.shape
+
+        if weights is not None:
+            self._weights = atleast_1d(weights).astype(float)
+            self._weights /= sum(self._weights)
+            if self.weights.ndim != 1:
+                raise ValueError("`weights` input should be one-dimensional.")
+            if len(self._weights) != self.n:
+                raise ValueError("`weights` input should be of length n")
+            self._neff = 1/sum(self._weights**2)
+
+        # This can be converted to a warning once gh-10205 is resolved
+        if self.d > self.n:
+            msg = ("Number of dimensions is greater than number of samples. "
+                   "This results in a singular data covariance matrix, which "
+                   "cannot be treated using the algorithms implemented in "
+                   "`gaussian_kde`. Note that `gaussian_kde` interprets each "
+                   "*column* of `dataset` to be a point; consider transposing "
+                   "the input to `dataset`.")
+            raise ValueError(msg)
+
+        try:
+            self.set_bandwidth(bw_method=bw_method)
+        except linalg.LinAlgError as e:
+            msg = ("The data appears to lie in a lower-dimensional subspace "
+                   "of the space in which it is expressed. This has resulted "
+                   "in a singular data covariance matrix, which cannot be "
+                   "treated using the algorithms implemented in "
+                   "`gaussian_kde`. Consider performing principal component "
+                   "analysis / dimensionality reduction and using "
+                   "`gaussian_kde` with the transformed data.")
+            raise linalg.LinAlgError(msg) from e
+
+    def evaluate(self, points):
+        """Evaluate the estimated pdf on a set of points.
+
+        Parameters
+        ----------
+        points : (# of dimensions, # of points)-array
+            Alternatively, a (# of dimensions,) vector can be passed in and
+            treated as a single point.
+
+        Returns
+        -------
+        values : (# of points,)-array
+            The values at each point.
+
+        Raises
+        ------
+        ValueError : if the dimensionality of the input points is different than
+                     the dimensionality of the KDE.
+
+        """
+        points = atleast_2d(asarray(points))
+
+        d, m = points.shape
+        if d != self.d:
+            if d == 1 and m == self.d:
+                # points was passed in as a row vector
+                points = reshape(points, (self.d, 1))
+                m = 1
+            else:
+                msg = (f"points have dimension {d}, "
+                       f"dataset has dimension {self.d}")
+                raise ValueError(msg)
+
+        output_dtype, spec = _get_output_dtype(self.covariance, points)
+        result = gaussian_kernel_estimate[spec](
+            self.dataset.T, self.weights[:, None],
+            points.T, self.cho_cov, output_dtype)
+
+        return result[:, 0]
+
+    __call__ = evaluate
+
+    def integrate_gaussian(self, mean, cov):
+        """
+        Multiply estimated density by a multivariate Gaussian and integrate
+        over the whole space.
+
+        Parameters
+        ----------
+        mean : aray_like
+            A 1-D array, specifying the mean of the Gaussian.
+        cov : array_like
+            A 2-D array, specifying the covariance matrix of the Gaussian.
+
+        Returns
+        -------
+        result : scalar
+            The value of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the mean or covariance of the input Gaussian differs from
+            the KDE's dimensionality.
+
+        """
+        mean = atleast_1d(squeeze(mean))
+        cov = atleast_2d(cov)
+
+        if mean.shape != (self.d,):
+            raise ValueError(f"mean does not have dimension {self.d}")
+        if cov.shape != (self.d, self.d):
+            raise ValueError(f"covariance does not have dimension {self.d}")
+
+        # make mean a column vector
+        mean = mean[:, newaxis]
+
+        sum_cov = self.covariance + cov
+
+        # This will raise LinAlgError if the new cov matrix is not s.p.d
+        # cho_factor returns (ndarray, bool) where bool is a flag for whether
+        # or not ndarray is upper or lower triangular
+        sum_cov_chol = linalg.cho_factor(sum_cov)
+
+        diff = self.dataset - mean
+        tdiff = linalg.cho_solve(sum_cov_chol, diff)
+
+        sqrt_det = np.prod(np.diagonal(sum_cov_chol[0]))
+        norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det
+
+        energies = sum(diff * tdiff, axis=0) / 2.0
+        result = sum(exp(-energies)*self.weights, axis=0) / norm_const
+
+        return result
+
+    def integrate_box_1d(self, low, high):
+        """
+        Computes the integral of a 1D pdf between two bounds.
+
+        Parameters
+        ----------
+        low : scalar
+            Lower bound of integration.
+        high : scalar
+            Upper bound of integration.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the KDE is over more than one dimension.
+
+        """
+        if self.d != 1:
+            raise ValueError("integrate_box_1d() only handles 1D pdfs")
+
+        stdev = ravel(sqrt(self.covariance))[0]
+
+        normalized_low = ravel((low - self.dataset) / stdev)
+        normalized_high = ravel((high - self.dataset) / stdev)
+
+        value = np.sum(self.weights*(
+                        special.ndtr(normalized_high) -
+                        special.ndtr(normalized_low)))
+        return value
+
+    def integrate_box(self, low_bounds, high_bounds, maxpts=None):
+        """Computes the integral of a pdf over a rectangular interval.
+
+        Parameters
+        ----------
+        low_bounds : array_like
+            A 1-D array containing the lower bounds of integration.
+        high_bounds : array_like
+            A 1-D array containing the upper bounds of integration.
+        maxpts : int, optional
+            The maximum number of points to use for integration.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        """
+        if maxpts is not None:
+            extra_kwds = {'maxpts': maxpts}
+        else:
+            extra_kwds = {}
+
+        with MVN_LOCK:
+            value, inform = _mvn.mvnun_weighted(low_bounds, high_bounds,
+                                                self.dataset, self.weights,
+                                                self.covariance, **extra_kwds)
+        if inform:
+            msg = f'An integral in _mvn.mvnun requires more points than {self.d * 1000}'
+            warnings.warn(msg, stacklevel=2)
+
+        return value
+
+    def integrate_kde(self, other):
+        """
+        Computes the integral of the product of this  kernel density estimate
+        with another.
+
+        Parameters
+        ----------
+        other : gaussian_kde instance
+            The other kde.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the KDEs have different dimensionality.
+
+        """
+        if other.d != self.d:
+            raise ValueError("KDEs are not the same dimensionality")
+
+        # we want to iterate over the smallest number of points
+        if other.n < self.n:
+            small = other
+            large = self
+        else:
+            small = self
+            large = other
+
+        sum_cov = small.covariance + large.covariance
+        sum_cov_chol = linalg.cho_factor(sum_cov)
+        result = 0.0
+        for i in range(small.n):
+            mean = small.dataset[:, i, newaxis]
+            diff = large.dataset - mean
+            tdiff = linalg.cho_solve(sum_cov_chol, diff)
+
+            energies = sum(diff * tdiff, axis=0) / 2.0
+            result += sum(exp(-energies)*large.weights, axis=0)*small.weights[i]
+
+        sqrt_det = np.prod(np.diagonal(sum_cov_chol[0]))
+        norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det
+
+        result /= norm_const
+
+        return result
+
+    def resample(self, size=None, seed=None):
+        """Randomly sample a dataset from the estimated pdf.
+
+        Parameters
+        ----------
+        size : int, optional
+            The number of samples to draw.  If not provided, then the size is
+            the same as the effective number of samples in the underlying
+            dataset.
+        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
+        -------
+        resample : (self.d, `size`) ndarray
+            The sampled dataset.
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        if size is None:
+            size = int(self.neff)
+
+        random_state = check_random_state(seed)
+        norm = transpose(random_state.multivariate_normal(
+            zeros((self.d,), float), self.covariance, size=size
+        ))
+        indices = random_state.choice(self.n, size=size, p=self.weights)
+        means = self.dataset[:, indices]
+
+        return means + norm
+
+    def scotts_factor(self):
+        """Compute Scott's factor.
+
+        Returns
+        -------
+        s : float
+            Scott's factor.
+        """
+        return power(self.neff, -1./(self.d+4))
+
+    def silverman_factor(self):
+        """Compute the Silverman factor.
+
+        Returns
+        -------
+        s : float
+            The silverman factor.
+        """
+        return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4))
+
+    #  Default method to calculate bandwidth, can be overwritten by subclass
+    covariance_factor = scotts_factor
+    covariance_factor.__doc__ = """Computes the coefficient (`kde.factor`) that
+        multiplies the data covariance matrix to obtain the kernel covariance
+        matrix. The default is `scotts_factor`.  A subclass can overwrite this
+        method to provide a different method, or set it through a call to
+        `kde.set_bandwidth`."""
+
+    def set_bandwidth(self, bw_method=None):
+        """Compute the estimator bandwidth with given method.
+
+        The new bandwidth calculated after a call to `set_bandwidth` is used
+        for subsequent evaluations of the estimated density.
+
+        Parameters
+        ----------
+        bw_method : str, scalar or callable, optional
+            The method used to calculate the estimator bandwidth.  This can be
+            'scott', 'silverman', a scalar constant or a callable.  If a
+            scalar, this will be used directly as `kde.factor`.  If a callable,
+            it should take a `gaussian_kde` instance as only parameter and
+            return a scalar.  If None (default), nothing happens; the current
+            `kde.covariance_factor` method is kept.
+
+        Notes
+        -----
+        .. versionadded:: 0.11
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.stats as stats
+        >>> x1 = np.array([-7, -5, 1, 4, 5.])
+        >>> kde = stats.gaussian_kde(x1)
+        >>> xs = np.linspace(-10, 10, num=50)
+        >>> y1 = kde(xs)
+        >>> kde.set_bandwidth(bw_method='silverman')
+        >>> y2 = kde(xs)
+        >>> kde.set_bandwidth(bw_method=kde.factor / 3.)
+        >>> y3 = kde(xs)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> ax.plot(x1, np.full(x1.shape, 1 / (4. * x1.size)), 'bo',
+        ...         label='Data points (rescaled)')
+        >>> ax.plot(xs, y1, label='Scott (default)')
+        >>> ax.plot(xs, y2, label='Silverman')
+        >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)')
+        >>> ax.legend()
+        >>> plt.show()
+
+        """
+        if bw_method is None:
+            pass
+        elif bw_method == 'scott':
+            self.covariance_factor = self.scotts_factor
+        elif bw_method == 'silverman':
+            self.covariance_factor = self.silverman_factor
+        elif np.isscalar(bw_method) and not isinstance(bw_method, str):
+            self._bw_method = 'use constant'
+            self.covariance_factor = lambda: bw_method
+        elif callable(bw_method):
+            self._bw_method = bw_method
+            self.covariance_factor = lambda: self._bw_method(self)
+        else:
+            msg = "`bw_method` should be 'scott', 'silverman', a scalar " \
+                  "or a callable."
+            raise ValueError(msg)
+
+        self._compute_covariance()
+
+    def _compute_covariance(self):
+        """Computes the covariance matrix for each Gaussian kernel using
+        covariance_factor().
+        """
+        self.factor = self.covariance_factor()
+        # Cache covariance and Cholesky decomp of covariance
+        if not hasattr(self, '_data_cho_cov'):
+            self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,
+                                               bias=False,
+                                               aweights=self.weights))
+            self._data_cho_cov = linalg.cholesky(self._data_covariance,
+                                                 lower=True)
+
+        self.covariance = self._data_covariance * self.factor**2
+        self.cho_cov = (self._data_cho_cov * self.factor).astype(np.float64)
+        self.log_det = 2*np.log(np.diag(self.cho_cov
+                                        * np.sqrt(2*pi))).sum()
+
+    @property
+    def inv_cov(self):
+        # Re-compute from scratch each time because I'm not sure how this is
+        # used in the wild. (Perhaps users change the `dataset`, since it's
+        # not a private attribute?) `_compute_covariance` used to recalculate
+        # all these, so we'll recalculate everything now that this is a
+        # a property.
+        self.factor = self.covariance_factor()
+        self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,
+                                           bias=False, aweights=self.weights))
+        return linalg.inv(self._data_covariance) / self.factor**2
+
+    def pdf(self, x):
+        """
+        Evaluate the estimated pdf on a provided set of points.
+
+        Notes
+        -----
+        This is an alias for `gaussian_kde.evaluate`.  See the ``evaluate``
+        docstring for more details.
+
+        """
+        return self.evaluate(x)
+
+    def logpdf(self, x):
+        """
+        Evaluate the log of the estimated pdf on a provided set of points.
+        """
+        points = atleast_2d(x)
+
+        d, m = points.shape
+        if d != self.d:
+            if d == 1 and m == self.d:
+                # points was passed in as a row vector
+                points = reshape(points, (self.d, 1))
+                m = 1
+            else:
+                msg = (f"points have dimension {d}, "
+                       f"dataset has dimension {self.d}")
+                raise ValueError(msg)
+
+        output_dtype, spec = _get_output_dtype(self.covariance, points)
+        result = gaussian_kernel_estimate_log[spec](
+            self.dataset.T, self.weights[:, None],
+            points.T, self.cho_cov, output_dtype)
+
+        return result[:, 0]
+
+    def marginal(self, dimensions):
+        """Return a marginal KDE distribution
+
+        Parameters
+        ----------
+        dimensions : int or 1-d array_like
+            The dimensions of the multivariate distribution corresponding
+            with the marginal variables, that is, the indices of the dimensions
+            that are being retained. The other dimensions are marginalized out.
+
+        Returns
+        -------
+        marginal_kde : gaussian_kde
+            An object representing the marginal distribution.
+
+        Notes
+        -----
+        .. versionadded:: 1.10.0
+
+        """
+
+        dims = np.atleast_1d(dimensions)
+
+        if not np.issubdtype(dims.dtype, np.integer):
+            msg = ("Elements of `dimensions` must be integers - the indices "
+                   "of the marginal variables being retained.")
+            raise ValueError(msg)
+
+        n = len(self.dataset)  # number of dimensions
+        original_dims = dims.copy()
+
+        dims[dims < 0] = n + dims[dims < 0]
+
+        if len(np.unique(dims)) != len(dims):
+            msg = ("All elements of `dimensions` must be unique.")
+            raise ValueError(msg)
+
+        i_invalid = (dims < 0) | (dims >= n)
+        if np.any(i_invalid):
+            msg = (f"Dimensions {original_dims[i_invalid]} are invalid "
+                   f"for a distribution in {n} dimensions.")
+            raise ValueError(msg)
+
+        dataset = self.dataset[dims]
+        weights = self.weights
+
+        return gaussian_kde(dataset, bw_method=self.covariance_factor(),
+                            weights=weights)
+
+    @property
+    def weights(self):
+        try:
+            return self._weights
+        except AttributeError:
+            self._weights = ones(self.n)/self.n
+            return self._weights
+
+    @property
+    def neff(self):
+        try:
+            return self._neff
+        except AttributeError:
+            self._neff = 1/sum(self.weights**2)
+            return self._neff
+
+
+def _get_output_dtype(covariance, points):
+    """
+    Calculates the output dtype and the "spec" (=C type name).
+
+    This was necessary in order to deal with the fused types in the Cython
+    routine `gaussian_kernel_estimate`. See gh-10824 for details.
+    """
+    output_dtype = np.common_type(covariance, points)
+    itemsize = np.dtype(output_dtype).itemsize
+    if itemsize == 4:
+        spec = 'float'
+    elif itemsize == 8:
+        spec = 'double'
+    elif itemsize in (12, 16):
+        spec = 'long double'
+    else:
+        raise ValueError(
+                f"{output_dtype} has unexpected item size: {itemsize}"
+            )
+
+    return output_dtype, spec
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_ksstats.py b/python_embeded/Lib/site-packages/scipy/stats/_ksstats.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ae1d126f51d9eb4ff9059736fb649ed3e86c483
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_ksstats.py
@@ -0,0 +1,600 @@
+# Compute the two-sided one-sample Kolmogorov-Smirnov Prob(Dn <= d) where:
+#    D_n = sup_x{|F_n(x) - F(x)|},
+#    F_n(x) is the empirical CDF for a sample of size n {x_i: i=1,...,n},
+#    F(x) is the CDF of a probability distribution.
+#
+# Exact methods:
+# Prob(D_n >= d) can be computed via a matrix algorithm of Durbin[1]
+#   or a recursion algorithm due to Pomeranz[2].
+# Marsaglia, Tsang & Wang[3] gave a computation-efficient way to perform
+#   the Durbin algorithm.
+#   D_n >= d <==>  D_n+ >= d or D_n- >= d (the one-sided K-S statistics), hence
+#   Prob(D_n >= d) = 2*Prob(D_n+ >= d) - Prob(D_n+ >= d and D_n- >= d).
+#   For d > 0.5, the latter intersection probability is 0.
+#
+# Approximate methods:
+# For d close to 0.5, ignoring that intersection term may still give a
+#   reasonable approximation.
+# Li-Chien[4] and Korolyuk[5] gave an asymptotic formula extending
+# Kolmogorov's initial asymptotic, suitable for large d. (See
+#   scipy.special.kolmogorov for that asymptotic)
+# Pelz-Good[6] used the functional equation for Jacobi theta functions to
+#   transform the Li-Chien/Korolyuk formula produce a computational formula
+#   suitable for small d.
+#
+# Simard and L'Ecuyer[7] provided an algorithm to decide when to use each of
+#   the above approaches and it is that which is used here.
+#
+# Other approaches:
+# Carvalho[8] optimizes Durbin's matrix algorithm for large values of d.
+# Moscovich and Nadler[9] use FFTs to compute the convolutions.
+
+# References:
+# [1] Durbin J (1968).
+#     "The Probability that the Sample Distribution Function Lies Between Two
+#     Parallel Straight Lines."
+#     Annals of Mathematical Statistics, 39, 398-411.
+# [2] Pomeranz J (1974).
+#     "Exact Cumulative Distribution of the Kolmogorov-Smirnov Statistic for
+#     Small Samples (Algorithm 487)."
+#     Communications of the ACM, 17(12), 703-704.
+# [3] Marsaglia G, Tsang WW, Wang J (2003).
+#     "Evaluating Kolmogorov's Distribution."
+#     Journal of Statistical Software, 8(18), 1-4.
+# [4] LI-CHIEN, C. (1956).
+#     "On the exact distribution of the statistics of A. N. Kolmogorov and
+#     their asymptotic expansion."
+#     Acta Matematica Sinica, 6, 55-81.
+# [5] KOROLYUK, V. S. (1960).
+#     "Asymptotic analysis of the distribution of the maximum deviation in
+#     the Bernoulli scheme."
+#     Theor. Probability Appl., 4, 339-366.
+# [6] Pelz W, Good IJ (1976).
+#     "Approximating the Lower Tail-areas of the Kolmogorov-Smirnov One-sample
+#     Statistic."
+#     Journal of the Royal Statistical Society, Series B, 38(2), 152-156.
+#  [7] Simard, R., L'Ecuyer, P. (2011)
+# 	  "Computing the Two-Sided Kolmogorov-Smirnov Distribution",
+# 	  Journal of Statistical Software, Vol 39, 11, 1-18.
+#  [8] Carvalho, Luis (2015)
+#     "An Improved Evaluation of Kolmogorov's Distribution"
+#     Journal of Statistical Software, Code Snippets; Vol 65(3), 1-8.
+#  [9] Amit Moscovich, Boaz Nadler (2017)
+#     "Fast calculation of boundary crossing probabilities for Poisson
+#     processes",
+#     Statistics & Probability Letters, Vol 123, 177-182.
+
+
+import numpy as np
+import scipy.special
+import scipy.special._ufuncs as scu
+from scipy._lib._finite_differences import _derivative
+
+_E128 = 128
+_EP128 = np.ldexp(np.longdouble(1), _E128)
+_EM128 = np.ldexp(np.longdouble(1), -_E128)
+
+_SQRT2PI = np.sqrt(2 * np.pi)
+_LOG_2PI = np.log(2 * np.pi)
+_MIN_LOG = -708
+_SQRT3 = np.sqrt(3)
+_PI_SQUARED = np.pi ** 2
+_PI_FOUR = np.pi ** 4
+_PI_SIX = np.pi ** 6
+
+# [Lifted from _loggamma.pxd.] If B_m are the Bernoulli numbers,
+# then Stirling coeffs are B_{2j}/(2j)/(2j-1) for j=8,...1.
+_STIRLING_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]
+
+
+def _log_nfactorial_div_n_pow_n(n):
+    # Computes n! / n**n
+    #    = (n-1)! / n**(n-1)
+    # Uses Stirling's approximation, but removes n*log(n) up-front to
+    # avoid subtractive cancellation.
+    #    = log(n)/2 - n + log(sqrt(2pi)) + sum B_{2j}/(2j)/(2j-1)/n**(2j-1)
+    rn = 1.0/n
+    return np.log(n)/2 - n + _LOG_2PI/2 + rn * np.polyval(_STIRLING_COEFFS, rn/n)
+
+
+def _clip_prob(p):
+    """clips a probability to range 0<=p<=1."""
+    return np.clip(p, 0.0, 1.0)
+
+
+def _select_and_clip_prob(cdfprob, sfprob, cdf=True):
+    """Selects either the CDF or SF, and then clips to range 0<=p<=1."""
+    p = np.where(cdf, cdfprob, sfprob)
+    return _clip_prob(p)
+
+
+def _kolmogn_DMTW(n, d, cdf=True):
+    r"""Computes the Kolmogorov CDF:  Pr(D_n <= d) using the MTW approach to
+    the Durbin matrix algorithm.
+
+    Durbin (1968); Marsaglia, Tsang, Wang (2003). [1], [3].
+    """
+    # Write d = (k-h)/n, where k is positive integer and 0 <= h < 1
+    # Generate initial matrix H of size m*m where m=(2k-1)
+    # Compute k-th row of (n!/n^n) * H^n, scaling intermediate results.
+    # Requires memory O(m^2) and computation O(m^2 log(n)).
+    # Most suitable for small m.
+
+    if d >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf)
+    nd = n * d
+    if nd <= 0.5:
+        return _select_and_clip_prob(0.0, 1.0, cdf)
+    k = int(np.ceil(nd))
+    h = k - nd
+    m = 2 * k - 1
+
+    H = np.zeros([m, m])
+
+    # Initialize: v is first column (and last row) of H
+    #  v[j] = (1-h^(j+1)/(j+1)!  (except for v[-1])
+    #  w[j] = 1/(j)!
+    # q = k-th row of H (actually i!/n^i*H^i)
+    intm = np.arange(1, m + 1)
+    v = 1.0 - h ** intm
+    w = np.empty(m)
+    fac = 1.0
+    for j in intm:
+        w[j - 1] = fac
+        fac /= j  # This might underflow.  Isn't a problem.
+        v[j - 1] *= fac
+    tt = max(2 * h - 1.0, 0)**m - 2*h**m
+    v[-1] = (1.0 + tt) * fac
+
+    for i in range(1, m):
+        H[i - 1:, i] = w[:m - i + 1]
+    H[:, 0] = v
+    H[-1, :] = np.flip(v, axis=0)
+
+    Hpwr = np.eye(np.shape(H)[0])  # Holds intermediate powers of H
+    nn = n
+    expnt = 0  # Scaling of Hpwr
+    Hexpnt = 0  # Scaling of H
+    while nn > 0:
+        if nn % 2:
+            Hpwr = np.matmul(Hpwr, H)
+            expnt += Hexpnt
+        H = np.matmul(H, H)
+        Hexpnt *= 2
+        # Scale as needed.
+        if np.abs(H[k - 1, k - 1]) > _EP128:
+            H /= _EP128
+            Hexpnt += _E128
+        nn = nn // 2
+
+    p = Hpwr[k - 1, k - 1]
+
+    # Multiply by n!/n^n
+    for i in range(1, n + 1):
+        p = i * p / n
+        if np.abs(p) < _EM128:
+            p *= _EP128
+            expnt -= _E128
+
+    # unscale
+    if expnt != 0:
+        p = np.ldexp(p, expnt)
+
+    return _select_and_clip_prob(p, 1.0-p, cdf)
+
+
+def _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf):
+    """Compute the endpoints of the interval for row i."""
+    if i == 0:
+        j1, j2 = -ll - ceilf - 1, ll + ceilf - 1
+    else:
+        # i + 1 = 2*ip1div2 + ip1mod2
+        ip1div2, ip1mod2 = divmod(i + 1, 2)
+        if ip1mod2 == 0:  # i is odd
+            if ip1div2 == n + 1:
+                j1, j2 = n - ll - ceilf - 1, n + ll + ceilf - 1
+            else:
+                j1, j2 = ip1div2 - 1 - ll - roundf - 1, ip1div2 + ll - 1 + ceilf - 1
+        else:
+            j1, j2 = ip1div2 - 1 - ll - 1, ip1div2 + ll + roundf - 1
+
+    return max(j1 + 2, 0), min(j2, n)
+
+
+def _kolmogn_Pomeranz(n, x, cdf=True):
+    r"""Computes Pr(D_n <= d) using the Pomeranz recursion algorithm.
+
+    Pomeranz (1974) [2]
+    """
+
+    # V is n*(2n+2) matrix.
+    # Each row is convolution of the previous row and probabilities from a
+    #  Poisson distribution.
+    # Desired CDF probability is n! V[n-1, 2n+1]  (final entry in final row).
+    # Only two rows are needed at any given stage:
+    #  - Call them V0 and V1.
+    #  - Swap each iteration
+    # Only a few (contiguous) entries in each row can be non-zero.
+    #  - Keep track of start and end (j1 and j2 below)
+    #  - V0s and V1s track the start in the two rows
+    # Scale intermediate results as needed.
+    # Only a few different Poisson distributions can occur
+    t = n * x
+    ll = int(np.floor(t))
+    f = 1.0 * (t - ll)  # fractional part of t
+    g = min(f, 1.0 - f)
+    ceilf = (1 if f > 0 else 0)
+    roundf = (1 if f > 0.5 else 0)
+    npwrs = 2 * (ll + 1)    # Maximum number of powers needed in convolutions
+    gpower = np.empty(npwrs)  # gpower = (g/n)^m/m!
+    twogpower = np.empty(npwrs)  # twogpower = (2g/n)^m/m!
+    onem2gpower = np.empty(npwrs)  # onem2gpower = ((1-2g)/n)^m/m!
+    # gpower etc are *almost* Poisson probs, just missing normalizing factor.
+
+    gpower[0] = 1.0
+    twogpower[0] = 1.0
+    onem2gpower[0] = 1.0
+    expnt = 0
+    g_over_n, two_g_over_n, one_minus_two_g_over_n = g/n, 2*g/n, (1 - 2*g)/n
+    for m in range(1, npwrs):
+        gpower[m] = gpower[m - 1] * g_over_n / m
+        twogpower[m] = twogpower[m - 1] * two_g_over_n / m
+        onem2gpower[m] = onem2gpower[m - 1] * one_minus_two_g_over_n / m
+
+    V0 = np.zeros([npwrs])
+    V1 = np.zeros([npwrs])
+    V1[0] = 1  # first row
+    V0s, V1s = 0, 0  # start indices of the two rows
+
+    j1, j2 = _pomeranz_compute_j1j2(0, n, ll, ceilf, roundf)
+    for i in range(1, 2 * n + 2):
+        # Preserve j1, V1, V1s, V0s from last iteration
+        k1 = j1
+        V0, V1 = V1, V0
+        V0s, V1s = V1s, V0s
+        V1.fill(0.0)
+        j1, j2 = _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf)
+        if i == 1 or i == 2 * n + 1:
+            pwrs = gpower
+        else:
+            pwrs = (twogpower if i % 2 else onem2gpower)
+        ln2 = j2 - k1 + 1
+        if ln2 > 0:
+            conv = np.convolve(V0[k1 - V0s:k1 - V0s + ln2], pwrs[:ln2])
+            conv_start = j1 - k1  # First index to use from conv
+            conv_len = j2 - j1 + 1  # Number of entries to use from conv
+            V1[:conv_len] = conv[conv_start:conv_start + conv_len]
+            # Scale to avoid underflow.
+            if 0 < np.max(V1) < _EM128:
+                V1 *= _EP128
+                expnt -= _E128
+            V1s = V0s + j1 - k1
+
+    # multiply by n!
+    ans = V1[n - V1s]
+    for m in range(1, n + 1):
+        if np.abs(ans) > _EP128:
+            ans *= _EM128
+            expnt += _E128
+        ans *= m
+
+    # Undo any intermediate scaling
+    if expnt != 0:
+        ans = np.ldexp(ans, expnt)
+    ans = _select_and_clip_prob(ans, 1.0 - ans, cdf)
+    return ans
+
+
+def _kolmogn_PelzGood(n, x, cdf=True):
+    """Computes the Pelz-Good approximation to Prob(Dn <= x) with 0<=x<=1.
+
+    Start with Li-Chien, Korolyuk approximation:
+        Prob(Dn <= x) ~ K0(z) + K1(z)/sqrt(n) + K2(z)/n + K3(z)/n**1.5
+    where z = x*sqrt(n).
+    Transform each K_(z) using Jacobi theta functions into a form suitable
+    for small z.
+    Pelz-Good (1976). [6]
+    """
+    if x <= 0.0:
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+    if x >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf=cdf)
+
+    z = np.sqrt(n) * x
+    zsquared, zthree, zfour, zsix = z**2, z**3, z**4, z**6
+
+    qlog = -_PI_SQUARED / 8 / zsquared
+    if qlog < _MIN_LOG:  # z ~ 0.041743441416853426
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+
+    q = np.exp(qlog)
+
+    # Coefficients of terms in the sums for K1, K2 and K3
+    k1a = -zsquared
+    k1b = _PI_SQUARED / 4
+
+    k2a = 6 * zsix + 2 * zfour
+    k2b = (2 * zfour - 5 * zsquared) * _PI_SQUARED / 4
+    k2c = _PI_FOUR * (1 - 2 * zsquared) / 16
+
+    k3d = _PI_SIX * (5 - 30 * zsquared) / 64
+    k3c = _PI_FOUR * (-60 * zsquared + 212 * zfour) / 16
+    k3b = _PI_SQUARED * (135 * zfour - 96 * zsix) / 4
+    k3a = -30 * zsix - 90 * z**8
+
+    K0to3 = np.zeros(4)
+    # Use a Horner scheme to evaluate sum c_i q^(i^2)
+    # Reduces to a sum over odd integers.
+    maxk = int(np.ceil(16 * z / np.pi))
+    for k in range(maxk, 0, -1):
+        m = 2 * k - 1
+        msquared, mfour, msix = m**2, m**4, m**6
+        qpower = np.power(q, 8 * k)
+        coeffs = np.array([1.0,
+                           k1a + k1b*msquared,
+                           k2a + k2b*msquared + k2c*mfour,
+                           k3a + k3b*msquared + k3c*mfour + k3d*msix])
+        K0to3 *= qpower
+        K0to3 += coeffs
+    K0to3 *= q
+    K0to3 *= _SQRT2PI
+    # z**10 > 0 as z > 0.04
+    K0to3 /= np.array([z, 6 * zfour, 72 * z**7, 6480 * z**10])
+
+    # Now do the other sum over the other terms, all integers k
+    # K_2:  (pi^2 k^2) q^(k^2),
+    # K_3:  (3pi^2 k^2 z^2 - pi^4 k^4)*q^(k^2)
+    # Don't expect much subtractive cancellation so use direct calculation
+    q = np.exp(-_PI_SQUARED / 2 / zsquared)
+    ks = np.arange(maxk, 0, -1)
+    ksquared = ks ** 2
+    sqrt3z = _SQRT3 * z
+    kspi = np.pi * ks
+    qpwers = q ** ksquared
+    k2extra = np.sum(ksquared * qpwers)
+    k2extra *= _PI_SQUARED * _SQRT2PI/(-36 * zthree)
+    K0to3[2] += k2extra
+    k3extra = np.sum((sqrt3z + kspi) * (sqrt3z - kspi) * ksquared * qpwers)
+    k3extra *= _PI_SQUARED * _SQRT2PI/(216 * zsix)
+    K0to3[3] += k3extra
+    powers_of_n = np.power(n * 1.0, np.arange(len(K0to3)) / 2.0)
+    K0to3 /= powers_of_n
+
+    if not cdf:
+        K0to3 *= -1
+        K0to3[0] += 1
+
+    Ksum = sum(K0to3)
+    return Ksum
+
+
+def _kolmogn(n, x, cdf=True):
+    """Computes the CDF(or SF) for the two-sided Kolmogorov-Smirnov statistic.
+
+    x must be of type float, n of type integer.
+
+    Simard & L'Ecuyer (2011) [7].
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if x >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf=cdf)
+    if x <= 0.0:
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+    t = n * x
+    if t <= 1.0:  # Ruben-Gambino: 1/2n <= x <= 1/n
+        if t <= 0.5:
+            return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+        if n <= 140:
+            prob = np.prod(np.arange(1, n+1) * (1.0/n) * (2*t - 1))
+        else:
+            prob = np.exp(_log_nfactorial_div_n_pow_n(n) + n * np.log(2*t-1))
+        return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+    if t >= n - 1:  # Ruben-Gambino
+        prob = 2 * (1.0 - x)**n
+        return _select_and_clip_prob(1 - prob, prob, cdf=cdf)
+    if x >= 0.5:  # Exact: 2 * smirnov
+        prob = 2 * scipy.special.smirnov(n, x)
+        return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf)
+
+    nxsquared = t * x
+    if n <= 140:
+        if nxsquared <= 0.754693:
+            prob = _kolmogn_DMTW(n, x, cdf=True)
+            return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+        if nxsquared <= 4:
+            prob = _kolmogn_Pomeranz(n, x, cdf=True)
+            return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+        # Now use Miller approximation of 2*smirnov
+        prob = 2 * scipy.special.smirnov(n, x)
+        return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf)
+
+    # Split CDF and SF as they have different cutoffs on nxsquared.
+    if not cdf:
+        if nxsquared >= 370.0:
+            return 0.0
+        if nxsquared >= 2.2:
+            prob = 2 * scipy.special.smirnov(n, x)
+            return _clip_prob(prob)
+        # Fall through and compute the SF as 1.0-CDF
+    if nxsquared >= 18.0:
+        cdfprob = 1.0
+    elif n <= 100000 and n * x**1.5 <= 1.4:
+        cdfprob = _kolmogn_DMTW(n, x, cdf=True)
+    else:
+        cdfprob = _kolmogn_PelzGood(n, x, cdf=True)
+    return _select_and_clip_prob(cdfprob, 1.0 - cdfprob, cdf=cdf)
+
+
+def _kolmogn_p(n, x):
+    """Computes the PDF for the two-sided Kolmogorov-Smirnov statistic.
+
+    x must be of type float, n of type integer.
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if x >= 1.0 or x <= 0:
+        return 0
+    t = n * x
+    if t <= 1.0:
+        # Ruben-Gambino: n!/n^n * (2t-1)^n -> 2 n!/n^n * n^2 * (2t-1)^(n-1)
+        if t <= 0.5:
+            return 0.0
+        if n <= 140:
+            prd = np.prod(np.arange(1, n) * (1.0 / n) * (2 * t - 1))
+        else:
+            prd = np.exp(_log_nfactorial_div_n_pow_n(n) + (n-1) * np.log(2 * t - 1))
+        return prd * 2 * n**2
+    if t >= n - 1:
+        # Ruben-Gambino : 1-2(1-x)**n -> 2n*(1-x)**(n-1)
+        return 2 * (1.0 - x) ** (n-1) * n
+    if x >= 0.5:
+        return 2 * scipy.stats.ksone.pdf(x, n)
+
+    # Just take a small delta.
+    # Ideally x +/- delta would stay within [i/n, (i+1)/n] for some integer a.
+    # as the CDF is a piecewise degree n polynomial.
+    # It has knots at 1/n, 2/n, ... (n-1)/n
+    # and is not a C-infinity function at the knots
+    delta = x / 2.0**16
+    delta = min(delta, x - 1.0/n)
+    delta = min(delta, 0.5 - x)
+
+    def _kk(_x):
+        return kolmogn(n, _x)
+
+    return _derivative(_kk, x, dx=delta, order=5)
+
+
+def _kolmogni(n, p, q):
+    """Computes the PPF/ISF of kolmogn.
+
+    n of type integer, n>= 1
+    p is the CDF, q the SF, p+q=1
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if p <= 0:
+        return 1.0/n
+    if q <= 0:
+        return 1.0
+    delta = np.exp((np.log(p) - scipy.special.loggamma(n+1))/n)
+    if delta <= 1.0/n:
+        return (delta + 1.0 / n) / 2
+    x = -np.expm1(np.log(q/2.0)/n)
+    if x >= 1 - 1.0/n:
+        return x
+    x1 = scu._kolmogci(p)/np.sqrt(n)
+    x1 = min(x1, 1.0 - 1.0/n)
+
+    def _f(x):
+        return _kolmogn(n, x) - p
+
+    return scipy.optimize.brentq(_f, 1.0/n, x1, xtol=1e-14)
+
+
+def kolmogn(n, x, cdf=True):
+    """Computes the CDF for the two-sided Kolmogorov-Smirnov distribution.
+
+    The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x),
+    for a sample of size n drawn from a distribution with CDF F(t), where
+    :math:`D_n &= sup_t |F_n(t) - F(t)|`, and
+    :math:`F_n(t)` is the Empirical Cumulative Distribution Function of the sample.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    x : float, array_like
+        The K-S statistic, float between 0 and 1
+    cdf : bool, optional
+        whether to compute the CDF(default=true) or the SF.
+
+    Returns
+    -------
+    cdf : ndarray
+        CDF (or SF it cdf is False) at the specified locations.
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, x, cdf, None], flags=['zerosize_ok'],
+                   op_dtypes=[None, np.float64, np.bool_, np.float64])
+    for _n, _x, _cdf, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        z[...] = _kolmogn(int(_n), _x, cdf=_cdf)
+    result = it.operands[-1]
+    return result
+
+
+def kolmognp(n, x):
+    """Computes the PDF for the two-sided Kolmogorov-Smirnov distribution.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    x : float, array_like
+        The K-S statistic, float between 0 and 1
+
+    Returns
+    -------
+    pdf : ndarray
+        The PDF at the specified locations
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, x, None])
+    for _n, _x, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        z[...] = _kolmogn_p(int(_n), _x)
+    result = it.operands[-1]
+    return result
+
+
+def kolmogni(n, q, cdf=True):
+    """Computes the PPF(or ISF) for the two-sided Kolmogorov-Smirnov distribution.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    q : float, array_like
+        Probabilities, float between 0 and 1
+    cdf : bool, optional
+        whether to compute the PPF(default=true) or the ISF.
+
+    Returns
+    -------
+    ppf : ndarray
+        PPF (or ISF if cdf is False) at the specified locations
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, q, cdf, None])
+    for _n, _q, _cdf, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        _pcdf, _psf = (_q, 1-_q) if _cdf else (1-_q, _q)
+        z[...] = _kolmogni(int(_n), _pcdf, _psf)
+    result = it.operands[-1]
+    return result
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_mannwhitneyu.py b/python_embeded/Lib/site-packages/scipy/stats/_mannwhitneyu.py
new file mode 100644
index 0000000000000000000000000000000000000000..00c48092fe13a5fde221b1a4b8ea5db203c056bc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_mannwhitneyu.py
@@ -0,0 +1,492 @@
+import threading
+import numpy as np
+from collections import namedtuple
+from scipy import special
+from scipy import stats
+from scipy.stats._stats_py import _rankdata
+from ._axis_nan_policy import _axis_nan_policy_factory
+
+
+def _broadcast_concatenate(x, y, axis):
+    '''Broadcast then concatenate arrays, leaving concatenation axis last'''
+    x = np.moveaxis(x, axis, -1)
+    y = np.moveaxis(y, axis, -1)
+    z = np.broadcast(x[..., 0], y[..., 0])
+    x = np.broadcast_to(x, z.shape + (x.shape[-1],))
+    y = np.broadcast_to(y, z.shape + (y.shape[-1],))
+    z = np.concatenate((x, y), axis=-1)
+    return x, y, z
+
+
+class _MWU:
+    '''Distribution of MWU statistic under the null hypothesis'''
+
+    def __init__(self, n1, n2):
+        self._reset(n1, n2)
+
+    def set_shapes(self, n1, n2):
+        n1, n2 = min(n1, n2), max(n1, n2)
+        if (n1, n2) == (self.n1, self.n2):
+            return
+
+        self.n1 = n1
+        self.n2 = n2
+        self.s_array = np.zeros(0, dtype=int)
+        self.configurations = np.zeros(0, dtype=np.uint64)
+
+    def reset(self):
+        self._reset(self.n1, self.n2)
+
+    def _reset(self, n1, n2):
+        self.n1 = None
+        self.n2 = None
+        self.set_shapes(n1, n2)
+
+    def pmf(self, k):
+
+        # In practice, `pmf` is never called with k > m*n/2.
+        # If it were, we'd exploit symmetry here:
+        # k = np.array(k, copy=True)
+        # k2 = m*n - k
+        # i = k2 < k
+        # k[i] = k2[i]
+
+        pmfs = self.build_u_freqs_array(np.max(k))
+        return pmfs[k]
+
+    def cdf(self, k):
+        '''Cumulative distribution function'''
+
+        # In practice, `cdf` is never called with k > m*n/2.
+        # If it were, we'd exploit symmetry here rather than in `sf`
+        pmfs = self.build_u_freqs_array(np.max(k))
+        cdfs = np.cumsum(pmfs)
+        return cdfs[k]
+
+    def sf(self, k):
+        '''Survival function'''
+        # Note that both CDF and SF include the PMF at k. The p-value is
+        # calculated from the SF and should include the mass at k, so this
+        # is desirable
+
+        # Use the fact that the distribution is symmetric and sum from the left
+        kc = np.asarray(self.n1*self.n2 - k)  # complement of k
+        i = k < kc
+        if np.any(i):
+            kc[i] = k[i]
+            cdfs = np.asarray(self.cdf(kc))
+            cdfs[i] = 1. - cdfs[i] + self.pmf(kc[i])
+        else:
+            cdfs = np.asarray(self.cdf(kc))
+        return cdfs[()]
+
+    # build_sigma_array and build_u_freqs_array adapted from code
+    # by @toobaz with permission. Thanks to @andreasloe for the suggestion.
+    # See https://github.com/scipy/scipy/pull/4933#issuecomment-1898082691
+    def build_sigma_array(self, a):
+        n1, n2 = self.n1, self.n2
+        if a + 1 <= self.s_array.size:
+            return self.s_array[1:a+1]
+
+        s_array = np.zeros(a + 1, dtype=int)
+
+        for d in np.arange(1, n1 + 1):
+            # All multiples of d, except 0:
+            indices = np.arange(d, a + 1, d)
+            # \epsilon_d = 1:
+            s_array[indices] += d
+
+        for d in np.arange(n2 + 1, n2 + n1 + 1):
+            # All multiples of d, except 0:
+            indices = np.arange(d, a + 1, d)
+            # \epsilon_d = -1:
+            s_array[indices] -= d
+
+        # We don't need 0:
+        self.s_array = s_array
+        return s_array[1:]
+
+    def build_u_freqs_array(self, maxu):
+        """
+        Build all the array of frequencies for u from 0 to maxu.
+        Assumptions:
+          n1 <= n2
+          maxu <= n1 * n2 / 2
+        """
+        n1, n2 = self.n1, self.n2
+        total = special.binom(n1 + n2, n1)
+
+        if maxu + 1 <= self.configurations.size:
+            return self.configurations[:maxu + 1] / total
+
+        s_array = self.build_sigma_array(maxu)
+
+        # Start working with ints, for maximum precision and efficiency:
+        configurations = np.zeros(maxu + 1, dtype=np.uint64)
+        configurations_is_uint = True
+        uint_max = np.iinfo(np.uint64).max
+        # How many ways to have U=0? 1
+        configurations[0] = 1
+
+        for u in np.arange(1, maxu + 1):
+            coeffs = s_array[u - 1::-1]
+            new_val = np.dot(configurations[:u], coeffs) / u
+            if new_val > uint_max and configurations_is_uint:
+                # OK, we got into numbers too big for uint64.
+                # So now we start working with floats.
+                # By doing this since the beginning, we would have lost precision.
+                # (And working on python long ints would be unbearably slow)
+                configurations = configurations.astype(float)
+                configurations_is_uint = False
+            configurations[u] = new_val
+
+        self.configurations = configurations
+        return configurations / total
+
+
+# Maintain state for faster repeat calls to `mannwhitneyu`.
+# _MWU() is calculated once per thread and stored as an attribute on
+# this thread-local variable inside mannwhitneyu().
+_mwu_state = threading.local()
+
+
+def _get_mwu_z(U, n1, n2, t, axis=0, continuity=True):
+    '''Standardized MWU statistic'''
+    # Follows mannwhitneyu [2]
+    mu = n1 * n2 / 2
+    n = n1 + n2
+
+    # Tie correction according to [2], "Normal approximation and tie correction"
+    # "A more computationally-efficient form..."
+    tie_term = (t**3 - t).sum(axis=-1)
+    s = np.sqrt(n1*n2/12 * ((n + 1) - tie_term/(n*(n-1))))
+
+    numerator = U - mu
+
+    # Continuity correction.
+    # Because SF is always used to calculate the p-value, we can always
+    # _subtract_ 0.5 for the continuity correction. This always increases the
+    # p-value to account for the rest of the probability mass _at_ q = U.
+    if continuity:
+        numerator -= 0.5
+
+    # no problem evaluating the norm SF at an infinity
+    with np.errstate(divide='ignore', invalid='ignore'):
+        z = numerator / s
+    return z
+
+
+def _mwu_input_validation(x, y, use_continuity, alternative, axis, method):
+    ''' Input validation and standardization for mannwhitneyu '''
+    # Would use np.asarray_chkfinite, but infs are OK
+    x, y = np.atleast_1d(x), np.atleast_1d(y)
+    if np.isnan(x).any() or np.isnan(y).any():
+        raise ValueError('`x` and `y` must not contain NaNs.')
+    if np.size(x) == 0 or np.size(y) == 0:
+        raise ValueError('`x` and `y` must be of nonzero size.')
+
+    bools = {True, False}
+    if use_continuity not in bools:
+        raise ValueError(f'`use_continuity` must be one of {bools}.')
+
+    alternatives = {"two-sided", "less", "greater"}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f'`alternative` must be one of {alternatives}.')
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError('`axis` must be an integer.')
+
+    if not isinstance(method, stats.PermutationMethod):
+        methods = {"asymptotic", "exact", "auto"}
+        method = method.lower()
+        if method not in methods:
+            raise ValueError(f'`method` must be one of {methods}.')
+
+    return x, y, use_continuity, alternative, axis_int, method
+
+
+def _mwu_choose_method(n1, n2, ties):
+    """Choose method 'asymptotic' or 'exact' depending on input size, ties"""
+
+    # if both inputs are large, asymptotic is OK
+    if n1 > 8 and n2 > 8:
+        return "asymptotic"
+
+    # if there are any ties, asymptotic is preferred
+    if ties:
+        return "asymptotic"
+
+    return "exact"
+
+
+MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(MannwhitneyuResult, n_samples=2)
+def mannwhitneyu(x, y, use_continuity=True, alternative="two-sided",
+                 axis=0, method="auto"):
+    r'''Perform the Mann-Whitney U rank test on two independent samples.
+
+    The Mann-Whitney U test is a nonparametric test of the null hypothesis
+    that the distribution underlying sample `x` is the same as the
+    distribution underlying sample `y`. It is often used as a test of
+    difference in location between distributions.
+
+    Parameters
+    ----------
+    x, y : array-like
+        N-d arrays of samples. The arrays must be broadcastable except along
+        the dimension given by `axis`.
+    use_continuity : bool, optional
+            Whether a continuity correction (1/2) should be applied.
+            Default is True when `method` is ``'asymptotic'``; has no effect
+            otherwise.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        Let *SX(u)* and *SY(u)* be the survival functions of the
+        distributions underlying `x` and `y`, respectively. Then the following
+        alternative hypotheses are available:
+
+        * 'two-sided': the distributions are not equal, i.e. *SX(u) ≠ SY(u)* for
+          at least one *u*.
+        * 'less': the distribution underlying `x` is stochastically less
+          than the distribution underlying `y`, i.e. *SX(u) < SY(u)* for all *u*.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`, i.e. *SX(u) > SY(u)* for all *u*.
+
+        Under a more restrictive set of assumptions, the alternative hypotheses
+        can be expressed in terms of the locations of the distributions;
+        see [5]_ section 5.1.
+    axis : int, optional
+        Axis along which to perform the test. Default is 0.
+    method : {'auto', 'asymptotic', 'exact'} or `PermutationMethod` instance, optional
+        Selects the method used to calculate the *p*-value.
+        Default is 'auto'. The following options are available.
+
+        * ``'asymptotic'``: compares the standardized test statistic
+          against the normal distribution, correcting for ties.
+        * ``'exact'``: computes the exact *p*-value by comparing the observed
+          :math:`U` statistic against the exact distribution of the :math:`U`
+          statistic under the null hypothesis. No correction is made for ties.
+        * ``'auto'``: chooses ``'exact'`` when the size of one of the samples
+          is less than or equal to 8 and there are no ties;
+          chooses ``'asymptotic'`` otherwise.
+        * `PermutationMethod` instance. In this case, the p-value
+          is computed using `permutation_test` with the provided
+          configuration options and other appropriate settings.
+
+    Returns
+    -------
+    res : MannwhitneyuResult
+        An object containing attributes:
+
+        statistic : float
+            The Mann-Whitney U statistic corresponding with sample `x`. See
+            Notes for the test statistic corresponding with sample `y`.
+        pvalue : float
+            The associated *p*-value for the chosen `alternative`.
+
+    Notes
+    -----
+    If ``U1`` is the statistic corresponding with sample `x`, then the
+    statistic corresponding with sample `y` is
+    ``U2 = x.shape[axis] * y.shape[axis] - U1``.
+
+    `mannwhitneyu` is for independent samples. For related / paired samples,
+    consider `scipy.stats.wilcoxon`.
+
+    `method` ``'exact'`` is recommended when there are no ties and when either
+    sample size is less than 8 [1]_. The implementation follows the algorithm
+    reported in [3]_.
+    Note that the exact method is *not* corrected for ties, but
+    `mannwhitneyu` will not raise errors or warnings if there are ties in the
+    data. If there are ties and either samples is small (fewer than ~10
+    observations), consider passing an instance of `PermutationMethod`
+    as the `method` to perform a permutation test.
+
+    The Mann-Whitney U test is a non-parametric version of the t-test for
+    independent samples. When the means of samples from the populations
+    are normally distributed, consider `scipy.stats.ttest_ind`.
+
+    See Also
+    --------
+    scipy.stats.wilcoxon, scipy.stats.ranksums, scipy.stats.ttest_ind
+
+    References
+    ----------
+    .. [1] H.B. Mann and D.R. Whitney, "On a test of whether one of two random
+           variables is stochastically larger than the other", The Annals of
+           Mathematical Statistics, Vol. 18, pp. 50-60, 1947.
+    .. [2] Mann-Whitney U Test, Wikipedia,
+           http://en.wikipedia.org/wiki/Mann-Whitney_U_test
+    .. [3] Andreas Löffler,
+           "Über eine Partition der nat. Zahlen und ihr Anwendung beim U-Test",
+           Wiss. Z. Univ. Halle, XXXII'83 pp. 87-89.
+    .. [4] Rosie Shier, "Statistics: 2.3 The Mann-Whitney U Test", Mathematics
+           Learning Support Centre, 2004.
+    .. [5] Michael P. Fay and Michael A. Proschan. "Wilcoxon-Mann-Whitney
+           or t-test? On assumptions for hypothesis tests and multiple \
+           interpretations of decision rules." Statistics surveys, Vol. 4, pp.
+           1-39, 2010. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2857732/
+
+    Examples
+    --------
+    We follow the example from [4]_: nine randomly sampled young adults were
+    diagnosed with type II diabetes at the ages below.
+
+    >>> males = [19, 22, 16, 29, 24]
+    >>> females = [20, 11, 17, 12]
+
+    We use the Mann-Whitney U test to assess whether there is a statistically
+    significant difference in the diagnosis age of males and females.
+    The null hypothesis is that the distribution of male diagnosis ages is
+    the same as the distribution of female diagnosis ages. We decide
+    that a confidence level of 95% is required to reject the null hypothesis
+    in favor of the alternative that the distributions are different.
+    Since the number of samples is very small and there are no ties in the
+    data, we can compare the observed test statistic against the *exact*
+    distribution of the test statistic under the null hypothesis.
+
+    >>> from scipy.stats import mannwhitneyu
+    >>> U1, p = mannwhitneyu(males, females, method="exact")
+    >>> print(U1)
+    17.0
+
+    `mannwhitneyu` always reports the statistic associated with the first
+    sample, which, in this case, is males. This agrees with :math:`U_M = 17`
+    reported in [4]_. The statistic associated with the second statistic
+    can be calculated:
+
+    >>> nx, ny = len(males), len(females)
+    >>> U2 = nx*ny - U1
+    >>> print(U2)
+    3.0
+
+    This agrees with :math:`U_F = 3` reported in [4]_. The two-sided
+    *p*-value can be calculated from either statistic, and the value produced
+    by `mannwhitneyu` agrees with :math:`p = 0.11` reported in [4]_.
+
+    >>> print(p)
+    0.1111111111111111
+
+    The exact distribution of the test statistic is asymptotically normal, so
+    the example continues by comparing the exact *p*-value against the
+    *p*-value produced using the normal approximation.
+
+    >>> _, pnorm = mannwhitneyu(males, females, method="asymptotic")
+    >>> print(pnorm)
+    0.11134688653314041
+
+    Here `mannwhitneyu`'s reported *p*-value appears to conflict with the
+    value :math:`p = 0.09` given in [4]_. The reason is that [4]_
+    does not apply the continuity correction performed by `mannwhitneyu`;
+    `mannwhitneyu` reduces the distance between the test statistic and the
+    mean :math:`\mu = n_x n_y / 2` by 0.5 to correct for the fact that the
+    discrete statistic is being compared against a continuous distribution.
+    Here, the :math:`U` statistic used is less than the mean, so we reduce
+    the distance by adding 0.5 in the numerator.
+
+    >>> import numpy as np
+    >>> from scipy.stats import norm
+    >>> U = min(U1, U2)
+    >>> N = nx + ny
+    >>> z = (U - nx*ny/2 + 0.5) / np.sqrt(nx*ny * (N + 1)/ 12)
+    >>> p = 2 * norm.cdf(z)  # use CDF to get p-value from smaller statistic
+    >>> print(p)
+    0.11134688653314041
+
+    If desired, we can disable the continuity correction to get a result
+    that agrees with that reported in [4]_.
+
+    >>> _, pnorm = mannwhitneyu(males, females, use_continuity=False,
+    ...                         method="asymptotic")
+    >>> print(pnorm)
+    0.0864107329737
+
+    Regardless of whether we perform an exact or asymptotic test, the
+    probability of the test statistic being as extreme or more extreme by
+    chance exceeds 5%, so we do not consider the results statistically
+    significant.
+
+    Suppose that, before seeing the data, we had hypothesized that females
+    would tend to be diagnosed at a younger age than males.
+    In that case, it would be natural to provide the female ages as the
+    first input, and we would have performed a one-sided test using
+    ``alternative = 'less'``: females are diagnosed at an age that is
+    stochastically less than that of males.
+
+    >>> res = mannwhitneyu(females, males, alternative="less", method="exact")
+    >>> print(res)
+    MannwhitneyuResult(statistic=3.0, pvalue=0.05555555555555555)
+
+    Again, the probability of getting a sufficiently low value of the
+    test statistic by chance under the null hypothesis is greater than 5%,
+    so we do not reject the null hypothesis in favor of our alternative.
+
+    If it is reasonable to assume that the means of samples from the
+    populations are normally distributed, we could have used a t-test to
+    perform the analysis.
+
+    >>> from scipy.stats import ttest_ind
+    >>> res = ttest_ind(females, males, alternative="less")
+    >>> print(res)
+    TtestResult(statistic=-2.239334696520584,
+                pvalue=0.030068441095757924,
+                df=7.0)
+
+    Under this assumption, the *p*-value would be low enough to reject the
+    null hypothesis in favor of the alternative.
+
+    '''
+
+    x, y, use_continuity, alternative, axis_int, method = (
+        _mwu_input_validation(x, y, use_continuity, alternative, axis, method))
+
+    x, y, xy = _broadcast_concatenate(x, y, axis)
+
+    n1, n2 = x.shape[-1], y.shape[-1]
+
+    # Follows [2]
+    ranks, t = _rankdata(xy, 'average', return_ties=True)  # method 2, step 1
+    R1 = ranks[..., :n1].sum(axis=-1)                      # method 2, step 2
+    U1 = R1 - n1*(n1+1)/2                                  # method 2, step 3
+    U2 = n1 * n2 - U1                                      # as U1 + U2 = n1 * n2
+
+    if alternative == "greater":
+        U, f = U1, 1  # U is the statistic to use for p-value, f is a factor
+    elif alternative == "less":
+        U, f = U2, 1  # Due to symmetry, use SF of U2 rather than CDF of U1
+    else:
+        U, f = np.maximum(U1, U2), 2  # multiply SF by two for two-sided test
+
+    if method == "auto":
+        method = _mwu_choose_method(n1, n2, np.any(t > 1))
+
+    if method == "exact":
+        if not hasattr(_mwu_state, 's'):
+            _mwu_state.s = _MWU(0, 0)
+        _mwu_state.s.set_shapes(n1, n2)
+        p = _mwu_state.s.sf(U.astype(int))
+    elif method == "asymptotic":
+        z = _get_mwu_z(U, n1, n2, t, continuity=use_continuity)
+        p = stats.norm.sf(z)
+    else:  # `PermutationMethod` instance (already validated)
+        def statistic(x, y, axis):
+            return mannwhitneyu(x, y, use_continuity=use_continuity,
+                                alternative=alternative, axis=axis,
+                                method="asymptotic").statistic
+
+        res = stats.permutation_test((x, y), statistic, axis=axis,
+                                     **method._asdict(), alternative=alternative)
+        p = res.pvalue
+        f = 1
+
+    p *= f
+
+    # Ensure that test statistic is not greater than 1
+    # This could happen for exact test when U = m*n/2
+    p = np.clip(p, 0, 1)
+
+    return MannwhitneyuResult(U1, p)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_mgc.py b/python_embeded/Lib/site-packages/scipy/stats/_mgc.py
new file mode 100644
index 0000000000000000000000000000000000000000..128792ec1410cb9545a9ae99ff468d233714b94e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_mgc.py
@@ -0,0 +1,550 @@
+import warnings
+import numpy as np
+
+from scipy._lib._util import check_random_state, MapWrapper, rng_integers, _contains_nan
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy.spatial.distance import cdist
+from scipy.ndimage import _measurements
+
+from ._stats import _local_correlations  # type: ignore[import-not-found]
+from . import distributions
+
+__all__ = ['multiscale_graphcorr']
+
+# FROM MGCPY: https://github.com/neurodata/mgcpy
+
+
+class _ParallelP:
+    """Helper function to calculate parallel p-value."""
+
+    def __init__(self, x, y, random_states):
+        self.x = x
+        self.y = y
+        self.random_states = random_states
+
+    def __call__(self, index):
+        order = self.random_states[index].permutation(self.y.shape[0])
+        permy = self.y[order][:, order]
+
+        # calculate permuted stats, store in null distribution
+        perm_stat = _mgc_stat(self.x, permy)[0]
+
+        return perm_stat
+
+
+def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None):
+    r"""Helper function that calculates the p-value. See below for uses.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        `x` and `y` have shapes ``(n, p)`` and ``(n, q)``.
+    stat : float
+        The sample test statistic.
+    reps : int, optional
+        The number of replications used to estimate the null when using the
+        permutation test. The default is 1000 replications.
+    workers : int or map-like callable, optional
+        If `workers` is an int the population is subdivided into `workers`
+        sections and evaluated in parallel (uses
+        `multiprocessing.Pool `). Supply `-1` to use all cores
+        available to the Process. Alternatively supply a map-like callable,
+        such as `multiprocessing.Pool.map` for evaluating the population in
+        parallel. This evaluation is carried out as `workers(func, iterable)`.
+        Requires that `func` be pickleable.
+    random_state : {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
+    -------
+    pvalue : float
+        The sample test p-value.
+    null_dist : list
+        The approximated null distribution.
+
+    """
+    # generate seeds for each rep (change to new parallel random number
+    # capabilities in numpy >= 1.17+)
+    random_state = check_random_state(random_state)
+    random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32,
+                     size=4, dtype=np.uint32)) for _ in range(reps)]
+
+    # parallelizes with specified workers over number of reps and set seeds
+    parallelp = _ParallelP(x=x, y=y, random_states=random_states)
+    with MapWrapper(workers) as mapwrapper:
+        null_dist = np.array(list(mapwrapper(parallelp, range(reps))))
+
+    # calculate p-value and significant permutation map through list
+    pvalue = (1 + (null_dist >= stat).sum()) / (1 + reps)
+
+    return pvalue, null_dist
+
+
+def _euclidean_dist(x):
+    return cdist(x, x)
+
+
+MGCResult = _make_tuple_bunch('MGCResult',
+                              ['statistic', 'pvalue', 'mgc_dict'], [])
+
+
+def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000,
+                         workers=1, is_twosamp=False, random_state=None):
+    r"""Computes the Multiscale Graph Correlation (MGC) test statistic.
+
+    Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
+    one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
+    the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
+    called the "scale". A priori, however, it is not know which scales will be
+    most informative. So, MGC computes all distance pairs, and then efficiently
+    computes the distance correlations for all scales. The local correlations
+    illustrate which scales are relatively informative about the relationship.
+    The key, therefore, to successfully discover and decipher relationships
+    between disparate data modalities is to adaptively determine which scales
+    are the most informative, and the geometric implication for the most
+    informative scales. Doing so not only provides an estimate of whether the
+    modalities are related, but also provides insight into how the
+    determination was made. This is especially important in high-dimensional
+    data, where simple visualizations do not reveal relationships to the
+    unaided human eye. Characterizations of this implementation in particular
+    have been derived from and benchmarked within in [2]_.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
+        the number of samples and `p` and `q` are the number of dimensions,
+        then the MGC independence test will be run.  Alternatively, ``x`` and
+        ``y`` can have shapes ``(n, n)`` if they are distance or similarity
+        matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
+        and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
+        two-sample MGC test will be run.
+    compute_distance : callable, optional
+        A function that computes the distance or similarity among the samples
+        within each data matrix. Set to ``None`` if ``x`` and ``y`` are
+        already distance matrices. The default uses the euclidean norm metric.
+        If you are calling a custom function, either create the distance
+        matrix before-hand or create a function of the form
+        ``compute_distance(x)`` where `x` is the data matrix for which
+        pairwise distances are calculated.
+    reps : int, optional
+        The number of replications used to estimate the null when using the
+        permutation test. The default is ``1000``.
+    workers : int or map-like callable, optional
+        If ``workers`` is an int the population is subdivided into ``workers``
+        sections and evaluated in parallel (uses ``multiprocessing.Pool
+        ``). Supply ``-1`` to use all cores available to the
+        Process. Alternatively supply a map-like callable, such as
+        ``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+        Requires that `func` be pickleable. The default is ``1``.
+    is_twosamp : bool, optional
+        If `True`, a two sample test will be run. If ``x`` and ``y`` have
+        shapes ``(n, p)`` and ``(m, p)``, this optional will be overridden and
+        set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
+        ``(n, p)`` and a two sample test is desired. The default is ``False``.
+        Note that this will not run if inputs are distance matrices.
+    random_state : {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
+    -------
+    res : MGCResult
+        An object containing attributes:
+
+        statistic : float
+            The sample MGC test statistic within ``[-1, 1]``.
+        pvalue : float
+            The p-value obtained via permutation.
+        mgc_dict : dict
+            Contains additional useful results:
+
+                - mgc_map : ndarray
+                    A 2D representation of the latent geometry of the
+                    relationship.
+                - opt_scale : (int, int)
+                    The estimated optimal scale as a ``(x, y)`` pair.
+                - null_dist : list
+                    The null distribution derived from the permuted matrices.
+
+    See Also
+    --------
+    pearsonr : Pearson correlation coefficient and p-value for testing
+               non-correlation.
+    kendalltau : Calculates Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+
+    Notes
+    -----
+    A description of the process of MGC and applications on neuroscience data
+    can be found in [1]_. It is performed using the following steps:
+
+    #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
+       modified to be mean zero columnwise. This results in two
+       :math:`n \times n` distance matrices :math:`A` and :math:`B` (the
+       centering and unbiased modification) [3]_.
+
+    #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,
+
+       * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
+         are calculated for each property. Here, :math:`G_k (i, j)` indicates
+         the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
+         and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
+         the :math:`i`-th row of :math:`B`
+
+       * Let :math:`\circ` denotes the entry-wise matrix product, then local
+         correlations are summed and normalized using the following statistic:
+
+    .. math::
+
+        c^{kl} = \frac{\sum_{ij} A G_k B H_l}
+                      {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}
+
+    #. The MGC test statistic is the smoothed optimal local correlation of
+       :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
+       (which essentially set all isolated large correlations) as 0 and
+       connected large correlations the same as before, see [3]_.) MGC is,
+
+    .. math::
+
+        MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
+                                                    \right)
+
+    The test statistic returns a value between :math:`(-1, 1)` since it is
+    normalized.
+
+    The p-value returned is calculated using a permutation test. This process
+    is completed by first randomly permuting :math:`y` to estimate the null
+    distribution and then calculating the probability of observing a test
+    statistic, under the null, at least as extreme as the observed test
+    statistic.
+
+    MGC requires at least 5 samples to run with reliable results. It can also
+    handle high-dimensional data sets.
+    In addition, by manipulating the input data matrices, the two-sample
+    testing problem can be reduced to the independence testing problem [4]_.
+    Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
+    :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
+    follows:
+
+    .. math::
+
+        X = [U | V] \in \mathcal{R}^{p \times (n + m)}
+        Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}
+
+    Then, the MGC statistic can be calculated as normal. This methodology can
+    be extended to similar tests such as distance correlation [4]_.
+
+    .. versionadded:: 1.4.0
+
+    References
+    ----------
+    .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
+           Maggioni, M., & Shen, C. (2019). Discovering and deciphering
+           relationships across disparate data modalities. ELife.
+    .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
+           Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
+           mgcpy: A Comprehensive High Dimensional Independence Testing Python
+           Package. :arXiv:`1907.02088`
+    .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
+           correlation to multiscale graph correlation. Journal of the American
+           Statistical Association.
+    .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
+           Distance and Kernel Methods for Hypothesis Testing.
+           :arXiv:`1806.05514`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import multiscale_graphcorr
+    >>> x = np.arange(100)
+    >>> y = x
+    >>> res = multiscale_graphcorr(x, y)
+    >>> res.statistic, res.pvalue
+    (1.0, 0.001)
+
+    To run an unpaired two-sample test,
+
+    >>> x = np.arange(100)
+    >>> y = np.arange(79)
+    >>> res = multiscale_graphcorr(x, y)
+    >>> res.statistic, res.pvalue  # doctest: +SKIP
+    (0.033258146255703246, 0.023)
+
+    or, if shape of the inputs are the same,
+
+    >>> x = np.arange(100)
+    >>> y = x
+    >>> res = multiscale_graphcorr(x, y, is_twosamp=True)
+    >>> res.statistic, res.pvalue  # doctest: +SKIP
+    (-0.008021809890200488, 1.0)
+
+    """
+    if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
+        raise ValueError("x and y must be ndarrays")
+
+    # convert arrays of type (n,) to (n, 1)
+    if x.ndim == 1:
+        x = x[:, np.newaxis]
+    elif x.ndim != 2:
+        raise ValueError(f"Expected a 2-D array `x`, found shape {x.shape}")
+    if y.ndim == 1:
+        y = y[:, np.newaxis]
+    elif y.ndim != 2:
+        raise ValueError(f"Expected a 2-D array `y`, found shape {y.shape}")
+
+    nx, px = x.shape
+    ny, py = y.shape
+
+    # check for NaNs
+    _contains_nan(x, nan_policy='raise')
+    _contains_nan(y, nan_policy='raise')
+
+    # check for positive or negative infinity and raise error
+    if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0:
+        raise ValueError("Inputs contain infinities")
+
+    if nx != ny:
+        if px == py:
+            # reshape x and y for two sample testing
+            is_twosamp = True
+        else:
+            raise ValueError("Shape mismatch, x and y must have shape [n, p] "
+                             "and [n, q] or have shape [n, p] and [m, p].")
+
+    if nx < 5 or ny < 5:
+        raise ValueError("MGC requires at least 5 samples to give reasonable "
+                         "results.")
+
+    # convert x and y to float
+    x = x.astype(np.float64)
+    y = y.astype(np.float64)
+
+    # check if compute_distance_matrix if a callable()
+    if not callable(compute_distance) and compute_distance is not None:
+        raise ValueError("Compute_distance must be a function.")
+
+    # check if number of reps exists, integer, or > 0 (if under 1000 raises
+    # warning)
+    if not isinstance(reps, int) or reps < 0:
+        raise ValueError("Number of reps must be an integer greater than 0.")
+    elif reps < 1000:
+        msg = ("The number of replications is low (under 1000), and p-value "
+               "calculations may be unreliable. Use the p-value result, with "
+               "caution!")
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+
+    if is_twosamp:
+        if compute_distance is None:
+            raise ValueError("Cannot run if inputs are distance matrices")
+        x, y = _two_sample_transform(x, y)
+
+    if compute_distance is not None:
+        # compute distance matrices for x and y
+        x = compute_distance(x)
+        y = compute_distance(y)
+
+    # calculate MGC stat
+    stat, stat_dict = _mgc_stat(x, y)
+    stat_mgc_map = stat_dict["stat_mgc_map"]
+    opt_scale = stat_dict["opt_scale"]
+
+    # calculate permutation MGC p-value
+    pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers,
+                                   random_state=random_state)
+
+    # save all stats (other than stat/p-value) in dictionary
+    mgc_dict = {"mgc_map": stat_mgc_map,
+                "opt_scale": opt_scale,
+                "null_dist": null_dist}
+
+    # create result object with alias for backward compatibility
+    res = MGCResult(stat, pvalue, mgc_dict)
+    res.stat = stat
+    return res
+
+
+def _mgc_stat(distx, disty):
+    r"""Helper function that calculates the MGC stat. See above for use.
+
+    Parameters
+    ----------
+    distx, disty : ndarray
+        `distx` and `disty` have shapes ``(n, p)`` and ``(n, q)`` or
+        ``(n, n)`` and ``(n, n)``
+        if distance matrices.
+
+    Returns
+    -------
+    stat : float
+        The sample MGC test statistic within ``[-1, 1]``.
+    stat_dict : dict
+        Contains additional useful additional returns containing the following
+        keys:
+
+            - stat_mgc_map : ndarray
+                MGC-map of the statistics.
+            - opt_scale : (float, float)
+                The estimated optimal scale as a ``(x, y)`` pair.
+
+    """
+    # calculate MGC map and optimal scale
+    stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc')
+
+    n, m = stat_mgc_map.shape
+    if m == 1 or n == 1:
+        # the global scale at is the statistic calculated at maximal nearest
+        # neighbors. There is not enough local scale to search over, so
+        # default to global scale
+        stat = stat_mgc_map[m - 1][n - 1]
+        opt_scale = m * n
+    else:
+        samp_size = len(distx) - 1
+
+        # threshold to find connected region of significant local correlations
+        sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size)
+
+        # maximum within the significant region
+        stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map)
+
+    stat_dict = {"stat_mgc_map": stat_mgc_map,
+                 "opt_scale": opt_scale}
+
+    return stat, stat_dict
+
+
+def _threshold_mgc_map(stat_mgc_map, samp_size):
+    r"""
+    Finds a connected region of significance in the MGC-map by thresholding.
+
+    Parameters
+    ----------
+    stat_mgc_map : ndarray
+        All local correlations within ``[-1,1]``.
+    samp_size : int
+        The sample size of original data.
+
+    Returns
+    -------
+    sig_connect : ndarray
+        A binary matrix with 1's indicating the significant region.
+
+    """
+    m, n = stat_mgc_map.shape
+
+    # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
+    # with varying levels of performance. Threshold is based on a beta
+    # approximation.
+    per_sig = 1 - (0.02 / samp_size)  # Percentile to consider as significant
+    threshold = samp_size * (samp_size - 3)/4 - 1/2  # Beta approximation
+    threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1
+
+    # the global scale at is the statistic calculated at maximal nearest
+    # neighbors. Threshold is the maximum on the global and local scales
+    threshold = max(threshold, stat_mgc_map[m - 1][n - 1])
+
+    # find the largest connected component of significant correlations
+    sig_connect = stat_mgc_map > threshold
+    if np.sum(sig_connect) > 0:
+        sig_connect, _ = _measurements.label(sig_connect)
+        _, label_counts = np.unique(sig_connect, return_counts=True)
+
+        # skip the first element in label_counts, as it is count(zeros)
+        max_label = np.argmax(label_counts[1:]) + 1
+        sig_connect = sig_connect == max_label
+    else:
+        sig_connect = np.array([[False]])
+
+    return sig_connect
+
+
+def _smooth_mgc_map(sig_connect, stat_mgc_map):
+    """Finds the smoothed maximal within the significant region R.
+
+    If area of R is too small it returns the last local correlation. Otherwise,
+    returns the maximum within significant_connected_region.
+
+    Parameters
+    ----------
+    sig_connect : ndarray
+        A binary matrix with 1's indicating the significant region.
+    stat_mgc_map : ndarray
+        All local correlations within ``[-1, 1]``.
+
+    Returns
+    -------
+    stat : float
+        The sample MGC statistic within ``[-1, 1]``.
+    opt_scale: (float, float)
+        The estimated optimal scale as an ``(x, y)`` pair.
+
+    """
+    m, n = stat_mgc_map.shape
+
+    # the global scale at is the statistic calculated at maximal nearest
+    # neighbors. By default, statistic and optimal scale are global.
+    stat = stat_mgc_map[m - 1][n - 1]
+    opt_scale = [m, n]
+
+    if np.linalg.norm(sig_connect) != 0:
+        # proceed only when the connected region's area is sufficiently large
+        # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
+        # with varying levels of performance
+        if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n):
+            max_corr = max(stat_mgc_map[sig_connect])
+
+            # find all scales within significant_connected_region that maximize
+            # the local correlation
+            max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect)
+
+            if max_corr >= stat:
+                stat = max_corr
+
+                k, l = max_corr_index
+                one_d_indices = k * n + l  # 2D to 1D indexing
+                k = np.max(one_d_indices) // n
+                l = np.max(one_d_indices) % n
+                opt_scale = [k+1, l+1]  # adding 1s to match R indexing
+
+    return stat, opt_scale
+
+
+def _two_sample_transform(u, v):
+    """Helper function that concatenates x and y for two sample MGC stat.
+
+    See above for use.
+
+    Parameters
+    ----------
+    u, v : ndarray
+        `u` and `v` have shapes ``(n, p)`` and ``(m, p)``.
+
+    Returns
+    -------
+    x : ndarray
+        Concatenate `u` and `v` along the ``axis = 0``. `x` thus has shape
+        ``(2n, p)``.
+    y : ndarray
+        Label matrix for `x` where 0 refers to samples that comes from `u` and
+        1 refers to samples that come from `v`. `y` thus has shape ``(2n, 1)``.
+
+    """
+    nx = u.shape[0]
+    ny = v.shape[0]
+    x = np.concatenate([u, v], axis=0)
+    y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1)
+    return x, y
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_morestats.py b/python_embeded/Lib/site-packages/scipy/stats/_morestats.py
new file mode 100644
index 0000000000000000000000000000000000000000..0198e0883891fc4327b975faa63a1c5260812ef5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_morestats.py
@@ -0,0 +1,4581 @@
+import math
+import warnings
+import threading
+from collections import namedtuple
+
+import numpy as np
+from numpy import (isscalar, r_, log, around, unique, asarray, zeros,
+                   arange, sort, amin, amax, sqrt, array,
+                   pi, exp, ravel, count_nonzero)
+
+from scipy import optimize, special, interpolate, stats
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy._lib._util import _rename_parameter, _contains_nan, _get_nan
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_moveaxis_to_end,
+    xp_vector_norm,
+)
+
+from ._ansari_swilk_statistics import gscale, swilk
+from . import _stats_py, _wilcoxon
+from ._fit import FitResult
+from ._stats_py import (find_repeats, _get_pvalue, SignificanceResult,  # noqa:F401
+                        _SimpleNormal, _SimpleChi2)
+from .contingency import chi2_contingency
+from . import distributions
+from ._distn_infrastructure import rv_generic
+from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays
+
+
+__all__ = ['mvsdist',
+           'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
+           'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
+           'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
+           'fligner', 'mood', 'wilcoxon', 'median_test',
+           'circmean', 'circvar', 'circstd', 'anderson_ksamp',
+           'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
+           'yeojohnson_normplot', 'directional_stats',
+           'false_discovery_control'
+           ]
+
+
+Mean = namedtuple('Mean', ('statistic', 'minmax'))
+Variance = namedtuple('Variance', ('statistic', 'minmax'))
+Std_dev = namedtuple('Std_dev', ('statistic', 'minmax'))
+
+
+def bayes_mvs(data, alpha=0.90):
+    r"""
+    Bayesian confidence intervals for the mean, var, and std.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
+        Requires 2 or more data points.
+    alpha : float, optional
+        Probability that the returned confidence interval contains
+        the true parameter.
+
+    Returns
+    -------
+    mean_cntr, var_cntr, std_cntr : tuple
+        The three results are for the mean, variance and standard deviation,
+        respectively.  Each result is a tuple of the form::
+
+            (center, (lower, upper))
+
+        with ``center`` the mean of the conditional pdf of the value given the
+        data, and ``(lower, upper)`` a confidence interval, centered on the
+        median, containing the estimate to a probability ``alpha``.
+
+    See Also
+    --------
+    mvsdist
+
+    Notes
+    -----
+    Each tuple of mean, variance, and standard deviation estimates represent
+    the (center, (lower, upper)) with center the mean of the conditional pdf
+    of the value given the data and (lower, upper) is a confidence interval
+    centered on the median, containing the estimate to a probability
+    ``alpha``.
+
+    Converts data to 1-D and assumes all data has the same mean and variance.
+    Uses Jeffrey's prior for variance and std.
+
+    Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``
+
+    References
+    ----------
+    T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
+    standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
+    2006.
+
+    Examples
+    --------
+    First a basic example to demonstrate the outputs:
+
+    >>> from scipy import stats
+    >>> data = [6, 9, 12, 7, 8, 8, 13]
+    >>> mean, var, std = stats.bayes_mvs(data)
+    >>> mean
+    Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))
+    >>> var
+    Variance(statistic=10.0, minmax=(3.176724206, 24.45910382))
+    >>> std
+    Std_dev(statistic=2.9724954732045084,
+            minmax=(1.7823367265645143, 4.945614605014631))
+
+    Now we generate some normally distributed random data, and get estimates of
+    mean and standard deviation with 95% confidence intervals for those
+    estimates:
+
+    >>> n_samples = 100000
+    >>> data = stats.norm.rvs(size=n_samples)
+    >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.hist(data, bins=100, density=True, label='Histogram of data')
+    >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
+    >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
+    ...            alpha=0.2, label=r'Estimated mean (95% limits)')
+    >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
+    >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
+    ...            label=r'Estimated scale (95% limits)')
+
+    >>> ax.legend(fontsize=10)
+    >>> ax.set_xlim([-4, 4])
+    >>> ax.set_ylim([0, 0.5])
+    >>> plt.show()
+
+    """
+    m, v, s = mvsdist(data)
+    if alpha >= 1 or alpha <= 0:
+        raise ValueError(f"0 < alpha < 1 is required, but {alpha=} was given.")
+
+    m_res = Mean(m.mean(), m.interval(alpha))
+    v_res = Variance(v.mean(), v.interval(alpha))
+    s_res = Std_dev(s.mean(), s.interval(alpha))
+
+    return m_res, v_res, s_res
+
+
+def mvsdist(data):
+    """
+    'Frozen' distributions for mean, variance, and standard deviation of data.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array. Converted to 1-D using ravel.
+        Requires 2 or more data-points.
+
+    Returns
+    -------
+    mdist : "frozen" distribution object
+        Distribution object representing the mean of the data.
+    vdist : "frozen" distribution object
+        Distribution object representing the variance of the data.
+    sdist : "frozen" distribution object
+        Distribution object representing the standard deviation of the data.
+
+    See Also
+    --------
+    bayes_mvs
+
+    Notes
+    -----
+    The return values from ``bayes_mvs(data)`` is equivalent to
+    ``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.
+
+    In other words, calling ``.mean()`` and ``.interval(0.90)``
+    on the three distribution objects returned from this function will give
+    the same results that are returned from `bayes_mvs`.
+
+    References
+    ----------
+    T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
+    standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
+    2006.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> data = [6, 9, 12, 7, 8, 8, 13]
+    >>> mean, var, std = stats.mvsdist(data)
+
+    We now have frozen distribution objects "mean", "var" and "std" that we can
+    examine:
+
+    >>> mean.mean()
+    9.0
+    >>> mean.interval(0.95)
+    (6.6120585482655692, 11.387941451734431)
+    >>> mean.std()
+    1.1952286093343936
+
+    """
+    x = ravel(data)
+    n = len(x)
+    if n < 2:
+        raise ValueError("Need at least 2 data-points.")
+    xbar = x.mean()
+    C = x.var()
+    if n > 1000:  # gaussian approximations for large n
+        mdist = distributions.norm(loc=xbar, scale=math.sqrt(C / n))
+        sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C / (2. * n)))
+        vdist = distributions.norm(loc=C, scale=math.sqrt(2.0 / n) * C)
+    else:
+        nm1 = n - 1
+        fac = n * C / 2.
+        val = nm1 / 2.
+        mdist = distributions.t(nm1, loc=xbar, scale=math.sqrt(C / nm1))
+        sdist = distributions.gengamma(val, -2, scale=math.sqrt(fac))
+        vdist = distributions.invgamma(val, scale=fac)
+    return mdist, vdist, sdist
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None
+)
+def kstat(data, n=2, *, axis=None):
+    r"""
+    Return the `n` th k-statistic ( ``1<=n<=4`` so far).
+
+    The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the
+    `n` th cumulant :math:`\kappa_n` [1]_ [2]_.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    n : int, {1, 2, 3, 4}, optional
+        Default is equal to 2.
+    axis : int or None, default: None
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    kstat : float
+        The `n` th k-statistic.
+
+    See Also
+    --------
+    kstatvar : Returns an unbiased estimator of the variance of the k-statistic
+    moment : Returns the n-th central moment about the mean for a sample.
+
+    Notes
+    -----
+    For a sample size :math:`n`, the first few k-statistics are given by
+
+    .. math::
+
+        k_1 &= \frac{S_1}{n}, \\
+        k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\
+        k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\
+        k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3
+        + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)},
+
+    where
+
+    .. math::
+
+        S_r \equiv \sum_{i=1}^n X_i^r,
+
+    and :math:`X_i` is the :math:`i` th data point.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/k-Statistic.html
+
+    .. [2] http://mathworld.wolfram.com/Cumulant.html
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+
+    As sample size increases, `n`-th moment and `n`-th k-statistic converge to the
+    same number (although they aren't identical). In the case of the normal
+    distribution, they converge to zero.
+
+    >>> for i in range(2,8):
+    ...     x = rng.normal(size=10**i)
+    ...     m, k = stats.moment(x, 3), stats.kstat(x, 3)
+    ...     print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}")
+    i=2: m=-0.631, k=-0.651, (m-k)=0.0194  # random
+    i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05
+    i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05
+    i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09
+    i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09
+    i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13
+    """
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    if n > 4 or n < 1:
+        raise ValueError("k-statistics only supported for 1<=n<=4")
+    n = int(n)
+    if axis is None:
+        data = xp.reshape(data, (-1,))
+        axis = 0
+
+    N = data.shape[axis]
+
+    S = [None] + [xp.sum(data**k, axis=axis) for k in range(1, n + 1)]
+    if n == 1:
+        return S[1] * 1.0/N
+    elif n == 2:
+        return (N*S[2] - S[1]**2.0) / (N*(N - 1.0))
+    elif n == 3:
+        return (2*S[1]**3 - 3*N*S[1]*S[2] + N*N*S[3]) / (N*(N - 1.0)*(N - 2.0))
+    elif n == 4:
+        return ((-6*S[1]**4 + 12*N*S[1]**2 * S[2] - 3*N*(N-1.0)*S[2]**2 -
+                 4*N*(N+1)*S[1]*S[3] + N*N*(N+1)*S[4]) /
+                (N*(N-1.0)*(N-2.0)*(N-3.0)))
+    else:
+        raise ValueError("Should not be here.")
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None
+)
+def kstatvar(data, n=2, *, axis=None):
+    r"""Return an unbiased estimator of the variance of the k-statistic.
+
+    See `kstat` and [1]_ for more details about the k-statistic.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    n : int, {1, 2}, optional
+        Default is equal to 2.
+    axis : int or None, default: None
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    kstatvar : float
+        The `n` th k-statistic variance.
+
+    See Also
+    --------
+    kstat : Returns the n-th k-statistic.
+    moment : Returns the n-th central moment about the mean for a sample.
+
+    Notes
+    -----
+    Unbiased estimators of the variances of the first two k-statistics are given by
+
+    .. math::
+
+        \mathrm{var}(k_1) &= \frac{k_2}{n}, \\
+        \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n - 1)}.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/k-Statistic.html
+
+    """  # noqa: E501
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    if axis is None:
+        data = xp.reshape(data, (-1,))
+        axis = 0
+    N = data.shape[axis]
+
+    if n == 1:
+        return kstat(data, n=2, axis=axis, _no_deco=True) * 1.0/N
+    elif n == 2:
+        k2 = kstat(data, n=2, axis=axis, _no_deco=True)
+        k4 = kstat(data, n=4, axis=axis, _no_deco=True)
+        return (2*N*k2**2 + (N-1)*k4) / (N*(N+1))
+    else:
+        raise ValueError("Only n=1 or n=2 supported.")
+
+
+def _calc_uniform_order_statistic_medians(n):
+    """Approximations of uniform order statistic medians.
+
+    Parameters
+    ----------
+    n : int
+        Sample size.
+
+    Returns
+    -------
+    v : 1d float array
+        Approximations of the order statistic medians.
+
+    References
+    ----------
+    .. [1] James J. Filliben, "The Probability Plot Correlation Coefficient
+           Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
+
+    Examples
+    --------
+    Order statistics of the uniform distribution on the unit interval
+    are marginally distributed according to beta distributions.
+    The expectations of these order statistic are evenly spaced across
+    the interval, but the distributions are skewed in a way that
+    pushes the medians slightly towards the endpoints of the unit interval:
+
+    >>> import numpy as np
+    >>> n = 4
+    >>> k = np.arange(1, n+1)
+    >>> from scipy.stats import beta
+    >>> a = k
+    >>> b = n-k+1
+    >>> beta.mean(a, b)
+    array([0.2, 0.4, 0.6, 0.8])
+    >>> beta.median(a, b)
+    array([0.15910358, 0.38572757, 0.61427243, 0.84089642])
+
+    The Filliben approximation uses the exact medians of the smallest
+    and greatest order statistics, and the remaining medians are approximated
+    by points spread evenly across a sub-interval of the unit interval:
+
+    >>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians
+    >>> _calc_uniform_order_statistic_medians(n)
+    array([0.15910358, 0.38545246, 0.61454754, 0.84089642])
+
+    This plot shows the skewed distributions of the order statistics
+    of a sample of size four from a uniform distribution on the unit interval:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0.0, 1.0, num=50, endpoint=True)
+    >>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)]
+    >>> plt.figure()
+    >>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3])
+
+    """
+    v = np.empty(n, dtype=np.float64)
+    v[-1] = 0.5**(1.0 / n)
+    v[0] = 1 - v[-1]
+    i = np.arange(2, n)
+    v[1:-1] = (i - 0.3175) / (n + 0.365)
+    return v
+
+
+def _parse_dist_kw(dist, enforce_subclass=True):
+    """Parse `dist` keyword.
+
+    Parameters
+    ----------
+    dist : str or stats.distributions instance.
+        Several functions take `dist` as a keyword, hence this utility
+        function.
+    enforce_subclass : bool, optional
+        If True (default), `dist` needs to be a
+        `_distn_infrastructure.rv_generic` instance.
+        It can sometimes be useful to set this keyword to False, if a function
+        wants to accept objects that just look somewhat like such an instance
+        (for example, they have a ``ppf`` method).
+
+    """
+    if isinstance(dist, rv_generic):
+        pass
+    elif isinstance(dist, str):
+        try:
+            dist = getattr(distributions, dist)
+        except AttributeError as e:
+            raise ValueError(f"{dist} is not a valid distribution name") from e
+    elif enforce_subclass:
+        msg = ("`dist` should be a stats.distributions instance or a string "
+               "with the name of such a distribution.")
+        raise ValueError(msg)
+
+    return dist
+
+
+def _add_axis_labels_title(plot, xlabel, ylabel, title):
+    """Helper function to add axes labels and a title to stats plots."""
+    try:
+        if hasattr(plot, 'set_title'):
+            # Matplotlib Axes instance or something that looks like it
+            plot.set_title(title)
+            plot.set_xlabel(xlabel)
+            plot.set_ylabel(ylabel)
+        else:
+            # matplotlib.pyplot module
+            plot.title(title)
+            plot.xlabel(xlabel)
+            plot.ylabel(ylabel)
+    except Exception:
+        # Not an MPL object or something that looks (enough) like it.
+        # Don't crash on adding labels or title
+        pass
+
+
+def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False):
+    """
+    Calculate quantiles for a probability plot, and optionally show the plot.
+
+    Generates a probability plot of sample data against the quantiles of a
+    specified theoretical distribution (the normal distribution by default).
+    `probplot` optionally calculates a best-fit line for the data and plots the
+    results using Matplotlib or a given plot function.
+
+    Parameters
+    ----------
+    x : array_like
+        Sample/response data from which `probplot` creates the plot.
+    sparams : tuple, optional
+        Distribution-specific shape parameters (shape parameters plus location
+        and scale).
+    dist : str or stats.distributions instance, optional
+        Distribution or distribution function name. The default is 'norm' for a
+        normal probability plot.  Objects that look enough like a
+        stats.distributions instance (i.e. they have a ``ppf`` method) are also
+        accepted.
+    fit : bool, optional
+        Fit a least-squares regression (best-fit) line to the sample data if
+        True (default).
+    plot : object, optional
+        If given, plots the quantiles.
+        If given and `fit` is True, also plots the least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    rvalue : bool, optional
+        If `plot` is provided and `fit` is True, setting `rvalue` to True
+        includes the coefficient of determination on the plot.
+        Default is False.
+
+    Returns
+    -------
+    (osm, osr) : tuple of ndarrays
+        Tuple of theoretical quantiles (osm, or order statistic medians) and
+        ordered responses (osr).  `osr` is simply sorted input `x`.
+        For details on how `osm` is calculated see the Notes section.
+    (slope, intercept, r) : tuple of floats, optional
+        Tuple  containing the result of the least-squares fit, if that is
+        performed by `probplot`. `r` is the square root of the coefficient of
+        determination.  If ``fit=False`` and ``plot=None``, this tuple is not
+        returned.
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by `probplot`;
+    ``plt.show()`` or ``plt.savefig('figname.png')`` should be used after
+    calling `probplot`.
+
+    `probplot` generates a probability plot, which should not be confused with
+    a Q-Q or a P-P plot.  Statsmodels has more extensive functionality of this
+    type, see ``statsmodels.api.ProbPlot``.
+
+    The formula used for the theoretical quantiles (horizontal axis of the
+    probability plot) is Filliben's estimate::
+
+        quantiles = dist.ppf(val), for
+
+                0.5**(1/n),                  for i = n
+          val = (i - 0.3175) / (n + 0.365),  for i = 2, ..., n-1
+                1 - 0.5**(1/n),              for i = 1
+
+    where ``i`` indicates the i-th ordered value and ``n`` is the total number
+    of values.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> nsample = 100
+    >>> rng = np.random.default_rng()
+
+    A t distribution with small degrees of freedom:
+
+    >>> ax1 = plt.subplot(221)
+    >>> x = stats.t.rvs(3, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    A t distribution with larger degrees of freedom:
+
+    >>> ax2 = plt.subplot(222)
+    >>> x = stats.t.rvs(25, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    A mixture of two normal distributions with broadcasting:
+
+    >>> ax3 = plt.subplot(223)
+    >>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5],
+    ...                    size=(nsample//2,2), random_state=rng).ravel()
+    >>> res = stats.probplot(x, plot=plt)
+
+    A standard normal distribution:
+
+    >>> ax4 = plt.subplot(224)
+    >>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    Produce a new figure with a loggamma distribution, using the ``dist`` and
+    ``sparams`` keywords:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng)
+    >>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax)
+    >>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5")
+
+    Show the results with Matplotlib:
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+    if x.size == 0:
+        if fit:
+            return (x, x), (np.nan, np.nan, 0.0)
+        else:
+            return x, x
+
+    osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+    dist = _parse_dist_kw(dist, enforce_subclass=False)
+    if sparams is None:
+        sparams = ()
+    if isscalar(sparams):
+        sparams = (sparams,)
+    if not isinstance(sparams, tuple):
+        sparams = tuple(sparams)
+
+    osm = dist.ppf(osm_uniform, *sparams)
+    osr = sort(x)
+    if fit:
+        # perform a linear least squares fit.
+        slope, intercept, r, prob, _ = _stats_py.linregress(osm, osr)
+
+    if plot is not None:
+        plot.plot(osm, osr, 'bo')
+        if fit:
+            plot.plot(osm, slope*osm + intercept, 'r-')
+        _add_axis_labels_title(plot, xlabel='Theoretical quantiles',
+                               ylabel='Ordered Values',
+                               title='Probability Plot')
+
+        # Add R^2 value to the plot as text
+        if fit and rvalue:
+            xmin = amin(osm)
+            xmax = amax(osm)
+            ymin = amin(x)
+            ymax = amax(x)
+            posx = xmin + 0.70 * (xmax - xmin)
+            posy = ymin + 0.01 * (ymax - ymin)
+            plot.text(posx, posy, f"$R^2={r ** 2:1.4f}$")
+
+    if fit:
+        return (osm, osr), (slope, intercept, r)
+    else:
+        return osm, osr
+
+
+def ppcc_max(x, brack=(0.0, 1.0), dist='tukeylambda'):
+    """Calculate the shape parameter that maximizes the PPCC.
+
+    The probability plot correlation coefficient (PPCC) plot can be used
+    to determine the optimal shape parameter for a one-parameter family
+    of distributions. ``ppcc_max`` returns the shape parameter that would
+    maximize the probability plot correlation coefficient for the given
+    data to a one-parameter family of distributions.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    brack : tuple, optional
+        Triple (a,b,c) where (a>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> c = 2.5
+    >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
+
+    Generate the PPCC plot for this data with the Weibull distribution.
+
+    >>> fig, ax = plt.subplots(figsize=(8, 6))
+    >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax)
+
+    We calculate the value where the shape should reach its maximum and a
+    red line is drawn there. The line should coincide with the highest
+    point in the PPCC graph.
+
+    >>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min')
+    >>> ax.axvline(cmax, color='r')
+    >>> plt.show()
+
+    """
+    dist = _parse_dist_kw(dist)
+    osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+    osr = sort(x)
+
+    # this function computes the x-axis values of the probability plot
+    #  and computes a linear regression (including the correlation)
+    #  and returns 1-r so that a minimization function maximizes the
+    #  correlation
+    def tempfunc(shape, mi, yvals, func):
+        xvals = func(mi, shape)
+        r, prob = _stats_py.pearsonr(xvals, yvals)
+        return 1 - r
+
+    return optimize.brent(tempfunc, brack=brack,
+                          args=(osm_uniform, osr, dist.ppf))
+
+
+def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80):
+    """Calculate and optionally plot probability plot correlation coefficient.
+
+    The probability plot correlation coefficient (PPCC) plot can be used to
+    determine the optimal shape parameter for a one-parameter family of
+    distributions.  It cannot be used for distributions without shape
+    parameters
+    (like the normal distribution) or with multiple shape parameters.
+
+    By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
+    Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
+    distributions via an approximately normal one, and is therefore
+    particularly useful in practice.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    a, b : scalar
+        Lower and upper bounds of the shape parameter to use.
+    dist : str or stats.distributions instance, optional
+        Distribution or distribution function name.  Objects that look enough
+        like a stats.distributions instance (i.e. they have a ``ppf`` method)
+        are also accepted.  The default is ``'tukeylambda'``.
+    plot : object, optional
+        If given, plots PPCC against the shape parameter.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `a` to `b`).
+
+    Returns
+    -------
+    svals : ndarray
+        The shape values for which `ppcc` was calculated.
+    ppcc : ndarray
+        The calculated probability plot correlation coefficient values.
+
+    See Also
+    --------
+    ppcc_max, probplot, boxcox_normplot, tukeylambda
+
+    References
+    ----------
+    J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
+    Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
+
+    Examples
+    --------
+    First we generate some random data from a Weibull distribution
+    with shape parameter 2.5, and plot the histogram of the data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> c = 2.5
+    >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
+
+    Take a look at the histogram of the data.
+
+    >>> fig1, ax = plt.subplots(figsize=(9, 4))
+    >>> ax.hist(x, bins=50)
+    >>> ax.set_title('Histogram of x')
+    >>> plt.show()
+
+    Now we explore this data with a PPCC plot as well as the related
+    probability plot and Box-Cox normplot.  A red line is drawn where we
+    expect the PPCC value to be maximal (at the shape parameter ``c``
+    used above):
+
+    >>> fig2 = plt.figure(figsize=(12, 4))
+    >>> ax1 = fig2.add_subplot(1, 3, 1)
+    >>> ax2 = fig2.add_subplot(1, 3, 2)
+    >>> ax3 = fig2.add_subplot(1, 3, 3)
+    >>> res = stats.probplot(x, plot=ax1)
+    >>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2)
+    >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3)
+    >>> ax3.axvline(c, color='r')
+    >>> plt.show()
+
+    """
+    if b <= a:
+        raise ValueError("`b` has to be larger than `a`.")
+
+    svals = np.linspace(a, b, num=N)
+    ppcc = np.empty_like(svals)
+    for k, sval in enumerate(svals):
+        _, r2 = probplot(x, sval, dist=dist, fit=True)
+        ppcc[k] = r2[-1]
+
+    if plot is not None:
+        plot.plot(svals, ppcc, 'x')
+        _add_axis_labels_title(plot, xlabel='Shape Values',
+                               ylabel='Prob Plot Corr. Coef.',
+                               title=f'({dist}) PPCC Plot')
+
+    return svals, ppcc
+
+
+def _log_mean(logx):
+    # compute log of mean of x from log(x)
+    res = special.logsumexp(logx, axis=0) - math.log(logx.shape[0])
+    return res
+
+
+def _log_var(logx, xp):
+    # compute log of variance of x from log(x)
+    logmean = _log_mean(logx)
+    # get complex dtype with component dtypes same as `logx` dtype;
+    # see data-apis/array-api#841
+    dtype = xp.result_type(logx.dtype, xp.complex64)
+    pij = xp.full(logx.shape, pi * 1j, dtype=dtype)
+    logxmu = special.logsumexp(xp.stack((logx, logmean + pij)), axis=0)
+    res = (xp.real(xp.asarray(special.logsumexp(2 * logxmu, axis=0)))
+           - math.log(logx.shape[0]))
+    return res
+
+
+def boxcox_llf(lmb, data):
+    r"""The boxcox log-likelihood function.
+
+    Parameters
+    ----------
+    lmb : scalar
+        Parameter for Box-Cox transformation.  See `boxcox` for details.
+    data : array_like
+        Data to calculate Box-Cox log-likelihood for.  If `data` is
+        multi-dimensional, the log-likelihood is calculated along the first
+        axis.
+
+    Returns
+    -------
+    llf : float or ndarray
+        Box-Cox log-likelihood of `data` given `lmb`.  A float for 1-D `data`,
+        an array otherwise.
+
+    See Also
+    --------
+    boxcox, probplot, boxcox_normplot, boxcox_normmax
+
+    Notes
+    -----
+    The Box-Cox log-likelihood function is defined here as
+
+    .. math::
+
+        llf = (\lambda - 1) \sum_i(\log(x_i)) -
+              N/2 \log(\sum_i (y_i - \bar{y})^2 / N),
+
+    where ``y`` is the Box-Cox transformed input data ``x``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+
+    Generate some random variates and calculate Box-Cox log-likelihood values
+    for them for a range of ``lmbda`` values:
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng)
+    >>> lmbdas = np.linspace(-2, 10)
+    >>> llf = np.zeros(lmbdas.shape, dtype=float)
+    >>> for ii, lmbda in enumerate(lmbdas):
+    ...     llf[ii] = stats.boxcox_llf(lmbda, x)
+
+    Also find the optimal lmbda value with `boxcox`:
+
+    >>> x_most_normal, lmbda_optimal = stats.boxcox(x)
+
+    Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
+    horizontal line to check that that's really the optimum:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(lmbdas, llf, 'b.-')
+    >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')
+    >>> ax.set_xlabel('lmbda parameter')
+    >>> ax.set_ylabel('Box-Cox log-likelihood')
+
+    Now add some probability plots to show that where the log-likelihood is
+    maximized the data transformed with `boxcox` looks closest to normal:
+
+    >>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
+    >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
+    ...     xt = stats.boxcox(x, lmbda=lmbda)
+    ...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
+    ...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
+    ...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
+    ...     ax_inset.set_xticklabels([])
+    ...     ax_inset.set_yticklabels([])
+    ...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
+
+    >>> plt.show()
+
+    """
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    N = data.shape[0]
+    if N == 0:
+        return xp.nan
+
+    dt = data.dtype
+    if xp.isdtype(dt, 'integral'):
+        data = xp.asarray(data, dtype=xp.float64)
+        dt = xp.float64
+
+    logdata = xp.log(data)
+
+    # Compute the variance of the transformed data.
+    if lmb == 0:
+        logvar = xp.log(xp.var(logdata, axis=0))
+    else:
+        # Transform without the constant offset 1/lmb.  The offset does
+        # not affect the variance, and the subtraction of the offset can
+        # lead to loss of precision.
+        # Division by lmb can be factored out to enhance numerical stability.
+        logx = lmb * logdata
+        logvar = _log_var(logx, xp) - 2 * math.log(abs(lmb))
+
+    res = (lmb - 1) * xp.sum(logdata, axis=0) - N/2 * logvar
+    res = xp.astype(res, dt)
+    res = res[()] if res.ndim == 0 else res
+    return res
+
+
+def _boxcox_conf_interval(x, lmax, alpha):
+    # Need to find the lambda for which
+    #  f(x,lmbda) >= f(x,lmax) - 0.5*chi^2_alpha;1
+    fac = 0.5 * distributions.chi2.ppf(1 - alpha, 1)
+    target = boxcox_llf(lmax, x) - fac
+
+    def rootfunc(lmbda, data, target):
+        return boxcox_llf(lmbda, data) - target
+
+    # Find positive endpoint of interval in which answer is to be found
+    newlm = lmax + 0.5
+    N = 0
+    while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
+        newlm += 0.1
+        N += 1
+
+    if N == 500:
+        raise RuntimeError("Could not find endpoint.")
+
+    lmplus = optimize.brentq(rootfunc, lmax, newlm, args=(x, target))
+
+    # Now find negative interval in the same way
+    newlm = lmax - 0.5
+    N = 0
+    while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
+        newlm -= 0.1
+        N += 1
+
+    if N == 500:
+        raise RuntimeError("Could not find endpoint.")
+
+    lmminus = optimize.brentq(rootfunc, newlm, lmax, args=(x, target))
+    return lmminus, lmplus
+
+
+def boxcox(x, lmbda=None, alpha=None, optimizer=None):
+    r"""Return a dataset transformed by a Box-Cox power transformation.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array to be transformed.
+
+        If `lmbda` is not None, this is an alias of
+        `scipy.special.boxcox`.
+        Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``.
+
+        If `lmbda` is None, array must be positive, 1-dimensional, and
+        non-constant.
+
+    lmbda : scalar, optional
+        If `lmbda` is None (default), find the value of `lmbda` that maximizes
+        the log-likelihood function and return it as the second output
+        argument.
+
+        If `lmbda` is not None, do the transformation for that value.
+
+    alpha : float, optional
+        If `lmbda` is None and `alpha` is not None (default), return the
+        ``100 * (1-alpha)%`` confidence  interval for `lmbda` as the third
+        output argument. Must be between 0.0 and 1.0.
+
+        If `lmbda` is not None, `alpha` is ignored.
+    optimizer : callable, optional
+        If `lmbda` is None, `optimizer` is the scalar optimizer used to find
+        the value of `lmbda` that minimizes the negative log-likelihood
+        function. `optimizer` is a callable that accepts one argument:
+
+        fun : callable
+            The objective function, which evaluates the negative
+            log-likelihood function at a provided value of `lmbda`
+
+        and returns an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal value of
+        `lmbda` in an attribute `x`.
+
+        See the example in `boxcox_normmax` or the documentation of
+        `scipy.optimize.minimize_scalar` for more information.
+
+        If `lmbda` is not None, `optimizer` is ignored.
+
+    Returns
+    -------
+    boxcox : ndarray
+        Box-Cox power transformed array.
+    maxlog : float, optional
+        If the `lmbda` parameter is None, the second returned argument is
+        the `lmbda` that maximizes the log-likelihood function.
+    (min_ci, max_ci) : tuple of float, optional
+        If `lmbda` parameter is None and `alpha` is not None, this returned
+        tuple of floats represents the minimum and maximum confidence limits
+        given `alpha`.
+
+    See Also
+    --------
+    probplot, boxcox_normplot, boxcox_normmax, boxcox_llf
+
+    Notes
+    -----
+    The Box-Cox transform is given by::
+
+        y = (x**lmbda - 1) / lmbda,  for lmbda != 0
+            log(x),                  for lmbda = 0
+
+    `boxcox` requires the input data to be positive.  Sometimes a Box-Cox
+    transformation provides a shift parameter to achieve this; `boxcox` does
+    not.  Such a shift parameter is equivalent to adding a positive constant to
+    `x` before calling `boxcox`.
+
+    The confidence limits returned when `alpha` is provided give the interval
+    where:
+
+    .. math::
+
+        llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1),
+
+    with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared
+    function.
+
+    References
+    ----------
+    G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the
+    Royal Statistical Society B, 26, 211-252 (1964).
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We generate some random variates from a non-normal distribution and make a
+    probability plot for it, to show it is non-normal in the tails:
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
+    >>> ax1.set_xlabel('')
+    >>> ax1.set_title('Probplot against normal distribution')
+
+    We now use `boxcox` to transform the data so it's closest to normal:
+
+    >>> ax2 = fig.add_subplot(212)
+    >>> xt, _ = stats.boxcox(x)
+    >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
+    >>> ax2.set_title('Probplot after Box-Cox transformation')
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+
+    if lmbda is not None:  # single transformation
+        return special.boxcox(x, lmbda)
+
+    if x.ndim != 1:
+        raise ValueError("Data must be 1-dimensional.")
+
+    if x.size == 0:
+        return x
+
+    if np.all(x == x[0]):
+        raise ValueError("Data must not be constant.")
+
+    if np.any(x <= 0):
+        raise ValueError("Data must be positive.")
+
+    # If lmbda=None, find the lmbda that maximizes the log-likelihood function.
+    lmax = boxcox_normmax(x, method='mle', optimizer=optimizer)
+    y = boxcox(x, lmax)
+
+    if alpha is None:
+        return y, lmax
+    else:
+        # Find confidence interval
+        interval = _boxcox_conf_interval(x, lmax, alpha)
+        return y, lmax, interval
+
+
+def _boxcox_inv_lmbda(x, y):
+    # compute lmbda given x and y for Box-Cox transformation
+    num = special.lambertw(-(x ** (-1 / y)) * np.log(x) / y, k=-1)
+    return np.real(-num / np.log(x) - 1 / y)
+
+
+class _BigFloat:
+    def __repr__(self):
+        return "BIG_FLOAT"
+
+
+_BigFloat_singleton = _BigFloat()
+
+
+def boxcox_normmax(
+    x, brack=None, method='pearsonr', optimizer=None, *, ymax=_BigFloat_singleton
+):
+    """Compute optimal Box-Cox transform parameter for input data.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array. All entries must be positive, finite, real numbers.
+    brack : 2-tuple, optional, default (-2.0, 2.0)
+         The starting interval for a downhill bracket search for the default
+         `optimize.brent` solver. Note that this is in most cases not
+         critical; the final result is allowed to be outside this bracket.
+         If `optimizer` is passed, `brack` must be None.
+    method : str, optional
+        The method to determine the optimal transform parameter (`boxcox`
+        ``lmbda`` parameter). Options are:
+
+        'pearsonr'  (default)
+            Maximizes the Pearson correlation coefficient between
+            ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be
+            normally-distributed.
+
+        'mle'
+            Maximizes the log-likelihood `boxcox_llf`.  This is the method used
+            in `boxcox`.
+
+        'all'
+            Use all optimization methods available, and return all results.
+            Useful to compare different methods.
+    optimizer : callable, optional
+        `optimizer` is a callable that accepts one argument:
+
+        fun : callable
+            The objective function to be minimized. `fun` accepts one argument,
+            the Box-Cox transform parameter `lmbda`, and returns the value of
+            the function (e.g., the negative log-likelihood) at the provided
+            argument. The job of `optimizer` is to find the value of `lmbda`
+            that *minimizes* `fun`.
+
+        and returns an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal value of
+        `lmbda` in an attribute `x`.
+
+        See the example below or the documentation of
+        `scipy.optimize.minimize_scalar` for more information.
+    ymax : float, optional
+        The unconstrained optimal transform parameter may cause Box-Cox
+        transformed data to have extreme magnitude or even overflow.
+        This parameter constrains MLE optimization such that the magnitude
+        of the transformed `x` does not exceed `ymax`. The default is
+        the maximum value of the input dtype. If set to infinity,
+        `boxcox_normmax` returns the unconstrained optimal lambda.
+        Ignored when ``method='pearsonr'``.
+
+    Returns
+    -------
+    maxlog : float or ndarray
+        The optimal transform parameter found.  An array instead of a scalar
+        for ``method='all'``.
+
+    See Also
+    --------
+    boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We can generate some data and determine the optimal ``lmbda`` in various
+    ways:
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
+    >>> y, lmax_mle = stats.boxcox(x)
+    >>> lmax_pearsonr = stats.boxcox_normmax(x)
+
+    >>> lmax_mle
+    2.217563431465757
+    >>> lmax_pearsonr
+    2.238318660200961
+    >>> stats.boxcox_normmax(x, method='all')
+    array([2.23831866, 2.21756343])
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax)
+    >>> ax.axvline(lmax_mle, color='r')
+    >>> ax.axvline(lmax_pearsonr, color='g', ls='--')
+
+    >>> plt.show()
+
+    Alternatively, we can define our own `optimizer` function. Suppose we
+    are only interested in values of `lmbda` on the interval [6, 7], we
+    want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``,
+    and we want to use tighter tolerances when optimizing the log-likelihood
+    function. To do this, we define a function that accepts positional argument
+    `fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject
+    to the provided bounds and tolerances:
+
+    >>> from scipy import optimize
+    >>> options = {'xatol': 1e-12}  # absolute tolerance on `x`
+    >>> def optimizer(fun):
+    ...     return optimize.minimize_scalar(fun, bounds=(6, 7),
+    ...                                     method="bounded", options=options)
+    >>> stats.boxcox_normmax(x, optimizer=optimizer)
+    6.000000000
+    """
+    x = np.asarray(x)
+
+    if not np.all(np.isfinite(x) & (x >= 0)):
+        message = ("The `x` argument of `boxcox_normmax` must contain "
+                   "only positive, finite, real numbers.")
+        raise ValueError(message)
+
+    end_msg = "exceed specified `ymax`."
+    if ymax is _BigFloat_singleton:
+        dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+        # 10000 is a safety factor because `special.boxcox` overflows prematurely.
+        ymax = np.finfo(dtype).max / 10000
+        end_msg = f"overflow in {dtype}."
+    elif ymax <= 0:
+        raise ValueError("`ymax` must be strictly positive")
+
+    # If optimizer is not given, define default 'brent' optimizer.
+    if optimizer is None:
+
+        # Set default value for `brack`.
+        if brack is None:
+            brack = (-2.0, 2.0)
+
+        def _optimizer(func, args):
+            return optimize.brent(func, args=args, brack=brack)
+
+    # Otherwise check optimizer.
+    else:
+        if not callable(optimizer):
+            raise ValueError("`optimizer` must be a callable")
+
+        if brack is not None:
+            raise ValueError("`brack` must be None if `optimizer` is given")
+
+        # `optimizer` is expected to return a `OptimizeResult` object, we here
+        # get the solution to the optimization problem.
+        def _optimizer(func, args):
+            def func_wrapped(x):
+                return func(x, *args)
+            return getattr(optimizer(func_wrapped), 'x', None)
+
+    def _pearsonr(x):
+        osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+        xvals = distributions.norm.ppf(osm_uniform)
+
+        def _eval_pearsonr(lmbda, xvals, samps):
+            # This function computes the x-axis values of the probability plot
+            # and computes a linear regression (including the correlation) and
+            # returns ``1 - r`` so that a minimization function maximizes the
+            # correlation.
+            y = boxcox(samps, lmbda)
+            yvals = np.sort(y)
+            r, prob = _stats_py.pearsonr(xvals, yvals)
+            return 1 - r
+
+        return _optimizer(_eval_pearsonr, args=(xvals, x))
+
+    def _mle(x):
+        def _eval_mle(lmb, data):
+            # function to minimize
+            return -boxcox_llf(lmb, data)
+
+        return _optimizer(_eval_mle, args=(x,))
+
+    def _all(x):
+        maxlog = np.empty(2, dtype=float)
+        maxlog[0] = _pearsonr(x)
+        maxlog[1] = _mle(x)
+        return maxlog
+
+    methods = {'pearsonr': _pearsonr,
+               'mle': _mle,
+               'all': _all}
+    if method not in methods.keys():
+        raise ValueError(f"Method {method} not recognized.")
+
+    optimfunc = methods[method]
+
+    res = optimfunc(x)
+
+    if res is None:
+        message = ("The `optimizer` argument of `boxcox_normmax` must return "
+                   "an object containing the optimal `lmbda` in attribute `x`.")
+        raise ValueError(message)
+    elif not np.isinf(ymax):  # adjust the final lambda
+        # x > 1, boxcox(x) > 0; x < 1, boxcox(x) < 0
+        xmax, xmin = np.max(x), np.min(x)
+        if xmin >= 1:
+            x_treme = xmax
+        elif xmax <= 1:
+            x_treme = xmin
+        else:  # xmin < 1 < xmax
+            indicator = special.boxcox(xmax, res) > abs(special.boxcox(xmin, res))
+            if isinstance(res, np.ndarray):
+                indicator = indicator[1]  # select corresponds with 'mle'
+            x_treme = xmax if indicator else xmin
+
+        mask = abs(special.boxcox(x_treme, res)) > ymax
+        if np.any(mask):
+            message = (
+                f"The optimal lambda is {res}, but the returned lambda is the "
+                f"constrained optimum to ensure that the maximum or the minimum "
+                f"of the transformed data does not " + end_msg
+            )
+            warnings.warn(message, stacklevel=2)
+
+            # Return the constrained lambda to ensure the transformation
+            # does not cause overflow or exceed specified `ymax`
+            constrained_res = _boxcox_inv_lmbda(x_treme, ymax * np.sign(x_treme - 1))
+
+            if isinstance(res, np.ndarray):
+                res[mask] = constrained_res
+            else:
+                res = constrained_res
+    return res
+
+
+def _normplot(method, x, la, lb, plot=None, N=80):
+    """Compute parameters for a Box-Cox or Yeo-Johnson normality plot,
+    optionally show it.
+
+    See `boxcox_normplot` or `yeojohnson_normplot` for details.
+    """
+
+    if method == 'boxcox':
+        title = 'Box-Cox Normality Plot'
+        transform_func = boxcox
+    else:
+        title = 'Yeo-Johnson Normality Plot'
+        transform_func = yeojohnson
+
+    x = np.asarray(x)
+    if x.size == 0:
+        return x
+
+    if lb <= la:
+        raise ValueError("`lb` has to be larger than `la`.")
+
+    if method == 'boxcox' and np.any(x <= 0):
+        raise ValueError("Data must be positive.")
+
+    lmbdas = np.linspace(la, lb, num=N)
+    ppcc = lmbdas * 0.0
+    for i, val in enumerate(lmbdas):
+        # Determine for each lmbda the square root of correlation coefficient
+        # of transformed x
+        z = transform_func(x, lmbda=val)
+        _, (_, _, r) = probplot(z, dist='norm', fit=True)
+        ppcc[i] = r
+
+    if plot is not None:
+        plot.plot(lmbdas, ppcc, 'x')
+        _add_axis_labels_title(plot, xlabel='$\\lambda$',
+                               ylabel='Prob Plot Corr. Coef.',
+                               title=title)
+
+    return lmbdas, ppcc
+
+
+def boxcox_normplot(x, la, lb, plot=None, N=80):
+    """Compute parameters for a Box-Cox normality plot, optionally show it.
+
+    A Box-Cox normality plot shows graphically what the best transformation
+    parameter is to use in `boxcox` to obtain a distribution that is close
+    to normal.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    la, lb : scalar
+        The lower and upper bounds for the ``lmbda`` values to pass to `boxcox`
+        for Box-Cox transformations.  These are also the limits of the
+        horizontal axis of the plot if that is generated.
+    plot : object, optional
+        If given, plots the quantiles and least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `la` to `lb`).
+
+    Returns
+    -------
+    lmbdas : ndarray
+        The ``lmbda`` values for which a Box-Cox transform was done.
+    ppcc : ndarray
+        Probability Plot Correlation Coefficient, as obtained from `probplot`
+        when fitting the Box-Cox transformed input `x` against a normal
+        distribution.
+
+    See Also
+    --------
+    probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by
+    `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
+    should be used after calling `probplot`.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some non-normally distributed data, and create a Box-Cox plot:
+
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax)
+
+    Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
+    the same plot:
+
+    >>> _, maxlog = stats.boxcox(x)
+    >>> ax.axvline(maxlog, color='r')
+
+    >>> plt.show()
+
+    """
+    return _normplot('boxcox', x, la, lb, plot, N)
+
+
+def yeojohnson(x, lmbda=None):
+    r"""Return a dataset transformed by a Yeo-Johnson power transformation.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.  Should be 1-dimensional.
+    lmbda : float, optional
+        If ``lmbda`` is ``None``, find the lambda that maximizes the
+        log-likelihood function and return it as the second output argument.
+        Otherwise the transformation is done for the given value.
+
+    Returns
+    -------
+    yeojohnson: ndarray
+        Yeo-Johnson power transformed array.
+    maxlog : float, optional
+        If the `lmbda` parameter is None, the second returned argument is
+        the lambda that maximizes the log-likelihood function.
+
+    See Also
+    --------
+    probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox
+
+    Notes
+    -----
+    The Yeo-Johnson transform is given by::
+
+        y = ((x + 1)**lmbda - 1) / lmbda,                for x >= 0, lmbda != 0
+            log(x + 1),                                  for x >= 0, lmbda = 0
+            -((-x + 1)**(2 - lmbda) - 1) / (2 - lmbda),  for x < 0, lmbda != 2
+            -log(-x + 1),                                for x < 0, lmbda = 2
+
+    Unlike `boxcox`, `yeojohnson` does not require the input data to be
+    positive.
+
+    .. versionadded:: 1.2.0
+
+
+    References
+    ----------
+    I. Yeo and R.A. Johnson, "A New Family of Power Transformations to
+    Improve Normality or Symmetry", Biometrika 87.4 (2000):
+
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We generate some random variates from a non-normal distribution and make a
+    probability plot for it, to show it is non-normal in the tails:
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
+    >>> ax1.set_xlabel('')
+    >>> ax1.set_title('Probplot against normal distribution')
+
+    We now use `yeojohnson` to transform the data so it's closest to normal:
+
+    >>> ax2 = fig.add_subplot(212)
+    >>> xt, lmbda = stats.yeojohnson(x)
+    >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
+    >>> ax2.set_title('Probplot after Yeo-Johnson transformation')
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+    if x.size == 0:
+        return x
+
+    if np.issubdtype(x.dtype, np.complexfloating):
+        raise ValueError('Yeo-Johnson transformation is not defined for '
+                         'complex numbers.')
+
+    if np.issubdtype(x.dtype, np.integer):
+        x = x.astype(np.float64, copy=False)
+
+    if lmbda is not None:
+        return _yeojohnson_transform(x, lmbda)
+
+    # if lmbda=None, find the lmbda that maximizes the log-likelihood function.
+    lmax = yeojohnson_normmax(x)
+    y = _yeojohnson_transform(x, lmax)
+
+    return y, lmax
+
+
+def _yeojohnson_transform(x, lmbda):
+    """Returns `x` transformed by the Yeo-Johnson power transform with given
+    parameter `lmbda`.
+    """
+    dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+    out = np.zeros_like(x, dtype=dtype)
+    pos = x >= 0  # binary mask
+
+    # when x >= 0
+    if abs(lmbda) < np.spacing(1.):
+        out[pos] = np.log1p(x[pos])
+    else:  # lmbda != 0
+        # more stable version of: ((x + 1) ** lmbda - 1) / lmbda
+        out[pos] = np.expm1(lmbda * np.log1p(x[pos])) / lmbda
+
+    # when x < 0
+    if abs(lmbda - 2) > np.spacing(1.):
+        out[~pos] = -np.expm1((2 - lmbda) * np.log1p(-x[~pos])) / (2 - lmbda)
+    else:  # lmbda == 2
+        out[~pos] = -np.log1p(-x[~pos])
+
+    return out
+
+
+def yeojohnson_llf(lmb, data):
+    r"""The yeojohnson log-likelihood function.
+
+    Parameters
+    ----------
+    lmb : scalar
+        Parameter for Yeo-Johnson transformation. See `yeojohnson` for
+        details.
+    data : array_like
+        Data to calculate Yeo-Johnson log-likelihood for. If `data` is
+        multi-dimensional, the log-likelihood is calculated along the first
+        axis.
+
+    Returns
+    -------
+    llf : float
+        Yeo-Johnson log-likelihood of `data` given `lmb`.
+
+    See Also
+    --------
+    yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax
+
+    Notes
+    -----
+    The Yeo-Johnson log-likelihood function is defined here as
+
+    .. math::
+
+        llf = -N/2 \log(\hat{\sigma}^2) + (\lambda - 1)
+              \sum_i \text{ sign }(x_i)\log(|x_i| + 1)
+
+    where :math:`\hat{\sigma}^2` is estimated variance of the Yeo-Johnson
+    transformed input data ``x``.
+
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+
+    Generate some random variates and calculate Yeo-Johnson log-likelihood
+    values for them for a range of ``lmbda`` values:
+
+    >>> x = stats.loggamma.rvs(5, loc=10, size=1000)
+    >>> lmbdas = np.linspace(-2, 10)
+    >>> llf = np.zeros(lmbdas.shape, dtype=float)
+    >>> for ii, lmbda in enumerate(lmbdas):
+    ...     llf[ii] = stats.yeojohnson_llf(lmbda, x)
+
+    Also find the optimal lmbda value with `yeojohnson`:
+
+    >>> x_most_normal, lmbda_optimal = stats.yeojohnson(x)
+
+    Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
+    horizontal line to check that that's really the optimum:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(lmbdas, llf, 'b.-')
+    >>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r')
+    >>> ax.set_xlabel('lmbda parameter')
+    >>> ax.set_ylabel('Yeo-Johnson log-likelihood')
+
+    Now add some probability plots to show that where the log-likelihood is
+    maximized the data transformed with `yeojohnson` looks closest to normal:
+
+    >>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
+    >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
+    ...     xt = stats.yeojohnson(x, lmbda=lmbda)
+    ...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
+    ...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
+    ...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
+    ...     ax_inset.set_xticklabels([])
+    ...     ax_inset.set_yticklabels([])
+    ...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
+
+    >>> plt.show()
+
+    """
+    data = np.asarray(data)
+    n_samples = data.shape[0]
+
+    if n_samples == 0:
+        return np.nan
+
+    trans = _yeojohnson_transform(data, lmb)
+    trans_var = trans.var(axis=0)
+    loglike = np.empty_like(trans_var)
+
+    # Avoid RuntimeWarning raised by np.log when the variance is too low
+    tiny_variance = trans_var < np.finfo(trans_var.dtype).tiny
+    loglike[tiny_variance] = np.inf
+
+    loglike[~tiny_variance] = (
+        -n_samples / 2 * np.log(trans_var[~tiny_variance]))
+    loglike[~tiny_variance] += (
+        (lmb - 1) * (np.sign(data) * np.log1p(np.abs(data))).sum(axis=0))
+    return loglike
+
+
+def yeojohnson_normmax(x, brack=None):
+    """Compute optimal Yeo-Johnson transform parameter.
+
+    Compute optimal Yeo-Johnson transform parameter for input data, using
+    maximum likelihood estimation.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    brack : 2-tuple, optional
+        The starting interval for a downhill bracket search with
+        `optimize.brent`. Note that this is in most cases not critical; the
+        final result is allowed to be outside this bracket. If None,
+        `optimize.fminbound` is used with bounds that avoid overflow.
+
+    Returns
+    -------
+    maxlog : float
+        The optimal transform parameter found.
+
+    See Also
+    --------
+    yeojohnson, yeojohnson_llf, yeojohnson_normplot
+
+    Notes
+    -----
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some data and determine optimal ``lmbda``
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
+    >>> lmax = stats.yeojohnson_normmax(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax)
+    >>> ax.axvline(lmax, color='r')
+
+    >>> plt.show()
+
+    """
+    def _neg_llf(lmbda, data):
+        llf = yeojohnson_llf(lmbda, data)
+        # reject likelihoods that are inf which are likely due to small
+        # variance in the transformed space
+        llf[np.isinf(llf)] = -np.inf
+        return -llf
+
+    with np.errstate(invalid='ignore'):
+        if not np.all(np.isfinite(x)):
+            raise ValueError('Yeo-Johnson input must be finite.')
+        if np.all(x == 0):
+            return 1.0
+        if brack is not None:
+            return optimize.brent(_neg_llf, brack=brack, args=(x,))
+        x = np.asarray(x)
+        dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+        # Allow values up to 20 times the maximum observed value to be safely
+        # transformed without over- or underflow.
+        log1p_max_x = np.log1p(20 * np.max(np.abs(x)))
+        # Use half of floating point's exponent range to allow safe computation
+        # of the variance of the transformed data.
+        log_eps = np.log(np.finfo(dtype).eps)
+        log_tiny_float = (np.log(np.finfo(dtype).tiny) - log_eps) / 2
+        log_max_float = (np.log(np.finfo(dtype).max) + log_eps) / 2
+        # Compute the bounds by approximating the inverse of the Yeo-Johnson
+        # transform on the smallest and largest floating point exponents, given
+        # the largest data we expect to observe. See [1] for further details.
+        # [1] https://github.com/scipy/scipy/pull/18852#issuecomment-1630286174
+        lb = log_tiny_float / log1p_max_x
+        ub = log_max_float / log1p_max_x
+        # Convert the bounds if all or some of the data is negative.
+        if np.all(x < 0):
+            lb, ub = 2 - ub, 2 - lb
+        elif np.any(x < 0):
+            lb, ub = max(2 - ub, lb), min(2 - lb, ub)
+        # Match `optimize.brent`'s tolerance.
+        tol_brent = 1.48e-08
+        return optimize.fminbound(_neg_llf, lb, ub, args=(x,), xtol=tol_brent)
+
+
+def yeojohnson_normplot(x, la, lb, plot=None, N=80):
+    """Compute parameters for a Yeo-Johnson normality plot, optionally show it.
+
+    A Yeo-Johnson normality plot shows graphically what the best
+    transformation parameter is to use in `yeojohnson` to obtain a
+    distribution that is close to normal.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    la, lb : scalar
+        The lower and upper bounds for the ``lmbda`` values to pass to
+        `yeojohnson` for Yeo-Johnson transformations. These are also the
+        limits of the horizontal axis of the plot if that is generated.
+    plot : object, optional
+        If given, plots the quantiles and least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `la` to `lb`).
+
+    Returns
+    -------
+    lmbdas : ndarray
+        The ``lmbda`` values for which a Yeo-Johnson transform was done.
+    ppcc : ndarray
+        Probability Plot Correlation Coefficient, as obtained from `probplot`
+        when fitting the Box-Cox transformed input `x` against a normal
+        distribution.
+
+    See Also
+    --------
+    probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by
+    `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
+    should be used after calling `probplot`.
+
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some non-normally distributed data, and create a Yeo-Johnson plot:
+
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax)
+
+    Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
+    the same plot:
+
+    >>> _, maxlog = stats.yeojohnson(x)
+    >>> ax.axvline(maxlog, color='r')
+
+    >>> plt.show()
+
+    """
+    return _normplot('yeojohnson', x, la, lb, plot, N)
+
+
+ShapiroResult = namedtuple('ShapiroResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(ShapiroResult, n_samples=1, too_small=2, default_axis=None)
+def shapiro(x):
+    r"""Perform the Shapiro-Wilk test for normality.
+
+    The Shapiro-Wilk test tests the null hypothesis that the
+    data was drawn from a normal distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Array of sample data. Must contain at least three observations.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    p-value : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    anderson : The Anderson-Darling test for normality
+    kstest : The Kolmogorov-Smirnov test for goodness of fit.
+    :ref:`hypothesis_shapiro` : Extended example
+
+    Notes
+    -----
+    The algorithm used is described in [4]_ but censoring parameters as
+    described are not implemented. For N > 5000 the W test statistic is
+    accurate, but the p-value may not be.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
+           :doi:`10.18434/M32189`
+    .. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for
+           normality (complete samples)", Biometrika, 1965, Vol. 52,
+           pp. 591-611, :doi:`10.2307/2333709`
+    .. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk,
+           Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal
+           of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33.
+    .. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The
+           W-test for Normality", 1995, Applied Statistics, Vol. 44,
+           :doi:`10.2307/2986146`
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng)
+    >>> shapiro_test = stats.shapiro(x)
+    >>> shapiro_test
+    ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585)
+    >>> shapiro_test.statistic
+    0.9813305735588074
+    >>> shapiro_test.pvalue
+    0.16855233907699585
+
+    For a more detailed example, see :ref:`hypothesis_shapiro`.
+    """
+    x = np.ravel(x).astype(np.float64)
+
+    N = len(x)
+    if N < 3:
+        raise ValueError("Data must be at least length 3.")
+
+    a = zeros(N//2, dtype=np.float64)
+    init = 0
+
+    y = sort(x)
+    y -= x[N//2]  # subtract the median (or a nearby value); see gh-15777
+
+    w, pw, ifault = swilk(y, a, init)
+    if ifault not in [0, 2]:
+        warnings.warn("scipy.stats.shapiro: Input data has range zero. The"
+                      " results may not be accurate.", stacklevel=2)
+    if N > 5000:
+        warnings.warn("scipy.stats.shapiro: For N > 5000, computed p-value "
+                      f"may not be accurate. Current N is {N}.",
+                      stacklevel=2)
+
+    # `w` and `pw` are always Python floats, which are double precision.
+    # We want to ensure that they are NumPy floats, so until dtypes are
+    # respected, we can explicitly convert each to float64 (faster than
+    # `np.array([w, pw])`).
+    return ShapiroResult(np.float64(w), np.float64(pw))
+
+
+# Values from Stephens, M A, "EDF Statistics for Goodness of Fit and
+#             Some Comparisons", Journal of the American Statistical
+#             Association, Vol. 69, Issue 347, Sept. 1974, pp 730-737
+_Avals_norm = array([0.576, 0.656, 0.787, 0.918, 1.092])
+_Avals_expon = array([0.922, 1.078, 1.341, 1.606, 1.957])
+# From Stephens, M A, "Goodness of Fit for the Extreme Value Distribution",
+#             Biometrika, Vol. 64, Issue 3, Dec. 1977, pp 583-588.
+_Avals_gumbel = array([0.474, 0.637, 0.757, 0.877, 1.038])
+# From Stephens, M A, "Tests of Fit for the Logistic Distribution Based
+#             on the Empirical Distribution Function.", Biometrika,
+#             Vol. 66, Issue 3, Dec. 1979, pp 591-595.
+_Avals_logistic = array([0.426, 0.563, 0.660, 0.769, 0.906, 1.010])
+# From Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
+#             Fit for the Three-Parameter Weibull Distribution"
+#             Journal of the Royal Statistical Society.Series B(Methodological)
+#             Vol. 56, No. 3 (1994), pp. 491-500, table 1. Keys are c*100
+_Avals_weibull = [[0.292, 0.395, 0.467, 0.522, 0.617, 0.711, 0.836, 0.931],
+                  [0.295, 0.399, 0.471, 0.527, 0.623, 0.719, 0.845, 0.941],
+                  [0.298, 0.403, 0.476, 0.534, 0.631, 0.728, 0.856, 0.954],
+                  [0.301, 0.408, 0.483, 0.541, 0.640, 0.738, 0.869, 0.969],
+                  [0.305, 0.414, 0.490, 0.549, 0.650, 0.751, 0.885, 0.986],
+                  [0.309, 0.421, 0.498, 0.559, 0.662, 0.765, 0.902, 1.007],
+                  [0.314, 0.429, 0.508, 0.570, 0.676, 0.782, 0.923, 1.030],
+                  [0.320, 0.438, 0.519, 0.583, 0.692, 0.802, 0.947, 1.057],
+                  [0.327, 0.448, 0.532, 0.598, 0.711, 0.824, 0.974, 1.089],
+                  [0.334, 0.469, 0.547, 0.615, 0.732, 0.850, 1.006, 1.125],
+                  [0.342, 0.472, 0.563, 0.636, 0.757, 0.879, 1.043, 1.167]]
+_Avals_weibull = np.array(_Avals_weibull)
+_cvals_weibull = np.linspace(0, 0.5, 11)
+_get_As_weibull = interpolate.interp1d(_cvals_weibull, _Avals_weibull.T,
+                                       kind='linear', bounds_error=False,
+                                       fill_value=_Avals_weibull[-1])
+
+
+def _weibull_fit_check(params, x):
+    # Refine the fit returned by `weibull_min.fit` to ensure that the first
+    # order necessary conditions are satisfied. If not, raise an error.
+    # Here, use `m` for the shape parameter to be consistent with [7]
+    # and avoid confusion with `c` as defined in [7].
+    n = len(x)
+    m, u, s = params
+
+    def dnllf_dm(m, u):
+        # Partial w.r.t. shape w/ optimal scale. See [7] Equation 5.
+        xu = x-u
+        return (1/m - (xu**m*np.log(xu)).sum()/(xu**m).sum()
+                + np.log(xu).sum()/n)
+
+    def dnllf_du(m, u):
+        # Partial w.r.t. loc w/ optimal scale. See [7] Equation 6.
+        xu = x-u
+        return (m-1)/m*(xu**-1).sum() - n*(xu**(m-1)).sum()/(xu**m).sum()
+
+    def get_scale(m, u):
+        # Partial w.r.t. scale solved in terms of shape and location.
+        # See [7] Equation 7.
+        return ((x-u)**m/n).sum()**(1/m)
+
+    def dnllf(params):
+        # Partial derivatives of the NLLF w.r.t. parameters, i.e.
+        # first order necessary conditions for MLE fit.
+        return [dnllf_dm(*params), dnllf_du(*params)]
+
+    suggestion = ("Maximum likelihood estimation is known to be challenging "
+                  "for the three-parameter Weibull distribution. Consider "
+                  "performing a custom goodness-of-fit test using "
+                  "`scipy.stats.monte_carlo_test`.")
+
+    if np.allclose(u, np.min(x)) or m < 1:
+        # The critical values provided by [7] don't seem to control the
+        # Type I error rate in this case. Error out.
+        message = ("Maximum likelihood estimation has converged to "
+                   "a solution in which the location is equal to the minimum "
+                   "of the data, the shape parameter is less than 2, or both. "
+                   "The table of critical values in [7] does not "
+                   "include this case. " + suggestion)
+        raise ValueError(message)
+
+    try:
+        # Refine the MLE / verify that first-order necessary conditions are
+        # satisfied. If so, the critical values provided in [7] seem reliable.
+        with np.errstate(over='raise', invalid='raise'):
+            res = optimize.root(dnllf, params[:-1])
+
+        message = ("Solution of MLE first-order conditions failed: "
+                   f"{res.message}. `anderson` cannot continue. " + suggestion)
+        if not res.success:
+            raise ValueError(message)
+
+    except (FloatingPointError, ValueError) as e:
+        message = ("An error occurred while fitting the Weibull distribution "
+                   "to the data, so `anderson` cannot continue. " + suggestion)
+        raise ValueError(message) from e
+
+    m, u = res.x
+    s = get_scale(m, u)
+    return m, u, s
+
+
+AndersonResult = _make_tuple_bunch('AndersonResult',
+                                   ['statistic', 'critical_values',
+                                    'significance_level'], ['fit_result'])
+
+
+def anderson(x, dist='norm'):
+    """Anderson-Darling test for data coming from a particular distribution.
+
+    The Anderson-Darling test tests the null hypothesis that a sample is
+    drawn from a population that follows a particular distribution.
+    For the Anderson-Darling test, the critical values depend on
+    which distribution is being tested against.  This function works
+    for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value
+    Type I) distributions.
+
+    Parameters
+    ----------
+    x : array_like
+        Array of sample data.
+    dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional
+        The type of distribution to test against.  The default is 'norm'.
+        The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the
+        same distribution.
+
+    Returns
+    -------
+    result : AndersonResult
+        An object with the following attributes:
+
+        statistic : float
+            The Anderson-Darling test statistic.
+        critical_values : list
+            The critical values for this distribution.
+        significance_level : list
+            The significance levels for the corresponding critical values
+            in percents.  The function returns critical values for a
+            differing set of significance levels depending on the
+            distribution that is being tested against.
+        fit_result : `~scipy.stats._result_classes.FitResult`
+            An object containing the results of fitting the distribution to
+            the data.
+
+    See Also
+    --------
+    kstest : The Kolmogorov-Smirnov test for goodness-of-fit.
+
+    Notes
+    -----
+    Critical values provided are for the following significance levels:
+
+    normal/exponential
+        15%, 10%, 5%, 2.5%, 1%
+    logistic
+        25%, 10%, 5%, 2.5%, 1%, 0.5%
+    gumbel_l / gumbel_r
+        25%, 10%, 5%, 2.5%, 1%
+    weibull_min
+        50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5%
+
+    If the returned statistic is larger than these critical values then
+    for the corresponding significance level, the null hypothesis that
+    the data come from the chosen distribution can be rejected.
+    The returned statistic is referred to as 'A2' in the references.
+
+    For `weibull_min`, maximum likelihood estimation is known to be
+    challenging. If the test returns successfully, then the first order
+    conditions for a maximum likelihood estimate have been verified and
+    the critical values correspond relatively well to the significance levels,
+    provided that the sample is sufficiently large (>10 observations [7]).
+    However, for some data - especially data with no left tail - `anderson`
+    is likely to result in an error message. In this case, consider
+    performing a custom goodness of fit test using
+    `scipy.stats.monte_carlo_test`.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
+    .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
+           Some Comparisons, Journal of the American Statistical Association,
+           Vol. 69, pp. 730-737.
+    .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
+           Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
+           pp. 357-369.
+    .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
+           Distribution, Biometrika, Vol. 64, pp. 583-588.
+    .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
+           to Tests for Exponentiality , Technical Report No. 262,
+           Department of Statistics, Stanford University, Stanford, CA.
+    .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
+           Based on the Empirical Distribution Function, Biometrika, Vol. 66,
+           pp. 591-595.
+    .. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
+           Fit for the Three-Parameter Weibull Distribution"
+           Journal of the Royal Statistical Society.Series B(Methodological)
+           Vol. 56, No. 3 (1994), pp. 491-500, Table 0.
+
+    Examples
+    --------
+    Test the null hypothesis that a random sample was drawn from a normal
+    distribution (with unspecified mean and standard deviation).
+
+    >>> import numpy as np
+    >>> from scipy.stats import anderson
+    >>> rng = np.random.default_rng()
+    >>> data = rng.random(size=35)
+    >>> res = anderson(data)
+    >>> res.statistic
+    0.8398018749744764
+    >>> res.critical_values
+    array([0.527, 0.6  , 0.719, 0.839, 0.998])
+    >>> res.significance_level
+    array([15. , 10. ,  5. ,  2.5,  1. ])
+
+    The value of the statistic (barely) exceeds the critical value associated
+    with a significance level of 2.5%, so the null hypothesis may be rejected
+    at a significance level of 2.5%, but not at a significance level of 1%.
+
+    """ # numpy/numpydoc#87  # noqa: E501
+    dist = dist.lower()
+    if dist in {'extreme1', 'gumbel'}:
+        dist = 'gumbel_l'
+    dists = {'norm', 'expon', 'gumbel_l',
+             'gumbel_r', 'logistic', 'weibull_min'}
+
+    if dist not in dists:
+        raise ValueError(f"Invalid distribution; dist must be in {dists}.")
+    y = sort(x)
+    xbar = np.mean(x, axis=0)
+    N = len(y)
+    if dist == 'norm':
+        s = np.std(x, ddof=1, axis=0)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.norm.logcdf(w)
+        logsf = distributions.norm.logsf(w)
+        sig = array([15, 10, 5, 2.5, 1])
+        critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N), 3)
+    elif dist == 'expon':
+        w = y / xbar
+        fit_params = 0, xbar
+        logcdf = distributions.expon.logcdf(w)
+        logsf = distributions.expon.logsf(w)
+        sig = array([15, 10, 5, 2.5, 1])
+        critical = around(_Avals_expon / (1.0 + 0.6/N), 3)
+    elif dist == 'logistic':
+        def rootfunc(ab, xj, N):
+            a, b = ab
+            tmp = (xj - a) / b
+            tmp2 = exp(tmp)
+            val = [np.sum(1.0/(1+tmp2), axis=0) - 0.5*N,
+                   np.sum(tmp*(1.0-tmp2)/(1+tmp2), axis=0) + N]
+            return array(val)
+
+        sol0 = array([xbar, np.std(x, ddof=1, axis=0)])
+        sol = optimize.fsolve(rootfunc, sol0, args=(x, N), xtol=1e-5)
+        w = (y - sol[0]) / sol[1]
+        fit_params = sol
+        logcdf = distributions.logistic.logcdf(w)
+        logsf = distributions.logistic.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1, 0.5])
+        critical = around(_Avals_logistic / (1.0 + 0.25/N), 3)
+    elif dist == 'gumbel_r':
+        xbar, s = distributions.gumbel_r.fit(x)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.gumbel_r.logcdf(w)
+        logsf = distributions.gumbel_r.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1])
+        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
+    elif dist == 'gumbel_l':
+        xbar, s = distributions.gumbel_l.fit(x)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.gumbel_l.logcdf(w)
+        logsf = distributions.gumbel_l.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1])
+        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
+    elif dist == 'weibull_min':
+        message = ("Critical values of the test statistic are given for the "
+                   "asymptotic distribution. These may not be accurate for "
+                   "samples with fewer than 10 observations. Consider using "
+                   "`scipy.stats.monte_carlo_test`.")
+        if N < 10:
+            warnings.warn(message, stacklevel=2)
+        # [7] writes our 'c' as 'm', and they write `c = 1/m`. Use their names.
+        m, loc, scale = distributions.weibull_min.fit(y)
+        m, loc, scale = _weibull_fit_check((m, loc, scale), y)
+        fit_params = m, loc, scale
+        logcdf = stats.weibull_min(*fit_params).logcdf(y)
+        logsf = stats.weibull_min(*fit_params).logsf(y)
+        c = 1 / m  # m and c are as used in [7]
+        sig = array([0.5, 0.75, 0.85, 0.9, 0.95, 0.975, 0.99, 0.995])
+        critical = _get_As_weibull(c)
+        # Goodness-of-fit tests should only be used to provide evidence
+        # _against_ the null hypothesis. Be conservative and round up.
+        critical = np.round(critical + 0.0005, decimals=3)
+
+    i = arange(1, N + 1)
+    A2 = -N - np.sum((2*i - 1.0) / N * (logcdf + logsf[::-1]), axis=0)
+
+    # FitResult initializer expects an optimize result, so let's work with it
+    message = '`anderson` successfully fit the distribution to the data.'
+    res = optimize.OptimizeResult(success=True, message=message)
+    res.x = np.array(fit_params)
+    fit_result = FitResult(getattr(distributions, dist), y,
+                           discrete=False, res=res)
+
+    return AndersonResult(A2, critical, sig, fit_result=fit_result)
+
+
+def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N):
+    """Compute A2akN equation 7 of Scholz and Stephens.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample arrays.
+    Z : array_like
+        Sorted array of all observations.
+    Zstar : array_like
+        Sorted array of unique observations.
+    k : int
+        Number of samples.
+    n : array_like
+        Number of observations in each sample.
+    N : int
+        Total number of observations.
+
+    Returns
+    -------
+    A2aKN : float
+        The A2aKN statistics of Scholz and Stephens 1987.
+
+    """
+    A2akN = 0.
+    Z_ssorted_left = Z.searchsorted(Zstar, 'left')
+    if N == Zstar.size:
+        lj = 1.
+    else:
+        lj = Z.searchsorted(Zstar, 'right') - Z_ssorted_left
+    Bj = Z_ssorted_left + lj / 2.
+    for i in arange(0, k):
+        s = np.sort(samples[i])
+        s_ssorted_right = s.searchsorted(Zstar, side='right')
+        Mij = s_ssorted_right.astype(float)
+        fij = s_ssorted_right - s.searchsorted(Zstar, 'left')
+        Mij -= fij / 2.
+        inner = lj / float(N) * (N*Mij - Bj*n[i])**2 / (Bj*(N - Bj) - N*lj/4.)
+        A2akN += inner.sum() / n[i]
+    A2akN *= (N - 1.) / N
+    return A2akN
+
+
+def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):
+    """Compute A2akN equation 6 of Scholz & Stephens.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample arrays.
+    Z : array_like
+        Sorted array of all observations.
+    Zstar : array_like
+        Sorted array of unique observations.
+    k : int
+        Number of samples.
+    n : array_like
+        Number of observations in each sample.
+    N : int
+        Total number of observations.
+
+    Returns
+    -------
+    A2KN : float
+        The A2KN statistics of Scholz and Stephens 1987.
+
+    """
+    A2kN = 0.
+    lj = Z.searchsorted(Zstar[:-1], 'right') - Z.searchsorted(Zstar[:-1],
+                                                              'left')
+    Bj = lj.cumsum()
+    for i in arange(0, k):
+        s = np.sort(samples[i])
+        Mij = s.searchsorted(Zstar[:-1], side='right')
+        inner = lj / float(N) * (N * Mij - Bj * n[i])**2 / (Bj * (N - Bj))
+        A2kN += inner.sum() / n[i]
+    return A2kN
+
+
+Anderson_ksampResult = _make_tuple_bunch(
+    'Anderson_ksampResult',
+    ['statistic', 'critical_values', 'pvalue'], []
+)
+
+
+def anderson_ksamp(samples, midrank=True, *, method=None):
+    """The Anderson-Darling test for k-samples.
+
+    The k-sample Anderson-Darling test is a modification of the
+    one-sample Anderson-Darling test. It tests the null hypothesis
+    that k-samples are drawn from the same population without having
+    to specify the distribution function of that population. The
+    critical values depend on the number of samples.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample data in arrays.
+    midrank : bool, optional
+        Type of Anderson-Darling test which is computed. Default
+        (True) is the midrank test applicable to continuous and
+        discrete populations. If False, the right side empirical
+        distribution is used.
+    method : PermutationMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`, the p-value is computed using
+        `scipy.stats.permutation_test` with the provided configuration options
+        and other appropriate settings. Otherwise, the p-value is interpolated
+        from tabulated values.
+
+    Returns
+    -------
+    res : Anderson_ksampResult
+        An object containing attributes:
+
+        statistic : float
+            Normalized k-sample Anderson-Darling test statistic.
+        critical_values : array
+            The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%,
+            0.5%, 0.1%.
+        pvalue : float
+            The approximate p-value of the test. If `method` is not
+            provided, the value is floored / capped at 0.1% / 25%.
+
+    Raises
+    ------
+    ValueError
+        If fewer than 2 samples are provided, a sample is empty, or no
+        distinct observations are in the samples.
+
+    See Also
+    --------
+    ks_2samp : 2 sample Kolmogorov-Smirnov test
+    anderson : 1 sample Anderson-Darling test
+
+    Notes
+    -----
+    [1]_ defines three versions of the k-sample Anderson-Darling test:
+    one for continuous distributions and two for discrete
+    distributions, in which ties between samples may occur. The
+    default of this routine is to compute the version based on the
+    midrank empirical distribution function. This test is applicable
+    to continuous and discrete data. If midrank is set to False, the
+    right side empirical distribution is used for a test for discrete
+    data. According to [1]_, the two discrete test statistics differ
+    only slightly if a few collisions due to round-off errors occur in
+    the test not adjusted for ties between samples.
+
+    The critical values corresponding to the significance levels from 0.01
+    to 0.25 are taken from [1]_. p-values are floored / capped
+    at 0.1% / 25%. Since the range of critical values might be extended in
+    future releases, it is recommended not to test ``p == 0.25``, but rather
+    ``p >= 0.25`` (analogously for the lower bound).
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample
+           Anderson-Darling Tests, Journal of the American Statistical
+           Association, Vol. 82, pp. 918-924.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> res = stats.anderson_ksamp([rng.normal(size=50),
+    ... rng.normal(loc=0.5, size=30)])
+    >>> res.statistic, res.pvalue
+    (1.974403288713695, 0.04991293614572478)
+    >>> res.critical_values
+    array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546])
+
+    The null hypothesis that the two random samples come from the same
+    distribution can be rejected at the 5% level because the returned
+    test value is greater than the critical value for 5% (1.961) but
+    not at the 2.5% level. The interpolation gives an approximate
+    p-value of 4.99%.
+
+    >>> samples = [rng.normal(size=50), rng.normal(size=30),
+    ...            rng.normal(size=20)]
+    >>> res = stats.anderson_ksamp(samples)
+    >>> res.statistic, res.pvalue
+    (-0.29103725200789504, 0.25)
+    >>> res.critical_values
+    array([ 0.44925884,  1.3052767 ,  1.9434184 ,  2.57696569,  3.41634856,
+      4.07210043, 5.56419101])
+
+    The null hypothesis cannot be rejected for three samples from an
+    identical distribution. The reported p-value (25%) has been capped and
+    may not be very accurate (since it corresponds to the value 0.449
+    whereas the statistic is -0.291).
+
+    In such cases where the p-value is capped or when sample sizes are
+    small, a permutation test may be more accurate.
+
+    >>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
+    >>> res = stats.anderson_ksamp(samples, method=method)
+    >>> res.pvalue
+    0.5254
+
+    """
+    k = len(samples)
+    if (k < 2):
+        raise ValueError("anderson_ksamp needs at least two samples")
+
+    samples = list(map(np.asarray, samples))
+    Z = np.sort(np.hstack(samples))
+    N = Z.size
+    Zstar = np.unique(Z)
+    if Zstar.size < 2:
+        raise ValueError("anderson_ksamp needs more than one distinct "
+                         "observation")
+
+    n = np.array([sample.size for sample in samples])
+    if np.any(n == 0):
+        raise ValueError("anderson_ksamp encountered sample without "
+                         "observations")
+
+    if midrank:
+        A2kN_fun = _anderson_ksamp_midrank
+    else:
+        A2kN_fun = _anderson_ksamp_right
+    A2kN = A2kN_fun(samples, Z, Zstar, k, n, N)
+
+    def statistic(*samples):
+        return A2kN_fun(samples, Z, Zstar, k, n, N)
+
+    if method is not None:
+        res = stats.permutation_test(samples, statistic, **method._asdict(),
+                                     alternative='greater')
+
+    H = (1. / n).sum()
+    hs_cs = (1. / arange(N - 1, 1, -1)).cumsum()
+    h = hs_cs[-1] + 1
+    g = (hs_cs / arange(2, N)).sum()
+
+    a = (4*g - 6) * (k - 1) + (10 - 6*g)*H
+    b = (2*g - 4)*k**2 + 8*h*k + (2*g - 14*h - 4)*H - 8*h + 4*g - 6
+    c = (6*h + 2*g - 2)*k**2 + (4*h - 4*g + 6)*k + (2*h - 6)*H + 4*h
+    d = (2*h + 6)*k**2 - 4*h*k
+    sigmasq = (a*N**3 + b*N**2 + c*N + d) / ((N - 1.) * (N - 2.) * (N - 3.))
+    m = k - 1
+    A2 = (A2kN - m) / math.sqrt(sigmasq)
+
+    # The b_i values are the interpolation coefficients from Table 2
+    # of Scholz and Stephens 1987
+    b0 = np.array([0.675, 1.281, 1.645, 1.96, 2.326, 2.573, 3.085])
+    b1 = np.array([-0.245, 0.25, 0.678, 1.149, 1.822, 2.364, 3.615])
+    b2 = np.array([-0.105, -0.305, -0.362, -0.391, -0.396, -0.345, -0.154])
+    critical = b0 + b1 / math.sqrt(m) + b2 / m
+
+    sig = np.array([0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.001])
+
+    if A2 < critical.min() and method is None:
+        p = sig.max()
+        msg = (f"p-value capped: true value larger than {p}. Consider "
+               "specifying `method` "
+               "(e.g. `method=stats.PermutationMethod()`.)")
+        warnings.warn(msg, stacklevel=2)
+    elif A2 > critical.max() and method is None:
+        p = sig.min()
+        msg = (f"p-value floored: true value smaller than {p}. Consider "
+               "specifying `method` "
+               "(e.g. `method=stats.PermutationMethod()`.)")
+        warnings.warn(msg, stacklevel=2)
+    elif method is None:
+        # interpolation of probit of significance level
+        pf = np.polyfit(critical, log(sig), 2)
+        p = math.exp(np.polyval(pf, A2))
+    else:
+        p = res.pvalue if method is not None else p
+
+    # create result object with alias for backward compatibility
+    res = Anderson_ksampResult(A2, critical, p)
+    res.significance_level = p
+    return res
+
+
+AnsariResult = namedtuple('AnsariResult', ('statistic', 'pvalue'))
+
+
+class _ABW:
+    """Distribution of Ansari-Bradley W-statistic under the null hypothesis."""
+    # TODO: calculate exact distribution considering ties
+    # We could avoid summing over more than half the frequencies,
+    # but initially it doesn't seem worth the extra complexity
+
+    def __init__(self):
+        """Minimal initializer."""
+        self.m = None
+        self.n = None
+        self.astart = None
+        self.total = None
+        self.freqs = None
+
+    def _recalc(self, n, m):
+        """When necessary, recalculate exact distribution."""
+        if n != self.n or m != self.m:
+            self.n, self.m = n, m
+            # distribution is NOT symmetric when m + n is odd
+            # n is len(x), m is len(y), and ratio of scales is defined x/y
+            astart, a1, _ = gscale(n, m)
+            self.astart = astart  # minimum value of statistic
+            # Exact distribution of test statistic under null hypothesis
+            # expressed as frequencies/counts/integers to maintain precision.
+            # Stored as floats to avoid overflow of sums.
+            self.freqs = a1.astype(np.float64)
+            self.total = self.freqs.sum()  # could calculate from m and n
+            # probability mass is self.freqs / self.total;
+
+    def pmf(self, k, n, m):
+        """Probability mass function."""
+        self._recalc(n, m)
+        # The convention here is that PMF at k = 12.5 is the same as at k = 12,
+        # -> use `floor` in case of ties.
+        ind = np.floor(k - self.astart).astype(int)
+        return self.freqs[ind] / self.total
+
+    def cdf(self, k, n, m):
+        """Cumulative distribution function."""
+        self._recalc(n, m)
+        # Null distribution derived without considering ties is
+        # approximate. Round down to avoid Type I error.
+        ind = np.ceil(k - self.astart).astype(int)
+        return self.freqs[:ind+1].sum() / self.total
+
+    def sf(self, k, n, m):
+        """Survival function."""
+        self._recalc(n, m)
+        # Null distribution derived without considering ties is
+        # approximate. Round down to avoid Type I error.
+        ind = np.floor(k - self.astart).astype(int)
+        return self.freqs[ind:].sum() / self.total
+
+
+# Maintain state for faster repeat calls to ansari w/ method='exact'
+# _ABW() is calculated once per thread and stored as an attribute on
+# this thread-local variable inside ansari().
+_abw_state = threading.local()
+
+
+@_axis_nan_policy_factory(AnsariResult, n_samples=2)
+def ansari(x, y, alternative='two-sided'):
+    """Perform the Ansari-Bradley test for equal scale parameters.
+
+    The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test
+    for the equality of the scale parameter of the distributions
+    from which two samples were drawn. The null hypothesis states that
+    the ratio of the scale of the distribution underlying `x` to the scale
+    of the distribution underlying `y` is 1.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of sample data.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the ratio of scales is not equal to 1.
+        * 'less': the ratio of scales is less than 1.
+        * 'greater': the ratio of scales is greater than 1.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The Ansari-Bradley test statistic.
+    pvalue : float
+        The p-value of the hypothesis test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    mood : A non-parametric test for the equality of two scale parameters
+
+    Notes
+    -----
+    The p-value given is exact when the sample sizes are both less than
+    55 and there are no ties, otherwise a normal approximation for the
+    p-value is used.
+
+    References
+    ----------
+    .. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for
+           dispersions, Annals of Mathematical Statistics, 31, 1174-1189.
+    .. [2] Sprent, Peter and N.C. Smeeton.  Applied nonparametric
+           statistical methods.  3rd ed. Chapman and Hall/CRC. 2001.
+           Section 5.8.2.
+    .. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality
+           Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ansari
+    >>> rng = np.random.default_rng()
+
+    For these examples, we'll create three random data sets.  The first
+    two, with sizes 35 and 25, are drawn from a normal distribution with
+    mean 0 and standard deviation 2.  The third data set has size 25 and
+    is drawn from a normal distribution with standard deviation 1.25.
+
+    >>> x1 = rng.normal(loc=0, scale=2, size=35)
+    >>> x2 = rng.normal(loc=0, scale=2, size=25)
+    >>> x3 = rng.normal(loc=0, scale=1.25, size=25)
+
+    First we apply `ansari` to `x1` and `x2`.  These samples are drawn
+    from the same distribution, so we expect the Ansari-Bradley test
+    should not lead us to conclude that the scales of the distributions
+    are different.
+
+    >>> ansari(x1, x2)
+    AnsariResult(statistic=541.0, pvalue=0.9762532927399098)
+
+    With a p-value close to 1, we cannot conclude that there is a
+    significant difference in the scales (as expected).
+
+    Now apply the test to `x1` and `x3`:
+
+    >>> ansari(x1, x3)
+    AnsariResult(statistic=425.0, pvalue=0.0003087020407974518)
+
+    The probability of observing such an extreme value of the statistic
+    under the null hypothesis of equal scales is only 0.03087%. We take this
+    as evidence against the null hypothesis in favor of the alternative:
+    the scales of the distributions from which the samples were drawn
+    are not equal.
+
+    We can use the `alternative` parameter to perform a one-tailed test.
+    In the above example, the scale of `x1` is greater than `x3` and so
+    the ratio of scales of `x1` and `x3` is greater than 1. This means
+    that the p-value when ``alternative='greater'`` should be near 0 and
+    hence we should be able to reject the null hypothesis:
+
+    >>> ansari(x1, x3, alternative='greater')
+    AnsariResult(statistic=425.0, pvalue=0.0001543510203987259)
+
+    As we can see, the p-value is indeed quite low. Use of
+    ``alternative='less'`` should thus yield a large p-value:
+
+    >>> ansari(x1, x3, alternative='less')
+    AnsariResult(statistic=425.0, pvalue=0.9998643258449039)
+
+    """
+    if alternative not in {'two-sided', 'greater', 'less'}:
+        raise ValueError("'alternative' must be 'two-sided',"
+                         " 'greater', or 'less'.")
+
+    if not hasattr(_abw_state, 'a'):
+        _abw_state.a = _ABW()
+
+    x, y = asarray(x), asarray(y)
+    n = len(x)
+    m = len(y)
+    if m < 1:
+        raise ValueError("Not enough other observations.")
+    if n < 1:
+        raise ValueError("Not enough test observations.")
+
+    N = m + n
+    xy = r_[x, y]  # combine
+    rank = _stats_py.rankdata(xy)
+    symrank = amin(array((rank, N - rank + 1)), 0)
+    AB = np.sum(symrank[:n], axis=0)
+    uxy = unique(xy)
+    repeats = (len(uxy) != len(xy))
+    exact = ((m < 55) and (n < 55) and not repeats)
+    if repeats and (m < 55 or n < 55):
+        warnings.warn("Ties preclude use of exact statistic.", stacklevel=2)
+    if exact:
+        if alternative == 'two-sided':
+            pval = 2.0 * np.minimum(_abw_state.a.cdf(AB, n, m),
+                                    _abw_state.a.sf(AB, n, m))
+        elif alternative == 'greater':
+            # AB statistic is _smaller_ when ratio of scales is larger,
+            # so this is the opposite of the usual calculation
+            pval = _abw_state.a.cdf(AB, n, m)
+        else:
+            pval = _abw_state.a.sf(AB, n, m)
+        return AnsariResult(AB, min(1.0, pval))
+
+    # otherwise compute normal approximation
+    if N % 2:  # N odd
+        mnAB = n * (N+1.0)**2 / 4.0 / N
+        varAB = n * m * (N+1.0) * (3+N**2) / (48.0 * N**2)
+    else:
+        mnAB = n * (N+2.0) / 4.0
+        varAB = m * n * (N+2) * (N-2.0) / 48 / (N-1.0)
+    if repeats:   # adjust variance estimates
+        # compute np.sum(tj * rj**2,axis=0)
+        fac = np.sum(symrank**2, axis=0)
+        if N % 2:  # N odd
+            varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1))
+        else:  # N even
+            varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1))
+
+    # Small values of AB indicate larger dispersion for the x sample.
+    # Large values of AB indicate larger dispersion for the y sample.
+    # This is opposite to the way we define the ratio of scales. see [1]_.
+    z = (mnAB - AB) / sqrt(varAB)
+    pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    return AnsariResult(AB[()], pvalue[()])
+
+
+BartlettResult = namedtuple('BartlettResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(BartlettResult, n_samples=None)
+def bartlett(*samples, axis=0):
+    r"""Perform Bartlett's test for equal variances.
+
+    Bartlett's test tests the null hypothesis that all input samples
+    are from populations with equal variances.  For samples
+    from significantly non-normal populations, Levene's test
+    `levene` is more robust.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        arrays of sample data.  Only 1d arrays are accepted, they may have
+        different lengths.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value of the test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    levene : A robust parametric test for equality of k variances
+    :ref:`hypothesis_bartlett` : Extended example
+
+    Notes
+    -----
+    Conover et al. (1981) examine many of the existing parametric and
+    nonparametric tests by extensive simulations and they conclude that the
+    tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
+    superior in terms of robustness of departures from normality and power
+    ([3]_).
+
+    References
+    ----------
+    .. [1]  https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
+    .. [2]  Snedecor, George W. and Cochran, William G. (1989), Statistical
+              Methods, Eighth Edition, Iowa State University Press.
+    .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+    .. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
+           Tests. Proceedings of the Royal Society of London. Series A,
+           Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282.
+
+    Examples
+    --------
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.bartlett(a, b, c)
+    >>> p
+    1.1254782518834628e-05
+
+    The very small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_bartlett`.
+    """
+    xp = array_namespace(*samples)
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    samples = _broadcast_arrays(samples, axis=axis, xp=xp)
+    samples = [xp_moveaxis_to_end(sample, axis, xp=xp) for sample in samples]
+
+    Ni = [xp.asarray(sample.shape[-1], dtype=sample.dtype) for sample in samples]
+    Ni = [xp.broadcast_to(N, samples[0].shape[:-1]) for N in Ni]
+    ssq = [xp.var(sample, correction=1, axis=-1) for sample in samples]
+    Ni = [arr[xp.newaxis, ...] for arr in Ni]
+    ssq = [arr[xp.newaxis, ...] for arr in ssq]
+    Ni = xp.concat(Ni, axis=0)
+    ssq = xp.concat(ssq, axis=0)
+    # sum dtype can be removed when 2023.12 rules kick in
+    dtype = Ni.dtype
+    Ntot = xp.sum(Ni, axis=0, dtype=dtype)
+    spsq = xp.sum((Ni - 1)*ssq, axis=0, dtype=dtype) / (Ntot - k)
+    numer = ((Ntot - k) * xp.log(spsq)
+             - xp.sum((Ni - 1)*xp.log(ssq), axis=0, dtype=dtype))
+    denom = (1 + 1/(3*(k - 1))
+             * ((xp.sum(1/(Ni - 1), axis=0, dtype=dtype)) - 1/(Ntot - k)))
+    T = numer / denom
+
+    chi2 = _SimpleChi2(xp.asarray(k-1))
+    pvalue = _get_pvalue(T, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    T = xp.clip(T, min=0., max=xp.inf)
+    T = T[()] if T.ndim == 0 else T
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return BartlettResult(T, pvalue)
+
+
+LeveneResult = namedtuple('LeveneResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(LeveneResult, n_samples=None)
+def levene(*samples, center='median', proportiontocut=0.05):
+    r"""Perform Levene test for equal variances.
+
+    The Levene test tests the null hypothesis that all input samples
+    are from populations with equal variances.  Levene's test is an
+    alternative to Bartlett's test `bartlett` in the case where
+    there are significant deviations from normality.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample data, possibly with different lengths. Only one-dimensional
+        samples are accepted.
+    center : {'mean', 'median', 'trimmed'}, optional
+        Which function of the data to use in the test.  The default
+        is 'median'.
+    proportiontocut : float, optional
+        When `center` is 'trimmed', this gives the proportion of data points
+        to cut from each end. (See `scipy.stats.trim_mean`.)
+        Default is 0.05.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value for the test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    bartlett : A parametric test for equality of k variances in normal samples
+    :ref:`hypothesis_levene` : Extended example
+
+    Notes
+    -----
+    Three variations of Levene's test are possible.  The possibilities
+    and their recommended usages are:
+
+    * 'median' : Recommended for skewed (non-normal) distributions>
+    * 'mean' : Recommended for symmetric, moderate-tailed distributions.
+    * 'trimmed' : Recommended for heavy-tailed distributions.
+
+    The test version using the mean was proposed in the original article
+    of Levene ([2]_) while the median and trimmed mean have been studied by
+    Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe
+    test.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
+    .. [2] Levene, H. (1960). In Contributions to Probability and Statistics:
+           Essays in Honor of Harold Hotelling, I. Olkin et al. eds.,
+           Stanford University Press, pp. 278-292.
+    .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American
+           Statistical Association, 69, 364-367
+
+    Examples
+    --------
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.levene(a, b, c)
+    >>> p
+    0.002431505967249681
+
+    The small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_levene`.
+    """
+    if center not in ['mean', 'median', 'trimmed']:
+        raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    Ni = np.empty(k)
+    Yci = np.empty(k, 'd')
+
+    if center == 'median':
+
+        def func(x):
+            return np.median(x, axis=0)
+
+    elif center == 'mean':
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    else:  # center == 'trimmed'
+        samples = tuple(_stats_py.trimboth(np.sort(sample), proportiontocut)
+                        for sample in samples)
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    for j in range(k):
+        Ni[j] = len(samples[j])
+        Yci[j] = func(samples[j])
+    Ntot = np.sum(Ni, axis=0)
+
+    # compute Zij's
+    Zij = [None] * k
+    for i in range(k):
+        Zij[i] = abs(asarray(samples[i]) - Yci[i])
+
+    # compute Zbari
+    Zbari = np.empty(k, 'd')
+    Zbar = 0.0
+    for i in range(k):
+        Zbari[i] = np.mean(Zij[i], axis=0)
+        Zbar += Zbari[i] * Ni[i]
+
+    Zbar /= Ntot
+    numer = (Ntot - k) * np.sum(Ni * (Zbari - Zbar)**2, axis=0)
+
+    # compute denom_variance
+    dvar = 0.0
+    for i in range(k):
+        dvar += np.sum((Zij[i] - Zbari[i])**2, axis=0)
+
+    denom = (k - 1.0) * dvar
+
+    W = numer / denom
+    pval = distributions.f.sf(W, k-1, Ntot-k)  # 1 - cdf
+    return LeveneResult(W, pval)
+
+
+def _apply_func(x, g, func):
+    # g is list of indices into x
+    #  separating x into different groups
+    #  func should be applied over the groups
+    g = unique(r_[0, g, len(x)])
+    output = [func(x[g[k]:g[k+1]]) for k in range(len(g) - 1)]
+
+    return asarray(output)
+
+
+FlignerResult = namedtuple('FlignerResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(FlignerResult, n_samples=None)
+def fligner(*samples, center='median', proportiontocut=0.05):
+    r"""Perform Fligner-Killeen test for equality of variance.
+
+    Fligner's test tests the null hypothesis that all input samples
+    are from populations with equal variances.  Fligner-Killeen's test is
+    distribution free when populations are identical [2]_.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        Arrays of sample data.  Need not be the same length.
+    center : {'mean', 'median', 'trimmed'}, optional
+        Keyword argument controlling which function of the data is used in
+        computing the test statistic.  The default is 'median'.
+    proportiontocut : float, optional
+        When `center` is 'trimmed', this gives the proportion of data points
+        to cut from each end. (See `scipy.stats.trim_mean`.)
+        Default is 0.05.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    bartlett : A parametric test for equality of k variances in normal samples
+    levene : A robust parametric test for equality of k variances
+    :ref:`hypothesis_fligner` : Extended example
+
+    Notes
+    -----
+    As with Levene's test there are three variants of Fligner's test that
+    differ by the measure of central tendency used in the test.  See `levene`
+    for more information.
+
+    Conover et al. (1981) examine many of the existing parametric and
+    nonparametric tests by extensive simulations and they conclude that the
+    tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
+    superior in terms of robustness of departures from normality and power
+    [3]_.
+
+    References
+    ----------
+    .. [1] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+           https://cecas.clemson.edu/~cspark/cv/paper/qif/draftqif2.pdf
+    .. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample
+           tests for scale. Journal of the American Statistical Association.
+           71(353), 210-213.
+    .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+    .. [4] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A
+           comparative study of tests for homogeneity of variances, with
+           applications to the outer continental shelf bidding data.
+           Technometrics, 23(4), 351-361.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.fligner(a, b, c)
+    >>> p
+    0.00450826080004775
+
+    The small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_fligner`.
+    """
+    if center not in ['mean', 'median', 'trimmed']:
+        raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    # Handle empty input
+    for sample in samples:
+        if sample.size == 0:
+            NaN = _get_nan(*samples)
+            return FlignerResult(NaN, NaN)
+
+    if center == 'median':
+
+        def func(x):
+            return np.median(x, axis=0)
+
+    elif center == 'mean':
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    else:  # center == 'trimmed'
+        samples = tuple(_stats_py.trimboth(sample, proportiontocut)
+                        for sample in samples)
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    Ni = asarray([len(samples[j]) for j in range(k)])
+    Yci = asarray([func(samples[j]) for j in range(k)])
+    Ntot = np.sum(Ni, axis=0)
+    # compute Zij's
+    Zij = [abs(asarray(samples[i]) - Yci[i]) for i in range(k)]
+    allZij = []
+    g = [0]
+    for i in range(k):
+        allZij.extend(list(Zij[i]))
+        g.append(len(allZij))
+
+    ranks = _stats_py.rankdata(allZij)
+    sample = distributions.norm.ppf(ranks / (2*(Ntot + 1.0)) + 0.5)
+
+    # compute Aibar
+    Aibar = _apply_func(sample, g, np.sum) / Ni
+    anbar = np.mean(sample, axis=0)
+    varsq = np.var(sample, axis=0, ddof=1)
+    statistic = np.sum(Ni * (asarray(Aibar) - anbar)**2.0, axis=0) / varsq
+    chi2 = _SimpleChi2(k-1)
+    pval = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np)
+    return FlignerResult(statistic, pval)
+
+
+@_axis_nan_policy_factory(lambda x1: (x1,), n_samples=4, n_outputs=1)
+def _mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N) -> float:
+    # Obtain the unique values and their frequencies from the pooled samples.
+    # "a_j, + b_j, = t_j, for j = 1, ... k" where `k` is the number of unique
+    # classes, and "[t]he number of values associated with the x's and y's in
+    # the jth class will be denoted by a_j, and b_j respectively."
+    # (Mielke, 312)
+    # Reuse previously computed sorted array and `diff` arrays to obtain the
+    # unique values and counts. Prepend `diffs` with a non-zero to indicate
+    # that the first element should be marked as not matching what preceded it.
+    diffs_prep = np.concatenate(([1], diffs))
+    # Unique elements are where the was a difference between elements in the
+    # sorted array
+    uniques = sorted_xy[diffs_prep != 0]
+    # The count of each element is the bin size for each set of consecutive
+    # differences where the difference is zero. Replace nonzero differences
+    # with 1 and then use the cumulative sum to count the indices.
+    t = np.bincount(np.cumsum(np.asarray(diffs_prep != 0, dtype=int)))[1:]
+    k = len(uniques)
+    js = np.arange(1, k + 1, dtype=int)
+    # the `b` array mentioned in the paper is not used, outside of the
+    # calculation of `t`, so we do not need to calculate it separately. Here
+    # we calculate `a`. In plain language, `a[j]` is the number of values in
+    # `x` that equal `uniques[j]`.
+    sorted_xyx = np.sort(np.concatenate((xy, x)))
+    diffs = np.diff(sorted_xyx)
+    diffs_prep = np.concatenate(([1], diffs))
+    diff_is_zero = np.asarray(diffs_prep != 0, dtype=int)
+    xyx_counts = np.bincount(np.cumsum(diff_is_zero))[1:]
+    a = xyx_counts - t
+    # "Define .. a_0 = b_0 = t_0 = S_0 = 0" (Mielke 312) so we shift  `a`
+    # and `t` arrays over 1 to allow a first element of 0 to accommodate this
+    # indexing.
+    t = np.concatenate(([0], t))
+    a = np.concatenate(([0], a))
+    # S is built from `t`, so it does not need a preceding zero added on.
+    S = np.cumsum(t)
+    # define a copy of `S` with a prepending zero for later use to avoid
+    # the need for indexing.
+    S_i_m1 = np.concatenate(([0], S[:-1]))
+
+    # Psi, as defined by the 6th unnumbered equation on page 313 (Mielke).
+    # Note that in the paper there is an error where the denominator `2` is
+    # squared when it should be the entire equation.
+    def psi(indicator):
+        return (indicator - (N + 1)/2)**2
+
+    # define summation range for use in calculation of phi, as seen in sum
+    # in the unnumbered equation on the bottom of page 312 (Mielke).
+    s_lower = S[js - 1] + 1
+    s_upper = S[js] + 1
+    phi_J = [np.arange(s_lower[idx], s_upper[idx]) for idx in range(k)]
+
+    # for every range in the above array, determine the sum of psi(I) for
+    # every element in the range. Divide all the sums by `t`. Following the
+    # last unnumbered equation on page 312.
+    phis = [np.sum(psi(I_j)) for I_j in phi_J] / t[js]
+
+    # `T` is equal to a[j] * phi[j], per the first unnumbered equation on
+    # page 312. `phis` is already in the order based on `js`, so we index
+    # into `a` with `js` as well.
+    T = sum(phis * a[js])
+
+    # The approximate statistic
+    E_0_T = n * (N * N - 1) / 12
+
+    varM = (m * n * (N + 1.0) * (N ** 2 - 4) / 180 -
+            m * n / (180 * N * (N - 1)) * np.sum(
+                t * (t**2 - 1) * (t**2 - 4 + (15 * (N - S - S_i_m1) ** 2))
+            ))
+
+    return ((T - E_0_T) / np.sqrt(varM),)
+
+
+def _mood_too_small(samples, kwargs, axis=-1):
+    x, y = samples
+    n = x.shape[axis]
+    m = y.shape[axis]
+    N = m + n
+    return N < 3
+
+
+@_axis_nan_policy_factory(SignificanceResult, n_samples=2, too_small=_mood_too_small)
+def mood(x, y, axis=0, alternative="two-sided"):
+    """Perform Mood's test for equal scale parameters.
+
+    Mood's two-sample test for scale parameters is a non-parametric
+    test for the null hypothesis that two samples are drawn from the
+    same distribution with the same scale parameter.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of sample data. There must be at least three observations
+        total.
+    axis : int, optional
+        The axis along which the samples are tested.  `x` and `y` can be of
+        different length along `axis`.
+        If `axis` is None, `x` and `y` are flattened and the test is done on
+        all values in the flattened arrays.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the scales of the distributions underlying `x` and `y`
+          are different.
+        * 'less': the scale of the distribution underlying `x` is less than
+          the scale of the distribution underlying `y`.
+        * 'greater': the scale of the distribution underlying `x` is greater
+          than the scale of the distribution underlying `y`.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : scalar or ndarray
+            The z-score for the hypothesis test.  For 1-D inputs a scalar is
+            returned.
+        pvalue : scalar ndarray
+            The p-value for the hypothesis test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    ansari : A non-parametric test for the equality of 2 variances
+    bartlett : A parametric test for equality of k variances in normal samples
+    levene : A parametric test for equality of k variances
+
+    Notes
+    -----
+    The data are assumed to be drawn from probability distributions ``f(x)``
+    and ``f(x/s) / s`` respectively, for some probability density function f.
+    The null hypothesis is that ``s == 1``.
+
+    For multi-dimensional arrays, if the inputs are of shapes
+    ``(n0, n1, n2, n3)``  and ``(n0, m1, n2, n3)``, then if ``axis=1``, the
+    resulting z and p values will have shape ``(n0, n2, n3)``.  Note that
+    ``n1`` and ``m1`` don't have to be equal, but the other dimensions do.
+
+    References
+    ----------
+    [1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties."
+        Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR,
+        https://doi.org/10.2307/1266427. Accessed 18 May 2022.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x2 = rng.standard_normal((2, 45, 6, 7))
+    >>> x1 = rng.standard_normal((2, 30, 6, 7))
+    >>> res = stats.mood(x1, x2, axis=1)
+    >>> res.pvalue.shape
+    (2, 6, 7)
+
+    Find the number of points where the difference in scale is not significant:
+
+    >>> (res.pvalue > 0.1).sum()
+    78
+
+    Perform the test with different scales:
+
+    >>> x1 = rng.standard_normal((2, 30))
+    >>> x2 = rng.standard_normal((2, 35)) * 10.0
+    >>> stats.mood(x1, x2, axis=1)
+    SignificanceResult(statistic=array([-5.76174136, -6.12650783]),
+                       pvalue=array([8.32505043e-09, 8.98287869e-10]))
+
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if axis < 0:
+        axis = x.ndim + axis
+
+    # Determine shape of the result arrays
+    res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis])
+    if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if
+                                ax != axis])):
+        raise ValueError("Dimensions of x and y on all axes except `axis` "
+                         "should match")
+
+    n = x.shape[axis]
+    m = y.shape[axis]
+    N = m + n
+    if N < 3:
+        raise ValueError("Not enough observations.")
+
+    xy = np.concatenate((x, y), axis=axis)
+    # determine if any of the samples contain ties
+    sorted_xy = np.sort(xy, axis=axis)
+    diffs = np.diff(sorted_xy, axis=axis)
+    if 0 in diffs:
+        z = np.asarray(_mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N,
+                                      axis=axis))
+    else:
+        if axis != 0:
+            xy = np.moveaxis(xy, axis, 0)
+
+        xy = xy.reshape(xy.shape[0], -1)
+        # Generalized to the n-dimensional case by adding the axis argument,
+        # and using for loops, since rankdata is not vectorized.  For improving
+        # performance consider vectorizing rankdata function.
+        all_ranks = np.empty_like(xy)
+        for j in range(xy.shape[1]):
+            all_ranks[:, j] = _stats_py.rankdata(xy[:, j])
+
+        Ri = all_ranks[:n]
+        M = np.sum((Ri - (N + 1.0) / 2) ** 2, axis=0)
+        # Approx stat.
+        mnM = n * (N * N - 1.0) / 12
+        varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180
+        z = (M - mnM) / sqrt(varM)
+    pval = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+
+    if res_shape == ():
+        # Return scalars, not 0-D arrays
+        z = z[0]
+        pval = pval[0]
+    else:
+        z.shape = res_shape
+        pval.shape = res_shape
+    return SignificanceResult(z[()], pval[()])
+
+
+WilcoxonResult = _make_tuple_bunch('WilcoxonResult', ['statistic', 'pvalue'])
+
+
+def wilcoxon_result_unpacker(res):
+    if hasattr(res, 'zstatistic'):
+        return res.statistic, res.pvalue, res.zstatistic
+    else:
+        return res.statistic, res.pvalue
+
+
+def wilcoxon_result_object(statistic, pvalue, zstatistic=None):
+    res = WilcoxonResult(statistic, pvalue)
+    if zstatistic is not None:
+        res.zstatistic = zstatistic
+    return res
+
+
+def wilcoxon_outputs(kwds):
+    method = kwds.get('method', 'auto')
+    if method == 'asymptotic':
+        return 3
+    return 2
+
+
+@_rename_parameter("mode", "method")
+@_axis_nan_policy_factory(
+    wilcoxon_result_object, paired=True,
+    n_samples=lambda kwds: 2 if kwds.get('y', None) is not None else 1,
+    result_to_tuple=wilcoxon_result_unpacker, n_outputs=wilcoxon_outputs,
+)
+def wilcoxon(x, y=None, zero_method="wilcox", correction=False,
+             alternative="two-sided", method='auto', *, axis=0):
+    """Calculate the Wilcoxon signed-rank test.
+
+    The Wilcoxon signed-rank test tests the null hypothesis that two
+    related paired samples come from the same distribution. In particular,
+    it tests whether the distribution of the differences ``x - y`` is symmetric
+    about zero. It is a non-parametric version of the paired T-test.
+
+    Parameters
+    ----------
+    x : array_like
+        Either the first set of measurements (in which case ``y`` is the second
+        set of measurements), or the differences between two sets of
+        measurements (in which case ``y`` is not to be specified.)  Must be
+        one-dimensional.
+    y : array_like, optional
+        Either the second set of measurements (if ``x`` is the first set of
+        measurements), or not specified (if ``x`` is the differences between
+        two sets of measurements.)  Must be one-dimensional.
+
+        .. warning::
+            When `y` is provided, `wilcoxon` calculates the test statistic
+            based on the ranks of the absolute values of ``d = x - y``.
+            Roundoff error in the subtraction can result in elements of ``d``
+            being assigned different ranks even when they would be tied with
+            exact arithmetic. Rather than passing `x` and `y` separately,
+            consider computing the difference ``x - y``, rounding as needed to
+            ensure that only truly unique elements are numerically distinct,
+            and passing the result as `x`, leaving `y` at the default (None).
+
+    zero_method : {"wilcox", "pratt", "zsplit"}, optional
+        There are different conventions for handling pairs of observations
+        with equal values ("zero-differences", or "zeros").
+
+        * "wilcox": Discards all zero-differences (default); see [4]_.
+        * "pratt": Includes zero-differences in the ranking process,
+          but drops the ranks of the zeros (more conservative); see [3]_.
+          In this case, the normal approximation is adjusted as in [5]_.
+        * "zsplit": Includes zero-differences in the ranking process and
+          splits the zero rank between positive and negative ones.
+
+    correction : bool, optional
+        If True, apply continuity correction by adjusting the Wilcoxon rank
+        statistic by 0.5 towards the mean value when computing the
+        z-statistic if a normal approximation is used.  Default is False.
+    alternative : {"two-sided", "greater", "less"}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        In the following, let ``d`` represent the difference between the paired
+        samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or
+        ``d = x`` otherwise.
+
+        * 'two-sided': the distribution underlying ``d`` is not symmetric
+          about zero.
+        * 'less': the distribution underlying ``d`` is stochastically less
+          than a distribution symmetric about zero.
+        * 'greater': the distribution underlying ``d`` is stochastically
+          greater than a distribution symmetric about zero.
+
+    method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional
+        Method to calculate the p-value, see Notes. Default is "auto".
+
+    axis : int or None, default: 0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    An object with the following attributes.
+
+    statistic : array_like
+        If `alternative` is "two-sided", the sum of the ranks of the
+        differences above or below zero, whichever is smaller.
+        Otherwise the sum of the ranks of the differences above zero.
+    pvalue : array_like
+        The p-value for the test depending on `alternative` and `method`.
+    zstatistic : array_like
+        When ``method = 'asymptotic'``, this is the normalized z-statistic::
+
+            z = (T - mn - d) / se
+
+        where ``T`` is `statistic` as defined above, ``mn`` is the mean of the
+        distribution under the null hypothesis, ``d`` is a continuity
+        correction, and ``se`` is the standard error.
+        When ``method != 'asymptotic'``, this attribute is not available.
+
+    See Also
+    --------
+    kruskal, mannwhitneyu
+
+    Notes
+    -----
+    In the following, let ``d`` represent the difference between the paired
+    samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x``
+    otherwise. Assume that all elements of ``d`` are independent and
+    identically distributed observations, and all are distinct and nonzero.
+
+    - When ``len(d)`` is sufficiently large, the null distribution of the
+      normalized test statistic (`zstatistic` above) is approximately normal,
+      and ``method = 'asymptotic'`` can be used to compute the p-value.
+
+    - When ``len(d)`` is small, the normal approximation may not be accurate,
+      and ``method='exact'`` is preferred (at the cost of additional
+      execution time).
+
+    - The default, ``method='auto'``, selects between the two:
+      ``method='exact'`` is used when ``len(d) <= 50``, and
+      ``method='asymptotic'`` is used otherwise.
+
+    The presence of "ties" (i.e. not all elements of ``d`` are unique) or
+    "zeros" (i.e. elements of ``d`` are zero) changes the null distribution
+    of the test statistic, and ``method='exact'`` no longer calculates
+    the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted
+    for more accurate comparison against the standard normal, but still,
+    for finite sample sizes, the standard normal is only an approximation of
+    the true null distribution of the z-statistic. For such situations, the
+    `method` parameter also accepts instances of `PermutationMethod`. In this
+    case, the p-value is computed using `permutation_test` with the provided
+    configuration options and other appropriate settings.
+
+    The presence of ties and zeros affects the resolution of ``method='auto'``
+    accordingly: exhasutive permutations are performed when ``len(d) <= 13``,
+    and the asymptotic method is used otherwise. Note that they asymptotic
+    method may not be very accurate even for ``len(d) > 14``; the threshold
+    was chosen as a compromise between execution time and accuracy under the
+    constraint that the results must be deterministic. Consider providing an
+    instance of `PermutationMethod` method manually, choosing the
+    ``n_resamples`` parameter to balance time constraints and accuracy
+    requirements.
+
+    Please also note that in the edge case that all elements of ``d`` are zero,
+    the p-value relying on the normal approximaton cannot be computed (NaN)
+    if ``zero_method='wilcox'`` or ``zero_method='pratt'``.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test
+    .. [2] Conover, W.J., Practical Nonparametric Statistics, 1971.
+    .. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed
+       Rank Procedures, Journal of the American Statistical Association,
+       Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526`
+    .. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods,
+       Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968`
+    .. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank
+       Sampling Distribution When Zero Differences are Present,
+       Journal of the American Statistical Association, Vol. 62, 1967,
+       pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917`
+
+    Examples
+    --------
+    In [4]_, the differences in height between cross- and self-fertilized
+    corn plants is given as follows:
+
+    >>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]
+
+    Cross-fertilized plants appear to be higher. To test the null
+    hypothesis that there is no height difference, we can apply the
+    two-sided test:
+
+    >>> from scipy.stats import wilcoxon
+    >>> res = wilcoxon(d)
+    >>> res.statistic, res.pvalue
+    (24.0, 0.041259765625)
+
+    Hence, we would reject the null hypothesis at a confidence level of 5%,
+    concluding that there is a difference in height between the groups.
+    To confirm that the median of the differences can be assumed to be
+    positive, we use:
+
+    >>> res = wilcoxon(d, alternative='greater')
+    >>> res.statistic, res.pvalue
+    (96.0, 0.0206298828125)
+
+    This shows that the null hypothesis that the median is negative can be
+    rejected at a confidence level of 5% in favor of the alternative that
+    the median is greater than zero. The p-values above are exact. Using the
+    normal approximation gives very similar values:
+
+    >>> res = wilcoxon(d, method='asymptotic')
+    >>> res.statistic, res.pvalue
+    (24.0, 0.04088813291185591)
+
+    Note that the statistic changed to 96 in the one-sided case (the sum
+    of ranks of positive differences) whereas it is 24 in the two-sided
+    case (the minimum of sum of ranks above and below zero).
+
+    In the example above, the differences in height between paired plants are
+    provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two
+    samples of equal length, calculates the differences between paired
+    elements, then performs the test. Consider the samples ``x`` and ``y``:
+
+    >>> import numpy as np
+    >>> x = np.array([0.5, 0.825, 0.375, 0.5])
+    >>> y = np.array([0.525, 0.775, 0.325, 0.55])
+    >>> res = wilcoxon(x, y, alternative='greater')
+    >>> res
+    WilcoxonResult(statistic=5.0, pvalue=0.5625)
+
+    Note that had we calculated the differences by hand, the test would have
+    produced different results:
+
+    >>> d = [-0.025, 0.05, 0.05, -0.05]
+    >>> ref = wilcoxon(d, alternative='greater')
+    >>> ref
+    WilcoxonResult(statistic=6.0, pvalue=0.5)
+
+    The substantial difference is due to roundoff error in the results of
+    ``x-y``:
+
+    >>> d - (x-y)
+    array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17])
+
+    Even though we expected all the elements of ``(x-y)[1:]`` to have the same
+    magnitude ``0.05``, they have slightly different magnitudes in practice,
+    and therefore are assigned different ranks in the test. Before performing
+    the test, consider calculating ``d`` and adjusting it as necessary to
+    ensure that theoretically identically values are not numerically distinct.
+    For example:
+
+    >>> d2 = np.around(x - y, decimals=3)
+    >>> wilcoxon(d2, alternative='greater')
+    WilcoxonResult(statistic=6.0, pvalue=0.5)
+
+    """
+    # replace approx by asymptotic to ensure backwards compatability
+    if method == "approx":
+        method = "asymptotic"
+    return _wilcoxon._wilcoxon_nd(x, y, zero_method, correction, alternative,
+                                  method, axis)
+
+
+MedianTestResult = _make_tuple_bunch(
+    'MedianTestResult',
+    ['statistic', 'pvalue', 'median', 'table'], []
+)
+
+
+def median_test(*samples, ties='below', correction=True, lambda_=1,
+                nan_policy='propagate'):
+    """Perform a Mood's median test.
+
+    Test that two or more samples come from populations with the same median.
+
+    Let ``n = len(samples)`` be the number of samples.  The "grand median" of
+    all the data is computed, and a contingency table is formed by
+    classifying the values in each sample as being above or below the grand
+    median.  The contingency table, along with `correction` and `lambda_`,
+    are passed to `scipy.stats.chi2_contingency` to compute the test statistic
+    and p-value.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The set of samples.  There must be at least two samples.
+        Each sample must be a one-dimensional sequence containing at least
+        one value.  The samples are not required to have the same length.
+    ties : str, optional
+        Determines how values equal to the grand median are classified in
+        the contingency table.  The string must be one of::
+
+            "below":
+                Values equal to the grand median are counted as "below".
+            "above":
+                Values equal to the grand median are counted as "above".
+            "ignore":
+                Values equal to the grand median are not counted.
+
+        The default is "below".
+    correction : bool, optional
+        If True, *and* there are just two samples, apply Yates' correction
+        for continuity when computing the test statistic associated with
+        the contingency table.  Default is True.
+    lambda_ : float or str, optional
+        By default, the statistic computed in this test is Pearson's
+        chi-squared statistic.  `lambda_` allows a statistic from the
+        Cressie-Read power divergence family to be used instead.  See
+        `power_divergence` for details.
+        Default is 1 (Pearson's chi-squared statistic).
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+
+    Returns
+    -------
+    res : MedianTestResult
+        An object containing attributes:
+
+        statistic : float
+            The test statistic.  The statistic that is returned is determined
+            by `lambda_`.  The default is Pearson's chi-squared statistic.
+        pvalue : float
+            The p-value of the test.
+        median : float
+            The grand median.
+        table : ndarray
+            The contingency table.  The shape of the table is (2, n), where
+            n is the number of samples.  The first row holds the counts of the
+            values above the grand median, and the second row holds the counts
+            of the values below the grand median.  The table allows further
+            analysis with, for example, `scipy.stats.chi2_contingency`, or with
+            `scipy.stats.fisher_exact` if there are two samples, without having
+            to recompute the table.  If ``nan_policy`` is "propagate" and there
+            are nans in the input, the return value for ``table`` is ``None``.
+
+    See Also
+    --------
+    kruskal : Compute the Kruskal-Wallis H-test for independent samples.
+    mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y.
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill
+        (1950), pp. 394-399.
+    .. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010).
+        See Sections 8.12 and 10.15.
+
+    Examples
+    --------
+    A biologist runs an experiment in which there are three groups of plants.
+    Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants.
+    Each plant produces a number of seeds.  The seed counts for each group
+    are::
+
+        Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49
+        Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99
+        Group 3:  0  3  9 22 23 25 25 33 34 34 40 45 46 48 62 67 84
+
+    The following code applies Mood's median test to these samples.
+
+    >>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49]
+    >>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99]
+    >>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84]
+    >>> from scipy.stats import median_test
+    >>> res = median_test(g1, g2, g3)
+
+    The median is
+
+    >>> res.median
+    34.0
+
+    and the contingency table is
+
+    >>> res.table
+    array([[ 5, 10,  7],
+           [11,  5, 10]])
+
+    `p` is too large to conclude that the medians are not the same:
+
+    >>> res.pvalue
+    0.12609082774093244
+
+    The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to
+    `median_test`.
+
+    >>> res = median_test(g1, g2, g3, lambda_="log-likelihood")
+    >>> res.pvalue
+    0.12224779737117837
+
+    The median occurs several times in the data, so we'll get a different
+    result if, for example, ``ties="above"`` is used:
+
+    >>> res = median_test(g1, g2, g3, ties="above")
+    >>> res.pvalue
+    0.063873276069553273
+
+    >>> res.table
+    array([[ 5, 11,  9],
+           [11,  4,  8]])
+
+    This example demonstrates that if the data set is not large and there
+    are values equal to the median, the p-value can be sensitive to the
+    choice of `ties`.
+
+    """
+    if len(samples) < 2:
+        raise ValueError('median_test requires two or more samples.')
+
+    ties_options = ['below', 'above', 'ignore']
+    if ties not in ties_options:
+        raise ValueError(f"invalid 'ties' option '{ties}'; 'ties' must be one "
+                         f"of: {str(ties_options)[1:-1]}")
+
+    data = [np.asarray(sample) for sample in samples]
+
+    # Validate the sizes and shapes of the arguments.
+    for k, d in enumerate(data):
+        if d.size == 0:
+            raise ValueError("Sample %d is empty. All samples must "
+                             "contain at least one value." % (k + 1))
+        if d.ndim != 1:
+            raise ValueError("Sample %d has %d dimensions.  All "
+                             "samples must be one-dimensional sequences." %
+                             (k + 1, d.ndim))
+
+    cdata = np.concatenate(data)
+    contains_nan, nan_policy = _contains_nan(cdata, nan_policy)
+    if contains_nan and nan_policy == 'propagate':
+        return MedianTestResult(np.nan, np.nan, np.nan, None)
+
+    if contains_nan:
+        grand_median = np.median(cdata[~np.isnan(cdata)])
+    else:
+        grand_median = np.median(cdata)
+    # When the minimum version of numpy supported by scipy is 1.9.0,
+    # the above if/else statement can be replaced by the single line:
+    #     grand_median = np.nanmedian(cdata)
+
+    # Create the contingency table.
+    table = np.zeros((2, len(data)), dtype=np.int64)
+    for k, sample in enumerate(data):
+        sample = sample[~np.isnan(sample)]
+
+        nabove = count_nonzero(sample > grand_median)
+        nbelow = count_nonzero(sample < grand_median)
+        nequal = sample.size - (nabove + nbelow)
+        table[0, k] += nabove
+        table[1, k] += nbelow
+        if ties == "below":
+            table[1, k] += nequal
+        elif ties == "above":
+            table[0, k] += nequal
+
+    # Check that no row or column of the table is all zero.
+    # Such a table can not be given to chi2_contingency, because it would have
+    # a zero in the table of expected frequencies.
+    rowsums = table.sum(axis=1)
+    if rowsums[0] == 0:
+        raise ValueError(f"All values are below the grand median ({grand_median}).")
+    if rowsums[1] == 0:
+        raise ValueError(f"All values are above the grand median ({grand_median}).")
+    if ties == "ignore":
+        # We already checked that each sample has at least one value, but it
+        # is possible that all those values equal the grand median.  If `ties`
+        # is "ignore", that would result in a column of zeros in `table`.  We
+        # check for that case here.
+        zero_cols = np.nonzero((table == 0).all(axis=0))[0]
+        if len(zero_cols) > 0:
+            msg = ("All values in sample %d are equal to the grand "
+                   "median (%r), so they are ignored, resulting in an "
+                   "empty sample." % (zero_cols[0] + 1, grand_median))
+            raise ValueError(msg)
+
+    stat, p, dof, expected = chi2_contingency(table, lambda_=lambda_,
+                                              correction=correction)
+    return MedianTestResult(stat, p, grand_median, table)
+
+
+def _circfuncs_common(samples, period, xp=None):
+    xp = array_namespace(samples) if xp is None else xp
+
+    if xp.isdtype(samples.dtype, 'integral'):
+        dtype = xp.asarray(1.).dtype  # get default float type
+        samples = xp.asarray(samples, dtype=dtype)
+
+    # Recast samples as radians that range between 0 and 2 pi and calculate
+    # the sine and cosine
+    scaled_samples = samples * ((2.0 * pi) / period)
+    sin_samp = xp.sin(scaled_samples)
+    cos_samp = xp.cos(scaled_samples)
+
+    return samples, sin_samp, cos_samp
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circmean(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
+    r"""Compute the circular mean of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4)
+
+    .. math::
+
+       \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right)
+
+    where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z`
+    gives the principal value of the argument of complex number :math:`z`,
+    restricted to the range :math:`[0,2\pi]` by default.  :math:`z` in the
+    above expression is known as the `mean resultant vector`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+
+    Returns
+    -------
+    circmean : float
+        Circular mean, restricted to the range ``[low, high]``.
+
+        If the mean resultant vector is zero, an input-dependent,
+        implementation-defined number between ``[low, high]`` is returned.
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circstd : Circular standard deviation.
+    circvar : Circular variance.
+
+    References
+    ----------
+    .. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    For readability, all angles are printed out in degrees.
+
+    >>> import numpy as np
+    >>> from scipy.stats import circmean
+    >>> import matplotlib.pyplot as plt
+    >>> angles = np.deg2rad(np.array([20, 30, 330]))
+    >>> circmean = circmean(angles)
+    >>> np.rad2deg(circmean)
+    7.294976657784009
+
+    >>> mean = angles.mean()
+    >>> np.rad2deg(mean)
+    126.66666666666666
+
+    Plot and compare the circular mean against the arithmetic mean.
+
+    >>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...          np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...          c='k')
+    >>> plt.scatter(np.cos(angles), np.sin(angles), c='k')
+    >>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b',
+    ...             label='circmean')
+    >>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean')
+    >>> plt.legend()
+    >>> plt.axis('equal')
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    # Needed for non-NumPy arrays to get appropriate NaN result
+    # Apparently atan2(0, 0) is 0, even though it is mathematically undefined
+    if xp_size(samples) == 0:
+        return xp.mean(samples, axis=axis)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_sum = xp.sum(sin_samp, axis=axis)
+    cos_sum = xp.sum(cos_samp, axis=axis)
+    res = xp.atan2(sin_sum, cos_sum)
+
+    res = res[()] if res.ndim == 0 else res
+    return (res * (period / (2.0 * pi)) - low) % period + low
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circvar(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
+    r"""Compute the circular variance of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3)
+
+    .. math::
+
+       1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right|
+
+    where :math:`i` is the imaginary unit and :math:`|z|` gives the length
+    of the complex number :math:`z`.  :math:`|z|` in the above expression
+    is known as the `mean resultant length`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+
+    Returns
+    -------
+    circvar : float
+        Circular variance.  The returned value is in the range ``[0, 1]``,
+        where ``0`` indicates no variance and ``1`` indicates large variance.
+
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circmean : Circular mean.
+    circstd : Circular standard deviation.
+
+    Notes
+    -----
+    In the limit of small angles, the circular variance is close to
+    half the 'linear' variance if measured in radians.
+
+    References
+    ----------
+    .. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge
+           University Press, 1993.
+    .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import circvar
+    >>> import matplotlib.pyplot as plt
+    >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
+    ...                       0.133, -0.473, -0.001, -0.348, 0.131])
+    >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
+    ...                       0.104, -0.136, -0.867,  0.012,  0.105])
+    >>> circvar_1 = circvar(samples_1)
+    >>> circvar_2 = circvar(samples_2)
+
+    Plot the samples.
+
+    >>> fig, (left, right) = plt.subplots(ncols=2)
+    >>> for image in (left, right):
+    ...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...                np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...                c='k')
+    ...     image.axis('equal')
+    ...     image.axis('off')
+    >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
+    >>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}")
+    >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
+    >>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}")
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_mean = xp.mean(sin_samp, axis=axis)
+    cos_mean = xp.mean(cos_samp, axis=axis)
+    hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
+    # hypotenuse can go slightly above 1 due to rounding errors
+    R = xp.clip(hypotenuse, max=1.)
+
+    res = 1. - R
+    return res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circstd(samples, high=2*pi, low=0, axis=None, nan_policy='propagate', *,
+            normalize=False):
+    r"""
+    Compute the circular standard deviation of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their `circular standard deviation` is defined by
+    ([2]_, Eq. 2.3.11)
+
+    .. math::
+
+       \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| }
+
+    where :math:`i` is the imaginary unit and :math:`|z|` gives the length
+    of the complex number :math:`z`.  :math:`|z|` in the above expression
+    is known as the `mean resultant length`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+    normalize : boolean, optional
+        If ``False`` (the default), the return value is computed from the
+        above formula with the input scaled by ``(2*pi)/(high-low)`` and
+        the output scaled (back) by ``(high-low)/(2*pi)``.  If ``True``,
+        the output is not scaled and is returned directly.
+
+    Returns
+    -------
+    circstd : float
+        Circular standard deviation, optionally normalized.
+
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circmean : Circular mean.
+    circvar : Circular variance.
+
+    Notes
+    -----
+    In the limit of small angles, the circular standard deviation is close
+    to the 'linear' standard deviation if ``normalize`` is ``False``.
+
+    References
+    ----------
+    .. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data*
+       (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`.
+    .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import circstd
+    >>> import matplotlib.pyplot as plt
+    >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
+    ...                       0.133, -0.473, -0.001, -0.348, 0.131])
+    >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
+    ...                       0.104, -0.136, -0.867,  0.012,  0.105])
+    >>> circstd_1 = circstd(samples_1)
+    >>> circstd_2 = circstd(samples_2)
+
+    Plot the samples.
+
+    >>> fig, (left, right) = plt.subplots(ncols=2)
+    >>> for image in (left, right):
+    ...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...                np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...                c='k')
+    ...     image.axis('equal')
+    ...     image.axis('off')
+    >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
+    >>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}")
+    >>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...            np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...            c='k')
+    >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
+    >>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}")
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_mean = xp.mean(sin_samp, axis=axis)  # [1] (2.2.3)
+    cos_mean = xp.mean(cos_samp, axis=axis)  # [1] (2.2.3)
+    hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
+    # hypotenuse can go slightly above 1 due to rounding errors
+    R = xp.clip(hypotenuse, max=1.)  # [1] (2.2.4)
+
+    res = (-2*xp.log(R))**0.5+0.0  # torch.pow returns -0.0 if R==1
+    if not normalize:
+        res *= (high-low)/(2.*pi)  # [1] (2.3.14) w/ (2.3.7)
+    return res
+
+
+class DirectionalStats:
+    def __init__(self, mean_direction, mean_resultant_length):
+        self.mean_direction = mean_direction
+        self.mean_resultant_length = mean_resultant_length
+
+    def __repr__(self):
+        return (f"DirectionalStats(mean_direction={self.mean_direction},"
+                f" mean_resultant_length={self.mean_resultant_length})")
+
+
+def directional_stats(samples, *, axis=0, normalize=True):
+    """
+    Computes sample statistics for directional data.
+
+    Computes the directional mean (also called the mean direction vector) and
+    mean resultant length of a sample of vectors.
+
+    The directional mean is a measure of "preferred direction" of vector data.
+    It is analogous to the sample mean, but it is for use when the length of
+    the data is irrelevant (e.g. unit vectors).
+
+    The mean resultant length is a value between 0 and 1 used to quantify the
+    dispersion of directional data: the smaller the mean resultant length, the
+    greater the dispersion. Several definitions of directional variance
+    involving the mean resultant length are given in [1]_ and [2]_.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array. Must be at least two-dimensional, and the last axis of the
+        input must correspond with the dimensionality of the vector space.
+        When the input is exactly two dimensional, this means that each row
+        of the data is a vector observation.
+    axis : int, default: 0
+        Axis along which the directional mean is computed.
+    normalize: boolean, default: True
+        If True, normalize the input to ensure that each observation is a
+        unit vector. It the observations are already unit vectors, consider
+        setting this to False to avoid unnecessary computation.
+
+    Returns
+    -------
+    res : DirectionalStats
+        An object containing attributes:
+
+        mean_direction : ndarray
+            Directional mean.
+        mean_resultant_length : ndarray
+            The mean resultant length [1]_.
+
+    See Also
+    --------
+    circmean: circular mean; i.e. directional mean for 2D *angles*
+    circvar: circular variance; i.e. directional variance for 2D *angles*
+
+    Notes
+    -----
+    This uses a definition of directional mean from [1]_.
+    Assuming the observations are unit vectors, the calculation is as follows.
+
+    .. code-block:: python
+
+        mean = samples.mean(axis=0)
+        mean_resultant_length = np.linalg.norm(mean)
+        mean_direction = mean / mean_resultant_length
+
+    This definition is appropriate for *directional* data (i.e. vector data
+    for which the magnitude of each observation is irrelevant) but not
+    for *axial* data (i.e. vector data for which the magnitude and *sign* of
+    each observation is irrelevant).
+
+    Several definitions of directional variance involving the mean resultant
+    length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2``
+    [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function
+    returns ``R`` as attribute `mean_resultant_length` so the user can compute
+    their preferred measure of dispersion.
+
+    References
+    ----------
+    .. [1] Mardia, Jupp. (2000). *Directional Statistics*
+       (p. 163). Wiley.
+
+    .. [2] https://en.wikipedia.org/wiki/Directional_statistics
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import directional_stats
+    >>> data = np.array([[3, 4],    # first observation, 2D vector space
+    ...                  [6, -8]])  # second observation
+    >>> dirstats = directional_stats(data)
+    >>> dirstats.mean_direction
+    array([1., 0.])
+
+    In contrast, the regular sample mean of the vectors would be influenced
+    by the magnitude of each observation. Furthermore, the result would not be
+    a unit vector.
+
+    >>> data.mean(axis=0)
+    array([4.5, -2.])
+
+    An exemplary use case for `directional_stats` is to find a *meaningful*
+    center for a set of observations on a sphere, e.g. geographical locations.
+
+    >>> data = np.array([[0.8660254, 0.5, 0.],
+    ...                  [0.8660254, -0.5, 0.]])
+    >>> dirstats = directional_stats(data)
+    >>> dirstats.mean_direction
+    array([1., 0., 0.])
+
+    The regular sample mean on the other hand yields a result which does not
+    lie on the surface of the sphere.
+
+    >>> data.mean(axis=0)
+    array([0.8660254, 0., 0.])
+
+    The function also returns the mean resultant length, which
+    can be used to calculate a directional variance. For example, using the
+    definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the
+    mean resultant length, we can calculate the directional variance of the
+    vectors in the above example as:
+
+    >>> 1 - dirstats.mean_resultant_length
+    0.13397459716167093
+    """
+    xp = array_namespace(samples)
+    samples = xp.asarray(samples)
+
+    if samples.ndim < 2:
+        raise ValueError("samples must at least be two-dimensional. "
+                         f"Instead samples has shape: {tuple(samples.shape)}")
+    samples = xp.moveaxis(samples, axis, 0)
+    if normalize:
+        vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp)
+        samples = samples/vectornorms
+    mean = xp.mean(samples, axis=0)
+    mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp)
+    mean_direction = mean / mean_resultant_length
+    mrl = xp.squeeze(mean_resultant_length, axis=-1)
+    mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl
+    return DirectionalStats(mean_direction, mean_resultant_length)
+
+
+def false_discovery_control(ps, *, axis=0, method='bh'):
+    """Adjust p-values to control the false discovery rate.
+
+    The false discovery rate (FDR) is the expected proportion of rejected null
+    hypotheses that are actually true.
+    If the null hypothesis is rejected when the *adjusted* p-value falls below
+    a specified level, the false discovery rate is controlled at that level.
+
+    Parameters
+    ----------
+    ps : 1D array_like
+        The p-values to adjust. Elements must be real numbers between 0 and 1.
+    axis : int
+        The axis along which to perform the adjustment. The adjustment is
+        performed independently along each axis-slice. If `axis` is None, `ps`
+        is raveled before performing the adjustment.
+    method : {'bh', 'by'}
+        The false discovery rate control procedure to apply: ``'bh'`` is for
+        Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli
+        [2]_ (Theorem 1.3). The latter is more conservative, but it is
+        guaranteed to control the FDR even when the p-values are not from
+        independent tests.
+
+    Returns
+    -------
+    ps_adusted : array_like
+        The adjusted p-values. If the null hypothesis is rejected where these
+        fall below a specified level, the false discovery rate is controlled
+        at that level.
+
+    See Also
+    --------
+    combine_pvalues
+    statsmodels.stats.multitest.multipletests
+
+    Notes
+    -----
+    In multiple hypothesis testing, false discovery control procedures tend to
+    offer higher power than familywise error rate control procedures (e.g.
+    Bonferroni correction [1]_).
+
+    If the p-values correspond with independent tests (or tests with
+    "positive regression dependencies" [2]_), rejecting null hypotheses
+    corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q`
+    controls the false discovery rate at a level less than or equal to
+    :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses
+    and :math:`m` is the total number of null hypotheses tested. The same is
+    true even for dependent tests when the p-values are adjusted accorded to
+    the more conservative Benjaminini-Yekutieli procedure.
+
+    The adjusted p-values produced by this function are comparable to those
+    produced by the R function ``p.adjust`` and the statsmodels function
+    `statsmodels.stats.multitest.multipletests`. Please consider the latter
+    for more advanced methods of multiple comparison correction.
+
+    References
+    ----------
+    .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false
+           discovery rate: a practical and powerful approach to multiple
+           testing." Journal of the Royal statistical society: series B
+           (Methodological) 57.1 (1995): 289-300.
+
+    .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false
+           discovery rate in multiple testing under dependency." Annals of
+           statistics (2001): 1165-1188.
+
+    .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube.
+           https://www.youtube.com/watch?v=rZKa4tW2NKs.
+
+    .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute
+           myocardial infarction with front-loaded administration of alteplase:
+           results of the rt-PA-APSAC patency study (TAPS)." Journal of the
+           American College of Cardiology 19.5 (1992): 885-891.
+
+    Examples
+    --------
+    We follow the example from [1]_.
+
+        Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA)
+        and anisoylated plasminogen streptokinase activator (APSAC) in
+        myocardial infarction has been proved to reduce mortality. [4]_
+        investigated the effects of a new front-loaded administration of rt-PA
+        versus those obtained with a standard regimen of APSAC, in a randomized
+        multicentre trial in 421 patients with acute myocardial infarction.
+
+    There were four families of hypotheses tested in the study, the last of
+    which was "cardiac and other events after the start of thrombolitic
+    treatment". FDR control may be desired in this family of hypotheses
+    because it would not be appropriate to conclude that the front-loaded
+    treatment is better if it is merely equivalent to the previous treatment.
+
+    The p-values corresponding with the 15 hypotheses in this family were
+
+    >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344,
+    ...       0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]
+
+    If the chosen significance level is 0.05, we may be tempted to reject the
+    null hypotheses for the tests corresponding with the first nine p-values,
+    as the first nine p-values fall below the chosen significance level.
+    However, this would ignore the problem of "multiplicity": if we fail to
+    correct for the fact that multiple comparisons are being performed, we
+    are more likely to incorrectly reject true null hypotheses.
+
+    One approach to the multiplicity problem is to control the family-wise
+    error rate (FWER), that is, the rate at which the null hypothesis is
+    rejected when it is actually true. A common procedure of this kind is the
+    Bonferroni correction [1]_.  We begin by multiplying the p-values by the
+    number of hypotheses tested.
+
+    >>> import numpy as np
+    >>> np.array(ps) * len(ps)
+    array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01,
+           4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00,
+           6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01])
+
+    To control the FWER at 5%, we reject only the hypotheses corresponding
+    with adjusted p-values less than 0.05. In this case, only the hypotheses
+    corresponding with the first three p-values can be rejected. According to
+    [1]_, these three hypotheses concerned "allergic reaction" and "two
+    different aspects of bleeding."
+
+    An alternative approach is to control the false discovery rate: the
+    expected fraction of rejected null hypotheses that are actually true. The
+    advantage of this approach is that it typically affords greater power: an
+    increased rate of rejecting the null hypothesis when it is indeed false. To
+    control the false discovery rate at 5%, we apply the Benjamini-Hochberg
+    p-value adjustment.
+
+    >>> from scipy import stats
+    >>> stats.false_discovery_control(ps)
+    array([0.0015    , 0.003     , 0.0095    , 0.035625  , 0.0603    ,
+           0.06385714, 0.06385714, 0.0645    , 0.0765    , 0.486     ,
+           0.58118182, 0.714875  , 0.75323077, 0.81321429, 1.        ])
+
+    Now, the first *four* adjusted p-values fall below 0.05, so we would reject
+    the null hypotheses corresponding with these *four* p-values. Rejection
+    of the fourth null hypothesis was particularly important to the original
+    study as it led to the conclusion that the new treatment had a
+    "substantially lower in-hospital mortality rate."
+
+    """
+    # Input Validation and Special Cases
+    ps = np.asarray(ps)
+
+    ps_in_range = (np.issubdtype(ps.dtype, np.number)
+                   and np.all(ps == np.clip(ps, 0, 1)))
+    if not ps_in_range:
+        raise ValueError("`ps` must include only numbers between 0 and 1.")
+
+    methods = {'bh', 'by'}
+    if method.lower() not in methods:
+        raise ValueError(f"Unrecognized `method` '{method}'."
+                         f"Method must be one of {methods}.")
+    method = method.lower()
+
+    if axis is None:
+        axis = 0
+        ps = ps.ravel()
+
+    axis = np.asarray(axis)[()]
+    if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1:
+        raise ValueError("`axis` must be an integer or `None`")
+
+    if ps.size <= 1 or ps.shape[axis] <= 1:
+        return ps[()]
+
+    ps = np.moveaxis(ps, axis, -1)
+    m = ps.shape[-1]
+
+    # Main Algorithm
+    # Equivalent to the ideas of [1] and [2], except that this adjusts the
+    # p-values as described in [3]. The results are similar to those produced
+    # by R's p.adjust.
+
+    # "Let [ps] be the ordered observed p-values..."
+    order = np.argsort(ps, axis=-1)
+    ps = np.take_along_axis(ps, order, axis=-1)  # this copies ps
+
+    # Equation 1 of [1] rearranged to reject when p is less than specified q
+    i = np.arange(1, m+1)
+    ps *= m / i
+
+    # Theorem 1.3 of [2]
+    if method == 'by':
+        ps *= np.sum(1 / i)
+
+    # accounts for rejecting all null hypotheses i for i < k, where k is
+    # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j
+    # of the second to last element, we replace element j with element j+1 if
+    # the latter is smaller.
+    np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1)
+
+    # Restore original order of axes and data
+    np.put_along_axis(ps, order, values=ps.copy(), axis=-1)
+    ps = np.moveaxis(ps, -1, axis)
+
+    return np.clip(ps, 0, 1)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_mstats_basic.py b/python_embeded/Lib/site-packages/scipy/stats/_mstats_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..403975429ea7388a74a931c38160af8ae235ed53
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_mstats_basic.py
@@ -0,0 +1,3662 @@
+"""
+An extension of scipy.stats._stats_py to support masked arrays
+
+"""
+# Original author (2007): Pierre GF Gerard-Marchant
+
+
+__all__ = ['argstoarray',
+           'count_tied_groups',
+           'describe',
+           'f_oneway', 'find_repeats','friedmanchisquare',
+           'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis',
+           'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest',
+           'ks_1samp', 'kstest',
+           'linregress',
+           'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign',
+           'normaltest',
+           'obrientransform',
+           'pearsonr','plotting_positions','pointbiserialr',
+           'rankdata',
+           'scoreatpercentile','sem',
+           'sen_seasonal_slopes','skew','skewtest','spearmanr',
+           'siegelslopes', 'theilslopes',
+           'tmax','tmean','tmin','trim','trimboth',
+           'trimtail','trima','trimr','trimmed_mean','trimmed_std',
+           'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp',
+           'ttest_ind','ttest_rel','tvar',
+           'variation',
+           'winsorize',
+           'brunnermunzel',
+           ]
+
+import numpy as np
+from numpy import ndarray
+import numpy.ma as ma
+from numpy.ma import masked, nomask
+import math
+
+import itertools
+import warnings
+from collections import namedtuple
+
+from . import distributions
+from scipy._lib._util import _rename_parameter, _contains_nan
+from scipy._lib._bunch import _make_tuple_bunch
+import scipy.special as special
+import scipy.stats._stats_py
+import scipy.stats._stats_py as _stats_py
+
+from ._stats_mstats_common import (
+        _find_repeats,
+        theilslopes as stats_theilslopes,
+        siegelslopes as stats_siegelslopes
+        )
+
+
+def _chk_asarray(a, axis):
+    # Always returns a masked array, raveled for axis=None
+    a = ma.asanyarray(a)
+    if axis is None:
+        a = ma.ravel(a)
+        outaxis = 0
+    else:
+        outaxis = axis
+    return a, outaxis
+
+
+def _chk2_asarray(a, b, axis):
+    a = ma.asanyarray(a)
+    b = ma.asanyarray(b)
+    if axis is None:
+        a = ma.ravel(a)
+        b = ma.ravel(b)
+        outaxis = 0
+    else:
+        outaxis = axis
+    return a, b, outaxis
+
+
+def _chk_size(a, b):
+    a = ma.asanyarray(a)
+    b = ma.asanyarray(b)
+    (na, nb) = (a.size, b.size)
+    if na != nb:
+        raise ValueError("The size of the input array should match!"
+                         f" ({na} <> {nb})")
+    return (a, b, na)
+
+
+def _ttest_finish(df, t, alternative):
+    """Common code between all 3 t-test functions."""
+    # We use ``stdtr`` directly here to preserve masked arrays
+
+    if alternative == 'less':
+        pval = special._ufuncs.stdtr(df, t)
+    elif alternative == 'greater':
+        pval = special._ufuncs.stdtr(df, -t)
+    elif alternative == 'two-sided':
+        pval = special._ufuncs.stdtr(df, -np.abs(t))*2
+    else:
+        raise ValueError("alternative must be "
+                         "'less', 'greater' or 'two-sided'")
+
+    if t.ndim == 0:
+        t = t[()]
+    if pval.ndim == 0:
+        pval = pval[()]
+
+    return t, pval
+
+
+def argstoarray(*args):
+    """
+    Constructs a 2D array from a group of sequences.
+
+    Sequences are filled with missing values to match the length of the longest
+    sequence.
+
+    Parameters
+    ----------
+    *args : sequences
+        Group of sequences.
+
+    Returns
+    -------
+    argstoarray : MaskedArray
+        A ( `m` x `n` ) masked array, where `m` is the number of arguments and
+        `n` the length of the longest argument.
+
+    Notes
+    -----
+    `numpy.ma.vstack` has identical behavior, but is called with a sequence
+    of sequences.
+
+    Examples
+    --------
+    A 2D masked array constructed from a group of sequences is returned.
+
+    >>> from scipy.stats.mstats import argstoarray
+    >>> argstoarray([1, 2, 3], [4, 5, 6])
+    masked_array(
+     data=[[1.0, 2.0, 3.0],
+           [4.0, 5.0, 6.0]],
+     mask=[[False, False, False],
+           [False, False, False]],
+     fill_value=1e+20)
+
+    The returned masked array filled with missing values when the lengths of
+    sequences are different.
+
+    >>> argstoarray([1, 3], [4, 5, 6])
+    masked_array(
+     data=[[1.0, 3.0, --],
+           [4.0, 5.0, 6.0]],
+     mask=[[False, False,  True],
+           [False, False, False]],
+     fill_value=1e+20)
+
+    """
+    if len(args) == 1 and not isinstance(args[0], ndarray):
+        output = ma.asarray(args[0])
+        if output.ndim != 2:
+            raise ValueError("The input should be 2D")
+    else:
+        n = len(args)
+        m = max([len(k) for k in args])
+        output = ma.array(np.empty((n,m), dtype=float), mask=True)
+        for (k,v) in enumerate(args):
+            output[k,:len(v)] = v
+
+    output[np.logical_not(np.isfinite(output._data))] = masked
+    return output
+
+
+def find_repeats(arr):
+    """Find repeats in arr and return a tuple (repeats, repeat_count).
+
+    The input is cast to float64. Masked values are discarded.
+
+    Parameters
+    ----------
+    arr : sequence
+        Input array. The array is flattened if it is not 1D.
+
+    Returns
+    -------
+    repeats : ndarray
+        Array of repeated values.
+    counts : ndarray
+        Array of counts.
+
+    Examples
+    --------
+    >>> from scipy.stats import mstats
+    >>> mstats.find_repeats([2, 1, 2, 3, 2, 2, 5])
+    (array([2.]), array([4]))
+
+    In the above example, 2 repeats 4 times.
+
+    >>> mstats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
+    (array([4., 5.]), array([2, 2]))
+
+    In the above example, both 4 and 5 repeat 2 times.
+
+    """
+    # Make sure we get a copy. ma.compressed promises a "new array", but can
+    # actually return a reference.
+    compr = np.asarray(ma.compressed(arr), dtype=np.float64)
+    try:
+        need_copy = np.may_share_memory(compr, arr)
+    except AttributeError:
+        # numpy < 1.8.2 bug: np.may_share_memory([], []) raises,
+        # while in numpy 1.8.2 and above it just (correctly) returns False.
+        need_copy = False
+    if need_copy:
+        compr = compr.copy()
+    return _find_repeats(compr)
+
+
+def count_tied_groups(x, use_missing=False):
+    """
+    Counts the number of tied values.
+
+    Parameters
+    ----------
+    x : sequence
+        Sequence of data on which to counts the ties
+    use_missing : bool, optional
+        Whether to consider missing values as tied.
+
+    Returns
+    -------
+    count_tied_groups : dict
+        Returns a dictionary (nb of ties: nb of groups).
+
+    Examples
+    --------
+    >>> from scipy.stats import mstats
+    >>> import numpy as np
+    >>> z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6]
+    >>> mstats.count_tied_groups(z)
+    {2: 1, 3: 2}
+
+    In the above example, the ties were 0 (3x), 2 (3x) and 3 (2x).
+
+    >>> z = np.ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6])
+    >>> mstats.count_tied_groups(z)
+    {2: 2, 3: 1}
+    >>> z[[1,-1]] = np.ma.masked
+    >>> mstats.count_tied_groups(z, use_missing=True)
+    {2: 2, 3: 1}
+
+    """
+    nmasked = ma.getmask(x).sum()
+    # We need the copy as find_repeats will overwrite the initial data
+    data = ma.compressed(x).copy()
+    (ties, counts) = find_repeats(data)
+    nties = {}
+    if len(ties):
+        nties = dict(zip(np.unique(counts), itertools.repeat(1)))
+        nties.update(dict(zip(*find_repeats(counts))))
+
+    if nmasked and use_missing:
+        try:
+            nties[nmasked] += 1
+        except KeyError:
+            nties[nmasked] = 1
+
+    return nties
+
+
+def rankdata(data, axis=None, use_missing=False):
+    """Returns the rank (also known as order statistics) of each data point
+    along the given axis.
+
+    If some values are tied, their rank is averaged.
+    If some values are masked, their rank is set to 0 if use_missing is False,
+    or set to the average rank of the unmasked values if use_missing is True.
+
+    Parameters
+    ----------
+    data : sequence
+        Input data. The data is transformed to a masked array
+    axis : {None,int}, optional
+        Axis along which to perform the ranking.
+        If None, the array is first flattened. An exception is raised if
+        the axis is specified for arrays with a dimension larger than 2
+    use_missing : bool, optional
+        Whether the masked values have a rank of 0 (False) or equal to the
+        average rank of the unmasked values (True).
+
+    """
+    def _rank1d(data, use_missing=False):
+        n = data.count()
+        rk = np.empty(data.size, dtype=float)
+        idx = data.argsort()
+        rk[idx[:n]] = np.arange(1,n+1)
+
+        if use_missing:
+            rk[idx[n:]] = (n+1)/2.
+        else:
+            rk[idx[n:]] = 0
+
+        repeats = find_repeats(data.copy())
+        for r in repeats[0]:
+            condition = (data == r).filled(False)
+            rk[condition] = rk[condition].mean()
+        return rk
+
+    data = ma.array(data, copy=False)
+    if axis is None:
+        if data.ndim > 1:
+            return _rank1d(data.ravel(), use_missing).reshape(data.shape)
+        else:
+            return _rank1d(data, use_missing)
+    else:
+        return ma.apply_along_axis(_rank1d,axis,data,use_missing).view(ndarray)
+
+
+ModeResult = namedtuple('ModeResult', ('mode', 'count'))
+
+
+def mode(a, axis=0):
+    """
+    Returns an array of the modal (most common) value in the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        n-dimensional array of which to find mode(s).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    mode : ndarray
+        Array of modal values.
+    count : ndarray
+        Array of counts for each mode.
+
+    Notes
+    -----
+    For more details, see `scipy.stats.mode`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats import mstats
+    >>> m_arr = np.ma.array([1, 1, 0, 0, 0, 0], mask=[0, 0, 1, 1, 1, 0])
+    >>> mstats.mode(m_arr)  # note that most zeros are masked
+    ModeResult(mode=array([1.]), count=array([2.]))
+
+    """
+    return _mode(a, axis=axis, keepdims=True)
+
+
+def _mode(a, axis=0, keepdims=True):
+    # Don't want to expose `keepdims` from the public `mstats.mode`
+    a, axis = _chk_asarray(a, axis)
+
+    def _mode1D(a):
+        (rep,cnt) = find_repeats(a)
+        if not cnt.ndim:
+            return (0, 0)
+        elif cnt.size:
+            return (rep[cnt.argmax()], cnt.max())
+        else:
+            return (a.min(), 1)
+
+    if axis is None:
+        output = _mode1D(ma.ravel(a))
+        output = (ma.array(output[0]), ma.array(output[1]))
+    else:
+        output = ma.apply_along_axis(_mode1D, axis, a)
+        if keepdims is None or keepdims:
+            newshape = list(a.shape)
+            newshape[axis] = 1
+            slices = [slice(None)] * output.ndim
+            slices[axis] = 0
+            modes = output[tuple(slices)].reshape(newshape)
+            slices[axis] = 1
+            counts = output[tuple(slices)].reshape(newshape)
+            output = (modes, counts)
+        else:
+            output = np.moveaxis(output, axis, 0)
+
+    return ModeResult(*output)
+
+
+def _betai(a, b, x):
+    x = np.asanyarray(x)
+    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
+    return special.betainc(a, b, x)
+
+
+def msign(x):
+    """Returns the sign of x, or 0 if x is masked."""
+    return ma.filled(np.sign(x), 0)
+
+
+def pearsonr(x, y):
+    r"""
+    Pearson correlation coefficient and p-value for testing non-correlation.
+
+    The Pearson correlation coefficient [1]_ measures the linear relationship
+    between two datasets.  The calculation of the p-value relies on the
+    assumption that each dataset is normally distributed.  (See Kowalski [3]_
+    for a discussion of the effects of non-normality of the input on the
+    distribution of the correlation coefficient.)  Like other correlation
+    coefficients, this one varies between -1 and +1 with 0 implying no
+    correlation. Correlations of -1 or +1 imply an exact linear relationship.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input array.
+    y : (N,) array_like
+        Input array.
+
+    Returns
+    -------
+    r : float
+        Pearson's correlation coefficient.
+    p-value : float
+        Two-tailed p-value.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    `~scipy.stats.NearConstantInputWarning`
+        Raised if an input is "nearly" constant.  The array ``x`` is considered
+        nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
+        Numerical errors in the calculation ``x - mean(x)`` in this case might
+        result in an inaccurate calculation of r.
+
+    See Also
+    --------
+    spearmanr : Spearman rank-order correlation coefficient.
+    kendalltau : Kendall's tau, a correlation measure for ordinal data.
+
+    Notes
+    -----
+    The correlation coefficient is calculated as follows:
+
+    .. math::
+
+        r = \frac{\sum (x - m_x) (y - m_y)}
+                 {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
+
+    where :math:`m_x` is the mean of the vector x and :math:`m_y` is
+    the mean of the vector y.
+
+    Under the assumption that x and y are drawn from
+    independent normal distributions (so the population correlation coefficient
+    is 0), the probability density function of the sample correlation
+    coefficient r is ([1]_, [2]_):
+
+    .. math::
+
+        f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
+
+    where n is the number of samples, and B is the beta function.  This
+    is sometimes referred to as the exact distribution of r.  This is
+    the distribution that is used in `pearsonr` to compute the p-value.
+    The distribution is a beta distribution on the interval [-1, 1],
+    with equal shape parameters a = b = n/2 - 1.  In terms of SciPy's
+    implementation of the beta distribution, the distribution of r is::
+
+        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
+
+    The p-value returned by `pearsonr` is a two-sided p-value. The p-value
+    roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Pearson correlation at least as extreme
+    as the one computed from these datasets. More precisely, for a
+    given sample with correlation coefficient r, the p-value is
+    the probability that abs(r') of a random sample x' and y' drawn from
+    the population with zero correlation would be greater than or equal
+    to abs(r). In terms of the object ``dist`` shown above, the p-value
+    for a given r and length n can be computed as::
+
+        p = 2*dist.cdf(-abs(r))
+
+    When n is 2, the above continuous distribution is not well-defined.
+    One can interpret the limit of the beta distribution as the shape
+    parameters a and b approach a = b = 0 as a discrete distribution with
+    equal probability masses at r = 1 and r = -1.  More directly, one
+    can observe that, given the data x = [x1, x2] and y = [y1, y2], and
+    assuming x1 != x2 and y1 != y2, the only possible values for r are 1
+    and -1.  Because abs(r') for any sample x' and y' with length 2 will
+    be 1, the two-sided p-value for a sample of length 2 is always 1.
+
+    References
+    ----------
+    .. [1] "Pearson correlation coefficient", Wikipedia,
+           https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+    .. [2] Student, "Probable error of a correlation coefficient",
+           Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
+    .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
+           of the Sample Product-Moment Correlation Coefficient"
+           Journal of the Royal Statistical Society. Series C (Applied
+           Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats import mstats
+    >>> mstats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
+    (-0.7426106572325057, 0.1505558088534455)
+
+    There is a linear dependence between x and y if y = a + b*x + e, where
+    a,b are constants and e is a random error term, assumed to be independent
+    of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
+    e follow a normal distribution with mean zero and standard deviation s>0.
+
+    >>> s = 0.5
+    >>> x = stats.norm.rvs(size=500)
+    >>> e = stats.norm.rvs(scale=s, size=500)
+    >>> y = x + e
+    >>> mstats.pearsonr(x, y)
+    (0.9029601878969703, 8.428978827629898e-185) # may vary
+
+    This should be close to the exact value given by
+
+    >>> 1/np.sqrt(1 + s**2)
+    0.8944271909999159
+
+    For s=0.5, we observe a high level of correlation. In general, a large
+    variance of the noise reduces the correlation, while the correlation
+    approaches one as the variance of the error goes to zero.
+
+    It is important to keep in mind that no correlation does not imply
+    independence unless (x, y) is jointly normal. Correlation can even be zero
+    when there is a very simple dependence structure: if X follows a
+    standard normal distribution, let y = abs(x). Note that the correlation
+    between x and y is zero. Indeed, since the expectation of x is zero,
+    cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
+    by symmetry. The following lines of code illustrate this observation:
+
+    >>> y = np.abs(x)
+    >>> mstats.pearsonr(x, y)
+    (-0.016172891856853524, 0.7182823678751942) # may vary
+
+    A non-zero correlation coefficient can be misleading. For example, if X has
+    a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
+    A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
+    implying a high level of correlation:
+
+    >>> y = np.where(x < 0, x, 0)
+    >>> mstats.pearsonr(x, y)
+    (0.8537091583771509, 3.183461621422181e-143) # may vary
+
+    This is unintuitive since there is no dependence of x and y if x is larger
+    than zero which happens in about half of the cases if we sample x and y.
+    """
+    (x, y, n) = _chk_size(x, y)
+    (x, y) = (x.ravel(), y.ravel())
+    # Get the common mask and the total nb of unmasked elements
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    n -= m.sum()
+    df = n-2
+    if df < 0:
+        return (masked, masked)
+
+    return scipy.stats._stats_py.pearsonr(
+                ma.masked_array(x, mask=m).compressed(),
+                ma.masked_array(y, mask=m).compressed())
+
+
+def spearmanr(x, y=None, use_ties=True, axis=None, nan_policy='propagate',
+              alternative='two-sided'):
+    """
+    Calculates a Spearman rank-order correlation coefficient and the p-value
+    to test for non-correlation.
+
+    The Spearman correlation is a nonparametric measure of the linear
+    relationship between two datasets. Unlike the Pearson correlation, the
+    Spearman correlation does not assume that both datasets are normally
+    distributed. Like other correlation coefficients, this one varies
+    between -1 and +1 with 0 implying no correlation. Correlations of -1 or
+    +1 imply a monotonic relationship. Positive correlations imply that
+    as `x` increases, so does `y`. Negative correlations imply that as `x`
+    increases, `y` decreases.
+
+    Missing values are discarded pair-wise: if a value is missing in `x`, the
+    corresponding value in `y` is masked.
+
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Spearman correlation at least as extreme
+    as the one computed from these datasets. The p-values are not entirely
+    reliable but are probably reasonable for datasets larger than 500 or so.
+
+    Parameters
+    ----------
+    x, y : 1D or 2D array_like, y is optional
+        One or two 1-D or 2-D arrays containing multiple variables and
+        observations. When these are 1-D, each represents a vector of
+        observations of a single variable. For the behavior in the 2-D case,
+        see under ``axis``, below.
+    use_ties : bool, optional
+        DO NOT USE.  Does not do anything, keyword is only left in place for
+        backwards compatibility reasons.
+    axis : int or None, optional
+        If axis=0 (default), then each column represents a variable, with
+        observations in the rows. If axis=1, the relationship is transposed:
+        each row represents a variable, while the columns contain observations.
+        If axis=None, then both arrays will be raveled.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float or ndarray (2-D square)
+            Spearman correlation matrix or correlation coefficient (if only 2
+            variables are given as parameters). Correlation matrix is square
+            with length equal to total number of variables (columns or rows) in
+            ``a`` and ``b`` combined.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis
+            is that two sets of data are linearly uncorrelated. See
+            `alternative` above for alternative hypotheses. `pvalue` has the
+            same shape as `statistic`.
+
+    References
+    ----------
+    [CRCProbStat2000] section 14.7
+
+    """
+    if not use_ties:
+        raise ValueError("`use_ties=False` is not supported in SciPy >= 1.2.0")
+
+    # Always returns a masked array, raveled if axis=None
+    x, axisout = _chk_asarray(x, axis)
+    if y is not None:
+        # Deal only with 2-D `x` case.
+        y, _ = _chk_asarray(y, axis)
+        if axisout == 0:
+            x = ma.column_stack((x, y))
+        else:
+            x = ma.vstack((x, y))
+
+    if axisout == 1:
+        # To simplify the code that follow (always use `n_obs, n_vars` shape)
+        x = x.T
+
+    if nan_policy == 'omit':
+        x = ma.masked_invalid(x)
+
+    def _spearmanr_2cols(x):
+        # Mask the same observations for all variables, and then drop those
+        # observations (can't leave them masked, rankdata is weird).
+        x = ma.mask_rowcols(x, axis=0)
+        x = x[~x.mask.any(axis=1), :]
+
+        # If either column is entirely NaN or Inf
+        if not np.any(x.data):
+            res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+
+        m = ma.getmask(x)
+        n_obs = x.shape[0]
+        dof = n_obs - 2 - int(m.sum(axis=0)[0])
+        if dof < 0:
+            raise ValueError("The input must have at least 3 entries!")
+
+        # Gets the ranks and rank differences
+        x_ranked = rankdata(x, axis=0)
+        rs = ma.corrcoef(x_ranked, rowvar=False).data
+
+        # rs can have elements equal to 1, so avoid zero division warnings
+        with np.errstate(divide='ignore'):
+            # clip the small negative values possibly caused by rounding
+            # errors before taking the square root
+            t = rs * np.sqrt((dof / ((rs+1.0) * (1.0-rs))).clip(0))
+
+        t, prob = _ttest_finish(dof, t, alternative)
+
+        # For backwards compatibility, return scalars when comparing 2 columns
+        if rs.shape == (2, 2):
+            res = scipy.stats._stats_py.SignificanceResult(rs[1, 0],
+                                                           prob[1, 0])
+            res.correlation = rs[1, 0]
+            return res
+        else:
+            res = scipy.stats._stats_py.SignificanceResult(rs, prob)
+            res.correlation = rs
+            return res
+
+    # Need to do this per pair of variables, otherwise the dropped observations
+    # in a third column mess up the result for a pair.
+    n_vars = x.shape[1]
+    if n_vars == 2:
+        return _spearmanr_2cols(x)
+    else:
+        rs = np.ones((n_vars, n_vars), dtype=float)
+        prob = np.zeros((n_vars, n_vars), dtype=float)
+        for var1 in range(n_vars - 1):
+            for var2 in range(var1+1, n_vars):
+                result = _spearmanr_2cols(x[:, [var1, var2]])
+                rs[var1, var2] = result.correlation
+                rs[var2, var1] = result.correlation
+                prob[var1, var2] = result.pvalue
+                prob[var2, var1] = result.pvalue
+
+        res = scipy.stats._stats_py.SignificanceResult(rs, prob)
+        res.correlation = rs
+        return res
+
+
+def _kendall_p_exact(n, c, alternative='two-sided'):
+
+    # Use the fact that distribution is symmetric: always calculate a CDF in
+    # the left tail.
+    # This will be the one-sided p-value if `c` is on the side of
+    # the null distribution predicted by the alternative hypothesis.
+    # The two-sided p-value will be twice this value.
+    # If `c` is on the other side of the null distribution, we'll need to
+    # take the complement and add back the probability mass at `c`.
+    in_right_tail = (c >= (n*(n-1))//2 - c)
+    alternative_greater = (alternative == 'greater')
+    c = int(min(c, (n*(n-1))//2 - c))
+
+    # Exact p-value, see Maurice G. Kendall, "Rank Correlation Methods"
+    # (4th Edition), Charles Griffin & Co., 1970.
+    if n <= 0:
+        raise ValueError(f'n ({n}) must be positive')
+    elif c < 0 or 4*c > n*(n-1):
+        raise ValueError(f'c ({c}) must satisfy 0 <= 4c <= n(n-1) = {n*(n-1)}.')
+    elif n == 1:
+        prob = 1.0
+        p_mass_at_c = 1
+    elif n == 2:
+        prob = 1.0
+        p_mass_at_c = 0.5
+    elif c == 0:
+        prob = 2.0/math.factorial(n) if n < 171 else 0.0
+        p_mass_at_c = prob/2
+    elif c == 1:
+        prob = 2.0/math.factorial(n-1) if n < 172 else 0.0
+        p_mass_at_c = (n-1)/math.factorial(n)
+    elif 4*c == n*(n-1) and alternative == 'two-sided':
+        # I'm sure there's a simple formula for p_mass_at_c in this
+        # case, but I don't know it. Use generic formula for one-sided p-value.
+        prob = 1.0
+    elif n < 171:
+        new = np.zeros(c+1)
+        new[0:2] = 1.0
+        for j in range(3,n+1):
+            new = np.cumsum(new)
+            if j <= c:
+                new[j:] -= new[:c+1-j]
+        prob = 2.0*np.sum(new)/math.factorial(n)
+        p_mass_at_c = new[-1]/math.factorial(n)
+    else:
+        new = np.zeros(c+1)
+        new[0:2] = 1.0
+        for j in range(3, n+1):
+            new = np.cumsum(new)/j
+            if j <= c:
+                new[j:] -= new[:c+1-j]
+        prob = np.sum(new)
+        p_mass_at_c = new[-1]/2
+
+    if alternative != 'two-sided':
+        # if the alternative hypothesis and alternative agree,
+        # one-sided p-value is half the two-sided p-value
+        if in_right_tail == alternative_greater:
+            prob /= 2
+        else:
+            prob = 1 - prob/2 + p_mass_at_c
+
+    prob = np.clip(prob, 0, 1)
+
+    return prob
+
+
+def kendalltau(x, y, use_ties=True, use_missing=False, method='auto',
+               alternative='two-sided'):
+    """
+    Computes Kendall's rank correlation tau on two variables *x* and *y*.
+
+    Parameters
+    ----------
+    x : sequence
+        First data list (for example, time).
+    y : sequence
+        Second data list.
+    use_ties : {True, False}, optional
+        Whether ties correction should be performed.
+    use_missing : {False, True}, optional
+        Whether missing data should be allocated a rank of 0 (False) or the
+        average rank (True)
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Defines which method is used to calculate the p-value [1]_.
+        'asymptotic' uses a normal approximation valid for large samples.
+        'exact' computes the exact p-value, but can only be used if no ties
+        are present. As the sample size increases, the 'exact' computation
+        time may grow and the result may lose some precision.
+        'auto' is the default and selects the appropriate
+        method based on a trade-off between speed and accuracy.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater':  the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The tau statistic.
+        pvalue : float
+           The p-value for a hypothesis test whose null hypothesis is
+           an absence of association, tau = 0.
+
+    References
+    ----------
+    .. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
+           Charles Griffin & Co., 1970.
+
+    """
+    (x, y, n) = _chk_size(x, y)
+    (x, y) = (x.flatten(), y.flatten())
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    if m is not nomask:
+        x = ma.array(x, mask=m, copy=True)
+        y = ma.array(y, mask=m, copy=True)
+        # need int() here, otherwise numpy defaults to 32 bit
+        # integer on all Windows architectures, causing overflow.
+        # int() will keep it infinite precision.
+        n -= int(m.sum())
+
+    if n < 2:
+        res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    rx = ma.masked_equal(rankdata(x, use_missing=use_missing), 0)
+    ry = ma.masked_equal(rankdata(y, use_missing=use_missing), 0)
+    idx = rx.argsort()
+    (rx, ry) = (rx[idx], ry[idx])
+    C = np.sum([((ry[i+1:] > ry[i]) * (rx[i+1:] > rx[i])).filled(0).sum()
+                for i in range(len(ry)-1)], dtype=float)
+    D = np.sum([((ry[i+1:] < ry[i])*(rx[i+1:] > rx[i])).filled(0).sum()
+                for i in range(len(ry)-1)], dtype=float)
+    xties = count_tied_groups(x)
+    yties = count_tied_groups(y)
+    if use_ties:
+        corr_x = np.sum([v*k*(k-1) for (k,v) in xties.items()], dtype=float)
+        corr_y = np.sum([v*k*(k-1) for (k,v) in yties.items()], dtype=float)
+        denom = ma.sqrt((n*(n-1)-corr_x)/2. * (n*(n-1)-corr_y)/2.)
+    else:
+        denom = n*(n-1)/2.
+    tau = (C-D) / denom
+
+    if method == 'exact' and (xties or yties):
+        raise ValueError("Ties found, exact method cannot be used.")
+
+    if method == 'auto':
+        if (not xties and not yties) and (n <= 33 or min(C, n*(n-1)/2.0-C) <= 1):
+            method = 'exact'
+        else:
+            method = 'asymptotic'
+
+    if not xties and not yties and method == 'exact':
+        prob = _kendall_p_exact(n, C, alternative)
+
+    elif method == 'asymptotic':
+        var_s = n*(n-1)*(2*n+5)
+        if use_ties:
+            var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in xties.items()])
+            var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in yties.items()])
+            v1 = (np.sum([v*k*(k-1) for (k, v) in xties.items()], dtype=float) *
+                  np.sum([v*k*(k-1) for (k, v) in yties.items()], dtype=float))
+            v1 /= 2.*n*(n-1)
+            if n > 2:
+                v2 = np.sum([v*k*(k-1)*(k-2) for (k,v) in xties.items()],
+                            dtype=float) * \
+                     np.sum([v*k*(k-1)*(k-2) for (k,v) in yties.items()],
+                            dtype=float)
+                v2 /= 9.*n*(n-1)*(n-2)
+            else:
+                v2 = 0
+        else:
+            v1 = v2 = 0
+
+        var_s /= 18.
+        var_s += (v1 + v2)
+        z = (C-D)/np.sqrt(var_s)
+        prob = scipy.stats._stats_py._get_pvalue(z, distributions.norm, alternative)
+    else:
+        raise ValueError("Unknown method "+str(method)+" specified, please "
+                         "use auto, exact or asymptotic.")
+
+    res = scipy.stats._stats_py.SignificanceResult(tau[()], prob[()])
+    res.correlation = tau
+    return res
+
+
+def kendalltau_seasonal(x):
+    """
+    Computes a multivariate Kendall's rank correlation tau, for seasonal data.
+
+    Parameters
+    ----------
+    x : 2-D ndarray
+        Array of seasonal data, with seasons in columns.
+
+    """
+    x = ma.array(x, subok=True, copy=False, ndmin=2)
+    (n,m) = x.shape
+    n_p = x.count(0)
+
+    S_szn = sum(msign(x[i:]-x[i]).sum(0) for i in range(n))
+    S_tot = S_szn.sum()
+
+    n_tot = x.count()
+    ties = count_tied_groups(x.compressed())
+    corr_ties = sum(v*k*(k-1) for (k,v) in ties.items())
+    denom_tot = ma.sqrt(1.*n_tot*(n_tot-1)*(n_tot*(n_tot-1)-corr_ties))/2.
+
+    R = rankdata(x, axis=0, use_missing=True)
+    K = ma.empty((m,m), dtype=int)
+    covmat = ma.empty((m,m), dtype=float)
+    denom_szn = ma.empty(m, dtype=float)
+    for j in range(m):
+        ties_j = count_tied_groups(x[:,j].compressed())
+        corr_j = sum(v*k*(k-1) for (k,v) in ties_j.items())
+        cmb = n_p[j]*(n_p[j]-1)
+        for k in range(j,m,1):
+            K[j,k] = sum(msign((x[i:,j]-x[i,j])*(x[i:,k]-x[i,k])).sum()
+                         for i in range(n))
+            covmat[j,k] = (K[j,k] + 4*(R[:,j]*R[:,k]).sum() -
+                           n*(n_p[j]+1)*(n_p[k]+1))/3.
+            K[k,j] = K[j,k]
+            covmat[k,j] = covmat[j,k]
+
+        denom_szn[j] = ma.sqrt(cmb*(cmb-corr_j)) / 2.
+
+    var_szn = covmat.diagonal()
+
+    z_szn = msign(S_szn) * (abs(S_szn)-1) / ma.sqrt(var_szn)
+    z_tot_ind = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(var_szn.sum())
+    z_tot_dep = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(covmat.sum())
+
+    prob_szn = special.erfc(abs(z_szn.data)/np.sqrt(2))
+    prob_tot_ind = special.erfc(abs(z_tot_ind)/np.sqrt(2))
+    prob_tot_dep = special.erfc(abs(z_tot_dep)/np.sqrt(2))
+
+    chi2_tot = (z_szn*z_szn).sum()
+    chi2_trd = m * z_szn.mean()**2
+    output = {'seasonal tau': S_szn/denom_szn,
+              'global tau': S_tot/denom_tot,
+              'global tau (alt)': S_tot/denom_szn.sum(),
+              'seasonal p-value': prob_szn,
+              'global p-value (indep)': prob_tot_ind,
+              'global p-value (dep)': prob_tot_dep,
+              'chi2 total': chi2_tot,
+              'chi2 trend': chi2_trd,
+              }
+    return output
+
+
+PointbiserialrResult = namedtuple('PointbiserialrResult', ('correlation',
+                                                           'pvalue'))
+
+
+def pointbiserialr(x, y):
+    """Calculates a point biserial correlation coefficient and its p-value.
+
+    Parameters
+    ----------
+    x : array_like of bools
+        Input array.
+    y : array_like
+        Input array.
+
+    Returns
+    -------
+    correlation : float
+        R value
+    pvalue : float
+        2-tailed p-value
+
+    Notes
+    -----
+    Missing values are considered pair-wise: if a value is missing in x,
+    the corresponding value in y is masked.
+
+    For more details on `pointbiserialr`, see `scipy.stats.pointbiserialr`.
+
+    """
+    x = ma.fix_invalid(x, copy=True).astype(bool)
+    y = ma.fix_invalid(y, copy=True).astype(float)
+    # Get rid of the missing data
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    if m is not nomask:
+        unmask = np.logical_not(m)
+        x = x[unmask]
+        y = y[unmask]
+
+    n = len(x)
+    # phat is the fraction of x values that are True
+    phat = x.sum() / float(n)
+    y0 = y[~x]  # y-values where x is False
+    y1 = y[x]  # y-values where x is True
+    y0m = y0.mean()
+    y1m = y1.mean()
+
+    rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / y.std()
+
+    df = n-2
+    t = rpb*ma.sqrt(df/(1.0-rpb**2))
+    prob = _betai(0.5*df, 0.5, df/(df+t*t))
+
+    return PointbiserialrResult(rpb, prob)
+
+
+def linregress(x, y=None):
+    r"""
+    Calculate a linear least-squares regression for two sets of measurements.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Two sets of measurements.  Both arrays should have the same length N.  If
+        only `x` is given (and ``y=None``), then it must be a two-dimensional
+        array where one dimension has length 2.  The two sets of measurements
+        are then found by splitting the array along the length-2 dimension. In
+        the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is
+        equivalent to ``linregress(x[0], x[1])``.
+
+    Returns
+    -------
+    result : ``LinregressResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Slope of the regression line.
+        intercept : float
+            Intercept of the regression line.
+        rvalue : float
+            The Pearson correlation coefficient. The square of ``rvalue``
+            is equal to the coefficient of determination.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis is
+            that the slope is zero, using Wald Test with t-distribution of
+            the test statistic. See `alternative` above for alternative
+            hypotheses.
+        stderr : float
+            Standard error of the estimated slope (gradient), under the
+            assumption of residual normality.
+        intercept_stderr : float
+            Standard error of the estimated intercept, under the assumption
+            of residual normality.
+
+    See Also
+    --------
+    scipy.optimize.curve_fit :
+        Use non-linear least squares to fit a function to data.
+    scipy.optimize.leastsq :
+        Minimize the sum of squares of a set of equations.
+
+    Notes
+    -----
+    Missing values are considered pair-wise: if a value is missing in `x`,
+    the corresponding value in `y` is masked.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
+    ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::
+
+        slope, intercept, r, p, se = linregress(x, y)
+
+    With that style, however, the standard error of the intercept is not
+    available.  To have access to all the computed values, including the
+    standard error of the intercept, use the return value as an object
+    with attributes, e.g.::
+
+        result = linregress(x, y)
+        print(result.intercept, result.intercept_stderr)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Generate some data:
+
+    >>> x = rng.random(10)
+    >>> y = 1.6*x + rng.random(10)
+
+    Perform the linear regression:
+
+    >>> res = stats.mstats.linregress(x, y)
+
+    Coefficient of determination (R-squared):
+
+    >>> print(f"R-squared: {res.rvalue**2:.6f}")
+    R-squared: 0.717533
+
+    Plot the data along with the fitted line:
+
+    >>> plt.plot(x, y, 'o', label='original data')
+    >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Calculate 95% confidence interval on slope and intercept:
+
+    >>> # Two-sided inverse Students t-distribution
+    >>> # p - probability, df - degrees of freedom
+    >>> from scipy.stats import t
+    >>> tinv = lambda p, df: abs(t.ppf(p/2, df))
+
+    >>> ts = tinv(0.05, len(x)-2)
+    >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
+    slope (95%): 1.453392 +/- 0.743465
+    >>> print(f"intercept (95%): {res.intercept:.6f}"
+    ...       f" +/- {ts*res.intercept_stderr:.6f}")
+    intercept (95%): 0.616950 +/- 0.544475
+
+    """
+    if y is None:
+        x = ma.array(x)
+        if x.shape[0] == 2:
+            x, y = x
+        elif x.shape[1] == 2:
+            x, y = x.T
+        else:
+            raise ValueError("If only `x` is given as input, "
+                             "it has to be of shape (2, N) or (N, 2), "
+                             f"provided shape was {x.shape}")
+    else:
+        x = ma.array(x)
+        y = ma.array(y)
+
+    x = x.flatten()
+    y = y.flatten()
+
+    if np.amax(x) == np.amin(x) and len(x) > 1:
+        raise ValueError("Cannot calculate a linear regression "
+                         "if all x values are identical")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y), shrink=False)
+    if m is not nomask:
+        x = ma.array(x, mask=m)
+        y = ma.array(y, mask=m)
+        if np.any(~m):
+            result = _stats_py.linregress(x.data[~m], y.data[~m])
+        else:
+            # All data is masked
+            result = _stats_py.LinregressResult(slope=None, intercept=None,
+                                                rvalue=None, pvalue=None,
+                                                stderr=None,
+                                                intercept_stderr=None)
+    else:
+        result = _stats_py.linregress(x.data, y.data)
+
+    return result
+
+
+def theilslopes(y, x=None, alpha=0.95, method='separate'):
+    r"""
+    Computes the Theil-Sen estimator for a set of points (x, y).
+
+    `theilslopes` implements a method for robust linear regression.  It
+    computes the slope as the median of all slopes between paired values.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    alpha : float, optional
+        Confidence degree between 0 and 1. Default is 95% confidence.
+        Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are
+        interpreted as "find the 90% confidence interval".
+    method : {'joint', 'separate'}, optional
+        Method to be used for computing estimate for intercept.
+        Following methods are supported,
+
+            * 'joint': Uses np.median(y - slope * x) as intercept.
+            * 'separate': Uses np.median(y) - slope * np.median(x)
+                          as intercept.
+
+        The default is 'separate'.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    result : ``TheilslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Theil slope.
+        intercept : float
+            Intercept of the Theil line.
+        low_slope : float
+            Lower bound of the confidence interval on `slope`.
+        high_slope : float
+            Upper bound of the confidence interval on `slope`.
+
+    See Also
+    --------
+    siegelslopes : a similar technique using repeated medians
+
+
+    Notes
+    -----
+    For more details on `theilslopes`, see `scipy.stats.theilslopes`.
+
+    """
+    y = ma.asarray(y).flatten()
+    if x is None:
+        x = ma.arange(len(y), dtype=float)
+    else:
+        x = ma.asarray(x).flatten()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    y._mask = x._mask = m
+    # Disregard any masked elements of x or y
+    y = y.compressed()
+    x = x.compressed().astype(float)
+    # We now have unmasked arrays so can use `scipy.stats.theilslopes`
+    return stats_theilslopes(y, x, alpha=alpha, method=method)
+
+
+def siegelslopes(y, x=None, method="hierarchical"):
+    r"""
+    Computes the Siegel estimator for a set of points (x, y).
+
+    `siegelslopes` implements a method for robust linear regression
+    using repeated medians to fit a line to the points (x, y).
+    The method is robust to outliers with an asymptotic breakdown point
+    of 50%.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    method : {'hierarchical', 'separate'}
+        If 'hierarchical', estimate the intercept using the estimated
+        slope ``slope`` (default option).
+        If 'separate', estimate the intercept independent of the estimated
+        slope. See Notes for details.
+
+    Returns
+    -------
+    result : ``SiegelslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Estimate of the slope of the regression line.
+        intercept : float
+            Estimate of the intercept of the regression line.
+
+    See Also
+    --------
+    theilslopes : a similar technique without repeated medians
+
+    Notes
+    -----
+    For more details on `siegelslopes`, see `scipy.stats.siegelslopes`.
+
+    """
+    y = ma.asarray(y).ravel()
+    if x is None:
+        x = ma.arange(len(y), dtype=float)
+    else:
+        x = ma.asarray(x).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    y._mask = x._mask = m
+    # Disregard any masked elements of x or y
+    y = y.compressed()
+    x = x.compressed().astype(float)
+    # We now have unmasked arrays so can use `scipy.stats.siegelslopes`
+    return stats_siegelslopes(y, x, method=method)
+
+
+SenSeasonalSlopesResult = _make_tuple_bunch('SenSeasonalSlopesResult',
+                                            ['intra_slope', 'inter_slope'])
+
+
+def sen_seasonal_slopes(x):
+    r"""
+    Computes seasonal Theil-Sen and Kendall slope estimators.
+
+    The seasonal generalization of Sen's slope computes the slopes between all
+    pairs of values within a "season" (column) of a 2D array. It returns an
+    array containing the median of these "within-season" slopes for each
+    season (the Theil-Sen slope estimator of each season), and it returns the
+    median of the within-season slopes across all seasons (the seasonal Kendall
+    slope estimator).
+
+    Parameters
+    ----------
+    x : 2D array_like
+        Each column of `x` contains measurements of the dependent variable
+        within a season. The independent variable (usually time) of each season
+        is assumed to be ``np.arange(x.shape[0])``.
+
+    Returns
+    -------
+    result : ``SenSeasonalSlopesResult`` instance
+        The return value is an object with the following attributes:
+
+        intra_slope : ndarray
+            For each season, the Theil-Sen slope estimator: the median of
+            within-season slopes.
+        inter_slope : float
+            The seasonal Kendall slope estimator: the median of within-season
+            slopes *across all* seasons.
+
+    See Also
+    --------
+    theilslopes : the analogous function for non-seasonal data
+    scipy.stats.theilslopes : non-seasonal slopes for non-masked arrays
+
+    Notes
+    -----
+    The slopes :math:`d_{ijk}` within season :math:`i` are:
+
+    .. math::
+
+        d_{ijk} = \frac{x_{ij} - x_{ik}}
+                            {j - k}
+
+    for pairs of distinct integer indices :math:`j, k` of :math:`x`.
+
+    Element :math:`i` of the returned `intra_slope` array is the median of the
+    :math:`d_{ijk}` over all :math:`j < k`; this is the Theil-Sen slope
+    estimator of season :math:`i`. The returned `inter_slope` value, better
+    known as the seasonal Kendall slope estimator, is the median of the
+    :math:`d_{ijk}` over all :math:`i, j, k`.
+
+    References
+    ----------
+    .. [1] Hirsch, Robert M., James R. Slack, and Richard A. Smith.
+           "Techniques of trend analysis for monthly water quality data."
+           *Water Resources Research* 18.1 (1982): 107-121.
+
+    Examples
+    --------
+    Suppose we have 100 observations of a dependent variable for each of four
+    seasons:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(size=(100, 4))
+
+    We compute the seasonal slopes as:
+
+    >>> from scipy import stats
+    >>> intra_slope, inter_slope = stats.mstats.sen_seasonal_slopes(x)
+
+    If we define a function to compute all slopes between observations within
+    a season:
+
+    >>> def dijk(yi):
+    ...     n = len(yi)
+    ...     x = np.arange(n)
+    ...     dy = yi - yi[:, np.newaxis]
+    ...     dx = x - x[:, np.newaxis]
+    ...     # we only want unique pairs of distinct indices
+    ...     mask = np.triu(np.ones((n, n), dtype=bool), k=1)
+    ...     return dy[mask]/dx[mask]
+
+    then element ``i`` of ``intra_slope`` is the median of ``dijk[x[:, i]]``:
+
+    >>> i = 2
+    >>> np.allclose(np.median(dijk(x[:, i])), intra_slope[i])
+    True
+
+    and ``inter_slope`` is the median of the values returned by ``dijk`` for
+    all seasons:
+
+    >>> all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])])
+    >>> np.allclose(np.median(all_slopes), inter_slope)
+    True
+
+    Because the data are randomly generated, we would expect the median slopes
+    to be nearly zero both within and across all seasons, and indeed they are:
+
+    >>> intra_slope.data
+    array([ 0.00124504, -0.00277761, -0.00221245, -0.00036338])
+    >>> inter_slope
+    -0.0010511779872922058
+
+    """
+    x = ma.array(x, subok=True, copy=False, ndmin=2)
+    (n,_) = x.shape
+    # Get list of slopes per season
+    szn_slopes = ma.vstack([(x[i+1:]-x[i])/np.arange(1,n-i)[:,None]
+                            for i in range(n)])
+    szn_medslopes = ma.median(szn_slopes, axis=0)
+    medslope = ma.median(szn_slopes, axis=None)
+    return SenSeasonalSlopesResult(szn_medslopes, medslope)
+
+
+Ttest_1sampResult = namedtuple('Ttest_1sampResult', ('statistic', 'pvalue'))
+
+
+def ttest_1samp(a, popmean, axis=0, alternative='two-sided'):
+    """
+    Calculates the T-test for the mean of ONE group of scores.
+
+    Parameters
+    ----------
+    a : array_like
+        sample observation
+    popmean : float or array_like
+        expected value in null hypothesis, if array_like than it must have the
+        same shape as `a` excluding the axis dimension
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the mean of the underlying distribution of the sample
+          is different than the given population mean (`popmean`)
+        * 'less': the mean of the underlying distribution of the sample is
+          less than the given population mean (`popmean`)
+        * 'greater': the mean of the underlying distribution of the sample is
+          greater than the given population mean (`popmean`)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        t-statistic
+    pvalue : float or array
+        The p-value
+
+    Notes
+    -----
+    For more details on `ttest_1samp`, see `scipy.stats.ttest_1samp`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if a.size == 0:
+        return (np.nan, np.nan)
+
+    x = a.mean(axis=axis)
+    v = a.var(axis=axis, ddof=1)
+    n = a.count(axis=axis)
+    # force df to be an array for masked division not to throw a warning
+    df = ma.asanyarray(n - 1.0)
+    svar = ((n - 1.0) * v) / df
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = (x - popmean) / ma.sqrt(svar / n)
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_1sampResult(t, prob)
+
+
+ttest_onesamp = ttest_1samp
+
+
+Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
+
+
+def ttest_ind(a, b, axis=0, equal_var=True, alternative='two-sided'):
+    """
+    Calculates the T-test for the means of TWO INDEPENDENT samples of scores.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape, except in the dimension
+        corresponding to `axis` (the first, by default).
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    equal_var : bool, optional
+        If True, perform a standard independent 2 sample test that assumes equal
+        population variances.
+        If False, perform Welch's t-test, which does not assume equal population
+        variance.
+
+        .. versionadded:: 0.17.0
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistic.
+    pvalue : float or array
+        The p-value.
+
+    Notes
+    -----
+    For more details on `ttest_ind`, see `scipy.stats.ttest_ind`.
+
+    """
+    a, b, axis = _chk2_asarray(a, b, axis)
+
+    if a.size == 0 or b.size == 0:
+        return Ttest_indResult(np.nan, np.nan)
+
+    (x1, x2) = (a.mean(axis), b.mean(axis))
+    (v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1))
+    (n1, n2) = (a.count(axis), b.count(axis))
+
+    if equal_var:
+        # force df to be an array for masked division not to throw a warning
+        df = ma.asanyarray(n1 + n2 - 2.0)
+        svar = ((n1-1)*v1+(n2-1)*v2) / df
+        denom = ma.sqrt(svar*(1.0/n1 + 1.0/n2))  # n-D computation here!
+    else:
+        vn1 = v1/n1
+        vn2 = v2/n2
+        with np.errstate(divide='ignore', invalid='ignore'):
+            df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
+
+        # If df is undefined, variances are zero.
+        # It doesn't matter what df is as long as it is not NaN.
+        df = np.where(np.isnan(df), 1, df)
+        denom = ma.sqrt(vn1 + vn2)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = (x1-x2) / denom
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_indResult(t, prob)
+
+
+Ttest_relResult = namedtuple('Ttest_relResult', ('statistic', 'pvalue'))
+
+
+def ttest_rel(a, b, axis=0, alternative='two-sided'):
+    """
+    Calculates the T-test on TWO RELATED samples of scores, a and b.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape.
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        t-statistic
+    pvalue : float or array
+        two-tailed p-value
+
+    Notes
+    -----
+    For more details on `ttest_rel`, see `scipy.stats.ttest_rel`.
+
+    """
+    a, b, axis = _chk2_asarray(a, b, axis)
+    if len(a) != len(b):
+        raise ValueError('unequal length arrays')
+
+    if a.size == 0 or b.size == 0:
+        return Ttest_relResult(np.nan, np.nan)
+
+    n = a.count(axis)
+    df = ma.asanyarray(n-1.0)
+    d = (a-b).astype('d')
+    dm = d.mean(axis)
+    v = d.var(axis=axis, ddof=1)
+    denom = ma.sqrt(v / n)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = dm / denom
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_relResult(t, prob)
+
+
+MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic',
+                                                       'pvalue'))
+
+
+def mannwhitneyu(x,y, use_continuity=True):
+    """
+    Computes the Mann-Whitney statistic
+
+    Missing values in `x` and/or `y` are discarded.
+
+    Parameters
+    ----------
+    x : sequence
+        Input
+    y : sequence
+        Input
+    use_continuity : {True, False}, optional
+        Whether a continuity correction (1/2.) should be taken into account.
+
+    Returns
+    -------
+    statistic : float
+        The minimum of the Mann-Whitney statistics
+    pvalue : float
+        Approximate two-sided p-value assuming a normal distribution.
+
+    """
+    x = ma.asarray(x).compressed().view(ndarray)
+    y = ma.asarray(y).compressed().view(ndarray)
+    ranks = rankdata(np.concatenate([x,y]))
+    (nx, ny) = (len(x), len(y))
+    nt = nx + ny
+    U = ranks[:nx].sum() - nx*(nx+1)/2.
+    U = max(U, nx*ny - U)
+    u = nx*ny - U
+
+    mu = (nx*ny)/2.
+    sigsq = (nt**3 - nt)/12.
+    ties = count_tied_groups(ranks)
+    sigsq -= sum(v*(k**3-k) for (k,v) in ties.items())/12.
+    sigsq *= nx*ny/float(nt*(nt-1))
+
+    if use_continuity:
+        z = (U - 1/2. - mu) / ma.sqrt(sigsq)
+    else:
+        z = (U - mu) / ma.sqrt(sigsq)
+
+    prob = special.erfc(abs(z)/np.sqrt(2))
+    return MannwhitneyuResult(u, prob)
+
+
+KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
+
+
+def kruskal(*args):
+    """
+    Compute the Kruskal-Wallis H-test for independent samples
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+       Two or more arrays with the sample measurements can be given as
+       arguments.
+
+    Returns
+    -------
+    statistic : float
+       The Kruskal-Wallis H statistic, corrected for ties
+    pvalue : float
+       The p-value for the test using the assumption that H has a chi
+       square distribution
+
+    Notes
+    -----
+    For more details on `kruskal`, see `scipy.stats.kruskal`.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import kruskal
+
+    Random samples from three different brands of batteries were tested
+    to see how long the charge lasted. Results were as follows:
+
+    >>> a = [6.3, 5.4, 5.7, 5.2, 5.0]
+    >>> b = [6.9, 7.0, 6.1, 7.9]
+    >>> c = [7.2, 6.9, 6.1, 6.5]
+
+    Test the hypothesis that the distribution functions for all of the brands'
+    durations are identical. Use 5% level of significance.
+
+    >>> kruskal(a, b, c)
+    KruskalResult(statistic=7.113812154696133, pvalue=0.028526948491942164)
+
+    The null hypothesis is rejected at the 5% level of significance
+    because the returned p-value is less than the critical value of 5%.
+
+    """
+    output = argstoarray(*args)
+    ranks = ma.masked_equal(rankdata(output, use_missing=False), 0)
+    sumrk = ranks.sum(-1)
+    ngrp = ranks.count(-1)
+    ntot = ranks.count()
+    H = 12./(ntot*(ntot+1)) * (sumrk**2/ngrp).sum() - 3*(ntot+1)
+    # Tie correction
+    ties = count_tied_groups(ranks)
+    T = 1. - sum(v*(k**3-k) for (k,v) in ties.items())/float(ntot**3-ntot)
+    if T == 0:
+        raise ValueError('All numbers are identical in kruskal')
+
+    H /= T
+    df = len(output) - 1
+    prob = distributions.chi2.sf(H, df)
+    return KruskalResult(H, prob)
+
+
+kruskalwallis = kruskal
+
+
+@_rename_parameter("mode", "method")
+def ks_1samp(x, cdf, args=(), alternative="two-sided", method='auto'):
+    """
+    Computes the Kolmogorov-Smirnov test on one sample of masked values.
+
+    Missing values in `x` are discarded.
+
+    Parameters
+    ----------
+    x : array_like
+        a 1-D array of observations of random variables.
+    cdf : str or callable
+        If a string, it should be the name of a distribution in `scipy.stats`.
+        If a callable, that callable is used to calculate the cdf.
+    args : tuple, sequence, optional
+        Distribution parameters, used if `cdf` is a string.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Indicates the alternative hypothesis.  Default is 'two-sided'.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use approximation to exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    d : float
+        Value of the Kolmogorov Smirnov test
+    p : float
+        Corresponding p-value.
+
+    """
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+       alternative.lower()[0], alternative)
+    return scipy.stats._stats_py.ks_1samp(
+        x, cdf, args=args, alternative=alternative, method=method)
+
+
+@_rename_parameter("mode", "method")
+def ks_2samp(data1, data2, alternative="two-sided", method='auto'):
+    """
+    Computes the Kolmogorov-Smirnov test on two samples.
+
+    Missing values in `x` and/or `y` are discarded.
+
+    Parameters
+    ----------
+    data1 : array_like
+        First data set
+    data2 : array_like
+        Second data set
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Indicates the alternative hypothesis.  Default is 'two-sided'.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use approximation to exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    d : float
+        Value of the Kolmogorov Smirnov test
+    p : float
+        Corresponding p-value.
+
+    """
+    # Ideally this would be accomplished by
+    # ks_2samp = scipy.stats._stats_py.ks_2samp
+    # but the circular dependencies between _mstats_basic and stats prevent that.
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+       alternative.lower()[0], alternative)
+    return scipy.stats._stats_py.ks_2samp(data1, data2,
+                                          alternative=alternative,
+                                          method=method)
+
+
+ks_twosamp = ks_2samp
+
+
+@_rename_parameter("mode", "method")
+def kstest(data1, data2, args=(), alternative='two-sided', method='auto'):
+    """
+
+    Parameters
+    ----------
+    data1 : array_like
+    data2 : str, callable or array_like
+    args : tuple, sequence, optional
+        Distribution parameters, used if `data1` or `data2` are strings.
+    alternative : str, as documented in stats.kstest
+    method : str, as documented in stats.kstest
+
+    Returns
+    -------
+    tuple of (K-S statistic, probability)
+
+    """
+    return scipy.stats._stats_py.kstest(data1, data2, args,
+                                        alternative=alternative, method=method)
+
+
+def trima(a, limits=None, inclusive=(True,True)):
+    """
+    Trims an array by masking the data outside some given limits.
+
+    Returns a masked version of the input array.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    limits : {None, tuple}, optional
+        Tuple of (lower limit, upper limit) in absolute values.
+        Values of the input array lower (greater) than the lower (upper) limit
+        will be masked.  A limit is None indicates an open interval.
+    inclusive : (bool, bool) tuple, optional
+        Tuple of (lower flag, upper flag), indicating whether values exactly
+        equal to the lower (upper) limit are allowed.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import trima
+    >>> import numpy as np
+
+    >>> a = np.arange(10)
+
+    The interval is left-closed and right-open, i.e., `[2, 8)`.
+    Trim the array by keeping only values in the interval.
+
+    >>> trima(a, limits=(2, 8), inclusive=(True, False))
+    masked_array(data=[--, --, 2, 3, 4, 5, 6, 7, --, --],
+                 mask=[ True,  True, False, False, False, False, False, False,
+                        True,  True],
+           fill_value=999999)
+
+    """
+    a = ma.asarray(a)
+    a.unshare_mask()
+    if (limits is None) or (limits == (None, None)):
+        return a
+
+    (lower_lim, upper_lim) = limits
+    (lower_in, upper_in) = inclusive
+    condition = False
+    if lower_lim is not None:
+        if lower_in:
+            condition |= (a < lower_lim)
+        else:
+            condition |= (a <= lower_lim)
+
+    if upper_lim is not None:
+        if upper_in:
+            condition |= (a > upper_lim)
+        else:
+            condition |= (a >= upper_lim)
+
+    a[condition.filled(True)] = masked
+    return a
+
+
+def trimr(a, limits=None, inclusive=(True, True), axis=None):
+    """
+    Trims an array by masking some proportion of the data on each end.
+    Returns a masked version of the input array.
+
+    Parameters
+    ----------
+    a : sequence
+        Input array.
+    limits : {None, tuple}, optional
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1.
+        Noting n the number of unmasked data before trimming, the
+        (n*limits[0])th smallest data and the (n*limits[1])th largest data are
+        masked, and the total number of unmasked data after trimming is
+        n*(1.-sum(limits)).  The value of one limit can be set to None to
+        indicate an open interval.
+    inclusive : {(True,True) tuple}, optional
+        Tuple of flags indicating whether the number of data being masked on
+        the left (right) end should be truncated (True) or rounded (False) to
+        integers.
+    axis : {None,int}, optional
+        Axis along which to trim. If None, the whole array is trimmed, but its
+        shape is maintained.
+
+    """
+    def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive):
+        n = a.count()
+        idx = a.argsort()
+        if low_limit:
+            if low_inclusive:
+                lowidx = int(low_limit*n)
+            else:
+                lowidx = int(np.round(low_limit*n))
+            a[idx[:lowidx]] = masked
+        if up_limit is not None:
+            if up_inclusive:
+                upidx = n - int(n*up_limit)
+            else:
+                upidx = n - int(np.round(n*up_limit))
+            a[idx[upidx:]] = masked
+        return a
+
+    a = ma.asarray(a)
+    a.unshare_mask()
+    if limits is None:
+        return a
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+
+    if axis is None:
+        shp = a.shape
+        return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp)
+    else:
+        return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc)
+
+
+trimdoc = """
+    Parameters
+    ----------
+    a : sequence
+        Input array
+    limits : {None, tuple}, optional
+        If `relative` is False, tuple (lower limit, upper limit) in absolute values.
+        Values of the input array lower (greater) than the lower (upper) limit are
+        masked.
+
+        If `relative` is True, tuple (lower percentage, upper percentage) to cut
+        on each side of the  array, with respect to the number of unmasked data.
+
+        Noting n the number of unmasked data before trimming, the (n*limits[0])th
+        smallest data and the (n*limits[1])th largest data are masked, and the
+        total number of unmasked data after trimming is n*(1.-sum(limits))
+        In each case, the value of one limit can be set to None to indicate an
+        open interval.
+
+        If limits is None, no trimming is performed
+    inclusive : {(bool, bool) tuple}, optional
+        If `relative` is False, tuple indicating whether values exactly equal
+        to the absolute limits are allowed.
+        If `relative` is True, tuple indicating whether the number of data
+        being masked on each side should be rounded (True) or truncated
+        (False).
+    relative : bool, optional
+        Whether to consider the limits as absolute values (False) or proportions
+        to cut (True).
+    axis : int, optional
+        Axis along which to trim.
+"""
+
+
+def trim(a, limits=None, inclusive=(True,True), relative=False, axis=None):
+    """
+    Trims an array by masking the data outside some given limits.
+
+    Returns a masked version of the input array.
+
+    %s
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import trim
+    >>> z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
+    >>> print(trim(z,(3,8)))
+    [-- -- 3 4 5 6 7 8 -- --]
+    >>> print(trim(z,(0.1,0.2),relative=True))
+    [-- 2 3 4 5 6 7 8 -- --]
+
+    """
+    if relative:
+        return trimr(a, limits=limits, inclusive=inclusive, axis=axis)
+    else:
+        return trima(a, limits=limits, inclusive=inclusive)
+
+
+if trim.__doc__:
+    trim.__doc__ = trim.__doc__ % trimdoc
+
+
+def trimboth(data, proportiontocut=0.2, inclusive=(True,True), axis=None):
+    """
+    Trims the smallest and largest data values.
+
+    Trims the `data` by masking the ``int(proportiontocut * n)`` smallest and
+    ``int(proportiontocut * n)`` largest values of data along the given axis,
+    where n is the number of unmasked values before trimming.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data to trim.
+    proportiontocut : float, optional
+        Percentage of trimming (as a float between 0 and 1).
+        If n is the number of unmasked values before trimming, the number of
+        values after trimming is ``(1 - 2*proportiontocut) * n``.
+        Default is 0.2.
+    inclusive : {(bool, bool) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.
+
+    """
+    return trimr(data, limits=(proportiontocut,proportiontocut),
+                 inclusive=inclusive, axis=axis)
+
+
+def trimtail(data, proportiontocut=0.2, tail='left', inclusive=(True,True),
+             axis=None):
+    """
+    Trims the data by masking values from one tail.
+
+    Parameters
+    ----------
+    data : array_like
+        Data to trim.
+    proportiontocut : float, optional
+        Percentage of trimming. If n is the number of unmasked values
+        before trimming, the number of values after trimming is
+        ``(1 - proportiontocut) * n``.  Default is 0.2.
+    tail : {'left','right'}, optional
+        If 'left' the `proportiontocut` lowest values will be masked.
+        If 'right' the `proportiontocut` highest values will be masked.
+        Default is 'left'.
+    inclusive : {(bool, bool) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).  Default is
+        (True, True).
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.  Default is None.
+
+    Returns
+    -------
+    trimtail : ndarray
+        Returned array of same shape as `data` with masked tail values.
+
+    """
+    tail = str(tail).lower()[0]
+    if tail == 'l':
+        limits = (proportiontocut,None)
+    elif tail == 'r':
+        limits = (None, proportiontocut)
+    else:
+        raise TypeError("The tail argument should be in ('left','right')")
+
+    return trimr(data, limits=limits, axis=axis, inclusive=inclusive)
+
+
+trim1 = trimtail
+
+
+def trimmed_mean(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                 axis=None):
+    """Returns the trimmed mean of the data along the given axis.
+
+    %s
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        return trimr(a,limits=limits,inclusive=inclusive,axis=axis).mean(axis=axis)
+    else:
+        return trima(a,limits=limits,inclusive=inclusive).mean(axis=axis)
+
+
+if trimmed_mean.__doc__:
+    trimmed_mean.__doc__ = trimmed_mean.__doc__ % trimdoc
+
+
+def trimmed_var(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                axis=None, ddof=0):
+    """Returns the trimmed variance of the data along the given axis.
+
+    %s
+    ddof : {0,integer}, optional
+        Means Delta Degrees of Freedom. The denominator used during computations
+        is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un-
+        biased estimate of the variance.
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        out = trimr(a,limits=limits, inclusive=inclusive,axis=axis)
+    else:
+        out = trima(a,limits=limits,inclusive=inclusive)
+
+    return out.var(axis=axis, ddof=ddof)
+
+
+if trimmed_var.__doc__:
+    trimmed_var.__doc__ = trimmed_var.__doc__ % trimdoc
+
+
+def trimmed_std(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                axis=None, ddof=0):
+    """Returns the trimmed standard deviation of the data along the given axis.
+
+    %s
+    ddof : {0,integer}, optional
+        Means Delta Degrees of Freedom. The denominator used during computations
+        is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un-
+        biased estimate of the variance.
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        out = trimr(a,limits=limits,inclusive=inclusive,axis=axis)
+    else:
+        out = trima(a,limits=limits,inclusive=inclusive)
+    return out.std(axis=axis,ddof=ddof)
+
+
+if trimmed_std.__doc__:
+    trimmed_std.__doc__ = trimmed_std.__doc__ % trimdoc
+
+
+def trimmed_stde(a, limits=(0.1,0.1), inclusive=(1,1), axis=None):
+    """
+    Returns the standard error of the trimmed mean along the given axis.
+
+    Parameters
+    ----------
+    a : sequence
+        Input array
+    limits : {(0.1,0.1), tuple of float}, optional
+        tuple (lower percentage, upper percentage) to cut  on each side of the
+        array, with respect to the number of unmasked data.
+
+        If n is the number of unmasked data before trimming, the values
+        smaller than ``n * limits[0]`` and the values larger than
+        ``n * `limits[1]`` are masked, and the total number of unmasked
+        data after trimming is ``n * (1.-sum(limits))``.  In each case,
+        the value of one limit can be set to None to indicate an open interval.
+        If `limits` is None, no trimming is performed.
+    inclusive : {(bool, bool) tuple} optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).
+    axis : int, optional
+        Axis along which to trim.
+
+    Returns
+    -------
+    trimmed_stde : scalar or ndarray
+
+    """
+    def _trimmed_stde_1D(a, low_limit, up_limit, low_inclusive, up_inclusive):
+        "Returns the standard error of the trimmed mean for a 1D input data."
+        n = a.count()
+        idx = a.argsort()
+        if low_limit:
+            if low_inclusive:
+                lowidx = int(low_limit*n)
+            else:
+                lowidx = np.round(low_limit*n)
+            a[idx[:lowidx]] = masked
+        if up_limit is not None:
+            if up_inclusive:
+                upidx = n - int(n*up_limit)
+            else:
+                upidx = n - np.round(n*up_limit)
+            a[idx[upidx:]] = masked
+        a[idx[:lowidx]] = a[idx[lowidx]]
+        a[idx[upidx:]] = a[idx[upidx-1]]
+        winstd = a.std(ddof=1)
+        return winstd / ((1-low_limit-up_limit)*np.sqrt(len(a)))
+
+    a = ma.array(a, copy=True, subok=True)
+    a.unshare_mask()
+    if limits is None:
+        return a.std(axis=axis,ddof=1)/ma.sqrt(a.count(axis))
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+    if (axis is None):
+        return _trimmed_stde_1D(a.ravel(),lolim,uplim,loinc,upinc)
+    else:
+        if a.ndim > 2:
+            raise ValueError("Array 'a' must be at most two dimensional, "
+                             "but got a.ndim = %d" % a.ndim)
+        return ma.apply_along_axis(_trimmed_stde_1D, axis, a,
+                                   lolim,uplim,loinc,upinc)
+
+
+def _mask_to_limits(a, limits, inclusive):
+    """Mask an array for values outside of given limits.
+
+    This is primarily a utility function.
+
+    Parameters
+    ----------
+    a : array
+    limits : (float or None, float or None)
+    A tuple consisting of the (lower limit, upper limit).  Values in the
+    input array less than the lower limit or greater than the upper limit
+    will be masked out. None implies no limit.
+    inclusive : (bool, bool)
+    A tuple consisting of the (lower flag, upper flag).  These flags
+    determine whether values exactly equal to lower or upper are allowed.
+
+    Returns
+    -------
+    A MaskedArray.
+
+    Raises
+    ------
+    A ValueError if there are no values within the given limits.
+    """
+    lower_limit, upper_limit = limits
+    lower_include, upper_include = inclusive
+    am = ma.MaskedArray(a)
+    if lower_limit is not None:
+        if lower_include:
+            am = ma.masked_less(am, lower_limit)
+        else:
+            am = ma.masked_less_equal(am, lower_limit)
+
+    if upper_limit is not None:
+        if upper_include:
+            am = ma.masked_greater(am, upper_limit)
+        else:
+            am = ma.masked_greater_equal(am, upper_limit)
+
+    if am.count() == 0:
+        raise ValueError("No array values within given limits")
+
+    return am
+
+
+def tmean(a, limits=None, inclusive=(True, True), axis=None):
+    """
+    Compute the trimmed mean.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored.  When limits is None (default), then all
+        values are used.  Either of the limit values in the tuple can also be
+        None representing a half-open interval.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is None.
+
+    Returns
+    -------
+    tmean : float
+
+    Notes
+    -----
+    For more details on `tmean`, see `scipy.stats.tmean`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 9, 1, 2],
+    ...               [8, 7, 8, 2],
+    ...               [5, 6, 0, 2],
+    ...               [4, 5, 5, 2]])
+    ...
+    ...
+    >>> mstats.tmean(a, (2,5))
+    3.3
+    >>> mstats.tmean(a, (2,5), axis=0)
+    masked_array(data=[4.0, 5.0, 4.0, 2.0],
+                 mask=[False, False, False, False],
+           fill_value=1e+20)
+
+    """
+    return trima(a, limits=limits, inclusive=inclusive).mean(axis=axis)
+
+
+def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """
+    Compute the trimmed variance
+
+    This function computes the sample variance of an array of values,
+    while ignoring values which are outside of given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is zero.
+    ddof : int, optional
+        Delta degrees of freedom. Default is 1.
+
+    Returns
+    -------
+    tvar : float
+        Trimmed variance.
+
+    Notes
+    -----
+    For more details on `tvar`, see `scipy.stats.tvar`.
+
+    """
+    a = a.astype(float).ravel()
+    if limits is None:
+        n = (~a.mask).sum()  # todo: better way to do that?
+        return np.ma.var(a) * n/(n-1.)
+    am = _mask_to_limits(a, limits=limits, inclusive=inclusive)
+
+    return np.ma.var(am, axis=axis, ddof=ddof)
+
+
+def tmin(a, lowerlimit=None, axis=0, inclusive=True):
+    """
+    Compute the trimmed minimum
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    lowerlimit : None or float, optional
+        Values in the input array less than the given limit will be ignored.
+        When lowerlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the lower limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmin : float, int or ndarray
+
+    Notes
+    -----
+    For more details on `tmin`, see `scipy.stats.tmin`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 2, 1, 2],
+    ...               [8, 1, 8, 2],
+    ...               [5, 3, 0, 2],
+    ...               [4, 7, 5, 2]])
+    ...
+    >>> mstats.tmin(a, 5)
+    masked_array(data=[5, 7, 5, --],
+                 mask=[False, False, False,  True],
+           fill_value=999999)
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    am = trima(a, (lowerlimit, None), (inclusive, False))
+    return ma.minimum.reduce(am, axis)
+
+
+def tmax(a, upperlimit=None, axis=0, inclusive=True):
+    """
+    Compute the trimmed maximum
+
+    This function computes the maximum value of an array along a given axis,
+    while ignoring values larger than a specified upper limit.
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    upperlimit : None or float, optional
+        Values in the input array greater than the given limit will be ignored.
+        When upperlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the upper limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmax : float, int or ndarray
+
+    Notes
+    -----
+    For more details on `tmax`, see `scipy.stats.tmax`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 9, 1, 2],
+    ...               [8, 7, 8, 2],
+    ...               [5, 6, 0, 2],
+    ...               [4, 5, 5, 2]])
+    ...
+    ...
+    >>> mstats.tmax(a, 4)
+    masked_array(data=[4, --, 3, 2],
+                 mask=[False,  True, False, False],
+           fill_value=999999)
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    am = trima(a, (None, upperlimit), (False, inclusive))
+    return ma.maximum.reduce(am, axis)
+
+
+def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """
+    Compute the trimmed standard error of the mean.
+
+    This function finds the standard error of the mean for given
+    values, ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is zero.
+    ddof : int, optional
+        Delta degrees of freedom. Default is 1.
+
+    Returns
+    -------
+    tsem : float
+
+    Notes
+    -----
+    For more details on `tsem`, see `scipy.stats.tsem`.
+
+    """
+    a = ma.asarray(a).ravel()
+    if limits is None:
+        n = float(a.count())
+        return a.std(axis=axis, ddof=ddof)/ma.sqrt(n)
+
+    am = trima(a.ravel(), limits, inclusive)
+    sd = np.sqrt(am.var(axis=axis, ddof=ddof))
+    return sd / np.sqrt(am.count())
+
+
+def winsorize(a, limits=None, inclusive=(True, True), inplace=False,
+              axis=None, nan_policy='propagate'):
+    """Returns a Winsorized version of the input array.
+
+    The (limits[0])th lowest values are set to the (limits[0])th percentile,
+    and the (limits[1])th highest values are set to the (1 - limits[1])th
+    percentile.
+    Masked values are skipped.
+
+
+    Parameters
+    ----------
+    a : sequence
+        Input array.
+    limits : {None, tuple of float}, optional
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1.
+        Noting n the number of unmasked data before trimming, the
+        (n*limits[0])th smallest data and the (n*limits[1])th largest data are
+        masked, and the total number of unmasked data after trimming
+        is n*(1.-sum(limits)) The value of one limit can be set to None to
+        indicate an open interval.
+    inclusive : {(True, True) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be truncated (True) or rounded (False).
+    inplace : {False, True}, optional
+        Whether to winsorize in place (True) or to use a copy (False)
+    axis : {None, int}, optional
+        Axis along which to trim. If None, the whole array is trimmed, but its
+        shape is maintained.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': allows nan values and may overwrite or propagate them
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Notes
+    -----
+    This function is applied to reduce the effect of possibly spurious outliers
+    by limiting the extreme values.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import winsorize
+
+    A shuffled array contains integers from 1 to 10.
+
+    >>> a = np.array([10, 4, 9, 8, 5, 3, 7, 2, 1, 6])
+
+    The 10% of the lowest value (i.e., ``1``) and the 20% of the highest
+    values (i.e., ``9`` and ``10``) are replaced.
+
+    >>> winsorize(a, limits=[0.1, 0.2])
+    masked_array(data=[8, 4, 8, 8, 5, 3, 7, 2, 2, 6],
+                 mask=False,
+           fill_value=999999)
+
+    """
+    def _winsorize1D(a, low_limit, up_limit, low_include, up_include,
+                     contains_nan, nan_policy):
+        n = a.count()
+        idx = a.argsort()
+        if contains_nan:
+            nan_count = np.count_nonzero(np.isnan(a))
+        if low_limit:
+            if low_include:
+                lowidx = int(low_limit * n)
+            else:
+                lowidx = np.round(low_limit * n).astype(int)
+            if contains_nan and nan_policy == 'omit':
+                lowidx = min(lowidx, n-nan_count-1)
+            a[idx[:lowidx]] = a[idx[lowidx]]
+        if up_limit is not None:
+            if up_include:
+                upidx = n - int(n * up_limit)
+            else:
+                upidx = n - np.round(n * up_limit).astype(int)
+            if contains_nan and nan_policy == 'omit':
+                a[idx[upidx:-nan_count]] = a[idx[upidx - 1]]
+            else:
+                a[idx[upidx:]] = a[idx[upidx - 1]]
+        return a
+
+    contains_nan, nan_policy = _contains_nan(a, nan_policy)
+    # We are going to modify a: better make a copy
+    a = ma.array(a, copy=np.logical_not(inplace))
+
+    if limits is None:
+        return a
+    if (not isinstance(limits, tuple)) and isinstance(limits, float):
+        limits = (limits, limits)
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+
+    if axis is None:
+        shp = a.shape
+        return _winsorize1D(a.ravel(), lolim, uplim, loinc, upinc,
+                            contains_nan, nan_policy).reshape(shp)
+    else:
+        return ma.apply_along_axis(_winsorize1D, axis, a, lolim, uplim, loinc,
+                                   upinc, contains_nan, nan_policy)
+
+
+def moment(a, moment=1, axis=0):
+    """
+    Calculates the nth moment about the mean for a sample.
+
+    Parameters
+    ----------
+    a : array_like
+       data
+    moment : int, optional
+       order of central moment that is returned
+    axis : int or None, optional
+       Axis along which the central moment is computed. Default is 0.
+       If None, compute over the whole array `a`.
+
+    Returns
+    -------
+    n-th central moment : ndarray or float
+       The appropriate moment along the given axis or over all values if axis
+       is None. The denominator for the moment calculation is the number of
+       observations, no degrees of freedom correction is done.
+
+    Notes
+    -----
+    For more details about `moment`, see `scipy.stats.moment`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if a.size == 0:
+        moment_shape = list(a.shape)
+        del moment_shape[axis]
+        dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64
+        # empty array, return nan(s) with shape matching `moment`
+        out_shape = (moment_shape if np.isscalar(moment)
+                     else [len(moment)] + moment_shape)
+        if len(out_shape) == 0:
+            return dtype(np.nan)
+        else:
+            return ma.array(np.full(out_shape, np.nan, dtype=dtype))
+
+    # for array_like moment input, return a value for each.
+    if not np.isscalar(moment):
+        mean = a.mean(axis, keepdims=True)
+        mmnt = [_moment(a, i, axis, mean=mean) for i in moment]
+        return ma.array(mmnt)
+    else:
+        return _moment(a, moment, axis)
+
+
+# Moment with optional pre-computed mean, equal to a.mean(axis, keepdims=True)
+def _moment(a, moment, axis, *, mean=None):
+    if np.abs(moment - np.round(moment)) > 0:
+        raise ValueError("All moment parameters must be integers")
+
+    if moment == 0 or moment == 1:
+        # By definition the zeroth moment about the mean is 1, and the first
+        # moment is 0.
+        shape = list(a.shape)
+        del shape[axis]
+        dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64
+
+        if len(shape) == 0:
+            return dtype(1.0 if moment == 0 else 0.0)
+        else:
+            return (ma.ones(shape, dtype=dtype) if moment == 0
+                    else ma.zeros(shape, dtype=dtype))
+    else:
+        # Exponentiation by squares: form exponent sequence
+        n_list = [moment]
+        current_n = moment
+        while current_n > 2:
+            if current_n % 2:
+                current_n = (current_n-1)/2
+            else:
+                current_n /= 2
+            n_list.append(current_n)
+
+        # Starting point for exponentiation by squares
+        mean = a.mean(axis, keepdims=True) if mean is None else mean
+        a_zero_mean = a - mean
+        if n_list[-1] == 1:
+            s = a_zero_mean.copy()
+        else:
+            s = a_zero_mean**2
+
+        # Perform multiplications
+        for n in n_list[-2::-1]:
+            s = s**2
+            if n % 2:
+                s *= a_zero_mean
+        return s.mean(axis)
+
+
+def variation(a, axis=0, ddof=0):
+    """
+    Compute the coefficient of variation.
+
+    The coefficient of variation is the standard deviation divided by the
+    mean.  This function is equivalent to::
+
+        np.std(x, axis=axis, ddof=ddof) / np.mean(x)
+
+    The default for ``ddof`` is 0, but many definitions of the coefficient
+    of variation use the square root of the unbiased sample variance
+    for the sample standard deviation, which corresponds to ``ddof=1``.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate the coefficient of variation. Default
+        is 0. If None, compute over the whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 0.
+
+    Returns
+    -------
+    variation : ndarray
+        The calculated variation along the requested axis.
+
+    Notes
+    -----
+    For more details about `variation`, see `scipy.stats.variation`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import variation
+    >>> a = np.array([2,8,4])
+    >>> variation(a)
+    0.5345224838248487
+    >>> b = np.array([2,8,3,4])
+    >>> c = np.ma.masked_array(b, mask=[0,0,1,0])
+    >>> variation(c)
+    0.5345224838248487
+
+    In the example above, it can be seen that this works the same as
+    `scipy.stats.variation` except 'stats.mstats.variation' ignores masked
+    array elements.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    return a.std(axis, ddof=ddof)/a.mean(axis)
+
+
+def skew(a, axis=0, bias=True):
+    """
+    Computes the skewness of a data set.
+
+    Parameters
+    ----------
+    a : ndarray
+        data
+    axis : int or None, optional
+        Axis along which skewness is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+
+    Returns
+    -------
+    skewness : ndarray
+        The skewness of values along an axis, returning 0 where all values are
+        equal.
+
+    Notes
+    -----
+    For more details about `skew`, see `scipy.stats.skew`.
+
+    """
+    a, axis = _chk_asarray(a,axis)
+    mean = a.mean(axis, keepdims=True)
+    m2 = _moment(a, 2, axis, mean=mean)
+    m3 = _moment(a, 3, axis, mean=mean)
+    zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
+    with np.errstate(all='ignore'):
+        vals = ma.where(zero, 0, m3 / m2**1.5)
+
+    if not bias and zero is not ma.masked and m2 is not ma.masked:
+        n = a.count(axis)
+        can_correct = ~zero & (n > 2)
+        if can_correct.any():
+            n = np.extract(can_correct, n)
+            m2 = np.extract(can_correct, m2)
+            m3 = np.extract(can_correct, m3)
+            nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5
+            np.place(vals, can_correct, nval)
+    return vals
+
+
+def kurtosis(a, axis=0, fisher=True, bias=True):
+    """
+    Computes the kurtosis (Fisher or Pearson) of a dataset.
+
+    Kurtosis is the fourth central moment divided by the square of the
+    variance. If Fisher's definition is used, then 3.0 is subtracted from
+    the result to give 0.0 for a normal distribution.
+
+    If bias is False then the kurtosis is calculated using k statistics to
+    eliminate bias coming from biased moment estimators
+
+    Use `kurtosistest` to see if result is close enough to normal.
+
+    Parameters
+    ----------
+    a : array
+        data for which the kurtosis is calculated
+    axis : int or None, optional
+        Axis along which the kurtosis is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    fisher : bool, optional
+        If True, Fisher's definition is used (normal ==> 0.0). If False,
+        Pearson's definition is used (normal ==> 3.0).
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+
+    Returns
+    -------
+    kurtosis : array
+        The kurtosis of values along an axis. If all values are equal,
+        return -3 for Fisher's definition and 0 for Pearson's definition.
+
+    Notes
+    -----
+    For more details about `kurtosis`, see `scipy.stats.kurtosis`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    mean = a.mean(axis, keepdims=True)
+    m2 = _moment(a, 2, axis, mean=mean)
+    m4 = _moment(a, 4, axis, mean=mean)
+    zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
+    with np.errstate(all='ignore'):
+        vals = ma.where(zero, 0, m4 / m2**2.0)
+
+    if not bias and zero is not ma.masked and m2 is not ma.masked:
+        n = a.count(axis)
+        can_correct = ~zero & (n > 3)
+        if can_correct.any():
+            n = np.extract(can_correct, n)
+            m2 = np.extract(can_correct, m2)
+            m4 = np.extract(can_correct, m4)
+            nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0)
+            np.place(vals, can_correct, nval+3.0)
+    if fisher:
+        return vals - 3
+    else:
+        return vals
+
+
+DescribeResult = namedtuple('DescribeResult', ('nobs', 'minmax', 'mean',
+                                               'variance', 'skewness',
+                                               'kurtosis'))
+
+
+def describe(a, axis=0, ddof=0, bias=True):
+    """
+    Computes several descriptive statistics of the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        Data array
+    axis : int or None, optional
+        Axis along which to calculate statistics. Default 0. If None,
+        compute over the whole array `a`.
+    ddof : int, optional
+        degree of freedom (default 0); note that default ddof is different
+        from the same routine in stats.describe
+    bias : bool, optional
+        If False, then the skewness and kurtosis calculations are corrected for
+        statistical bias.
+
+    Returns
+    -------
+    nobs : int
+        (size of the data (discarding missing values)
+
+    minmax : (int, int)
+        min, max
+
+    mean : float
+        arithmetic mean
+
+    variance : float
+        unbiased variance
+
+    skewness : float
+        biased skewness
+
+    kurtosis : float
+        biased kurtosis
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import describe
+    >>> ma = np.ma.array(range(6), mask=[0, 0, 0, 1, 1, 1])
+    >>> describe(ma)
+    DescribeResult(nobs=np.int64(3), minmax=(masked_array(data=0,
+                 mask=False,
+           fill_value=999999), masked_array(data=2,
+                 mask=False,
+           fill_value=999999)), mean=np.float64(1.0),
+           variance=np.float64(0.6666666666666666),
+           skewness=masked_array(data=0., mask=False, fill_value=1e+20),
+            kurtosis=np.float64(-1.5))
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis)
+    mm = (ma.minimum.reduce(a, axis=axis), ma.maximum.reduce(a, axis=axis))
+    m = a.mean(axis)
+    v = a.var(axis, ddof=ddof)
+    sk = skew(a, axis, bias=bias)
+    kurt = kurtosis(a, axis, bias=bias)
+
+    return DescribeResult(n, mm, m, v, sk, kurt)
+
+
+def stde_median(data, axis=None):
+    """Returns the McKean-Schrader estimate of the standard error of the sample
+    median along the given axis. masked values are discarded.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data to trim.
+    axis : {None,int}, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.
+
+    """
+    def _stdemed_1D(data):
+        data = np.sort(data.compressed())
+        n = len(data)
+        z = 2.5758293035489004
+        k = int(np.round((n+1)/2. - z * np.sqrt(n/4.),0))
+        return ((data[n-k] - data[k-1])/(2.*z))
+
+    data = ma.array(data, copy=False, subok=True)
+    if (axis is None):
+        return _stdemed_1D(data)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        return ma.apply_along_axis(_stdemed_1D, axis, data)
+
+
+SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
+
+
+def skewtest(a, axis=0, alternative='two-sided'):
+    """
+    Tests whether the skew is different from the normal distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        The data to be tested
+    axis : int or None, optional
+       Axis along which statistics are calculated. Default is 0.
+       If None, compute over the whole array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the skewness of the distribution underlying the sample
+          is different from that of the normal distribution (i.e. 0)
+        * 'less': the skewness of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the skewness of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : array_like
+        The computed z-score for this test.
+    pvalue : array_like
+        A p-value for the hypothesis test
+
+    Notes
+    -----
+    For more details about `skewtest`, see `scipy.stats.skewtest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+    b2 = skew(a,axis)
+    n = a.count(axis)
+    if np.min(n) < 8:
+        raise ValueError(
+            "skewtest is not valid with less than 8 samples; %i samples"
+            " were given." % np.min(n))
+
+    y = b2 * ma.sqrt(((n+1)*(n+3)) / (6.0*(n-2)))
+    beta2 = (3.0*(n*n+27*n-70)*(n+1)*(n+3)) / ((n-2.0)*(n+5)*(n+7)*(n+9))
+    W2 = -1 + ma.sqrt(2*(beta2-1))
+    delta = 1/ma.sqrt(0.5*ma.log(W2))
+    alpha = ma.sqrt(2.0/(W2-1))
+    y = ma.where(y == 0, 1, y)
+    Z = delta*ma.log(y/alpha + ma.sqrt((y/alpha)**2+1))
+    pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative)
+
+    return SkewtestResult(Z[()], pvalue[()])
+
+
+KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
+
+
+def kurtosistest(a, axis=0, alternative='two-sided'):
+    """
+    Tests whether a dataset has normal kurtosis
+
+    Parameters
+    ----------
+    a : array_like
+        array of the sample data
+    axis : int or None, optional
+       Axis along which to compute test. Default is 0. If None,
+       compute over the whole array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the kurtosis of the distribution underlying the sample
+          is different from that of the normal distribution
+        * 'less': the kurtosis of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the kurtosis of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : array_like
+        The computed z-score for this test.
+    pvalue : array_like
+        The p-value for the hypothesis test
+
+    Notes
+    -----
+    For more details about `kurtosistest`, see `scipy.stats.kurtosistest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis=axis)
+    if np.min(n) < 5:
+        raise ValueError(
+            "kurtosistest requires at least 5 observations; %i observations"
+            " were given." % np.min(n))
+    if np.min(n) < 20:
+        warnings.warn(
+            "kurtosistest only valid for n>=20 ... continuing anyway, n=%i" % np.min(n),
+            stacklevel=2,
+        )
+
+    b2 = kurtosis(a, axis, fisher=False)
+    E = 3.0*(n-1) / (n+1)
+    varb2 = 24.0*n*(n-2.)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5))
+    x = (b2-E)/ma.sqrt(varb2)
+    sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) /
+                                                        (n*(n-2)*(n-3)))
+    A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2)))
+    term1 = 1 - 2./(9.0*A)
+    denom = 1 + x*ma.sqrt(2/(A-4.0))
+    if np.ma.isMaskedArray(denom):
+        # For multi-dimensional array input
+        denom[denom == 0.0] = masked
+    elif denom == 0.0:
+        denom = masked
+
+    term2 = np.ma.where(denom > 0, ma.power((1-2.0/A)/denom, 1/3.0),
+                        -ma.power(-(1-2.0/A)/denom, 1/3.0))
+    Z = (term1 - term2) / np.sqrt(2/(9.0*A))
+    pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative)
+
+    return KurtosistestResult(Z[()], pvalue[()])
+
+
+NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
+
+
+def normaltest(a, axis=0):
+    """
+    Tests whether a sample differs from a normal distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        The array containing the data to be tested.
+    axis : int or None, optional
+        Axis along which to compute test. Default is 0. If None,
+        compute over the whole array `a`.
+
+    Returns
+    -------
+    statistic : float or array
+        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
+        ``k`` is the z-score returned by `kurtosistest`.
+    pvalue : float or array
+       A 2-sided chi squared probability for the hypothesis test.
+
+    Notes
+    -----
+    For more details about `normaltest`, see `scipy.stats.normaltest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    s, _ = skewtest(a, axis)
+    k, _ = kurtosistest(a, axis)
+    k2 = s*s + k*k
+
+    return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
+
+
+def mquantiles(a, prob=(.25, .5, .75), alphap=.4, betap=.4, axis=None,
+               limit=()):
+    """
+    Computes empirical quantiles for a data array.
+
+    Samples quantile are defined by ``Q(p) = (1-gamma)*x[j] + gamma*x[j+1]``,
+    where ``x[j]`` is the j-th order statistic, and gamma is a function of
+    ``j = floor(n*p + m)``, ``m = alphap + p*(1 - alphap - betap)`` and
+    ``g = n*p + m - j``.
+
+    Reinterpreting the above equations to compare to **R** lead to the
+    equation: ``p(k) = (k - alphap)/(n + 1 - alphap - betap)``
+
+    Typical values of (alphap,betap) are:
+        - (0,1)    : ``p(k) = k/n`` : linear interpolation of cdf
+          (**R** type 4)
+        - (.5,.5)  : ``p(k) = (k - 1/2.)/n`` : piecewise linear function
+          (**R** type 5)
+        - (0,0)    : ``p(k) = k/(n+1)`` :
+          (**R** type 6)
+        - (1,1)    : ``p(k) = (k-1)/(n-1)``: p(k) = mode[F(x[k])].
+          (**R** type 7, **R** default)
+        - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``: Then p(k) ~ median[F(x[k])].
+          The resulting quantile estimates are approximately median-unbiased
+          regardless of the distribution of x.
+          (**R** type 8)
+        - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``: Blom.
+          The resulting quantile estimates are approximately unbiased
+          if x is normally distributed
+          (**R** type 9)
+        - (.4,.4)  : approximately quantile unbiased (Cunnane)
+        - (.35,.35): APL, used with PWM
+
+    Parameters
+    ----------
+    a : array_like
+        Input data, as a sequence or array of dimension at most 2.
+    prob : array_like, optional
+        List of quantiles to compute.
+    alphap : float, optional
+        Plotting positions parameter, default is 0.4.
+    betap : float, optional
+        Plotting positions parameter, default is 0.4.
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None (default), the input array is first flattened.
+    limit : tuple, optional
+        Tuple of (lower, upper) values.
+        Values of `a` outside this open interval are ignored.
+
+    Returns
+    -------
+    mquantiles : MaskedArray
+        An array containing the calculated quantiles.
+
+    Notes
+    -----
+    This formulation is very similar to **R** except the calculation of
+    ``m`` from ``alphap`` and ``betap``, where in **R** ``m`` is defined
+    with each type.
+
+    References
+    ----------
+    .. [1] *R* statistical software: https://www.r-project.org/
+    .. [2] *R* ``quantile`` function:
+            http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import mquantiles
+    >>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.])
+    >>> mquantiles(a)
+    array([ 19.2,  40. ,  42.8])
+
+    Using a 2D array, specifying axis and limit.
+
+    >>> data = np.array([[   6.,    7.,    1.],
+    ...                  [  47.,   15.,    2.],
+    ...                  [  49.,   36.,    3.],
+    ...                  [  15.,   39.,    4.],
+    ...                  [  42.,   40., -999.],
+    ...                  [  41.,   41., -999.],
+    ...                  [   7., -999., -999.],
+    ...                  [  39., -999., -999.],
+    ...                  [  43., -999., -999.],
+    ...                  [  40., -999., -999.],
+    ...                  [  36., -999., -999.]])
+    >>> print(mquantiles(data, axis=0, limit=(0, 50)))
+    [[19.2  14.6   1.45]
+     [40.   37.5   2.5 ]
+     [42.8  40.05  3.55]]
+
+    >>> data[:, 2] = -999.
+    >>> print(mquantiles(data, axis=0, limit=(0, 50)))
+    [[19.200000000000003 14.6 --]
+     [40.0 37.5 --]
+     [42.800000000000004 40.05 --]]
+
+    """
+    def _quantiles1D(data,m,p):
+        x = np.sort(data.compressed())
+        n = len(x)
+        if n == 0:
+            return ma.array(np.empty(len(p), dtype=float), mask=True)
+        elif n == 1:
+            return ma.array(np.resize(x, p.shape), mask=nomask)
+        aleph = (n*p + m)
+        k = np.floor(aleph.clip(1, n-1)).astype(int)
+        gamma = (aleph-k).clip(0,1)
+        return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()]
+
+    data = ma.array(a, copy=False)
+    if data.ndim > 2:
+        raise TypeError("Array should be 2D at most !")
+
+    if limit:
+        condition = (limit[0] < data) & (data < limit[1])
+        data[~condition.filled(True)] = masked
+
+    p = np.atleast_1d(np.asarray(prob))
+    m = alphap + p*(1.-alphap-betap)
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        return _quantiles1D(data, m, p)
+
+    return ma.apply_along_axis(_quantiles1D, axis, data, m, p)
+
+
+def scoreatpercentile(data, per, limit=(), alphap=.4, betap=.4):
+    """Calculate the score at the given 'per' percentile of the
+    sequence a.  For example, the score at per=50 is the median.
+
+    This function is a shortcut to mquantile
+
+    """
+    if (per < 0) or (per > 100.):
+        raise ValueError(f"The percentile should be between 0. and 100. ! (got {per})")
+
+    return mquantiles(data, prob=[per/100.], alphap=alphap, betap=betap,
+                      limit=limit, axis=0).squeeze()
+
+
+def plotting_positions(data, alpha=0.4, beta=0.4):
+    """
+    Returns plotting positions (or empirical percentile points) for the data.
+
+    Plotting positions are defined as ``(i-alpha)/(n+1-alpha-beta)``, where:
+        - i is the rank order statistics
+        - n is the number of unmasked values along the given axis
+        - `alpha` and `beta` are two parameters.
+
+    Typical values for `alpha` and `beta` are:
+        - (0,1)    : ``p(k) = k/n``, linear interpolation of cdf (R, type 4)
+        - (.5,.5)  : ``p(k) = (k-1/2.)/n``, piecewise linear function
+          (R, type 5)
+        - (0,0)    : ``p(k) = k/(n+1)``, Weibull (R type 6)
+        - (1,1)    : ``p(k) = (k-1)/(n-1)``, in this case,
+          ``p(k) = mode[F(x[k])]``. That's R default (R type 7)
+        - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``, then
+          ``p(k) ~ median[F(x[k])]``.
+          The resulting quantile estimates are approximately median-unbiased
+          regardless of the distribution of x. (R type 8)
+        - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``, Blom.
+          The resulting quantile estimates are approximately unbiased
+          if x is normally distributed (R type 9)
+        - (.4,.4)  : approximately quantile unbiased (Cunnane)
+        - (.35,.35): APL, used with PWM
+        - (.3175, .3175): used in scipy.stats.probplot
+
+    Parameters
+    ----------
+    data : array_like
+        Input data, as a sequence or array of dimension at most 2.
+    alpha : float, optional
+        Plotting positions parameter. Default is 0.4.
+    beta : float, optional
+        Plotting positions parameter. Default is 0.4.
+
+    Returns
+    -------
+    positions : MaskedArray
+        The calculated plotting positions.
+
+    """
+    data = ma.array(data, copy=False).reshape(1,-1)
+    n = data.count()
+    plpos = np.empty(data.size, dtype=float)
+    plpos[n:] = 0
+    plpos[data.argsort(axis=None)[:n]] = ((np.arange(1, n+1) - alpha) /
+                                          (n + 1.0 - alpha - beta))
+    return ma.array(plpos, mask=data._mask)
+
+
+meppf = plotting_positions
+
+
+def obrientransform(*args):
+    """
+    Computes a transform on input data (any number of columns).  Used to
+    test for homogeneity of variance prior to running one-way stats.  Each
+    array in ``*args`` is one level of a factor.  If an `f_oneway()` run on
+    the transformed data and found significant, variances are unequal.   From
+    Maxwell and Delaney, p.112.
+
+    Returns: transformed data for use in an ANOVA
+    """
+    data = argstoarray(*args).T
+    v = data.var(axis=0,ddof=1)
+    m = data.mean(0)
+    n = data.count(0).astype(float)
+    # result = ((N-1.5)*N*(a-m)**2 - 0.5*v*(n-1))/((n-1)*(n-2))
+    data -= m
+    data **= 2
+    data *= (n-1.5)*n
+    data -= 0.5*v*(n-1)
+    data /= (n-1.)*(n-2.)
+    if not ma.allclose(v,data.mean(0)):
+        raise ValueError("Lack of convergence in obrientransform.")
+
+    return data
+
+
+def sem(a, axis=0, ddof=1):
+    """
+    Calculates the standard error of the mean of the input array.
+
+    Also sometimes called standard error of measurement.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing the values for which the standard error is
+        returned.
+    axis : int or None, optional
+        If axis is None, ravel `a` first. If axis is an integer, this will be
+        the axis over which to operate. Defaults to 0.
+    ddof : int, optional
+        Delta degrees-of-freedom. How many degrees of freedom to adjust
+        for bias in limited samples relative to the population estimate
+        of variance. Defaults to 1.
+
+    Returns
+    -------
+    s : ndarray or float
+        The standard error of the mean in the sample(s), along the input axis.
+
+    Notes
+    -----
+    The default value for `ddof` changed in scipy 0.15.0 to be consistent with
+    `scipy.stats.sem` as well as with the most common definition used (like in
+    the R documentation).
+
+    Examples
+    --------
+    Find standard error along the first axis:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(20).reshape(5,4)
+    >>> print(stats.mstats.sem(a))
+    [2.8284271247461903 2.8284271247461903 2.8284271247461903
+     2.8284271247461903]
+
+    Find standard error across the whole array, using n degrees of freedom:
+
+    >>> print(stats.mstats.sem(a, axis=None, ddof=0))
+    1.2893796958227628
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis=axis)
+    s = a.std(axis=axis, ddof=ddof) / ma.sqrt(n)
+    return s
+
+
+F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
+
+
+def f_oneway(*args):
+    """
+    Performs a 1-way ANOVA, returning an F-value and probability given
+    any number of groups.  From Heiman, pp.394-7.
+
+    Usage: ``f_oneway(*args)``, where ``*args`` is 2 or more arrays,
+    one per treatment group.
+
+    Returns
+    -------
+    statistic : float
+        The computed F-value of the test.
+    pvalue : float
+        The associated p-value from the F-distribution.
+
+    """
+    # Construct a single array of arguments: each row is a group
+    data = argstoarray(*args)
+    ngroups = len(data)
+    ntot = data.count()
+    sstot = (data**2).sum() - (data.sum())**2/float(ntot)
+    ssbg = (data.count(-1) * (data.mean(-1)-data.mean())**2).sum()
+    sswg = sstot-ssbg
+    dfbg = ngroups-1
+    dfwg = ntot - ngroups
+    msb = ssbg/float(dfbg)
+    msw = sswg/float(dfwg)
+    f = msb/msw
+    prob = special.fdtrc(dfbg, dfwg, f)  # equivalent to stats.f.sf
+
+    return F_onewayResult(f, prob)
+
+
+FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
+                                     ('statistic', 'pvalue'))
+
+
+def friedmanchisquare(*args):
+    """Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA.
+    This function calculates the Friedman Chi-square test for repeated measures
+    and returns the result, along with the associated probability value.
+
+    Each input is considered a given group. Ideally, the number of treatments
+    among each group should be equal. If this is not the case, only the first
+    n treatments are taken into account, where n is the number of treatments
+    of the smallest group.
+    If a group has some missing values, the corresponding treatments are masked
+    in the other groups.
+    The test statistic is corrected for ties.
+
+    Masked values in one group are propagated to the other groups.
+
+    Returns
+    -------
+    statistic : float
+        the test statistic.
+    pvalue : float
+        the associated p-value.
+
+    """
+    data = argstoarray(*args).astype(float)
+    k = len(data)
+    if k < 3:
+        raise ValueError("Less than 3 groups (%i): " % k +
+                         "the Friedman test is NOT appropriate.")
+
+    ranked = ma.masked_values(rankdata(data, axis=0), 0)
+    if ranked._mask is not nomask:
+        ranked = ma.mask_cols(ranked)
+        ranked = ranked.compressed().reshape(k,-1).view(ndarray)
+    else:
+        ranked = ranked._data
+    (k,n) = ranked.shape
+    # Ties correction
+    repeats = [find_repeats(row) for row in ranked.T]
+    ties = np.array([y for x, y in repeats if x.size > 0])
+    tie_correction = 1 - (ties**3-ties).sum()/float(n*(k**3-k))
+
+    ssbg = np.sum((ranked.sum(-1) - n*(k+1)/2.)**2)
+    chisq = ssbg * 12./(n*k*(k+1)) * 1./tie_correction
+
+    return FriedmanchisquareResult(chisq,
+                                   distributions.chi2.sf(chisq, k-1))
+
+
+BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', ('statistic', 'pvalue'))
+
+
+def brunnermunzel(x, y, alternative="two-sided", distribution="t"):
+    """
+    Compute the Brunner-Munzel test on samples x and y.
+
+    Any missing values in `x` and/or `y` are discarded.
+
+    The Brunner-Munzel test is a nonparametric test of the null hypothesis that
+    when values are taken one by one from each group, the probabilities of
+    getting large values in both groups are equal.
+    Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
+    assumption of equivariance of two groups. Note that this does not assume
+    the distributions are same. This test works on two independent samples,
+    which may have different sizes.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Array of samples, should be one-dimensional.
+    alternative : 'less', 'two-sided', or 'greater', optional
+        Whether to get the p-value for the one-sided hypothesis ('less'
+        or 'greater') or for the two-sided hypothesis ('two-sided').
+        Defaults value is 'two-sided' .
+    distribution : 't' or 'normal', optional
+        Whether to get the p-value by t-distribution or by standard normal
+        distribution.
+        Defaults value is 't' .
+
+    Returns
+    -------
+    statistic : float
+        The Brunner-Munzer W statistic.
+    pvalue : float
+        p-value assuming an t distribution. One-sided or
+        two-sided, depending on the choice of `alternative` and `distribution`.
+
+    See Also
+    --------
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+
+    Notes
+    -----
+    For more details on `brunnermunzel`, see `scipy.stats.brunnermunzel`.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import brunnermunzel
+    >>> import numpy as np
+    >>> x1 = [1, 2, np.nan, np.nan, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1]
+    >>> x2 = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+    >>> brunnermunzel(x1, x2)
+    BrunnerMunzelResult(statistic=1.4723186918922935, pvalue=0.15479415300426624)  # may vary
+
+    """  # noqa: E501
+    x = ma.asarray(x).compressed().view(ndarray)
+    y = ma.asarray(y).compressed().view(ndarray)
+    nx = len(x)
+    ny = len(y)
+    if nx == 0 or ny == 0:
+        return BrunnerMunzelResult(np.nan, np.nan)
+    rankc = rankdata(np.concatenate((x,y)))
+    rankcx = rankc[0:nx]
+    rankcy = rankc[nx:nx+ny]
+    rankcx_mean = np.mean(rankcx)
+    rankcy_mean = np.mean(rankcy)
+    rankx = rankdata(x)
+    ranky = rankdata(y)
+    rankx_mean = np.mean(rankx)
+    ranky_mean = np.mean(ranky)
+
+    Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
+    Sx /= nx - 1
+    Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
+    Sy /= ny - 1
+
+    wbfn = nx * ny * (rankcy_mean - rankcx_mean)
+    wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
+
+    if distribution == "t":
+        df_numer = np.power(nx * Sx + ny * Sy, 2.0)
+        df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
+        df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
+        df = df_numer / df_denom
+        p = distributions.t.cdf(wbfn, df)
+    elif distribution == "normal":
+        p = distributions.norm.cdf(wbfn)
+    else:
+        raise ValueError(
+            "distribution should be 't' or 'normal'")
+
+    if alternative == "greater":
+        pass
+    elif alternative == "less":
+        p = 1 - p
+    elif alternative == "two-sided":
+        p = 2 * np.min([p, 1-p])
+    else:
+        raise ValueError(
+            "alternative should be 'less', 'greater' or 'two-sided'")
+
+    return BrunnerMunzelResult(wbfn, p)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_mstats_extras.py b/python_embeded/Lib/site-packages/scipy/stats/_mstats_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4d46366160556a7b92b92c9d3f5ceb63d0f75c7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_mstats_extras.py
@@ -0,0 +1,521 @@
+"""
+Additional statistics functions with support for masked arrays.
+
+"""
+
+# Original author (2007): Pierre GF Gerard-Marchant
+
+
+__all__ = ['compare_medians_ms',
+           'hdquantiles', 'hdmedian', 'hdquantiles_sd',
+           'idealfourths',
+           'median_cihs','mjci','mquantiles_cimj',
+           'rsh',
+           'trimmed_mean_ci',]
+
+
+import numpy as np
+from numpy import float64, ndarray
+
+import numpy.ma as ma
+from numpy.ma import MaskedArray
+
+from . import _mstats_basic as mstats
+
+from scipy.stats.distributions import norm, beta, t, binom
+
+
+def hdquantiles(data, prob=(.25, .5, .75), axis=None, var=False,):
+    """
+    Computes quantile estimates with the Harrell-Davis method.
+
+    The quantile estimates are calculated as a weighted linear combination
+    of order statistics.
+
+    Parameters
+    ----------
+    data : array_like
+        Data array.
+    prob : sequence, optional
+        Sequence of probabilities at which to compute the quantiles.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+    var : bool, optional
+        Whether to return the variance of the estimate.
+
+    Returns
+    -------
+    hdquantiles : MaskedArray
+        A (p,) array of quantiles (if `var` is False), or a (2,p) array of
+        quantiles and variances (if `var` is True), where ``p`` is the
+        number of quantiles.
+
+    See Also
+    --------
+    hdquantiles_sd
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import hdquantiles
+    >>>
+    >>> # Sample data
+    >>> data = np.array([1.2, 2.5, 3.7, 4.0, 5.1, 6.3, 7.0, 8.2, 9.4])
+    >>>
+    >>> # Probabilities at which to compute quantiles
+    >>> probabilities = [0.25, 0.5, 0.75]
+    >>>
+    >>> # Compute Harrell-Davis quantile estimates
+    >>> quantile_estimates = hdquantiles(data, prob=probabilities)
+    >>>
+    >>> # Display the quantile estimates
+    >>> for i, quantile in enumerate(probabilities):
+    ...     print(f"{int(quantile * 100)}th percentile: {quantile_estimates[i]}")
+    25th percentile: 3.1505820231763066 # may vary
+    50th percentile: 5.194344084883956
+    75th percentile: 7.430626414674935
+
+    """
+    def _hd_1D(data,prob,var):
+        "Computes the HD quantiles for a 1D array. Returns nan for invalid data."
+        xsorted = np.squeeze(np.sort(data.compressed().view(ndarray)))
+        # Don't use length here, in case we have a numpy scalar
+        n = xsorted.size
+
+        hd = np.empty((2,len(prob)), float64)
+        if n < 2:
+            hd.flat = np.nan
+            if var:
+                return hd
+            return hd[0]
+
+        v = np.arange(n+1) / float(n)
+        betacdf = beta.cdf
+        for (i,p) in enumerate(prob):
+            _w = betacdf(v, (n+1)*p, (n+1)*(1-p))
+            w = _w[1:] - _w[:-1]
+            hd_mean = np.dot(w, xsorted)
+            hd[0,i] = hd_mean
+            #
+            hd[1,i] = np.dot(w, (xsorted-hd_mean)**2)
+            #
+        hd[0, prob == 0] = xsorted[0]
+        hd[0, prob == 1] = xsorted[-1]
+        if var:
+            hd[1, prob == 0] = hd[1, prob == 1] = np.nan
+            return hd
+        return hd[0]
+    # Initialization & checks
+    data = ma.array(data, copy=False, dtype=float64)
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None) or (data.ndim == 1):
+        result = _hd_1D(data, p, var)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_hd_1D, axis, data, p, var)
+
+    return ma.fix_invalid(result, copy=False)
+
+
+def hdmedian(data, axis=-1, var=False):
+    """
+    Returns the Harrell-Davis estimate of the median along the given axis.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    axis : int, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+    var : bool, optional
+        Whether to return the variance of the estimate.
+
+    Returns
+    -------
+    hdmedian : MaskedArray
+        The median values.  If ``var=True``, the variance is returned inside
+        the masked array.  E.g. for a 1-D array the shape change from (1,) to
+        (2,).
+
+    """
+    result = hdquantiles(data,[0.5], axis=axis, var=var)
+    return result.squeeze()
+
+
+def hdquantiles_sd(data, prob=(.25, .5, .75), axis=None):
+    """
+    The standard error of the Harrell-Davis quantile estimates by jackknife.
+
+    Parameters
+    ----------
+    data : array_like
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    axis : int, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    Returns
+    -------
+    hdquantiles_sd : MaskedArray
+        Standard error of the Harrell-Davis quantile estimates.
+
+    See Also
+    --------
+    hdquantiles
+
+    """
+    def _hdsd_1D(data, prob):
+        "Computes the std error for 1D arrays."
+        xsorted = np.sort(data.compressed())
+        n = len(xsorted)
+
+        hdsd = np.empty(len(prob), float64)
+        if n < 2:
+            hdsd.flat = np.nan
+
+        vv = np.arange(n) / float(n-1)
+        betacdf = beta.cdf
+
+        for (i,p) in enumerate(prob):
+            _w = betacdf(vv, n*p, n*(1-p))
+            w = _w[1:] - _w[:-1]
+            # cumulative sum of weights and data points if
+            # ith point is left out for jackknife
+            mx_ = np.zeros_like(xsorted)
+            mx_[1:] = np.cumsum(w * xsorted[:-1])
+            # similar but from the right
+            mx_[:-1] += np.cumsum(w[::-1] * xsorted[:0:-1])[::-1]
+            hdsd[i] = np.sqrt(mx_.var() * (n - 1))
+        return hdsd
+
+    # Initialization & checks
+    data = ma.array(data, copy=False, dtype=float64)
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        result = _hdsd_1D(data, p)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_hdsd_1D, axis, data, p)
+
+    return ma.fix_invalid(result, copy=False).ravel()
+
+
+def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True),
+                    alpha=0.05, axis=None):
+    """
+    Selected confidence interval of the trimmed mean along the given axis.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data.
+    limits : {None, tuple}, optional
+        None or a two item tuple.
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1. If ``n``
+        is the number of unmasked data before trimming, then
+        (``n * limits[0]``)th smallest data and (``n * limits[1]``)th
+        largest data are masked.  The total number of unmasked data after
+        trimming is ``n * (1. - sum(limits))``.
+        The value of one limit can be set to None to indicate an open interval.
+
+        Defaults to (0.2, 0.2).
+    inclusive : (2,) tuple of boolean, optional
+        If relative==False, tuple indicating whether values exactly equal to
+        the absolute limits are allowed.
+        If relative==True, tuple indicating whether the number of data being
+        masked on each side should be rounded (True) or truncated (False).
+
+        Defaults to (True, True).
+    alpha : float, optional
+        Confidence level of the intervals.
+
+        Defaults to 0.05.
+    axis : int, optional
+        Axis along which to cut. If None, uses a flattened version of `data`.
+
+        Defaults to None.
+
+    Returns
+    -------
+    trimmed_mean_ci : (2,) ndarray
+        The lower and upper confidence intervals of the trimmed data.
+
+    """
+    data = ma.array(data, copy=False)
+    trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)
+    tmean = trimmed.mean(axis)
+    tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis)
+    df = trimmed.count(axis) - 1
+    tppf = t.ppf(1-alpha/2.,df)
+    return np.array((tmean - tppf*tstde, tmean+tppf*tstde))
+
+
+def mjci(data, prob=(0.25, 0.5, 0.75), axis=None):
+    """
+    Returns the Maritz-Jarrett estimators of the standard error of selected
+    experimental quantiles of the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    """
+    def _mjci_1D(data, p):
+        data = np.sort(data.compressed())
+        n = data.size
+        prob = (np.array(p) * n + 0.5).astype(int)
+        betacdf = beta.cdf
+
+        mj = np.empty(len(prob), float64)
+        x = np.arange(1,n+1, dtype=float64) / n
+        y = x - 1./n
+        for (i,m) in enumerate(prob):
+            W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m)
+            C1 = np.dot(W,data)
+            C2 = np.dot(W,data**2)
+            mj[i] = np.sqrt(C2 - C1**2)
+        return mj
+
+    data = ma.array(data, copy=False)
+    if data.ndim > 2:
+        raise ValueError("Array 'data' must be at most two dimensional, "
+                         "but got data.ndim = %d" % data.ndim)
+
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        return _mjci_1D(data, p)
+    else:
+        return ma.apply_along_axis(_mjci_1D, axis, data, p)
+
+
+def mquantiles_cimj(data, prob=(0.25, 0.50, 0.75), alpha=0.05, axis=None):
+    """
+    Computes the alpha confidence interval for the selected quantiles of the
+    data, with Maritz-Jarrett estimators.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    alpha : float, optional
+        Confidence level of the intervals.
+    axis : int or None, optional
+        Axis along which to compute the quantiles.
+        If None, use a flattened array.
+
+    Returns
+    -------
+    ci_lower : ndarray
+        The lower boundaries of the confidence interval.  Of the same length as
+        `prob`.
+    ci_upper : ndarray
+        The upper boundaries of the confidence interval.  Of the same length as
+        `prob`.
+
+    """
+    alpha = min(alpha, 1 - alpha)
+    z = norm.ppf(1 - alpha/2.)
+    xq = mstats.mquantiles(data, prob, alphap=0, betap=0, axis=axis)
+    smj = mjci(data, prob, axis=axis)
+    return (xq - z * smj, xq + z * smj)
+
+
+def median_cihs(data, alpha=0.05, axis=None):
+    """
+    Computes the alpha-level confidence interval for the median of the data.
+
+    Uses the Hettmasperger-Sheather method.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data. Masked values are discarded. The input should be 1D only,
+        or `axis` should be set to None.
+    alpha : float, optional
+        Confidence level of the intervals.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    Returns
+    -------
+    median_cihs
+        Alpha level confidence interval.
+
+    """
+    def _cihs_1D(data, alpha):
+        data = np.sort(data.compressed())
+        n = len(data)
+        alpha = min(alpha, 1-alpha)
+        k = int(binom._ppf(alpha/2., n, 0.5))
+        gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
+        if gk < 1-alpha:
+            k -= 1
+            gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
+        gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5)
+        I = (gk - 1 + alpha)/(gk - gkk)
+        lambd = (n-k) * I / float(k + (n-2*k)*I)
+        lims = (lambd*data[k] + (1-lambd)*data[k-1],
+                lambd*data[n-k-1] + (1-lambd)*data[n-k])
+        return lims
+    data = ma.array(data, copy=False)
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        result = _cihs_1D(data, alpha)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_cihs_1D, axis, data, alpha)
+
+    return result
+
+
+def compare_medians_ms(group_1, group_2, axis=None):
+    """
+    Compares the medians from two independent groups along the given axis.
+
+    The comparison is performed using the McKean-Schrader estimate of the
+    standard error of the medians.
+
+    Parameters
+    ----------
+    group_1 : array_like
+        First dataset.  Has to be of size >=7.
+    group_2 : array_like
+        Second dataset.  Has to be of size >=7.
+    axis : int, optional
+        Axis along which the medians are estimated. If None, the arrays are
+        flattened.  If `axis` is not None, then `group_1` and `group_2`
+        should have the same shape.
+
+    Returns
+    -------
+    compare_medians_ms : {float, ndarray}
+        If `axis` is None, then returns a float, otherwise returns a 1-D
+        ndarray of floats with a length equal to the length of `group_1`
+        along `axis`.
+
+    Examples
+    --------
+
+    >>> from scipy import stats
+    >>> a = [1, 2, 3, 4, 5, 6, 7]
+    >>> b = [8, 9, 10, 11, 12, 13, 14]
+    >>> stats.mstats.compare_medians_ms(a, b, axis=None)
+    1.0693225866553746e-05
+
+    The function is vectorized to compute along a given axis.
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(size=(3, 7))
+    >>> y = rng.random(size=(3, 8))
+    >>> stats.mstats.compare_medians_ms(x, y, axis=1)
+    array([0.36908985, 0.36092538, 0.2765313 ])
+
+    References
+    ----------
+    .. [1] McKean, Joseph W., and Ronald M. Schrader. "A comparison of methods
+       for studentizing the sample median." Communications in
+       Statistics-Simulation and Computation 13.6 (1984): 751-773.
+
+    """
+    (med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis))
+    (std_1, std_2) = (mstats.stde_median(group_1, axis=axis),
+                      mstats.stde_median(group_2, axis=axis))
+    W = np.abs(med_1 - med_2) / ma.sqrt(std_1**2 + std_2**2)
+    return 1 - norm.cdf(W)
+
+
+def idealfourths(data, axis=None):
+    """
+    Returns an estimate of the lower and upper quartiles.
+
+    Uses the ideal fourths algorithm.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    axis : int, optional
+        Axis along which the quartiles are estimated. If None, the arrays are
+        flattened.
+
+    Returns
+    -------
+    idealfourths : {list of floats, masked array}
+        Returns the two internal values that divide `data` into four parts
+        using the ideal fourths algorithm either along the flattened array
+        (if `axis` is None) or along `axis` of `data`.
+
+    """
+    def _idf(data):
+        x = data.compressed()
+        n = len(x)
+        if n < 3:
+            return [np.nan,np.nan]
+        (j,h) = divmod(n/4. + 5/12.,1)
+        j = int(j)
+        qlo = (1-h)*x[j-1] + h*x[j]
+        k = n - j
+        qup = (1-h)*x[k] + h*x[k-1]
+        return [qlo, qup]
+    data = ma.sort(data, axis=axis).view(MaskedArray)
+    if (axis is None):
+        return _idf(data)
+    else:
+        return ma.apply_along_axis(_idf, axis, data)
+
+
+def rsh(data, points=None):
+    """
+    Evaluates Rosenblatt's shifted histogram estimators for each data point.
+
+    Rosenblatt's estimator is a centered finite-difference approximation to the
+    derivative of the empirical cumulative distribution function.
+
+    Parameters
+    ----------
+    data : sequence
+        Input data, should be 1-D. Masked values are ignored.
+    points : sequence or None, optional
+        Sequence of points where to evaluate Rosenblatt shifted histogram.
+        If None, use the data.
+
+    """
+    data = ma.array(data, copy=False)
+    if points is None:
+        points = data
+    else:
+        points = np.atleast_1d(np.asarray(points))
+
+    if data.ndim != 1:
+        raise AttributeError("The input array should be 1D only !")
+
+    n = data.count()
+    r = idealfourths(data, axis=None)
+    h = 1.2 * (r[-1]-r[0]) / n**(1./5)
+    nhi = (data[:,None] <= points[None,:] + h).sum(0)
+    nlo = (data[:,None] < points[None,:] - h).sum(0)
+    return (nhi-nlo) / (2.*n*h)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_multicomp.py b/python_embeded/Lib/site-packages/scipy/stats/_multicomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..7582dcc46ff254b59bf678e19640d0a98ba50d77
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_multicomp.py
@@ -0,0 +1,449 @@
+import warnings
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Literal
+
+import numpy as np
+
+from scipy import stats
+from scipy.optimize import minimize_scalar
+from scipy.stats._common import ConfidenceInterval
+from scipy.stats._qmc import check_random_state
+from scipy.stats._stats_py import _var
+from scipy._lib._util import _transition_to_rng, DecimalNumber, SeedType
+
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+
+__all__ = [
+    'dunnett'
+]
+
+
+@dataclass
+class DunnettResult:
+    """Result object returned by `scipy.stats.dunnett`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic of the test for each comparison. The element
+        at index ``i`` is the statistic for the comparison between
+        groups ``i`` and the control.
+    pvalue : float ndarray
+        The computed p-value of the test for each comparison. The element
+        at index ``i`` is the p-value for the comparison between
+        group ``i`` and the control.
+    """
+    statistic: np.ndarray
+    pvalue: np.ndarray
+    _alternative: Literal['two-sided', 'less', 'greater'] = field(repr=False)
+    _rho: np.ndarray = field(repr=False)
+    _df: int = field(repr=False)
+    _std: float = field(repr=False)
+    _mean_samples: np.ndarray = field(repr=False)
+    _mean_control: np.ndarray = field(repr=False)
+    _n_samples: np.ndarray = field(repr=False)
+    _n_control: int = field(repr=False)
+    _rng: SeedType = field(repr=False)
+    _ci: ConfidenceInterval | None = field(default=None, repr=False)
+    _ci_cl: DecimalNumber | None = field(default=None, repr=False)
+
+    def __str__(self):
+        # Note: `__str__` prints the confidence intervals from the most
+        # recent call to `confidence_interval`. If it has not been called,
+        # it will be called with the default CL of .95.
+        if self._ci is None:
+            self.confidence_interval(confidence_level=.95)
+        s = (
+            "Dunnett's test"
+            f" ({self._ci_cl*100:.1f}% Confidence Interval)\n"
+            "Comparison               Statistic  p-value  Lower CI  Upper CI\n"
+        )
+        for i in range(self.pvalue.size):
+            s += (f" (Sample {i} - Control) {self.statistic[i]:>10.3f}"
+                  f"{self.pvalue[i]:>10.3f}"
+                  f"{self._ci.low[i]:>10.3f}"
+                  f"{self._ci.high[i]:>10.3f}\n")
+
+        return s
+
+    def _allowance(
+        self, confidence_level: DecimalNumber = 0.95, tol: DecimalNumber = 1e-3
+    ) -> float:
+        """Allowance.
+
+        It is the quantity to add/subtract from the observed difference
+        between the means of observed groups and the mean of the control
+        group. The result gives confidence limits.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval.
+            Default is .95.
+        tol : float, optional
+            A tolerance for numerical optimization: the allowance will produce
+            a confidence within ``10*tol*(1 - confidence_level)`` of the
+            specified level, or a warning will be emitted. Tight tolerances
+            may be impractical due to noisy evaluation of the objective.
+            Default is 1e-3.
+
+        Returns
+        -------
+        allowance : float
+            Allowance around the mean.
+        """
+        alpha = 1 - confidence_level
+
+        def pvalue_from_stat(statistic):
+            statistic = np.array(statistic)
+            sf = _pvalue_dunnett(
+                rho=self._rho, df=self._df,
+                statistic=statistic, alternative=self._alternative,
+                rng=self._rng
+            )
+            return abs(sf - alpha)/alpha
+
+        # Evaluation of `pvalue_from_stat` is noisy due to the use of RQMC to
+        # evaluate `multivariate_t.cdf`. `minimize_scalar` is not designed
+        # to tolerate a noisy objective function and may fail to find the
+        # minimum accurately. We mitigate this possibility with the validation
+        # step below, but implementation of a noise-tolerant root finder or
+        # minimizer would be a welcome enhancement. See gh-18150.
+        res = minimize_scalar(pvalue_from_stat, method='brent', tol=tol)
+        critical_value = res.x
+
+        # validation
+        # tol*10 because tol=1e-3 means we tolerate a 1% change at most
+        if res.success is False or res.fun >= tol*10:
+            warnings.warn(
+                "Computation of the confidence interval did not converge to "
+                "the desired level. The confidence level corresponding with "
+                f"the returned interval is approximately {alpha*(1+res.fun)}.",
+                stacklevel=3
+            )
+
+        # From [1] p. 1101 between (1) and (3)
+        allowance = critical_value*self._std*np.sqrt(
+            1/self._n_samples + 1/self._n_control
+        )
+        return abs(allowance)
+
+    def confidence_interval(
+        self, confidence_level: DecimalNumber = 0.95
+    ) -> ConfidenceInterval:
+        """Compute the confidence interval for the specified confidence level.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval.
+            Default is .95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence intervals for each
+            comparison. The high and low values are accessible for each
+            comparison at index ``i`` for each group ``i``.
+
+        """
+        # check to see if the supplied confidence level matches that of the
+        # previously computed CI.
+        if (self._ci is not None) and (confidence_level == self._ci_cl):
+            return self._ci
+
+        if not (0 < confidence_level < 1):
+            raise ValueError("Confidence level must be between 0 and 1.")
+
+        allowance = self._allowance(confidence_level=confidence_level)
+        diff_means = self._mean_samples - self._mean_control
+
+        low = diff_means-allowance
+        high = diff_means+allowance
+
+        if self._alternative == 'greater':
+            high = [np.inf] * len(diff_means)
+        elif self._alternative == 'less':
+            low = [-np.inf] * len(diff_means)
+
+        self._ci_cl = confidence_level
+        self._ci = ConfidenceInterval(
+            low=low,
+            high=high
+        )
+        return self._ci
+
+
+@_transition_to_rng('random_state', replace_doc=False)
+def dunnett(
+    *samples: "npt.ArrayLike",  # noqa: D417
+    control: "npt.ArrayLike",
+    alternative: Literal['two-sided', 'less', 'greater'] = "two-sided",
+    rng: SeedType = None
+) -> DunnettResult:
+    """Dunnett's test: multiple comparisons of means against a control group.
+
+    This is an implementation of Dunnett's original, single-step test as
+    described in [1]_.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : 1D array_like
+        The sample measurements for each experimental group.
+    control : 1D array_like
+        The sample measurements for the control group.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+
+        The null hypothesis is that the means of the distributions underlying
+        the samples and control are equal. The following alternative
+        hypotheses are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          and control are unequal.
+        * 'less': the means of the distributions underlying the samples
+          are less than the mean of the distribution underlying the control.
+        * 'greater': the means of the distributions underlying the
+          samples are greater than the mean of the distribution underlying
+          the control.
+    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`, this keyword was changed from `random_state` 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 `random_state` keyword will emit warnings. Following a
+            deprecation period, the `random_state` keyword will be removed.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.DunnettResult`
+        An object containing attributes:
+
+        statistic : float ndarray
+            The computed statistic of the test for each comparison. The element
+            at index ``i`` is the statistic for the comparison between
+            groups ``i`` and the control.
+        pvalue : float ndarray
+            The computed p-value of the test for each comparison. The element
+            at index ``i`` is the p-value for the comparison between
+            group ``i`` and the control.
+
+        And the following method:
+
+        confidence_interval(confidence_level=0.95) :
+            Compute the difference in means of the groups
+            with the control +- the allowance.
+
+    See Also
+    --------
+    tukey_hsd : performs pairwise comparison of means.
+    :ref:`hypothesis_dunnett` : Extended example
+
+    Notes
+    -----
+    Like the independent-sample t-test, Dunnett's test [1]_ is used to make
+    inferences about the means of distributions from which samples were drawn.
+    However, when multiple t-tests are performed at a fixed significance level,
+    the "family-wise error rate" - the probability of incorrectly rejecting the
+    null hypothesis in at least one test - will exceed the significance level.
+    Dunnett's test is designed to perform multiple comparisons while
+    controlling the family-wise error rate.
+
+    Dunnett's test compares the means of multiple experimental groups
+    against a single control group. Tukey's Honestly Significant Difference Test
+    is another multiple-comparison test that controls the family-wise error
+    rate, but `tukey_hsd` performs *all* pairwise comparisons between groups.
+    When pairwise comparisons between experimental groups are not needed,
+    Dunnett's test is preferable due to its higher power.
+
+    The use of this test relies on several assumptions.
+
+    1. The observations are independent within and among groups.
+    2. The observations within each group are normally distributed.
+    3. The distributions from which the samples are drawn have the same finite
+       variance.
+
+    References
+    ----------
+    .. [1] Dunnett, Charles W. (1955) "A Multiple Comparison Procedure for
+           Comparing Several Treatments with a Control." Journal of the American
+           Statistical Association, 50:272, 1096-1121,
+           :doi:`10.1080/01621459.1955.10501294`
+    .. [2] Thomson, M. L., & Short, M. D. (1969). Mucociliary function in
+           health, chronic obstructive airway disease, and asbestosis. Journal
+           of applied physiology, 26(5), 535-539.
+           :doi:`10.1152/jappl.1969.26.5.535`
+
+    Examples
+    --------
+    We'll use data from [2]_, Table 1. The null hypothesis is that the means of
+    the distributions underlying the samples and control are equal.
+
+    First, we test that the means of the distributions underlying the samples
+    and control are unequal (``alternative='two-sided'``, the default).
+
+    >>> import numpy as np
+    >>> from scipy.stats import dunnett
+    >>> samples = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]
+    >>> control = [2.9, 3.0, 2.5, 2.6, 3.2]
+    >>> res = dunnett(*samples, control=control)
+    >>> res.statistic
+    array([ 0.90874545, -0.05007117])
+    >>> res.pvalue
+    array([0.58325114, 0.99819341])
+
+    Now, we test that the means of the distributions underlying the samples are
+    greater than the mean of the distribution underlying the control.
+
+    >>> res = dunnett(*samples, control=control, alternative='greater')
+    >>> res.statistic
+    array([ 0.90874545, -0.05007117])
+    >>> res.pvalue
+    array([0.30230596, 0.69115597])
+
+    For a more detailed example, see :ref:`hypothesis_dunnett`.
+    """
+    samples_, control_, rng = _iv_dunnett(
+        samples=samples, control=control,
+        alternative=alternative, rng=rng
+    )
+
+    rho, df, n_group, n_samples, n_control = _params_dunnett(
+        samples=samples_, control=control_
+    )
+
+    statistic, std, mean_control, mean_samples = _statistic_dunnett(
+        samples_, control_, df, n_samples, n_control
+    )
+
+    pvalue = _pvalue_dunnett(
+        rho=rho, df=df, statistic=statistic, alternative=alternative, rng=rng
+    )
+
+    return DunnettResult(
+        statistic=statistic, pvalue=pvalue,
+        _alternative=alternative,
+        _rho=rho, _df=df, _std=std,
+        _mean_samples=mean_samples,
+        _mean_control=mean_control,
+        _n_samples=n_samples,
+        _n_control=n_control,
+        _rng=rng
+    )
+
+
+def _iv_dunnett(
+    samples: Sequence["npt.ArrayLike"],
+    control: "npt.ArrayLike",
+    alternative: Literal['two-sided', 'less', 'greater'],
+    rng: SeedType
+) -> tuple[list[np.ndarray], np.ndarray, SeedType]:
+    """Input validation for Dunnett's test."""
+    rng = check_random_state(rng)
+
+    if alternative not in {'two-sided', 'less', 'greater'}:
+        raise ValueError(
+            "alternative must be 'less', 'greater' or 'two-sided'"
+        )
+
+    ndim_msg = "Control and samples groups must be 1D arrays"
+    n_obs_msg = "Control and samples groups must have at least 1 observation"
+
+    control = np.asarray(control)
+    samples_ = [np.asarray(sample) for sample in samples]
+
+    # samples checks
+    samples_control: list[np.ndarray] = samples_ + [control]
+    for sample in samples_control:
+        if sample.ndim > 1:
+            raise ValueError(ndim_msg)
+
+        if sample.size < 1:
+            raise ValueError(n_obs_msg)
+
+    return samples_, control, rng
+
+
+def _params_dunnett(
+    samples: list[np.ndarray], control: np.ndarray
+) -> tuple[np.ndarray, int, int, np.ndarray, int]:
+    """Specific parameters for Dunnett's test.
+
+    Degree of freedom is the number of observations minus the number of groups
+    including the control.
+    """
+    n_samples = np.array([sample.size for sample in samples])
+
+    # From [1] p. 1100 d.f. = (sum N)-(p+1)
+    n_sample = n_samples.sum()
+    n_control = control.size
+    n = n_sample + n_control
+    n_groups = len(samples)
+    df = n - n_groups - 1
+
+    # From [1] p. 1103 rho_ij = 1/sqrt((N0/Ni+1)(N0/Nj+1))
+    rho = n_control/n_samples + 1
+    rho = 1/np.sqrt(rho[:, None] * rho[None, :])
+    np.fill_diagonal(rho, 1)
+
+    return rho, df, n_groups, n_samples, n_control
+
+
+def _statistic_dunnett(
+    samples: list[np.ndarray], control: np.ndarray, df: int,
+    n_samples: np.ndarray, n_control: int
+) -> tuple[np.ndarray, float, np.ndarray, np.ndarray]:
+    """Statistic of Dunnett's test.
+
+    Computation based on the original single-step test from [1].
+    """
+    mean_control = np.mean(control)
+    mean_samples = np.array([np.mean(sample) for sample in samples])
+    all_samples = [control] + samples
+    all_means = np.concatenate([[mean_control], mean_samples])
+
+    # Variance estimate s^2 from [1] Eq. 1
+    s2 = np.sum([_var(sample, mean=mean)*sample.size
+                 for sample, mean in zip(all_samples, all_means)]) / df
+    std = np.sqrt(s2)
+
+    # z score inferred from [1] unlabeled equation after Eq. 1
+    z = (mean_samples - mean_control) / np.sqrt(1/n_samples + 1/n_control)
+
+    return z / std, std, mean_control, mean_samples
+
+
+def _pvalue_dunnett(
+    rho: np.ndarray, df: int, statistic: np.ndarray,
+    alternative: Literal['two-sided', 'less', 'greater'],
+    rng: SeedType = None
+) -> np.ndarray:
+    """pvalue from the multivariate t-distribution.
+
+    Critical values come from the multivariate student-t distribution.
+    """
+    statistic = statistic.reshape(-1, 1)
+
+    mvt = stats.multivariate_t(shape=rho, df=df, seed=rng)
+    if alternative == "two-sided":
+        statistic = abs(statistic)
+        pvalue = 1 - mvt.cdf(statistic, lower_limit=-statistic)
+    elif alternative == "greater":
+        pvalue = 1 - mvt.cdf(statistic, lower_limit=-np.inf)
+    else:
+        pvalue = 1 - mvt.cdf(np.inf, lower_limit=statistic)
+
+    return np.atleast_1d(pvalue)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_multivariate.py b/python_embeded/Lib/site-packages/scipy/stats/_multivariate.py
new file mode 100644
index 0000000000000000000000000000000000000000..6270f1b9c765425c72d9a9f357cbd3bfcaa5f7b1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_multivariate.py
@@ -0,0 +1,7305 @@
+#
+# Author: Joris Vankerschaver 2013
+#
+import math
+import threading
+import numpy as np
+import scipy.linalg
+from scipy._lib import doccer
+from scipy.special import (gammaln, psi, multigammaln, xlogy, entr, betaln,
+                           ive, loggamma)
+from scipy import special
+from scipy._lib._util import check_random_state, _lazywhere
+from scipy.linalg.blas import drot, get_blas_funcs
+from ._continuous_distns import norm, invgamma
+from ._discrete_distns import binom
+from . import _mvn, _covariance, _rcont
+from ._qmvnt import _qmvt
+from ._morestats import directional_stats
+from scipy.optimize import root_scalar
+
+__all__ = ['multivariate_normal',
+           'matrix_normal',
+           'dirichlet',
+           'dirichlet_multinomial',
+           'wishart',
+           'invwishart',
+           'multinomial',
+           'special_ortho_group',
+           'ortho_group',
+           'random_correlation',
+           'unitary_group',
+           'multivariate_t',
+           'multivariate_hypergeom',
+           'random_table',
+           'uniform_direction',
+           'vonmises_fisher',
+           'normal_inverse_gamma']
+
+_LOG_2PI = np.log(2 * np.pi)
+_LOG_2 = np.log(2)
+_LOG_PI = np.log(np.pi)
+MVN_LOCK = threading.Lock()
+
+
+_doc_random_state = """\
+seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+    Used for drawing random variates.
+    If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+    If `seed` is an int, a new ``RandomState`` instance is used, seeded
+    with seed.
+    If `seed` is already a ``RandomState`` or ``Generator`` instance,
+    then that object is used.
+    Default is `None`.
+"""
+
+
+def _squeeze_output(out):
+    """
+    Remove single-dimensional entries from array and convert to scalar,
+    if necessary.
+    """
+    out = out.squeeze()
+    if out.ndim == 0:
+        out = out[()]
+    return out
+
+
+def _eigvalsh_to_eps(spectrum, cond=None, rcond=None):
+    """Determine which eigenvalues are "small" given the spectrum.
+
+    This is for compatibility across various linear algebra functions
+    that should agree about whether or not a Hermitian matrix is numerically
+    singular and what is its numerical matrix rank.
+    This is designed to be compatible with scipy.linalg.pinvh.
+
+    Parameters
+    ----------
+    spectrum : 1d ndarray
+        Array of eigenvalues of a Hermitian matrix.
+    cond, rcond : float, optional
+        Cutoff for small eigenvalues.
+        Singular values smaller than rcond * largest_eigenvalue are
+        considered zero.
+        If None or -1, suitable machine precision is used.
+
+    Returns
+    -------
+    eps : float
+        Magnitude cutoff for numerical negligibility.
+
+    """
+    if rcond is not None:
+        cond = rcond
+    if cond in [None, -1]:
+        t = spectrum.dtype.char.lower()
+        factor = {'f': 1E3, 'd': 1E6}
+        cond = factor[t] * np.finfo(t).eps
+    eps = cond * np.max(abs(spectrum))
+    return eps
+
+
+def _pinv_1d(v, eps=1e-5):
+    """A helper function for computing the pseudoinverse.
+
+    Parameters
+    ----------
+    v : iterable of numbers
+        This may be thought of as a vector of eigenvalues or singular values.
+    eps : float
+        Values with magnitude no greater than eps are considered negligible.
+
+    Returns
+    -------
+    v_pinv : 1d float ndarray
+        A vector of pseudo-inverted numbers.
+
+    """
+    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)
+
+
+class _PSD:
+    """
+    Compute coordinated functions of a symmetric positive semidefinite matrix.
+
+    This class addresses two issues.  Firstly it allows the pseudoinverse,
+    the logarithm of the pseudo-determinant, and the rank of the matrix
+    to be computed using one call to eigh instead of three.
+    Secondly it allows these functions to be computed in a way
+    that gives mutually compatible results.
+    All of the functions are computed with a common understanding as to
+    which of the eigenvalues are to be considered negligibly small.
+    The functions are designed to coordinate with scipy.linalg.pinvh()
+    but not necessarily with np.linalg.det() or with np.linalg.matrix_rank().
+
+    Parameters
+    ----------
+    M : array_like
+        Symmetric positive semidefinite matrix (2-D).
+    cond, rcond : float, optional
+        Cutoff for small eigenvalues.
+        Singular values smaller than rcond * largest_eigenvalue are
+        considered zero.
+        If None or -1, suitable machine precision is used.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower
+        or upper triangle of M. (Default: lower)
+    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.
+    allow_singular : bool, optional
+        Whether to allow a singular matrix.  (Default: True)
+
+    Notes
+    -----
+    The arguments are similar to those of scipy.linalg.pinvh().
+
+    """
+
+    def __init__(self, M, cond=None, rcond=None, lower=True,
+                 check_finite=True, allow_singular=True):
+        self._M = np.asarray(M)
+
+        # Compute the symmetric eigendecomposition.
+        # Note that eigh takes care of array conversion, chkfinite,
+        # and assertion that the matrix is square.
+        s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite)
+
+        eps = _eigvalsh_to_eps(s, cond, rcond)
+        if np.min(s) < -eps:
+            msg = "The input matrix must be symmetric positive semidefinite."
+            raise ValueError(msg)
+        d = s[s > eps]
+        if len(d) < len(s) and not allow_singular:
+            msg = ("When `allow_singular is False`, the input matrix must be "
+                   "symmetric positive definite.")
+            raise np.linalg.LinAlgError(msg)
+        s_pinv = _pinv_1d(s, eps)
+        U = np.multiply(u, np.sqrt(s_pinv))
+
+        # Save the eigenvector basis, and tolerance for testing support
+        self.eps = 1e3*eps
+        self.V = u[:, s <= eps]
+
+        # Initialize the eagerly precomputed attributes.
+        self.rank = len(d)
+        self.U = U
+        self.log_pdet = np.sum(np.log(d))
+
+        # Initialize attributes to be lazily computed.
+        self._pinv = None
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        residual = np.linalg.norm(x @ self.V, axis=-1)
+        in_support = residual < self.eps
+        return in_support
+
+    @property
+    def pinv(self):
+        if self._pinv is None:
+            self._pinv = np.dot(self.U, self.U.T)
+        return self._pinv
+
+
+class multi_rv_generic:
+    """
+    Class which encapsulates common functionality between all multivariate
+    distributions.
+    """
+    def __init__(self, seed=None):
+        super().__init__()
+        self._random_state = check_random_state(seed)
+
+    @property
+    def random_state(self):
+        """ Get or set the Generator object for generating random variates.
+
+        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.
+
+        """
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._random_state = check_random_state(seed)
+
+    def _get_random_state(self, random_state):
+        if random_state is not None:
+            return check_random_state(random_state)
+        else:
+            return self._random_state
+
+
+class multi_rv_frozen:
+    """
+    Class which encapsulates common functionality between all frozen
+    multivariate distributions.
+    """
+    @property
+    def random_state(self):
+        return self._dist._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._dist._random_state = check_random_state(seed)
+
+
+_mvn_doc_default_callparams = """\
+mean : array_like, default: ``[0]``
+    Mean of the distribution.
+cov : array_like or `Covariance`, default: ``[1]``
+    Symmetric positive (semi)definite covariance matrix of the distribution.
+allow_singular : bool, default: ``False``
+    Whether to allow a singular covariance matrix. This is ignored if `cov` is
+    a `Covariance` object.
+"""
+
+_mvn_doc_callparams_note = """\
+Setting the parameter `mean` to `None` is equivalent to having `mean`
+be the zero-vector. The parameter `cov` can be a scalar, in which case
+the covariance matrix is the identity times that value, a vector of
+diagonal entries for the covariance matrix, a two-dimensional array_like,
+or a `Covariance` object.
+"""
+
+_mvn_doc_frozen_callparams = ""
+
+_mvn_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mvn_docdict_params = {
+    '_mvn_doc_default_callparams': _mvn_doc_default_callparams,
+    '_mvn_doc_callparams_note': _mvn_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mvn_docdict_noparams = {
+    '_mvn_doc_default_callparams': _mvn_doc_frozen_callparams,
+    '_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_normal_gen(multi_rv_generic):
+    r"""A multivariate normal random variable.
+
+    The `mean` keyword specifies the mean. The `cov` keyword specifies the
+    covariance matrix.
+
+    Methods
+    -------
+    pdf(x, mean=None, cov=1, allow_singular=False)
+        Probability density function.
+    logpdf(x, mean=None, cov=1, allow_singular=False)
+        Log of the probability density function.
+    cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5, lower_limit=None)
+        Cumulative distribution function.
+    logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)
+        Log of the cumulative distribution function.
+    rvs(mean=None, cov=1, size=1, random_state=None)
+        Draw random samples from a multivariate normal distribution.
+    entropy(mean=None, cov=1)
+        Compute the differential entropy of the multivariate normal.
+    fit(x, fix_mean=None, fix_cov=None)
+        Fit a multivariate normal distribution to data.
+
+    Parameters
+    ----------
+    %(_mvn_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_mvn_doc_callparams_note)s
+
+    The covariance matrix `cov` may be an instance of a subclass of
+    `Covariance`, e.g. `scipy.stats.CovViaPrecision`. If so, `allow_singular`
+    is ignored.
+
+    Otherwise, `cov` must be a symmetric positive semidefinite
+    matrix when `allow_singular` is True; it must be (strictly) positive
+    definite when `allow_singular` is False.
+    Symmetry is not checked; only the lower triangular portion is used.
+    The determinant and inverse of `cov` are computed
+    as the pseudo-determinant and pseudo-inverse, respectively, so
+    that `cov` does not need to have full rank.
+
+    The probability density function for `multivariate_normal` is
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}}
+               \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right),
+
+    where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix,
+    :math:`k` the rank of :math:`\Sigma`. In case of singular :math:`\Sigma`,
+    SciPy extends this definition according to [1]_.
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] Multivariate Normal Distribution - Degenerate Case, Wikipedia,
+           https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import multivariate_normal
+
+    >>> x = np.linspace(0, 5, 10, endpoint=False)
+    >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y
+    array([ 0.00108914,  0.01033349,  0.05946514,  0.20755375,  0.43939129,
+            0.56418958,  0.43939129,  0.20755375,  0.05946514,  0.01033349])
+    >>> fig1 = plt.figure()
+    >>> ax = fig1.add_subplot(111)
+    >>> ax.plot(x, y)
+    >>> plt.show()
+
+    Alternatively, the object may be called (as a function) to fix the mean
+    and covariance parameters, returning a "frozen" multivariate normal
+    random variable:
+
+    >>> rv = multivariate_normal(mean=None, cov=1, allow_singular=False)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # mean and covariance fixed.
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.  This allows us for instance to
+    display the frozen pdf for a non-isotropic random variable in 2D as
+    follows:
+
+    >>> x, y = np.mgrid[-1:1:.01, -1:1:.01]
+    >>> pos = np.dstack((x, y))
+    >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]])
+    >>> fig2 = plt.figure()
+    >>> ax2 = fig2.add_subplot(111)
+    >>> ax2.contourf(x, y, rv.pdf(pos))
+
+    """  # noqa: E501
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params)
+
+    def __call__(self, mean=None, cov=1, allow_singular=False, seed=None):
+        """Create a frozen multivariate normal distribution.
+
+        See `multivariate_normal_frozen` for more information.
+        """
+        return multivariate_normal_frozen(mean, cov,
+                                          allow_singular=allow_singular,
+                                          seed=seed)
+
+    def _process_parameters(self, mean, cov, allow_singular=True):
+        """
+        Infer dimensionality from mean or covariance matrix, ensure that
+        mean and covariance are full vector resp. matrix.
+        """
+        if isinstance(cov, _covariance.Covariance):
+            return self._process_parameters_Covariance(mean, cov)
+        else:
+            # Before `Covariance` classes were introduced,
+            # `multivariate_normal` accepted plain arrays as `cov` and used the
+            # following input validation. To avoid disturbing the behavior of
+            # `multivariate_normal` when plain arrays are used, we use the
+            # original input validation here.
+            dim, mean, cov = self._process_parameters_psd(None, mean, cov)
+            # After input validation, some methods then processed the arrays
+            # with a `_PSD` object and used that to perform computation.
+            # To avoid branching statements in each method depending on whether
+            # `cov` is an array or `Covariance` object, we always process the
+            # array with `_PSD`, and then use wrapper that satisfies the
+            # `Covariance` interface, `CovViaPSD`.
+            psd = _PSD(cov, allow_singular=allow_singular)
+            cov_object = _covariance.CovViaPSD(psd)
+            return dim, mean, cov_object
+
+    def _process_parameters_Covariance(self, mean, cov):
+        dim = cov.shape[-1]
+        mean = np.array([0.]) if mean is None else mean
+        message = (f"`cov` represents a covariance matrix in {dim} dimensions,"
+                   f"and so `mean` must be broadcastable to shape {(dim,)}")
+        try:
+            mean = np.broadcast_to(mean, dim)
+        except ValueError as e:
+            raise ValueError(message) from e
+        return dim, mean, cov
+
+    def _process_parameters_psd(self, dim, mean, cov):
+        # Try to infer dimensionality
+        if dim is None:
+            if mean is None:
+                if cov is None:
+                    dim = 1
+                else:
+                    cov = np.asarray(cov, dtype=float)
+                    if cov.ndim < 2:
+                        dim = 1
+                    else:
+                        dim = cov.shape[0]
+            else:
+                mean = np.asarray(mean, dtype=float)
+                dim = mean.size
+        else:
+            if not np.isscalar(dim):
+                raise ValueError("Dimension of random variable must be "
+                                 "a scalar.")
+
+        # Check input sizes and return full arrays for mean and cov if
+        # necessary
+        if mean is None:
+            mean = np.zeros(dim)
+        mean = np.asarray(mean, dtype=float)
+
+        if cov is None:
+            cov = 1.0
+        cov = np.asarray(cov, dtype=float)
+
+        if dim == 1:
+            mean = mean.reshape(1)
+            cov = cov.reshape(1, 1)
+
+        if mean.ndim != 1 or mean.shape[0] != dim:
+            raise ValueError("Array 'mean' must be a vector of length %d." %
+                             dim)
+        if cov.ndim == 0:
+            cov = cov * np.eye(dim)
+        elif cov.ndim == 1:
+            cov = np.diag(cov)
+        elif cov.ndim == 2 and cov.shape != (dim, dim):
+            rows, cols = cov.shape
+            if rows != cols:
+                msg = ("Array 'cov' must be square if it is two dimensional,"
+                       f" but cov.shape = {str(cov.shape)}.")
+            else:
+                msg = ("Dimension mismatch: array 'cov' is of shape %s,"
+                       " but 'mean' is a vector of length %d.")
+                msg = msg % (str(cov.shape), len(mean))
+            raise ValueError(msg)
+        elif cov.ndim > 2:
+            raise ValueError("Array 'cov' must be at most two-dimensional,"
+                             " but cov.ndim = %d" % cov.ndim)
+
+        return dim, mean, cov
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+
+        if x.ndim == 0:
+            x = x[np.newaxis]
+        elif x.ndim == 1:
+            if dim == 1:
+                x = x[:, np.newaxis]
+            else:
+                x = x[np.newaxis, :]
+
+        return x
+
+    def _logpdf(self, x, mean, cov_object):
+        """Log of the multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        mean : ndarray
+            Mean of the distribution
+        cov_object : Covariance
+            An object representing the Covariance matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        log_det_cov, rank = cov_object.log_pdet, cov_object.rank
+        dev = x - mean
+        if dev.ndim > 1:
+            log_det_cov = log_det_cov[..., np.newaxis]
+            rank = rank[..., np.newaxis]
+        maha = np.sum(np.square(cov_object.whiten(dev)), axis=-1)
+        return -0.5 * (rank * _LOG_2PI + log_det_cov + maha)
+
+    def logpdf(self, x, mean=None, cov=1, allow_singular=False):
+        """Log of the multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        x = self._process_quantiles(x, dim)
+        out = self._logpdf(x, mean, cov_object)
+        if np.any(cov_object.rank < dim):
+            out_of_bounds = ~cov_object._support_mask(x-mean)
+            out[out_of_bounds] = -np.inf
+        return _squeeze_output(out)
+
+    def pdf(self, x, mean=None, cov=1, allow_singular=False):
+        """Multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        x = self._process_quantiles(x, dim)
+        out = np.exp(self._logpdf(x, mean, cov_object))
+        if np.any(cov_object.rank < dim):
+            out_of_bounds = ~cov_object._support_mask(x-mean)
+            out[out_of_bounds] = 0.0
+        return _squeeze_output(out)
+
+    def _cdf(self, x, mean, cov, maxpts, abseps, releps, lower_limit):
+        """Multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the cumulative distribution function.
+        mean : ndarray
+            Mean of the distribution
+        cov : array_like
+            Covariance matrix of the distribution
+        maxpts : integer
+            The maximum number of points to use for integration
+        abseps : float
+            Absolute error tolerance
+        releps : float
+            Relative error tolerance
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'cdf' instead.
+
+
+        .. versionadded:: 1.0.0
+
+        """
+        lower = (np.full(mean.shape, -np.inf)
+                 if lower_limit is None else lower_limit)
+        # In 2d, _mvn.mvnun accepts input in which `lower` bound elements
+        # are greater than `x`. Not so in other dimensions. Fix this by
+        # ensuring that lower bounds are indeed lower when passed, then
+        # set signs of resulting CDF manually.
+        b, a = np.broadcast_arrays(x, lower)
+        i_swap = b < a
+        signs = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+        a, b = a.copy(), b.copy()
+        a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+        n = x.shape[-1]
+        limits = np.concatenate((a, b), axis=-1)
+
+        # mvnun expects 1-d arguments, so process points sequentially
+        def func1d(limits):
+            with MVN_LOCK:
+                return _mvn.mvnun(limits[:n], limits[n:], mean, cov,
+                                maxpts, abseps, releps)[0]
+
+        out = np.apply_along_axis(func1d, -1, limits) * signs
+        return _squeeze_output(out)
+
+    def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
+               abseps=1e-5, releps=1e-5, *, lower_limit=None):
+        """Log of the multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+        maxpts : integer, optional
+            The maximum number of points to use for integration
+            (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance (default 1e-5)
+        releps : float, optional
+            Relative error tolerance (default 1e-5)
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Log of the cumulative distribution function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        .. versionadded:: 1.0.0
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        cov = cov_object.covariance
+        x = self._process_quantiles(x, dim)
+        if not maxpts:
+            maxpts = 1000000 * dim
+        cdf = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit)
+        # the log of a negative real is complex, and cdf can be negative
+        # if lower limit is greater than upper limit
+        cdf = cdf + 0j if np.any(cdf < 0) else cdf
+        out = np.log(cdf)
+        return out
+
+    def cdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
+            abseps=1e-5, releps=1e-5, *, lower_limit=None):
+        """Multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+        maxpts : integer, optional
+            The maximum number of points to use for integration
+            (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance (default 1e-5)
+        releps : float, optional
+            Relative error tolerance (default 1e-5)
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Cumulative distribution function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        .. versionadded:: 1.0.0
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        cov = cov_object.covariance
+        x = self._process_quantiles(x, dim)
+        if not maxpts:
+            maxpts = 1000000 * dim
+        out = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit)
+        return out
+
+    def rvs(self, mean=None, cov=1, size=1, random_state=None):
+        """Draw random samples from a multivariate normal distribution.
+
+        Parameters
+        ----------
+        %(_mvn_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the random variable.
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        dim, mean, cov_object = self._process_parameters(mean, cov)
+        random_state = self._get_random_state(random_state)
+
+        if isinstance(cov_object, _covariance.CovViaPSD):
+            cov = cov_object.covariance
+            out = random_state.multivariate_normal(mean, cov, size)
+            out = _squeeze_output(out)
+        else:
+            size = size or tuple()
+            if not np.iterable(size):
+                size = (size,)
+            shape = tuple(size) + (cov_object.shape[-1],)
+            x = random_state.normal(size=shape)
+            out = mean + cov_object.colorize(x)
+        return out
+
+    def entropy(self, mean=None, cov=1):
+        """Compute the differential entropy of the multivariate normal.
+
+        Parameters
+        ----------
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the multivariate normal distribution
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        dim, mean, cov_object = self._process_parameters(mean, cov)
+        return 0.5 * (cov_object.rank * (_LOG_2PI + 1) + cov_object.log_pdet)
+
+    def fit(self, x, fix_mean=None, fix_cov=None):
+        """Fit a multivariate normal distribution to data.
+
+        Parameters
+        ----------
+        x : ndarray (m, n)
+            Data the distribution is fitted to. Must have two axes.
+            The first axis of length `m` represents the number of vectors
+            the distribution is fitted to. The second axis of length `n`
+            determines the dimensionality of the fitted distribution.
+        fix_mean : ndarray(n, )
+            Fixed mean vector. Must have length `n`.
+        fix_cov: ndarray (n, n)
+            Fixed covariance matrix. Must have shape ``(n, n)``.
+
+        Returns
+        -------
+        mean : ndarray (n, )
+            Maximum likelihood estimate of the mean vector
+        cov : ndarray (n, n)
+            Maximum likelihood estimate of the covariance matrix
+
+        """
+        # input validation for data to be fitted
+        x = np.asarray(x)
+        if x.ndim != 2:
+            raise ValueError("`x` must be two-dimensional.")
+
+        n_vectors, dim = x.shape
+
+        # parameter estimation
+        # reference: https://home.ttic.edu/~shubhendu/Slides/Estimation.pdf
+        if fix_mean is not None:
+            # input validation for `fix_mean`
+            fix_mean = np.atleast_1d(fix_mean)
+            if fix_mean.shape != (dim, ):
+                msg = ("`fix_mean` must be a one-dimensional array the same "
+                       "length as the dimensionality of the vectors `x`.")
+                raise ValueError(msg)
+            mean = fix_mean
+        else:
+            mean = x.mean(axis=0)
+
+        if fix_cov is not None:
+            # input validation for `fix_cov`
+            fix_cov = np.atleast_2d(fix_cov)
+            # validate shape
+            if fix_cov.shape != (dim, dim):
+                msg = ("`fix_cov` must be a two-dimensional square array "
+                       "of same side length as the dimensionality of the "
+                       "vectors `x`.")
+                raise ValueError(msg)
+            # validate positive semidefiniteness
+            # a trimmed down copy from _PSD
+            s, u = scipy.linalg.eigh(fix_cov, lower=True, check_finite=True)
+            eps = _eigvalsh_to_eps(s)
+            if np.min(s) < -eps:
+                msg = "`fix_cov` must be symmetric positive semidefinite."
+                raise ValueError(msg)
+            cov = fix_cov
+        else:
+            centered_data = x - mean
+            cov = centered_data.T @ centered_data / n_vectors
+        return mean, cov
+
+
+multivariate_normal = multivariate_normal_gen()
+
+
+class multivariate_normal_frozen(multi_rv_frozen):
+    def __init__(self, mean=None, cov=1, allow_singular=False, seed=None,
+                 maxpts=None, abseps=1e-5, releps=1e-5):
+        """Create a frozen multivariate normal distribution.
+
+        Parameters
+        ----------
+        mean : array_like, default: ``[0]``
+            Mean of the distribution.
+        cov : array_like, default: ``[1]``
+            Symmetric positive (semi)definite covariance matrix of the
+            distribution.
+        allow_singular : bool, default: ``False``
+            Whether to allow a singular covariance matrix.
+        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.
+        maxpts : integer, optional
+            The maximum number of points to use for integration of the
+            cumulative distribution function (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance for the cumulative distribution function
+            (default 1e-5)
+        releps : float, optional
+            Relative error tolerance for the cumulative distribution function
+            (default 1e-5)
+
+        Examples
+        --------
+        When called with the default parameters, this will create a 1D random
+        variable with mean 0 and covariance 1:
+
+        >>> from scipy.stats import multivariate_normal
+        >>> r = multivariate_normal()
+        >>> r.mean
+        array([ 0.])
+        >>> r.cov
+        array([[1.]])
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = multivariate_normal_gen(seed)
+        self.dim, self.mean, self.cov_object = (
+            self._dist._process_parameters(mean, cov, allow_singular))
+        self.allow_singular = allow_singular or self.cov_object._allow_singular
+        if not maxpts:
+            maxpts = 1000000 * self.dim
+        self.maxpts = maxpts
+        self.abseps = abseps
+        self.releps = releps
+
+    @property
+    def cov(self):
+        return self.cov_object.covariance
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._logpdf(x, self.mean, self.cov_object)
+        if np.any(self.cov_object.rank < self.dim):
+            out_of_bounds = ~self.cov_object._support_mask(x-self.mean)
+            out[out_of_bounds] = -np.inf
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def logcdf(self, x, *, lower_limit=None):
+        cdf = self.cdf(x, lower_limit=lower_limit)
+        # the log of a negative real is complex, and cdf can be negative
+        # if lower limit is greater than upper limit
+        cdf = cdf + 0j if np.any(cdf < 0) else cdf
+        out = np.log(cdf)
+        return out
+
+    def cdf(self, x, *, lower_limit=None):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._cdf(x, self.mean, self.cov_object.covariance,
+                              self.maxpts, self.abseps, self.releps,
+                              lower_limit)
+        return _squeeze_output(out)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.mean, self.cov_object, size, random_state)
+
+    def entropy(self):
+        """Computes the differential entropy of the multivariate normal.
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the multivariate normal distribution
+
+        """
+        log_pdet = self.cov_object.log_pdet
+        rank = self.cov_object.rank
+        return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'logcdf', 'cdf', 'rvs']:
+    method = multivariate_normal_gen.__dict__[name]
+    method_frozen = multivariate_normal_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params)
+
+_matnorm_doc_default_callparams = """\
+mean : array_like, optional
+    Mean of the distribution (default: `None`)
+rowcov : array_like, optional
+    Among-row covariance matrix of the distribution (default: ``1``)
+colcov : array_like, optional
+    Among-column covariance matrix of the distribution (default: ``1``)
+"""
+
+_matnorm_doc_callparams_note = """\
+If `mean` is set to `None` then a matrix of zeros is used for the mean.
+The dimensions of this matrix are inferred from the shape of `rowcov` and
+`colcov`, if these are provided, or set to ``1`` if ambiguous.
+
+`rowcov` and `colcov` can be two-dimensional array_likes specifying the
+covariance matrices directly. Alternatively, a one-dimensional array will
+be be interpreted as the entries of a diagonal matrix, and a scalar or
+zero-dimensional array will be interpreted as this value times the
+identity matrix.
+"""
+
+_matnorm_doc_frozen_callparams = ""
+
+_matnorm_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+matnorm_docdict_params = {
+    '_matnorm_doc_default_callparams': _matnorm_doc_default_callparams,
+    '_matnorm_doc_callparams_note': _matnorm_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+matnorm_docdict_noparams = {
+    '_matnorm_doc_default_callparams': _matnorm_doc_frozen_callparams,
+    '_matnorm_doc_callparams_note': _matnorm_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class matrix_normal_gen(multi_rv_generic):
+    r"""A matrix normal random variable.
+
+    The `mean` keyword specifies the mean. The `rowcov` keyword specifies the
+    among-row covariance matrix. The 'colcov' keyword specifies the
+    among-column covariance matrix.
+
+    Methods
+    -------
+    pdf(X, mean=None, rowcov=1, colcov=1)
+        Probability density function.
+    logpdf(X, mean=None, rowcov=1, colcov=1)
+        Log of the probability density function.
+    rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None)
+        Draw random samples.
+    entropy(rowcol=1, colcov=1)
+        Differential entropy.
+
+    Parameters
+    ----------
+    %(_matnorm_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_matnorm_doc_callparams_note)s
+
+    The covariance matrices specified by `rowcov` and `colcov` must be
+    (symmetric) positive definite. If the samples in `X` are
+    :math:`m \times n`, then `rowcov` must be :math:`m \times m` and
+    `colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`.
+
+    The probability density function for `matrix_normal` is
+
+    .. math::
+
+        f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}}
+               \exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1}
+               (X-M)^T \right] \right),
+
+    where :math:`M` is the mean, :math:`U` the among-row covariance matrix,
+    :math:`V` the among-column covariance matrix.
+
+    The `allow_singular` behaviour of the `multivariate_normal`
+    distribution is not currently supported. Covariance matrices must be
+    full rank.
+
+    The `matrix_normal` distribution is closely related to the
+    `multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)`
+    (the vector formed by concatenating the columns  of :math:`X`) has a
+    multivariate normal distribution with mean :math:`\mathrm{Vec}(M)`
+    and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker
+    product). Sampling and pdf evaluation are
+    :math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but
+    :math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal,
+    making this equivalent form algorithmically inefficient.
+
+    .. versionadded:: 0.17.0
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.stats import matrix_normal
+
+    >>> M = np.arange(6).reshape(3,2); M
+    array([[0, 1],
+           [2, 3],
+           [4, 5]])
+    >>> U = np.diag([1,2,3]); U
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3]])
+    >>> V = 0.3*np.identity(2); V
+    array([[ 0.3,  0. ],
+           [ 0. ,  0.3]])
+    >>> X = M + 0.1; X
+    array([[ 0.1,  1.1],
+           [ 2.1,  3.1],
+           [ 4.1,  5.1]])
+    >>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
+    0.023410202050005054
+
+    >>> # Equivalent multivariate normal
+    >>> from scipy.stats import multivariate_normal
+    >>> vectorised_X = X.T.flatten()
+    >>> equiv_mean = M.T.flatten()
+    >>> equiv_cov = np.kron(V,U)
+    >>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov)
+    0.023410202050005054
+
+    Alternatively, the object may be called (as a function) to fix the mean
+    and covariance parameters, returning a "frozen" matrix normal
+    random variable:
+
+    >>> rv = matrix_normal(mean=None, rowcov=1, colcov=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # mean and covariance fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, matnorm_docdict_params)
+
+    def __call__(self, mean=None, rowcov=1, colcov=1, seed=None):
+        """Create a frozen matrix normal distribution.
+
+        See `matrix_normal_frozen` for more information.
+
+        """
+        return matrix_normal_frozen(mean, rowcov, colcov, seed=seed)
+
+    def _process_parameters(self, mean, rowcov, colcov):
+        """
+        Infer dimensionality from mean or covariance matrices. Handle
+        defaults. Ensure compatible dimensions.
+        """
+
+        # Process mean
+        if mean is not None:
+            mean = np.asarray(mean, dtype=float)
+            meanshape = mean.shape
+            if len(meanshape) != 2:
+                raise ValueError("Array `mean` must be two dimensional.")
+            if np.any(meanshape == 0):
+                raise ValueError("Array `mean` has invalid shape.")
+
+        # Process among-row covariance
+        rowcov = np.asarray(rowcov, dtype=float)
+        if rowcov.ndim == 0:
+            if mean is not None:
+                rowcov = rowcov * np.identity(meanshape[0])
+            else:
+                rowcov = rowcov * np.identity(1)
+        elif rowcov.ndim == 1:
+            rowcov = np.diag(rowcov)
+        rowshape = rowcov.shape
+        if len(rowshape) != 2:
+            raise ValueError("`rowcov` must be a scalar or a 2D array.")
+        if rowshape[0] != rowshape[1]:
+            raise ValueError("Array `rowcov` must be square.")
+        if rowshape[0] == 0:
+            raise ValueError("Array `rowcov` has invalid shape.")
+        numrows = rowshape[0]
+
+        # Process among-column covariance
+        colcov = np.asarray(colcov, dtype=float)
+        if colcov.ndim == 0:
+            if mean is not None:
+                colcov = colcov * np.identity(meanshape[1])
+            else:
+                colcov = colcov * np.identity(1)
+        elif colcov.ndim == 1:
+            colcov = np.diag(colcov)
+        colshape = colcov.shape
+        if len(colshape) != 2:
+            raise ValueError("`colcov` must be a scalar or a 2D array.")
+        if colshape[0] != colshape[1]:
+            raise ValueError("Array `colcov` must be square.")
+        if colshape[0] == 0:
+            raise ValueError("Array `colcov` has invalid shape.")
+        numcols = colshape[0]
+
+        # Ensure mean and covariances compatible
+        if mean is not None:
+            if meanshape[0] != numrows:
+                raise ValueError("Arrays `mean` and `rowcov` must have the "
+                                 "same number of rows.")
+            if meanshape[1] != numcols:
+                raise ValueError("Arrays `mean` and `colcov` must have the "
+                                 "same number of columns.")
+        else:
+            mean = np.zeros((numrows, numcols))
+
+        dims = (numrows, numcols)
+
+        return dims, mean, rowcov, colcov
+
+    def _process_quantiles(self, X, dims):
+        """
+        Adjust quantiles array so that last two axes labels the components of
+        each data point.
+        """
+        X = np.asarray(X, dtype=float)
+        if X.ndim == 2:
+            X = X[np.newaxis, :]
+        if X.shape[-2:] != dims:
+            raise ValueError("The shape of array `X` is not compatible "
+                             "with the distribution parameters.")
+        return X
+
+    def _logpdf(self, dims, X, mean, row_prec_rt, log_det_rowcov,
+                col_prec_rt, log_det_colcov):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        dims : tuple
+            Dimensions of the matrix variates
+        X : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        mean : ndarray
+            Mean of the distribution
+        row_prec_rt : ndarray
+            A decomposition such that np.dot(row_prec_rt, row_prec_rt.T)
+            is the inverse of the among-row covariance matrix
+        log_det_rowcov : float
+            Logarithm of the determinant of the among-row covariance matrix
+        col_prec_rt : ndarray
+            A decomposition such that np.dot(col_prec_rt, col_prec_rt.T)
+            is the inverse of the among-column covariance matrix
+        log_det_colcov : float
+            Logarithm of the determinant of the among-column covariance matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        numrows, numcols = dims
+        roll_dev = np.moveaxis(X-mean, -1, 0)
+        scale_dev = np.tensordot(col_prec_rt.T,
+                                 np.dot(roll_dev, row_prec_rt), 1)
+        maha = np.sum(np.sum(np.square(scale_dev), axis=-1), axis=0)
+        return -0.5 * (numrows*numcols*_LOG_2PI + numcols*log_det_rowcov
+                       + numrows*log_det_colcov + maha)
+
+    def logpdf(self, X, mean=None, rowcov=1, colcov=1):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        X : array_like
+            Quantiles, with the last two axes of `X` denoting the components.
+        %(_matnorm_doc_default_callparams)s
+
+        Returns
+        -------
+        logpdf : ndarray
+            Log of the probability density function evaluated at `X`
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
+                                                              colcov)
+        X = self._process_quantiles(X, dims)
+        rowpsd = _PSD(rowcov, allow_singular=False)
+        colpsd = _PSD(colcov, allow_singular=False)
+        out = self._logpdf(dims, X, mean, rowpsd.U, rowpsd.log_pdet, colpsd.U,
+                           colpsd.log_pdet)
+        return _squeeze_output(out)
+
+    def pdf(self, X, mean=None, rowcov=1, colcov=1):
+        """Matrix normal probability density function.
+
+        Parameters
+        ----------
+        X : array_like
+            Quantiles, with the last two axes of `X` denoting the components.
+        %(_matnorm_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `X`
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(X, mean, rowcov, colcov))
+
+    def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None):
+        """Draw random samples from a matrix normal distribution.
+
+        Parameters
+        ----------
+        %(_matnorm_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `dims`), where `dims` is the
+            dimension of the random matrices.
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        size = int(size)
+        dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
+                                                              colcov)
+        rowchol = scipy.linalg.cholesky(rowcov, lower=True)
+        colchol = scipy.linalg.cholesky(colcov, lower=True)
+        random_state = self._get_random_state(random_state)
+        # We aren't generating standard normal variates with size=(size,
+        # dims[0], dims[1]) directly to ensure random variates remain backwards
+        # compatible. See https://github.com/scipy/scipy/pull/12312 for more
+        # details.
+        std_norm = random_state.standard_normal(
+            size=(dims[1], size, dims[0])
+        ).transpose(1, 2, 0)
+        out = mean + np.einsum('jp,ipq,kq->ijk',
+                               rowchol, std_norm, colchol,
+                               optimize=True)
+        if size == 1:
+            out = out.reshape(mean.shape)
+        return out
+
+    def entropy(self, rowcov=1, colcov=1):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        rowcov : array_like, optional
+            Among-row covariance matrix of the distribution (default: ``1``)
+        colcov : array_like, optional
+            Among-column covariance matrix of the distribution (default: ``1``)
+
+        Returns
+        -------
+        entropy : float
+            Entropy of the distribution
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        dummy_mean = np.zeros((rowcov.shape[0], colcov.shape[0]))
+        dims, _, rowcov, colcov = self._process_parameters(dummy_mean,
+                                                           rowcov,
+                                                           colcov)
+        rowpsd = _PSD(rowcov, allow_singular=False)
+        colpsd = _PSD(colcov, allow_singular=False)
+
+        return self._entropy(dims, rowpsd.log_pdet, colpsd.log_pdet)
+
+    def _entropy(self, dims, row_cov_logdet, col_cov_logdet):
+        n, p = dims
+        return (0.5 * n * p * (1 + _LOG_2PI) + 0.5 * p * row_cov_logdet +
+                0.5 * n * col_cov_logdet)
+
+
+matrix_normal = matrix_normal_gen()
+
+
+class matrix_normal_frozen(multi_rv_frozen):
+    """
+    Create a frozen matrix normal distribution.
+
+    Parameters
+    ----------
+    %(_matnorm_doc_default_callparams)s
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is `None` the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import matrix_normal
+
+    >>> distn = matrix_normal(mean=np.zeros((3,3)))
+    >>> X = distn.rvs(); X
+    array([[-0.02976962,  0.93339138, -0.09663178],
+           [ 0.67405524,  0.28250467, -0.93308929],
+           [-0.31144782,  0.74535536,  1.30412916]])
+    >>> distn.pdf(X)
+    2.5160642368346784e-05
+    >>> distn.logpdf(X)
+    -10.590229595124615
+    """
+
+    def __init__(self, mean=None, rowcov=1, colcov=1, seed=None):
+        self._dist = matrix_normal_gen(seed)
+        self.dims, self.mean, self.rowcov, self.colcov = \
+            self._dist._process_parameters(mean, rowcov, colcov)
+        self.rowpsd = _PSD(self.rowcov, allow_singular=False)
+        self.colpsd = _PSD(self.colcov, allow_singular=False)
+
+    def logpdf(self, X):
+        X = self._dist._process_quantiles(X, self.dims)
+        out = self._dist._logpdf(self.dims, X, self.mean, self.rowpsd.U,
+                                 self.rowpsd.log_pdet, self.colpsd.U,
+                                 self.colpsd.log_pdet)
+        return _squeeze_output(out)
+
+    def pdf(self, X):
+        return np.exp(self.logpdf(X))
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.mean, self.rowcov, self.colcov, size,
+                              random_state)
+
+    def entropy(self):
+        return self._dist._entropy(self.dims, self.rowpsd.log_pdet,
+                                   self.colpsd.log_pdet)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# matrix_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'entropy']:
+    method = matrix_normal_gen.__dict__[name]
+    method_frozen = matrix_normal_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             matnorm_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_params)
+
+_dirichlet_doc_default_callparams = """\
+alpha : array_like
+    The concentration parameters. The number of entries determines the
+    dimensionality of the distribution.
+"""
+_dirichlet_doc_frozen_callparams = ""
+
+_dirichlet_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+dirichlet_docdict_params = {
+    '_dirichlet_doc_default_callparams': _dirichlet_doc_default_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+dirichlet_docdict_noparams = {
+    '_dirichlet_doc_default_callparams': _dirichlet_doc_frozen_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+
+def _dirichlet_check_parameters(alpha):
+    alpha = np.asarray(alpha)
+    if np.min(alpha) <= 0:
+        raise ValueError("All parameters must be greater than 0")
+    elif alpha.ndim != 1:
+        raise ValueError("Parameter vector 'a' must be one dimensional, "
+                         f"but a.shape = {alpha.shape}.")
+    return alpha
+
+
+def _dirichlet_check_input(alpha, x):
+    x = np.asarray(x)
+
+    if x.shape[0] + 1 != alpha.shape[0] and x.shape[0] != alpha.shape[0]:
+        raise ValueError("Vector 'x' must have either the same number "
+                         "of entries as, or one entry fewer than, "
+                         f"parameter vector 'a', but alpha.shape = {alpha.shape} "
+                         f"and x.shape = {x.shape}.")
+
+    if x.shape[0] != alpha.shape[0]:
+        xk = np.array([1 - np.sum(x, 0)])
+        if xk.ndim == 1:
+            x = np.append(x, xk)
+        elif xk.ndim == 2:
+            x = np.vstack((x, xk))
+        else:
+            raise ValueError("The input must be one dimensional or a two "
+                             "dimensional matrix containing the entries.")
+
+    if np.min(x) < 0:
+        raise ValueError("Each entry in 'x' must be greater than or equal "
+                         "to zero.")
+
+    if np.max(x) > 1:
+        raise ValueError("Each entry in 'x' must be smaller or equal one.")
+
+    # Check x_i > 0 or alpha_i > 1
+    xeq0 = (x == 0)
+    alphalt1 = (alpha < 1)
+    if x.shape != alpha.shape:
+        alphalt1 = np.repeat(alphalt1, x.shape[-1], axis=-1).reshape(x.shape)
+    chk = np.logical_and(xeq0, alphalt1)
+
+    if np.sum(chk):
+        raise ValueError("Each entry in 'x' must be greater than zero if its "
+                         "alpha is less than one.")
+
+    if (np.abs(np.sum(x, 0) - 1.0) > 10e-10).any():
+        raise ValueError("The input vector 'x' must lie within the normal "
+                         f"simplex. but np.sum(x, 0) = {np.sum(x, 0)}.")
+
+    return x
+
+
+def _lnB(alpha):
+    r"""Internal helper function to compute the log of the useful quotient.
+
+    .. math::
+
+        B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}
+                         {\Gamma\left(\sum_{i=1}^{K} \alpha_i \right)}
+
+    Parameters
+    ----------
+    %(_dirichlet_doc_default_callparams)s
+
+    Returns
+    -------
+    B : scalar
+        Helper quotient, internal use only
+
+    """
+    return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))
+
+
+class dirichlet_gen(multi_rv_generic):
+    r"""A Dirichlet random variable.
+
+    The ``alpha`` keyword specifies the concentration parameters of the
+    distribution.
+
+    .. versionadded:: 0.15.0
+
+    Methods
+    -------
+    pdf(x, alpha)
+        Probability density function.
+    logpdf(x, alpha)
+        Log of the probability density function.
+    rvs(alpha, size=1, random_state=None)
+        Draw random samples from a Dirichlet distribution.
+    mean(alpha)
+        The mean of the Dirichlet distribution
+    var(alpha)
+        The variance of the Dirichlet distribution
+    cov(alpha)
+        The covariance of the Dirichlet distribution
+    entropy(alpha)
+        Compute the differential entropy of the Dirichlet distribution.
+
+    Parameters
+    ----------
+    %(_dirichlet_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    Each :math:`\alpha` entry must be positive. The distribution has only
+    support on the simplex defined by
+
+    .. math::
+        \sum_{i=1}^{K} x_i = 1
+
+    where :math:`0 < x_i < 1`.
+
+    If the quantiles don't lie within the simplex, a ValueError is raised.
+
+    The probability density function for `dirichlet` is
+
+    .. math::
+
+        f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}
+
+    where
+
+    .. math::
+
+        \mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)}
+                                     {\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)}
+
+    and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the
+    concentration parameters and :math:`K` is the dimension of the space
+    where :math:`x` takes values.
+
+    Note that the `dirichlet` interface is somewhat inconsistent.
+    The array returned by the rvs function is transposed
+    with respect to the format expected by the pdf and logpdf.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import dirichlet
+
+    Generate a dirichlet random variable
+
+    >>> quantiles = np.array([0.2, 0.2, 0.6])  # specify quantiles
+    >>> alpha = np.array([0.4, 5, 15])  # specify concentration parameters
+    >>> dirichlet.pdf(quantiles, alpha)
+    0.2843831684937255
+
+    The same PDF but following a log scale
+
+    >>> dirichlet.logpdf(quantiles, alpha)
+    -1.2574327653159187
+
+    Once we specify the dirichlet distribution
+    we can then calculate quantities of interest
+
+    >>> dirichlet.mean(alpha)  # get the mean of the distribution
+    array([0.01960784, 0.24509804, 0.73529412])
+    >>> dirichlet.var(alpha) # get variance
+    array([0.00089829, 0.00864603, 0.00909517])
+    >>> dirichlet.entropy(alpha)  # calculate the differential entropy
+    -4.3280162474082715
+
+    We can also return random samples from the distribution
+
+    >>> dirichlet.rvs(alpha, size=1, random_state=1)
+    array([[0.00766178, 0.24670518, 0.74563305]])
+    >>> dirichlet.rvs(alpha, size=2, random_state=2)
+    array([[0.01639427, 0.1292273 , 0.85437844],
+           [0.00156917, 0.19033695, 0.80809388]])
+
+    Alternatively, the object may be called (as a function) to fix
+    concentration parameters, returning a "frozen" Dirichlet
+    random variable:
+
+    >>> rv = dirichlet(alpha)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # concentration parameters fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, dirichlet_docdict_params)
+
+    def __call__(self, alpha, seed=None):
+        return dirichlet_frozen(alpha, seed=seed)
+
+    def _logpdf(self, x, alpha):
+        """Log of the Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        %(_dirichlet_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        lnB = _lnB(alpha)
+        return - lnB + np.sum((xlogy(alpha - 1, x.T)).T, 0)
+
+    def logpdf(self, x, alpha):
+        """Log of the Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        x = _dirichlet_check_input(alpha, x)
+
+        out = self._logpdf(x, alpha)
+        return _squeeze_output(out)
+
+    def pdf(self, x, alpha):
+        """The Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            The probability density function evaluated at `x`.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        x = _dirichlet_check_input(alpha, x)
+
+        out = np.exp(self._logpdf(x, alpha))
+        return _squeeze_output(out)
+
+    def mean(self, alpha):
+        """Mean of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        mu : ndarray or scalar
+            Mean of the Dirichlet distribution.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+
+        out = alpha / (np.sum(alpha))
+        return _squeeze_output(out)
+
+    def var(self, alpha):
+        """Variance of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        v : ndarray or scalar
+            Variance of the Dirichlet distribution.
+
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+
+        alpha0 = np.sum(alpha)
+        out = (alpha * (alpha0 - alpha)) / ((alpha0 * alpha0) * (alpha0 + 1))
+        return _squeeze_output(out)
+
+    def cov(self, alpha):
+        """Covariance matrix of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : ndarray
+            The covariance matrix of the distribution.
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+        alpha0 = np.sum(alpha)
+        a = alpha / alpha0
+
+        cov = (np.diag(a) - np.outer(a, a)) / (alpha0 + 1)
+        return _squeeze_output(cov)
+
+    def entropy(self, alpha):
+        """
+        Differential entropy of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Dirichlet distribution
+
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+
+        alpha0 = np.sum(alpha)
+        lnB = _lnB(alpha)
+        K = alpha.shape[0]
+
+        out = lnB + (alpha0 - K) * scipy.special.psi(alpha0) - np.sum(
+            (alpha - 1) * scipy.special.psi(alpha))
+        return _squeeze_output(out)
+
+    def rvs(self, alpha, size=1, random_state=None):
+        """
+        Draw random samples from a Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+        size : int, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the random variable.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        random_state = self._get_random_state(random_state)
+        return random_state.dirichlet(alpha, size=size)
+
+
+dirichlet = dirichlet_gen()
+
+
+class dirichlet_frozen(multi_rv_frozen):
+    def __init__(self, alpha, seed=None):
+        self.alpha = _dirichlet_check_parameters(alpha)
+        self._dist = dirichlet_gen(seed)
+
+    def logpdf(self, x):
+        return self._dist.logpdf(x, self.alpha)
+
+    def pdf(self, x):
+        return self._dist.pdf(x, self.alpha)
+
+    def mean(self):
+        return self._dist.mean(self.alpha)
+
+    def var(self):
+        return self._dist.var(self.alpha)
+
+    def cov(self):
+        return self._dist.cov(self.alpha)
+
+    def entropy(self):
+        return self._dist.entropy(self.alpha)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.alpha, size, random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'mean', 'var', 'cov', 'entropy']:
+    method = dirichlet_gen.__dict__[name]
+    method_frozen = dirichlet_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, dirichlet_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, dirichlet_docdict_params)
+
+
+_wishart_doc_default_callparams = """\
+df : int
+    Degrees of freedom, must be greater than or equal to dimension of the
+    scale matrix
+scale : array_like
+    Symmetric positive definite scale matrix of the distribution
+"""
+
+_wishart_doc_callparams_note = ""
+
+_wishart_doc_frozen_callparams = ""
+
+_wishart_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+wishart_docdict_params = {
+    '_doc_default_callparams': _wishart_doc_default_callparams,
+    '_doc_callparams_note': _wishart_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+wishart_docdict_noparams = {
+    '_doc_default_callparams': _wishart_doc_frozen_callparams,
+    '_doc_callparams_note': _wishart_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class wishart_gen(multi_rv_generic):
+    r"""A Wishart random variable.
+
+    The `df` keyword specifies the degrees of freedom. The `scale` keyword
+    specifies the scale matrix, which must be symmetric and positive definite.
+    In this context, the scale matrix is often interpreted in terms of a
+    multivariate normal precision matrix (the inverse of the covariance
+    matrix). These arguments must satisfy the relationship
+    ``df > scale.ndim - 1``, but see notes on using the `rvs` method with
+    ``df < scale.ndim``.
+
+    Methods
+    -------
+    pdf(x, df, scale)
+        Probability density function.
+    logpdf(x, df, scale)
+        Log of the probability density function.
+    rvs(df, scale, size=1, random_state=None)
+        Draw random samples from a Wishart distribution.
+    entropy()
+        Compute the differential entropy of the Wishart distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Raises
+    ------
+    scipy.linalg.LinAlgError
+        If the scale matrix `scale` is not positive definite.
+
+    See Also
+    --------
+    invwishart, chi2
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The scale matrix `scale` must be a symmetric positive definite
+    matrix. Singular matrices, including the symmetric positive semi-definite
+    case, are not supported. Symmetry is not checked; only the lower triangular
+    portion is used.
+
+    The Wishart distribution is often denoted
+
+    .. math::
+
+        W_p(\nu, \Sigma)
+
+    where :math:`\nu` is the degrees of freedom and :math:`\Sigma` is the
+    :math:`p \times p` scale matrix.
+
+    The probability density function for `wishart` has support over positive
+    definite matrices :math:`S`; if :math:`S \sim W_p(\nu, \Sigma)`, then
+    its PDF is given by:
+
+    .. math::
+
+        f(S) = \frac{|S|^{\frac{\nu - p - 1}{2}}}{2^{ \frac{\nu p}{2} }
+               |\Sigma|^\frac{\nu}{2} \Gamma_p \left ( \frac{\nu}{2} \right )}
+               \exp\left( -tr(\Sigma^{-1} S) / 2 \right)
+
+    If :math:`S \sim W_p(\nu, \Sigma)` (Wishart) then
+    :math:`S^{-1} \sim W_p^{-1}(\nu, \Sigma^{-1})` (inverse Wishart).
+
+    If the scale matrix is 1-dimensional and equal to one, then the Wishart
+    distribution :math:`W_1(\nu, 1)` collapses to the :math:`\chi^2(\nu)`
+    distribution.
+
+    The algorithm [2]_ implemented by the `rvs` method may
+    produce numerically singular matrices with :math:`p - 1 < \nu < p`; the
+    user may wish to check for this condition and generate replacement samples
+    as necessary.
+
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
+           Wiley, 1983.
+    .. [2] W.B. Smith and R.R. Hocking, "Algorithm AS 53: Wishart Variate
+           Generator", Applied Statistics, vol. 21, pp. 341-345, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import wishart, chi2
+    >>> x = np.linspace(1e-5, 8, 100)
+    >>> w = wishart.pdf(x, df=3, scale=1); w[:5]
+    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
+    >>> c = chi2.pdf(x, 3); c[:5]
+    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
+    >>> plt.plot(x, w)
+    >>> plt.show()
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.
+
+    Alternatively, the object may be called (as a function) to fix the degrees
+    of freedom and scale parameters, returning a "frozen" Wishart random
+    variable:
+
+    >>> rv = wishart(df=1, scale=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params)
+
+    def __call__(self, df=None, scale=None, seed=None):
+        """Create a frozen Wishart distribution.
+
+        See `wishart_frozen` for more information.
+        """
+        return wishart_frozen(df, scale, seed)
+
+    def _process_parameters(self, df, scale):
+        if scale is None:
+            scale = 1.0
+        scale = np.asarray(scale, dtype=float)
+
+        if scale.ndim == 0:
+            scale = scale[np.newaxis, np.newaxis]
+        elif scale.ndim == 1:
+            scale = np.diag(scale)
+        elif scale.ndim == 2 and not scale.shape[0] == scale.shape[1]:
+            raise ValueError("Array 'scale' must be square if it is two dimensional,"
+                             f" but scale.scale = {str(scale.shape)}.")
+        elif scale.ndim > 2:
+            raise ValueError("Array 'scale' must be at most two-dimensional,"
+                             " but scale.ndim = %d" % scale.ndim)
+
+        dim = scale.shape[0]
+
+        if df is None:
+            df = dim
+        elif not np.isscalar(df):
+            raise ValueError("Degrees of freedom must be a scalar.")
+        elif df <= dim - 1:
+            raise ValueError("Degrees of freedom must be greater than the "
+                             "dimension of scale matrix minus 1.")
+
+        return dim, df, scale
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+
+        if x.ndim == 0:
+            x = x * np.eye(dim)[:, :, np.newaxis]
+        if x.ndim == 1:
+            if dim == 1:
+                x = x[np.newaxis, np.newaxis, :]
+            else:
+                x = np.diag(x)[:, :, np.newaxis]
+        elif x.ndim == 2:
+            if not x.shape[0] == x.shape[1]:
+                raise ValueError(
+                    "Quantiles must be square if they are two dimensional,"
+                    f" but x.shape = {str(x.shape)}.")
+            x = x[:, :, np.newaxis]
+        elif x.ndim == 3:
+            if not x.shape[0] == x.shape[1]:
+                raise ValueError(
+                    "Quantiles must be square in the first two dimensions "
+                    f"if they are three dimensional, but x.shape = {str(x.shape)}.")
+        elif x.ndim > 3:
+            raise ValueError("Quantiles must be at most two-dimensional with"
+                             " an additional dimension for multiple"
+                             "components, but x.ndim = %d" % x.ndim)
+
+        # Now we have 3-dim array; should have shape [dim, dim, *]
+        if not x.shape[0:2] == (dim, dim):
+            raise ValueError('Quantiles have incompatible dimensions: should'
+                             f' be {(dim, dim)}, got {x.shape[0:2]}.')
+
+        return x
+
+    def _process_size(self, size):
+        size = np.asarray(size)
+
+        if size.ndim == 0:
+            size = size[np.newaxis]
+        elif size.ndim > 1:
+            raise ValueError('Size must be an integer or tuple of integers;'
+                 ' thus must have dimension <= 1.'
+                 f' Got size.ndim = {str(tuple(size))}')
+        n = size.prod()
+        shape = tuple(size)
+
+        return n, shape
+
+    def _logpdf(self, x, dim, df, scale, log_det_scale, C):
+        """Log of the Wishart probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        scale : ndarray
+            Scale matrix
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        # log determinant of x
+        # Note: x has components along the last axis, so that x.T has
+        # components alone the 0-th axis. Then since det(A) = det(A'), this
+        # gives us a 1-dim vector of determinants
+
+        # Retrieve tr(scale^{-1} x)
+        log_det_x = np.empty(x.shape[-1])
+        scale_inv_x = np.empty(x.shape)
+        tr_scale_inv_x = np.empty(x.shape[-1])
+        for i in range(x.shape[-1]):
+            _, log_det_x[i] = self._cholesky_logdet(x[:, :, i])
+            scale_inv_x[:, :, i] = scipy.linalg.cho_solve((C, True), x[:, :, i])
+            tr_scale_inv_x[i] = scale_inv_x[:, :, i].trace()
+
+        # Log PDF
+        out = ((0.5 * (df - dim - 1) * log_det_x - 0.5 * tr_scale_inv_x) -
+               (0.5 * df * dim * _LOG_2 + 0.5 * df * log_det_scale +
+                multigammaln(0.5*df, dim)))
+
+        return out
+
+    def logpdf(self, x, df, scale):
+        """Log of the Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        x = self._process_quantiles(x, dim)
+
+        # Cholesky decomposition of scale, get log(det(scale))
+        C, log_det_scale = self._cholesky_logdet(scale)
+
+        out = self._logpdf(x, dim, df, scale, log_det_scale, C)
+        return _squeeze_output(out)
+
+    def pdf(self, x, df, scale):
+        """Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(x, df, scale))
+
+    def _mean(self, dim, df, scale):
+        """Mean of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mean' instead.
+
+        """
+        return df * scale
+
+    def mean(self, df, scale):
+        """Mean of the Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float
+            The mean of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mean(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _mode(self, dim, df, scale):
+        """Mode of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mode' instead.
+
+        """
+        if df >= dim + 1:
+            out = (df-dim-1) * scale
+        else:
+            out = None
+        return out
+
+    def mode(self, df, scale):
+        """Mode of the Wishart distribution
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mode : float or None
+            The Mode of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mode(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _var(self, dim, df, scale):
+        """Variance of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'var' instead.
+
+        """
+        var = scale**2
+        diag = scale.diagonal()  # 1 x dim array
+        var += np.outer(diag, diag)
+        var *= df
+        return var
+
+    def var(self, df, scale):
+        """Variance of the Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        var : float
+            The variance of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._var(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _standard_rvs(self, n, shape, dim, df, random_state):
+        """
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        random_state : {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.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        # Random normal variates for off-diagonal elements
+        n_tril = dim * (dim-1) // 2
+        covariances = random_state.normal(
+            size=n*n_tril).reshape(shape+(n_tril,))
+
+        # Random chi-square variates for diagonal elements
+        variances = (np.r_[[random_state.chisquare(df-(i+1)+1, size=n)**0.5
+                            for i in range(dim)]].reshape((dim,) +
+                                                          shape[::-1]).T)
+
+        # Create the A matri(ces) - lower triangular
+        A = np.zeros(shape + (dim, dim))
+
+        # Input the covariances
+        size_idx = tuple([slice(None, None, None)]*len(shape))
+        tril_idx = np.tril_indices(dim, k=-1)
+        A[size_idx + tril_idx] = covariances
+
+        # Input the variances
+        diag_idx = np.diag_indices(dim)
+        A[size_idx + diag_idx] = variances
+
+        return A
+
+    def _rvs(self, n, shape, dim, df, C, random_state):
+        """Draw random samples from a Wishart distribution.
+
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+        %(_doc_random_state)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        random_state = self._get_random_state(random_state)
+        # Calculate the matrices A, which are actually lower triangular
+        # Cholesky factorizations of a matrix B such that B ~ W(df, I)
+        A = self._standard_rvs(n, shape, dim, df, random_state)
+
+        # Calculate SA = C A A' C', where SA ~ W(df, scale)
+        # Note: this is the product of a (lower) (lower) (lower)' (lower)'
+        #       or, denoting B = AA', it is C B C' where C is the lower
+        #       triangular Cholesky factorization of the scale matrix.
+        #       this appears to conflict with the instructions in [1]_, which
+        #       suggest that it should be D' B D where D is the lower
+        #       triangular factorization of the scale matrix. However, it is
+        #       meant to refer to the Bartlett (1933) representation of a
+        #       Wishart random variate as L A A' L' where L is lower triangular
+        #       so it appears that understanding D' to be upper triangular
+        #       is either a typo in or misreading of [1]_.
+        for index in np.ndindex(shape):
+            CA = np.dot(C, A[index])
+            A[index] = np.dot(CA, CA.T)
+
+        return A
+
+    def rvs(self, df, scale, size=1, random_state=None):
+        """Draw random samples from a Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`) + (``dim``, ``dim``), where
+            ``dim`` is the dimension of the scale matrix.
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        n, shape = self._process_size(size)
+        dim, df, scale = self._process_parameters(df, scale)
+
+        # Cholesky decomposition of scale
+        C = scipy.linalg.cholesky(scale, lower=True)
+
+        out = self._rvs(n, shape, dim, df, C, random_state)
+
+        return _squeeze_output(out)
+
+    def _entropy(self, dim, df, log_det_scale):
+        """Compute the differential entropy of the Wishart.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'entropy' instead.
+
+        """
+        return (
+            0.5 * (dim+1) * log_det_scale +
+            0.5 * dim * (dim+1) * _LOG_2 +
+            multigammaln(0.5*df, dim) -
+            0.5 * (df - dim - 1) * np.sum(
+                [psi(0.5*(df + 1 - (i+1))) for i in range(dim)]
+            ) +
+            0.5 * df * dim
+        )
+
+    def entropy(self, df, scale):
+        """Compute the differential entropy of the Wishart.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Wishart distribution
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        _, log_det_scale = self._cholesky_logdet(scale)
+        return self._entropy(dim, df, log_det_scale)
+
+    def _cholesky_logdet(self, scale):
+        """Compute Cholesky decomposition and determine (log(det(scale)).
+
+        Parameters
+        ----------
+        scale : ndarray
+            Scale matrix.
+
+        Returns
+        -------
+        c_decomp : ndarray
+            The Cholesky decomposition of `scale`.
+        logdet : scalar
+            The log of the determinant of `scale`.
+
+        Notes
+        -----
+        This computation of ``logdet`` is equivalent to
+        ``np.linalg.slogdet(scale)``.  It is ~2x faster though.
+
+        """
+        c_decomp = scipy.linalg.cholesky(scale, lower=True)
+        logdet = 2 * np.sum(np.log(c_decomp.diagonal()))
+        return c_decomp, logdet
+
+
+wishart = wishart_gen()
+
+
+class wishart_frozen(multi_rv_frozen):
+    """Create a frozen Wishart distribution.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution
+    scale : array_like
+        Scale matrix of the distribution
+    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.
+
+    """
+    def __init__(self, df, scale, seed=None):
+        self._dist = wishart_gen(seed)
+        self.dim, self.df, self.scale = self._dist._process_parameters(
+            df, scale)
+        self.C, self.log_det_scale = self._dist._cholesky_logdet(self.scale)
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+
+        out = self._dist._logpdf(x, self.dim, self.df, self.scale,
+                                 self.log_det_scale, self.C)
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def mean(self):
+        out = self._dist._mean(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def mode(self):
+        out = self._dist._mode(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def var(self):
+        out = self._dist._var(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def rvs(self, size=1, random_state=None):
+        n, shape = self._dist._process_size(size)
+        out = self._dist._rvs(n, shape, self.dim, self.df,
+                              self.C, random_state)
+        return _squeeze_output(out)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.log_det_scale)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# Wishart and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs', 'entropy']:
+    method = wishart_gen.__dict__[name]
+    method_frozen = wishart_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, wishart_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params)
+
+
+class invwishart_gen(wishart_gen):
+    r"""An inverse Wishart random variable.
+
+    The `df` keyword specifies the degrees of freedom. The `scale` keyword
+    specifies the scale matrix, which must be symmetric and positive definite.
+    In this context, the scale matrix is often interpreted in terms of a
+    multivariate normal covariance matrix.
+
+    Methods
+    -------
+    pdf(x, df, scale)
+        Probability density function.
+    logpdf(x, df, scale)
+        Log of the probability density function.
+    rvs(df, scale, size=1, random_state=None)
+        Draw random samples from an inverse Wishart distribution.
+    entropy(df, scale)
+        Differential entropy of the distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Raises
+    ------
+    scipy.linalg.LinAlgError
+        If the scale matrix `scale` is not positive definite.
+
+    See Also
+    --------
+    wishart
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The scale matrix `scale` must be a symmetric positive definite
+    matrix. Singular matrices, including the symmetric positive semi-definite
+    case, are not supported. Symmetry is not checked; only the lower triangular
+    portion is used.
+
+    The inverse Wishart distribution is often denoted
+
+    .. math::
+
+        W_p^{-1}(\nu, \Psi)
+
+    where :math:`\nu` is the degrees of freedom and :math:`\Psi` is the
+    :math:`p \times p` scale matrix.
+
+    The probability density function for `invwishart` has support over positive
+    definite matrices :math:`S`; if :math:`S \sim W^{-1}_p(\nu, \Sigma)`,
+    then its PDF is given by:
+
+    .. math::
+
+        f(S) = \frac{|\Sigma|^\frac{\nu}{2}}{2^{ \frac{\nu p}{2} }
+               |S|^{\frac{\nu + p + 1}{2}} \Gamma_p \left(\frac{\nu}{2} \right)}
+               \exp\left( -tr(\Sigma S^{-1}) / 2 \right)
+
+    If :math:`S \sim W_p^{-1}(\nu, \Psi)` (inverse Wishart) then
+    :math:`S^{-1} \sim W_p(\nu, \Psi^{-1})` (Wishart).
+
+    If the scale matrix is 1-dimensional and equal to one, then the inverse
+    Wishart distribution :math:`W_1(\nu, 1)` collapses to the
+    inverse Gamma distribution with parameters shape = :math:`\frac{\nu}{2}`
+    and scale = :math:`\frac{1}{2}`.
+
+    Instead of inverting a randomly generated Wishart matrix as described in [2],
+    here the algorithm in [4] is used to directly generate a random inverse-Wishart
+    matrix without inversion.
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
+           Wiley, 1983.
+    .. [2] M.C. Jones, "Generating Inverse Wishart Matrices", Communications
+           in Statistics - Simulation and Computation, vol. 14.2, pp.511-514,
+           1985.
+    .. [3] Gupta, M. and Srivastava, S. "Parametric Bayesian Estimation of
+           Differential Entropy and Relative Entropy". Entropy 12, 818 - 843.
+           2010.
+    .. [4] S.D. Axen, "Efficiently generating inverse-Wishart matrices and
+           their Cholesky factors", :arXiv:`2310.15884v1`. 2023.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import invwishart, invgamma
+    >>> x = np.linspace(0.01, 1, 100)
+    >>> iw = invwishart.pdf(x, df=6, scale=1)
+    >>> iw[:3]
+    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
+    >>> ig = invgamma.pdf(x, 6/2., scale=1./2)
+    >>> ig[:3]
+    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
+    >>> plt.plot(x, iw)
+    >>> plt.show()
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.
+
+    Alternatively, the object may be called (as a function) to fix the degrees
+    of freedom and scale parameters, returning a "frozen" inverse Wishart
+    random variable:
+
+    >>> rv = invwishart(df=1, scale=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params)
+
+    def __call__(self, df=None, scale=None, seed=None):
+        """Create a frozen inverse Wishart distribution.
+
+        See `invwishart_frozen` for more information.
+
+        """
+        return invwishart_frozen(df, scale, seed)
+
+    def _logpdf(self, x, dim, df, log_det_scale, C):
+        """Log of the inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function.
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        # Retrieve tr(scale x^{-1})
+        log_det_x = np.empty(x.shape[-1])
+        tr_scale_x_inv = np.empty(x.shape[-1])
+        trsm = get_blas_funcs(('trsm'), (x,))
+        if dim > 1:
+            for i in range(x.shape[-1]):
+                Cx, log_det_x[i] = self._cholesky_logdet(x[:, :, i])
+                A = trsm(1., Cx, C, side=0, lower=True)
+                tr_scale_x_inv[i] = np.linalg.norm(A)**2
+        else:
+            log_det_x[:] = np.log(x[0, 0])
+            tr_scale_x_inv[:] = C[0, 0]**2 / x[0, 0]
+
+        # Log PDF
+        out = ((0.5 * df * log_det_scale - 0.5 * tr_scale_x_inv) -
+               (0.5 * df * dim * _LOG_2 + 0.5 * (df + dim + 1) * log_det_x) -
+               multigammaln(0.5*df, dim))
+
+        return out
+
+    def logpdf(self, x, df, scale):
+        """Log of the inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        x = self._process_quantiles(x, dim)
+        C, log_det_scale = self._cholesky_logdet(scale)
+        out = self._logpdf(x, dim, df, log_det_scale, C)
+        return _squeeze_output(out)
+
+    def pdf(self, x, df, scale):
+        """Inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(x, df, scale))
+
+    def _mean(self, dim, df, scale):
+        """Mean of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mean' instead.
+
+        """
+        if df > dim + 1:
+            out = scale / (df - dim - 1)
+        else:
+            out = None
+        return out
+
+    def mean(self, df, scale):
+        """Mean of the inverse Wishart distribution.
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix plus one.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float or None
+            The mean of the distribution
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mean(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _mode(self, dim, df, scale):
+        """Mode of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mode' instead.
+
+        """
+        return scale / (df + dim + 1)
+
+    def mode(self, df, scale):
+        """Mode of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mode : float
+            The Mode of the distribution
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mode(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _var(self, dim, df, scale):
+        """Variance of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'var' instead.
+
+        """
+        if df > dim + 3:
+            var = (df - dim + 1) * scale**2
+            diag = scale.diagonal()  # 1 x dim array
+            var += (df - dim - 1) * np.outer(diag, diag)
+            var /= (df - dim) * (df - dim - 1)**2 * (df - dim - 3)
+        else:
+            var = None
+        return var
+
+    def var(self, df, scale):
+        """Variance of the inverse Wishart distribution.
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix plus three.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        var : float
+            The variance of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._var(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _inv_standard_rvs(self, n, shape, dim, df, random_state):
+        """
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        random_state : {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
+        -------
+        A : ndarray
+            Random variates of shape (`shape`) + (``dim``, ``dim``).
+            Each slice `A[..., :, :]` is lower-triangular, and its
+            inverse is the lower Cholesky factor of a draw from
+            `invwishart(df, np.eye(dim))`.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        A = np.zeros(shape + (dim, dim))
+
+        # Random normal variates for off-diagonal elements
+        tri_rows, tri_cols = np.tril_indices(dim, k=-1)
+        n_tril = dim * (dim-1) // 2
+        A[..., tri_rows, tri_cols] = random_state.normal(
+            size=(*shape, n_tril),
+        )
+
+        # Random chi variates for diagonal elements
+        rows = np.arange(dim)
+        chi_dfs = (df - dim + 1) + rows
+        A[..., rows, rows] = random_state.chisquare(
+            df=chi_dfs, size=(*shape, dim),
+        )**0.5
+
+        return A
+
+    def _rvs(self, n, shape, dim, df, C, random_state):
+        """Draw random samples from an inverse Wishart distribution.
+
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+        %(_doc_random_state)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        random_state = self._get_random_state(random_state)
+        # Get random draws A such that inv(A) ~ iW(df, I)
+        A = self._inv_standard_rvs(n, shape, dim, df, random_state)
+
+        # Calculate SA = (CA)'^{-1} (CA)^{-1} ~ iW(df, scale)
+        trsm = get_blas_funcs(('trsm'), (A,))
+        trmm = get_blas_funcs(('trmm'), (A,))
+
+        for index in np.ndindex(A.shape[:-2]):
+            if dim > 1:
+                # Calculate CA
+                # Get CA = C A^{-1} via triangular solver
+                CA = trsm(1., A[index], C, side=1, lower=True)
+                # get SA
+                A[index] = trmm(1., CA, CA, side=1, lower=True, trans_a=True)
+            else:
+                A[index][0, 0] = (C[0, 0] / A[index][0, 0])**2
+
+        return A
+
+    def rvs(self, df, scale, size=1, random_state=None):
+        """Draw random samples from an inverse Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`) + (``dim``, ``dim``), where
+            ``dim`` is the dimension of the scale matrix.
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        n, shape = self._process_size(size)
+        dim, df, scale = self._process_parameters(df, scale)
+
+        # Cholesky decomposition of scale
+        C = scipy.linalg.cholesky(scale, lower=True)
+
+        out = self._rvs(n, shape, dim, df, C, random_state)
+
+        return _squeeze_output(out)
+
+    def _entropy(self, dim, df, log_det_scale):
+        # reference: eq. (17) from ref. 3
+        psi_eval_points = [0.5 * (df - dim + i) for i in range(1, dim + 1)]
+        psi_eval_points = np.asarray(psi_eval_points)
+        return multigammaln(0.5 * df, dim) + 0.5 * dim * df + \
+            0.5 * (dim + 1) * (log_det_scale - _LOG_2) - \
+            0.5 * (df + dim + 1) * \
+            psi(psi_eval_points, out=psi_eval_points).sum()
+
+    def entropy(self, df, scale):
+        dim, df, scale = self._process_parameters(df, scale)
+        _, log_det_scale = self._cholesky_logdet(scale)
+        return self._entropy(dim, df, log_det_scale)
+
+
+invwishart = invwishart_gen()
+
+
+class invwishart_frozen(multi_rv_frozen):
+    def __init__(self, df, scale, seed=None):
+        """Create a frozen inverse Wishart distribution.
+
+        Parameters
+        ----------
+        df : array_like
+            Degrees of freedom of the distribution
+        scale : array_like
+            Scale matrix of the distribution
+        seed : {None, int, `numpy.random.Generator`}, optional
+            If `seed` is None the `numpy.random.Generator` singleton is used.
+            If `seed` is an int, a new ``Generator`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` instance then that instance is
+            used.
+
+        """
+        self._dist = invwishart_gen(seed)
+        self.dim, self.df, self.scale = self._dist._process_parameters(
+            df, scale
+        )
+
+        # Get the determinant via Cholesky factorization
+        self.C = scipy.linalg.cholesky(self.scale, lower=True)
+        self.log_det_scale = 2 * np.sum(np.log(self.C.diagonal()))
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._logpdf(x, self.dim, self.df,
+                                 self.log_det_scale, self.C)
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def mean(self):
+        out = self._dist._mean(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def mode(self):
+        out = self._dist._mode(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def var(self):
+        out = self._dist._var(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def rvs(self, size=1, random_state=None):
+        n, shape = self._dist._process_size(size)
+
+        out = self._dist._rvs(n, shape, self.dim, self.df,
+                              self.C, random_state)
+
+        return _squeeze_output(out)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.log_det_scale)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# inverse Wishart and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs']:
+    method = invwishart_gen.__dict__[name]
+    method_frozen = wishart_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, wishart_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params)
+
+_multinomial_doc_default_callparams = """\
+n : int
+    Number of trials
+p : array_like
+    Probability of a trial falling into each category; should sum to 1
+"""
+
+_multinomial_doc_callparams_note = """\
+`n` should be a nonnegative integer. Each element of `p` should be in the
+interval :math:`[0,1]` and the elements should sum to 1. If they do not sum to
+1, the last element of the `p` array is not used and is replaced with the
+remaining probability left over from the earlier elements.
+"""
+
+_multinomial_doc_frozen_callparams = ""
+
+_multinomial_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+multinomial_docdict_params = {
+    '_doc_default_callparams': _multinomial_doc_default_callparams,
+    '_doc_callparams_note': _multinomial_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+multinomial_docdict_noparams = {
+    '_doc_default_callparams': _multinomial_doc_frozen_callparams,
+    '_doc_callparams_note': _multinomial_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multinomial_gen(multi_rv_generic):
+    r"""A multinomial random variable.
+
+    Methods
+    -------
+    pmf(x, n, p)
+        Probability mass function.
+    logpmf(x, n, p)
+        Log of the probability mass function.
+    rvs(n, p, size=1, random_state=None)
+        Draw random samples from a multinomial distribution.
+    entropy(n, p)
+        Compute the entropy of the multinomial distribution.
+    cov(n, p)
+        Compute the covariance matrix of the multinomial distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The probability mass function for `multinomial` is
+
+    .. math::
+
+        f(x) = \frac{n!}{x_1! \cdots x_k!} p_1^{x_1} \cdots p_k^{x_k},
+
+    supported on :math:`x=(x_1, \ldots, x_k)` where each :math:`x_i` is a
+    nonnegative integer and their sum is :math:`n`.
+
+    .. versionadded:: 0.19.0
+
+    Examples
+    --------
+
+    >>> from scipy.stats import multinomial
+    >>> rv = multinomial(8, [0.3, 0.2, 0.5])
+    >>> rv.pmf([1, 3, 4])
+    0.042000000000000072
+
+    The multinomial distribution for :math:`k=2` is identical to the
+    corresponding binomial distribution (tiny numerical differences
+    notwithstanding):
+
+    >>> from scipy.stats import binom
+    >>> multinomial.pmf([3, 4], n=7, p=[0.4, 0.6])
+    0.29030399999999973
+    >>> binom.pmf(3, 7, 0.4)
+    0.29030400000000012
+
+    The functions ``pmf``, ``logpmf``, ``entropy``, and ``cov`` support
+    broadcasting, under the convention that the vector parameters (``x`` and
+    ``p``) are interpreted as if each row along the last axis is a single
+    object. For instance:
+
+    >>> multinomial.pmf([[3, 4], [3, 5]], n=[7, 8], p=[.3, .7])
+    array([0.2268945,  0.25412184])
+
+    Here, ``x.shape == (2, 2)``, ``n.shape == (2,)``, and ``p.shape == (2,)``,
+    but following the rules mentioned above they behave as if the rows
+    ``[3, 4]`` and ``[3, 5]`` in ``x`` and ``[.3, .7]`` in ``p`` were a single
+    object, and as if we had ``x.shape = (2,)``, ``n.shape = (2,)``, and
+    ``p.shape = ()``. To obtain the individual elements without broadcasting,
+    we would do this:
+
+    >>> multinomial.pmf([3, 4], n=7, p=[.3, .7])
+    0.2268945
+    >>> multinomial.pmf([3, 5], 8, p=[.3, .7])
+    0.25412184
+
+    This broadcasting also works for ``cov``, where the output objects are
+    square matrices of size ``p.shape[-1]``. For example:
+
+    >>> multinomial.cov([4, 5], [[.3, .7], [.4, .6]])
+    array([[[ 0.84, -0.84],
+            [-0.84,  0.84]],
+           [[ 1.2 , -1.2 ],
+            [-1.2 ,  1.2 ]]])
+
+    In this example, ``n.shape == (2,)`` and ``p.shape == (2, 2)``, and
+    following the rules above, these broadcast as if ``p.shape == (2,)``.
+    Thus the result should also be of shape ``(2,)``, but since each output is
+    a :math:`2 \times 2` matrix, the result in fact has shape ``(2, 2, 2)``,
+    where ``result[0]`` is equal to ``multinomial.cov(n=4, p=[.3, .7])`` and
+    ``result[1]`` is equal to ``multinomial.cov(n=5, p=[.4, .6])``.
+
+    Alternatively, the object may be called (as a function) to fix the `n` and
+    `p` parameters, returning a "frozen" multinomial random variable:
+
+    >>> rv = multinomial(n=7, p=[.3, .7])
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    See also
+    --------
+    scipy.stats.binom : The binomial distribution.
+    numpy.random.Generator.multinomial : Sampling from the multinomial distribution.
+    scipy.stats.multivariate_hypergeom :
+        The multivariate hypergeometric distribution.
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = \
+            doccer.docformat(self.__doc__, multinomial_docdict_params)
+
+    def __call__(self, n, p, seed=None):
+        """Create a frozen multinomial distribution.
+
+        See `multinomial_frozen` for more information.
+        """
+        return multinomial_frozen(n, p, seed)
+
+    def _process_parameters(self, n, p, eps=1e-15):
+        """Returns: n_, p_, npcond.
+
+        n_ and p_ are arrays of the correct shape; npcond is a boolean array
+        flagging values out of the domain.
+        """
+        p = np.array(p, dtype=np.float64, copy=True)
+        p_adjusted = 1. - p[..., :-1].sum(axis=-1)
+        i_adjusted = np.abs(p_adjusted) > eps
+        p[i_adjusted, -1] = p_adjusted[i_adjusted]
+
+        # true for bad p
+        pcond = np.any(p < 0, axis=-1)
+        pcond |= np.any(p > 1, axis=-1)
+
+        n = np.array(n, dtype=int, copy=True)
+
+        # true for bad n
+        ncond = n < 0
+
+        return n, p, ncond | pcond
+
+    def _process_quantiles(self, x, n, p):
+        """Returns: x_, xcond.
+
+        x_ is an int array; xcond is a boolean array flagging values out of the
+        domain.
+        """
+        xx = np.asarray(x, dtype=int)
+
+        if xx.ndim == 0:
+            raise ValueError("x must be an array.")
+
+        if xx.size != 0 and not xx.shape[-1] == p.shape[-1]:
+            raise ValueError("Size of each quantile should be size of p: "
+                             "received %d, but expected %d." %
+                             (xx.shape[-1], p.shape[-1]))
+
+        # true for x out of the domain
+        cond = np.any(xx != x, axis=-1)
+        cond |= np.any(xx < 0, axis=-1)
+        cond = cond | (np.sum(xx, axis=-1) != n)
+
+        return xx, cond
+
+    def _checkresult(self, result, cond, bad_value):
+        result = np.asarray(result)
+
+        if cond.ndim != 0:
+            result[cond] = bad_value
+        elif cond:
+            if result.ndim == 0:
+                return bad_value
+            result[...] = bad_value
+        return result
+
+    def _logpmf(self, x, n, p):
+        return gammaln(n+1) + np.sum(xlogy(x, p) - gammaln(x+1), axis=-1)
+
+    def logpmf(self, x, n, p):
+        """Log of the Multinomial probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        x, xcond = self._process_quantiles(x, n, p)
+
+        result = self._logpmf(x, n, p)
+
+        # replace values for which x was out of the domain; broadcast
+        # xcond to the right shape
+        xcond_ = xcond | np.zeros(npcond.shape, dtype=np.bool_)
+        result = self._checkresult(result, xcond_, -np.inf)
+
+        # replace values bad for n or p; broadcast npcond to the right shape
+        npcond_ = npcond | np.zeros(xcond.shape, dtype=np.bool_)
+        return self._checkresult(result, npcond_, np.nan)
+
+    def pmf(self, x, n, p):
+        """Multinomial probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        return np.exp(self.logpmf(x, n, p))
+
+    def mean(self, n, p):
+        """Mean of the Multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float
+            The mean of the distribution
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        result = n[..., np.newaxis]*p
+        return self._checkresult(result, npcond, np.nan)
+
+    def cov(self, n, p):
+        """Covariance matrix of the multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : ndarray
+            The covariance matrix of the distribution
+        """
+        n, p, npcond = self._process_parameters(n, p)
+
+        nn = n[..., np.newaxis, np.newaxis]
+        result = nn * np.einsum('...j,...k->...jk', -p, p)
+
+        # change the diagonal
+        for i in range(p.shape[-1]):
+            result[..., i, i] += n*p[..., i]
+
+        return self._checkresult(result, npcond, np.nan)
+
+    def entropy(self, n, p):
+        r"""Compute the entropy of the multinomial distribution.
+
+        The entropy is computed using this expression:
+
+        .. math::
+
+            f(x) = - \log n! - n\sum_{i=1}^k p_i \log p_i +
+            \sum_{i=1}^k \sum_{x=0}^n \binom n x p_i^x(1-p_i)^{n-x} \log x!
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Multinomial distribution
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+
+        x = np.r_[1:np.max(n)+1]
+
+        term1 = n*np.sum(entr(p), axis=-1)
+        term1 -= gammaln(n+1)
+
+        n = n[..., np.newaxis]
+        new_axes_needed = max(p.ndim, n.ndim) - x.ndim + 1
+        x.shape += (1,)*new_axes_needed
+
+        term2 = np.sum(binom.pmf(x, n, p)*gammaln(x+1),
+                       axis=(-1, -1-new_axes_needed))
+
+        return self._checkresult(term1 + term2, npcond, np.nan)
+
+    def rvs(self, n, p, size=None, random_state=None):
+        """Draw random samples from a Multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of shape (`size`, `len(p)`)
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        random_state = self._get_random_state(random_state)
+        return random_state.multinomial(n, p, size)
+
+
+multinomial = multinomial_gen()
+
+
+class multinomial_frozen(multi_rv_frozen):
+    r"""Create a frozen Multinomial distribution.
+
+    Parameters
+    ----------
+    n : int
+        number of trials
+    p: array_like
+        probability of a trial falling into each category; should sum to 1
+    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.
+    """
+    def __init__(self, n, p, seed=None):
+        self._dist = multinomial_gen(seed)
+        self.n, self.p, self.npcond = self._dist._process_parameters(n, p)
+
+        # monkey patch self._dist
+        def _process_parameters(n, p):
+            return self.n, self.p, self.npcond
+
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.n, self.p)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.n, self.p)
+
+    def mean(self):
+        return self._dist.mean(self.n, self.p)
+
+    def cov(self):
+        return self._dist.cov(self.n, self.p)
+
+    def entropy(self):
+        return self._dist.entropy(self.n, self.p)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.n, self.p, size, random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multinomial and fill in default strings in class docstrings
+for name in ['logpmf', 'pmf', 'mean', 'cov', 'rvs']:
+    method = multinomial_gen.__dict__[name]
+    method_frozen = multinomial_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, multinomial_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      multinomial_docdict_params)
+
+
+class special_ortho_group_gen(multi_rv_generic):
+    r"""A Special Orthogonal matrix (SO(N)) random variable.
+
+    Return a random rotation matrix, drawn from the Haar distribution
+    (the only uniform distribution on SO(N)) with a determinant of +1.
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from SO(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is wrapping the random_rot code from the MDP Toolkit,
+    https://github.com/mdp-toolkit/mdp-toolkit
+
+    Return a random rotation matrix, drawn from the Haar distribution
+    (the only uniform distribution on SO(N)).
+    The algorithm is described in the paper
+    Stewart, G.W., "The efficient generation of random orthogonal
+    matrices with an application to condition estimators", SIAM Journal
+    on Numerical Analysis, 17(3), pp. 403-409, 1980.
+    For more information see
+    https://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization
+
+    See also the similar `ortho_group`. For a random rotation in three
+    dimensions, see `scipy.spatial.transform.Rotation.random`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import special_ortho_group
+    >>> x = special_ortho_group.rvs(3)
+
+    >>> np.dot(x, x.T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])
+
+    >>> import scipy.linalg
+    >>> scipy.linalg.det(x)
+    1.0
+
+    This generates one random matrix from SO(3). It is orthogonal and
+    has a determinant of 1.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, returning a "frozen" special_ortho_group random variable:
+
+    >>> rv = special_ortho_group(5)
+    >>> # Frozen object with the same methods but holding the
+    >>> # dimension parameter fixed.
+
+    See Also
+    --------
+    ortho_group, scipy.spatial.transform.Rotation.random
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen SO(N) distribution.
+
+        See `special_ortho_group_frozen` for more information.
+        """
+        return special_ortho_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("""Dimension of rotation must be specified,
+                                and must be a scalar greater than 1.""")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from SO(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of rotation space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+        size = (size,) if size > 1 else ()
+
+        dim = self._process_parameters(dim)
+
+        # H represents a (dim, dim) matrix, while D represents the diagonal of
+        # a (dim, dim) diagonal matrix. The algorithm that follows is
+        # broadcasted on the leading shape in `size` to vectorize along
+        # samples.
+        H = np.empty(size + (dim, dim))
+        H[..., :, :] = np.eye(dim)
+        D = np.empty(size + (dim,))
+
+        for n in range(dim-1):
+
+            # x is a vector with length dim-n, xrow and xcol are views of it as
+            # a row vector and column vector respectively. It's important they
+            # are views and not copies because we are going to modify x
+            # in-place.
+            x = random_state.normal(size=size + (dim-n,))
+            xrow = x[..., None, :]
+            xcol = x[..., :, None]
+
+            # This is the squared norm of x, without vectorization it would be
+            # dot(x, x), to have proper broadcasting we use matmul and squeeze
+            # out (convert to scalar) the resulting 1x1 matrix
+            norm2 = np.matmul(xrow, xcol).squeeze((-2, -1))
+
+            x0 = x[..., 0].copy()
+            D[..., n] = np.where(x0 != 0, np.sign(x0), 1)
+            x[..., 0] += D[..., n]*np.sqrt(norm2)
+
+            # In renormalizing x we have to append an additional axis with
+            # [..., None] to broadcast the scalar against the vector x
+            x /= np.sqrt((norm2 - x0**2 + x[..., 0]**2) / 2.)[..., None]
+
+            # Householder transformation, without vectorization the RHS can be
+            # written as outer(H @ x, x) (apart from the slicing)
+            H[..., :, n:] -= np.matmul(H[..., :, n:], xcol) * xrow
+
+        D[..., -1] = (-1)**(dim-1)*D[..., :-1].prod(axis=-1)
+
+        # Without vectorization this could be written as H = diag(D) @ H,
+        # left-multiplication by a diagonal matrix amounts to multiplying each
+        # row of H by an element of the diagonal, so we add a dummy axis for
+        # the column index
+        H *= D[..., :, None]
+        return H
+
+
+special_ortho_group = special_ortho_group_gen()
+
+
+class special_ortho_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen SO(N) distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        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.
+
+        Examples
+        --------
+        >>> from scipy.stats import special_ortho_group
+        >>> g = special_ortho_group(5)
+        >>> x = g.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = special_ortho_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+class ortho_group_gen(multi_rv_generic):
+    r"""An Orthogonal matrix (O(N)) random variable.
+
+    Return a random orthogonal matrix, drawn from the O(N) Haar
+    distribution (the only uniform distribution on O(N)).
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from O(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is closely related to `special_ortho_group`.
+
+    Some care is taken to avoid numerical error, as per the paper by Mezzadri.
+
+    References
+    ----------
+    .. [1] F. Mezzadri, "How to generate random matrices from the classical
+           compact groups", :arXiv:`math-ph/0609050v2`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ortho_group
+    >>> x = ortho_group.rvs(3)
+
+    >>> np.dot(x, x.T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])
+
+    >>> import scipy.linalg
+    >>> np.fabs(scipy.linalg.det(x))
+    1.0
+
+    This generates one random matrix from O(3). It is orthogonal and
+    has a determinant of +1 or -1.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, returning a "frozen" ortho_group random variable:
+
+    >>> rv = ortho_group(5)
+    >>> # Frozen object with the same methods but holding the
+    >>> # dimension parameter fixed.
+
+    See Also
+    --------
+    special_ortho_group
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen O(N) distribution.
+
+        See `ortho_group_frozen` for more information.
+        """
+        return ortho_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("Dimension of rotation must be specified,"
+                             "and must be a scalar greater than 1.")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from O(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of rotation space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+
+        dim = self._process_parameters(dim)
+
+        size = (size,) if size > 1 else ()
+        z = random_state.normal(size=size + (dim, dim))
+        q, r = np.linalg.qr(z)
+        # The last two dimensions are the rows and columns of R matrices.
+        # Extract the diagonals. Note that this eliminates a dimension.
+        d = r.diagonal(offset=0, axis1=-2, axis2=-1)
+        # Add back a dimension for proper broadcasting: we're dividing
+        # each row of each R matrix by the diagonal of the R matrix.
+        q *= (d/abs(d))[..., np.newaxis, :]  # to broadcast properly
+        return q
+
+
+ortho_group = ortho_group_gen()
+
+
+class ortho_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen O(N) distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        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.
+
+        Examples
+        --------
+        >>> from scipy.stats import ortho_group
+        >>> g = ortho_group(5)
+        >>> x = g.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = ortho_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+class random_correlation_gen(multi_rv_generic):
+    r"""A random correlation matrix.
+
+    Return a random correlation matrix, given a vector of eigenvalues.
+
+    The `eigs` keyword specifies the eigenvalues of the correlation matrix,
+    and implies the dimension.
+
+    Methods
+    -------
+    rvs(eigs=None, random_state=None)
+        Draw random correlation matrices, all with eigenvalues eigs.
+
+    Parameters
+    ----------
+    eigs : 1d ndarray
+        Eigenvalues of correlation matrix
+    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.
+    tol : float, optional
+        Tolerance for input parameter checks
+    diag_tol : float, optional
+        Tolerance for deviation of the diagonal of the resulting
+        matrix. Default: 1e-7
+
+    Raises
+    ------
+    RuntimeError
+        Floating point error prevented generating a valid correlation
+        matrix.
+
+    Returns
+    -------
+    rvs : ndarray or scalar
+        Random size N-dimensional matrices, dimension (size, dim, dim),
+        each having eigenvalues eigs.
+
+    Notes
+    -----
+
+    Generates a random correlation matrix following a numerically stable
+    algorithm spelled out by Davies & Higham. This algorithm uses a single O(N)
+    similarity transformation to construct a symmetric positive semi-definite
+    matrix, and applies a series of Givens rotations to scale it to have ones
+    on the diagonal.
+
+    References
+    ----------
+
+    .. [1] Davies, Philip I; Higham, Nicholas J; "Numerically stable generation
+           of correlation matrices and their factors", BIT 2000, Vol. 40,
+           No. 4, pp. 640 651
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import random_correlation
+    >>> rng = np.random.default_rng()
+    >>> x = random_correlation.rvs((.5, .8, 1.2, 1.5), random_state=rng)
+    >>> x
+    array([[ 1.        , -0.02423399,  0.03130519,  0.4946965 ],
+           [-0.02423399,  1.        ,  0.20334736,  0.04039817],
+           [ 0.03130519,  0.20334736,  1.        ,  0.02694275],
+           [ 0.4946965 ,  0.04039817,  0.02694275,  1.        ]])
+    >>> import scipy.linalg
+    >>> e, v = scipy.linalg.eigh(x)
+    >>> e
+    array([ 0.5,  0.8,  1.2,  1.5])
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7):
+        """Create a frozen random correlation matrix.
+
+        See `random_correlation_frozen` for more information.
+        """
+        return random_correlation_frozen(eigs, seed=seed, tol=tol,
+                                         diag_tol=diag_tol)
+
+    def _process_parameters(self, eigs, tol):
+        eigs = np.asarray(eigs, dtype=float)
+        dim = eigs.size
+
+        if eigs.ndim != 1 or eigs.shape[0] != dim or dim <= 1:
+            raise ValueError("Array 'eigs' must be a vector of length "
+                             "greater than 1.")
+
+        if np.fabs(np.sum(eigs) - dim) > tol:
+            raise ValueError("Sum of eigenvalues must equal dimensionality.")
+
+        for x in eigs:
+            if x < -tol:
+                raise ValueError("All eigenvalues must be non-negative.")
+
+        return dim, eigs
+
+    def _givens_to_1(self, aii, ajj, aij):
+        """Computes a 2x2 Givens matrix to put 1's on the diagonal.
+
+        The input matrix is a 2x2 symmetric matrix M = [ aii aij ; aij ajj ].
+
+        The output matrix g is a 2x2 anti-symmetric matrix of the form
+        [ c s ; -s c ];  the elements c and s are returned.
+
+        Applying the output matrix to the input matrix (as b=g.T M g)
+        results in a matrix with bii=1, provided tr(M) - det(M) >= 1
+        and floating point issues do not occur. Otherwise, some other
+        valid rotation is returned. When tr(M)==2, also bjj=1.
+
+        """
+        aiid = aii - 1.
+        ajjd = ajj - 1.
+
+        if ajjd == 0:
+            # ajj==1, so swap aii and ajj to avoid division by zero
+            return 0., 1.
+
+        dd = math.sqrt(max(aij**2 - aiid*ajjd, 0))
+
+        # The choice of t should be chosen to avoid cancellation [1]
+        t = (aij + math.copysign(dd, aij)) / ajjd
+        c = 1. / math.sqrt(1. + t*t)
+        if c == 0:
+            # Underflow
+            s = 1.0
+        else:
+            s = c*t
+        return c, s
+
+    def _to_corr(self, m):
+        """
+        Given a psd matrix m, rotate to put one's on the diagonal, turning it
+        into a correlation matrix.  This also requires the trace equal the
+        dimensionality. Note: modifies input matrix
+        """
+        # Check requirements for in-place Givens
+        if not (m.flags.c_contiguous and m.dtype == np.float64 and
+                m.shape[0] == m.shape[1]):
+            raise ValueError()
+
+        d = m.shape[0]
+        for i in range(d-1):
+            if m[i, i] == 1:
+                continue
+            elif m[i, i] > 1:
+                for j in range(i+1, d):
+                    if m[j, j] < 1:
+                        break
+            else:
+                for j in range(i+1, d):
+                    if m[j, j] > 1:
+                        break
+
+            c, s = self._givens_to_1(m[i, i], m[j, j], m[i, j])
+
+            # Use BLAS to apply Givens rotations in-place. Equivalent to:
+            # g = np.eye(d)
+            # g[i, i] = g[j,j] = c
+            # g[j, i] = -s; g[i, j] = s
+            # m = np.dot(g.T, np.dot(m, g))
+            mv = m.ravel()
+            drot(mv, mv, c, -s, n=d,
+                 offx=i*d, incx=1, offy=j*d, incy=1,
+                 overwrite_x=True, overwrite_y=True)
+            drot(mv, mv, c, -s, n=d,
+                 offx=i, incx=d, offy=j, incy=d,
+                 overwrite_x=True, overwrite_y=True)
+
+        return m
+
+    def rvs(self, eigs, random_state=None, tol=1e-13, diag_tol=1e-7):
+        """Draw random correlation matrices.
+
+        Parameters
+        ----------
+        eigs : 1d ndarray
+            Eigenvalues of correlation matrix
+        tol : float, optional
+            Tolerance for input parameter checks
+        diag_tol : float, optional
+            Tolerance for deviation of the diagonal of the resulting
+            matrix. Default: 1e-7
+
+        Raises
+        ------
+        RuntimeError
+            Floating point error prevented generating a valid correlation
+            matrix.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim),
+            each having eigenvalues eigs.
+
+        """
+        dim, eigs = self._process_parameters(eigs, tol=tol)
+
+        random_state = self._get_random_state(random_state)
+
+        m = ortho_group.rvs(dim, random_state=random_state)
+        m = np.dot(np.dot(m, np.diag(eigs)), m.T)  # Set the trace of m
+        m = self._to_corr(m)  # Carefully rotate to unit diagonal
+
+        # Check diagonal
+        if abs(m.diagonal() - 1).max() > diag_tol:
+            raise RuntimeError("Failed to generate a valid correlation matrix")
+
+        return m
+
+
+random_correlation = random_correlation_gen()
+
+
+class random_correlation_frozen(multi_rv_frozen):
+    def __init__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7):
+        """Create a frozen random correlation matrix distribution.
+
+        Parameters
+        ----------
+        eigs : 1d ndarray
+            Eigenvalues of correlation matrix
+        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.
+        tol : float, optional
+            Tolerance for input parameter checks
+        diag_tol : float, optional
+            Tolerance for deviation of the diagonal of the resulting
+            matrix. Default: 1e-7
+
+        Raises
+        ------
+        RuntimeError
+            Floating point error prevented generating a valid correlation
+            matrix.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim),
+            each having eigenvalues eigs.
+        """ # numpy/numpydoc#87  # noqa: E501
+
+        self._dist = random_correlation_gen(seed)
+        self.tol = tol
+        self.diag_tol = diag_tol
+        _, self.eigs = self._dist._process_parameters(eigs, tol=self.tol)
+
+    def rvs(self, random_state=None):
+        return self._dist.rvs(self.eigs, random_state=random_state,
+                              tol=self.tol, diag_tol=self.diag_tol)
+
+
+class unitary_group_gen(multi_rv_generic):
+    r"""A matrix-valued U(N) random variable.
+
+    Return a random unitary matrix.
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from U(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices, must be greater than 1.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is similar to `ortho_group`.
+
+    References
+    ----------
+    .. [1] F. Mezzadri, "How to generate random matrices from the classical
+           compact groups", :arXiv:`math-ph/0609050v2`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import unitary_group
+    >>> x = unitary_group.rvs(3)
+
+    >>> np.dot(x, x.conj().T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])  # may vary
+
+    This generates one random matrix from U(3). The dot product confirms that
+    it is unitary up to machine precision.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, return a "frozen" unitary_group random variable:
+
+    >>> rv = unitary_group(5)
+
+    See Also
+    --------
+    ortho_group
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen (U(N)) n-dimensional unitary matrix distribution.
+
+        See `unitary_group_frozen` for more information.
+        """
+        return unitary_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("Dimension of rotation must be specified,"
+                             "and must be a scalar greater than 1.")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from U(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+
+        dim = self._process_parameters(dim)
+
+        size = (size,) if size > 1 else ()
+        z = 1/math.sqrt(2)*(random_state.normal(size=size + (dim, dim)) +
+                            1j*random_state.normal(size=size + (dim, dim)))
+        q, r = np.linalg.qr(z)
+        # The last two dimensions are the rows and columns of R matrices.
+        # Extract the diagonals. Note that this eliminates a dimension.
+        d = r.diagonal(offset=0, axis1=-2, axis2=-1)
+        # Add back a dimension for proper broadcasting: we're dividing
+        # each row of each R matrix by the diagonal of the R matrix.
+        q *= (d/abs(d))[..., np.newaxis, :]  # to broadcast properly
+        return q
+
+
+unitary_group = unitary_group_gen()
+
+
+class unitary_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen (U(N)) n-dimensional unitary matrix distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        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.
+
+        Examples
+        --------
+        >>> from scipy.stats import unitary_group
+        >>> x = unitary_group(3)
+        >>> x.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = unitary_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+_mvt_doc_default_callparams = """\
+loc : array_like, optional
+    Location of the distribution. (default ``0``)
+shape : array_like, optional
+    Positive semidefinite matrix of the distribution. (default ``1``)
+df : float, optional
+    Degrees of freedom of the distribution; must be greater than zero.
+    If ``np.inf`` then results are multivariate normal. The default is ``1``.
+allow_singular : bool, optional
+    Whether to allow a singular matrix. (default ``False``)
+"""
+
+_mvt_doc_callparams_note = """\
+Setting the parameter `loc` to ``None`` is equivalent to having `loc`
+be the zero-vector. The parameter `shape` can be a scalar, in which case
+the shape matrix is the identity times that value, a vector of
+diagonal entries for the shape matrix, or a two-dimensional array_like.
+"""
+
+_mvt_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mvt_docdict_params = {
+    '_mvt_doc_default_callparams': _mvt_doc_default_callparams,
+    '_mvt_doc_callparams_note': _mvt_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mvt_docdict_noparams = {
+    '_mvt_doc_default_callparams': "",
+    '_mvt_doc_callparams_note': _mvt_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_t_gen(multi_rv_generic):
+    r"""A multivariate t-distributed random variable.
+
+    The `loc` parameter specifies the location. The `shape` parameter specifies
+    the positive semidefinite shape matrix. The `df` parameter specifies the
+    degrees of freedom.
+
+    In addition to calling the methods below, the object itself may be called
+    as a function to fix the location, shape matrix, and degrees of freedom
+    parameters, returning a "frozen" multivariate t-distribution random.
+
+    Methods
+    -------
+    pdf(x, loc=None, shape=1, df=1, allow_singular=False)
+        Probability density function.
+    logpdf(x, loc=None, shape=1, df=1, allow_singular=False)
+        Log of the probability density function.
+    cdf(x, loc=None, shape=1, df=1, allow_singular=False, *,
+        maxpts=None, lower_limit=None, random_state=None)
+        Cumulative distribution function.
+    rvs(loc=None, shape=1, df=1, size=1, random_state=None)
+        Draw random samples from a multivariate t-distribution.
+    entropy(loc=None, shape=1, df=1)
+        Differential entropy of a multivariate t-distribution.
+
+    Parameters
+    ----------
+    %(_mvt_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_mvt_doc_callparams_note)s
+    The matrix `shape` must be a (symmetric) positive semidefinite matrix. The
+    determinant and inverse of `shape` are computed as the pseudo-determinant
+    and pseudo-inverse, respectively, so that `shape` does not need to have
+    full rank.
+
+    The probability density function for `multivariate_t` is
+
+    .. math::
+
+        f(x) = \frac{\Gamma((\nu + p)/2)}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}}
+               \left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top}
+               \boldsymbol{\Sigma}^{-1}
+               (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2},
+
+    where :math:`p` is the dimension of :math:`\mathbf{x}`,
+    :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location,
+    :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape
+    matrix, and :math:`\nu` is the degrees of freedom.
+
+    .. versionadded:: 1.6.0
+
+    References
+    ----------
+    .. [1] Arellano-Valle et al. "Shannon Entropy and Mutual Information for
+           Multivariate Skew-Elliptical Distributions". Scandinavian Journal
+           of Statistics. Vol. 40, issue 1.
+
+    Examples
+    --------
+    The object may be called (as a function) to fix the `loc`, `shape`,
+    `df`, and `allow_singular` parameters, returning a "frozen"
+    multivariate_t random variable:
+
+    >>> import numpy as np
+    >>> from scipy.stats import multivariate_t
+    >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2)
+    >>> # Frozen object with the same methods but holding the given location,
+    >>> # scale, and degrees of freedom fixed.
+
+    Create a contour plot of the PDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01]
+    >>> pos = np.dstack((x, y))
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.set_aspect('equal')
+    >>> plt.contourf(x, y, rv.pdf(pos))
+
+    """
+
+    def __init__(self, seed=None):
+        """Initialize a multivariate t-distributed random variable.
+
+        Parameters
+        ----------
+        seed : Random state.
+
+        """
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mvt_docdict_params)
+        self._random_state = check_random_state(seed)
+
+    def __call__(self, loc=None, shape=1, df=1, allow_singular=False,
+                 seed=None):
+        """Create a frozen multivariate t-distribution.
+
+        See `multivariate_t_frozen` for parameters.
+        """
+        if df == np.inf:
+            return multivariate_normal_frozen(mean=loc, cov=shape,
+                                              allow_singular=allow_singular,
+                                              seed=seed)
+        return multivariate_t_frozen(loc=loc, shape=shape, df=df,
+                                     allow_singular=allow_singular, seed=seed)
+
+    def pdf(self, x, loc=None, shape=1, df=1, allow_singular=False):
+        """Multivariate t-distribution probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the probability density function.
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : Probability density function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.pdf(x, loc, shape, df)
+        0.00075713
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        x = self._process_quantiles(x, dim)
+        shape_info = _PSD(shape, allow_singular=allow_singular)
+        logpdf = self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df,
+                              dim, shape_info.rank)
+        return np.exp(logpdf)
+
+    def logpdf(self, x, loc=None, shape=1, df=1):
+        """Log of the multivariate t-distribution probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability density
+            function.
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        logpdf : Log of the probability density function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.logpdf(x, loc, shape, df)
+        -7.1859802
+
+        See Also
+        --------
+        pdf : Probability density function.
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        x = self._process_quantiles(x, dim)
+        shape_info = _PSD(shape)
+        return self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim,
+                            shape_info.rank)
+
+    def _logpdf(self, x, loc, prec_U, log_pdet, df, dim, rank):
+        """Utility method `pdf`, `logpdf` for parameters.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability density
+            function.
+        loc : ndarray
+            Location of the distribution.
+        prec_U : ndarray
+            A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse
+            of the shape matrix.
+        log_pdet : float
+            Logarithm of the determinant of the shape matrix.
+        df : float
+            Degrees of freedom of the distribution.
+        dim : int
+            Dimension of the quantiles x.
+        rank : int
+            Rank of the shape matrix.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be called
+        directly; use 'logpdf' instead.
+
+        """
+        if df == np.inf:
+            return multivariate_normal._logpdf(x, loc, prec_U, log_pdet, rank)
+
+        dev = x - loc
+        maha = np.square(np.dot(dev, prec_U)).sum(axis=-1)
+
+        t = 0.5 * (df + dim)
+        A = gammaln(t)
+        B = gammaln(0.5 * df)
+        C = dim/2. * np.log(df * np.pi)
+        D = 0.5 * log_pdet
+        E = -t * np.log(1 + (1./df) * maha)
+
+        return _squeeze_output(A - B - C - D + E)
+
+    def _cdf(self, x, loc, shape, df, dim, maxpts=None, lower_limit=None,
+             random_state=None):
+
+        # All of this -  random state validation, maxpts, apply_along_axis,
+        # etc. needs to go in this private method unless we want
+        # frozen distribution's `cdf` method to duplicate it or call `cdf`,
+        # which would require re-processing parameters
+        if random_state is not None:
+            rng = check_random_state(random_state)
+        else:
+            rng = self._random_state
+
+        if not maxpts:
+            maxpts = 1000 * dim
+
+        x = self._process_quantiles(x, dim)
+        lower_limit = (np.full(loc.shape, -np.inf)
+                       if lower_limit is None else lower_limit)
+
+        # remove the mean
+        x, lower_limit = x - loc, lower_limit - loc
+
+        b, a = np.broadcast_arrays(x, lower_limit)
+        i_swap = b < a
+        signs = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+        a, b = a.copy(), b.copy()
+        a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+        n = x.shape[-1]
+        limits = np.concatenate((a, b), axis=-1)
+
+        def func1d(limits):
+            a, b = limits[:n], limits[n:]
+            return _qmvt(maxpts, df, shape, a, b, rng)[0]
+
+        res = np.apply_along_axis(func1d, -1, limits) * signs
+        # Fixing the output shape for existing distributions is a separate
+        # issue. For now, let's keep this consistent with pdf.
+        return _squeeze_output(res)
+
+    def cdf(self, x, loc=None, shape=1, df=1, allow_singular=False, *,
+            maxpts=None, lower_limit=None, random_state=None):
+        """Multivariate t-distribution cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the cumulative distribution function.
+        %(_mvt_doc_default_callparams)s
+        maxpts : int, optional
+            Maximum number of points to use for integration. The default is
+            1000 times the number of dimensions.
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Cumulative distribution function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.cdf(x, loc, shape, df)
+        0.64798491
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        shape = _PSD(shape, allow_singular=allow_singular)._M
+
+        return self._cdf(x, loc, shape, df, dim, maxpts,
+                         lower_limit, random_state)
+
+    def _entropy(self, dim, df=1, shape=1):
+        if df == np.inf:
+            return multivariate_normal(None, cov=shape).entropy()
+
+        shape_info = _PSD(shape)
+        shape_term = 0.5 * shape_info.log_pdet
+
+        def regular(dim, df):
+            halfsum = 0.5 * (dim + df)
+            half_df = 0.5 * df
+            return (
+                -gammaln(halfsum) + gammaln(half_df)
+                + 0.5 * dim * np.log(df * np.pi) + halfsum
+                * (psi(halfsum) - psi(half_df))
+                + shape_term
+            )
+
+        def asymptotic(dim, df):
+            # Formula from Wolfram Alpha:
+            # "asymptotic expansion -gammaln((m+d)/2) + gammaln(d/2) + (m*log(d*pi))/2
+            #  + ((m+d)/2) * (digamma((m+d)/2) - digamma(d/2))"
+            return (
+                dim * norm._entropy() + dim / df
+                - dim * (dim - 2) * df**-2.0 / 4
+                + dim**2 * (dim - 2) * df**-3.0 / 6
+                + dim * (-3 * dim**3 + 8 * dim**2 - 8) * df**-4.0 / 24
+                + dim**2 * (3 * dim**3 - 10 * dim**2 + 16) * df**-5.0 / 30
+                + shape_term
+            )[()]
+
+        # preserves ~12 digits accuracy up to at least `dim=1e5`. See gh-18465.
+        threshold = dim * 100 * 4 / (np.log(dim) + 1)
+        return _lazywhere(df >= threshold, (dim, df), f=asymptotic, f2=regular)
+
+    def entropy(self, loc=None, shape=1, df=1):
+        """Calculate the differential entropy of a multivariate
+        t-distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        h : float
+            Differential entropy
+
+        """
+        dim, loc, shape, df = self._process_parameters(None, shape, df)
+        return self._entropy(dim, df, shape)
+
+    def rvs(self, loc=None, shape=1, df=1, size=1, random_state=None):
+        """Draw random samples from a multivariate t-distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `P`), where `P` is the
+            dimension of the random variable.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.rvs(loc, shape, df)
+        array([[0.93477495, 3.00408716]])
+
+        """
+        # For implementation details, see equation (3):
+        #
+        #    Hofert, "On Sampling from the Multivariatet Distribution", 2013
+        #     http://rjournal.github.io/archive/2013-2/hofert.pdf
+        #
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        if random_state is not None:
+            rng = check_random_state(random_state)
+        else:
+            rng = self._random_state
+
+        if np.isinf(df):
+            x = np.ones(size)
+        else:
+            x = rng.chisquare(df, size=size) / df
+
+        z = rng.multivariate_normal(np.zeros(dim), shape, size=size)
+        samples = loc + z / np.sqrt(x)[..., None]
+        return _squeeze_output(samples)
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+        if x.ndim == 0:
+            x = x[np.newaxis]
+        elif x.ndim == 1:
+            if dim == 1:
+                x = x[:, np.newaxis]
+            else:
+                x = x[np.newaxis, :]
+        return x
+
+    def _process_parameters(self, loc, shape, df):
+        """
+        Infer dimensionality from location array and shape matrix, handle
+        defaults, and ensure compatible dimensions.
+        """
+        if loc is None and shape is None:
+            loc = np.asarray(0, dtype=float)
+            shape = np.asarray(1, dtype=float)
+            dim = 1
+        elif loc is None:
+            shape = np.asarray(shape, dtype=float)
+            if shape.ndim < 2:
+                dim = 1
+            else:
+                dim = shape.shape[0]
+            loc = np.zeros(dim)
+        elif shape is None:
+            loc = np.asarray(loc, dtype=float)
+            dim = loc.size
+            shape = np.eye(dim)
+        else:
+            shape = np.asarray(shape, dtype=float)
+            loc = np.asarray(loc, dtype=float)
+            dim = loc.size
+
+        if dim == 1:
+            loc = loc.reshape(1)
+            shape = shape.reshape(1, 1)
+
+        if loc.ndim != 1 or loc.shape[0] != dim:
+            raise ValueError("Array 'loc' must be a vector of length %d." %
+                             dim)
+        if shape.ndim == 0:
+            shape = shape * np.eye(dim)
+        elif shape.ndim == 1:
+            shape = np.diag(shape)
+        elif shape.ndim == 2 and shape.shape != (dim, dim):
+            rows, cols = shape.shape
+            if rows != cols:
+                msg = ("Array 'cov' must be square if it is two dimensional,"
+                       f" but cov.shape = {str(shape.shape)}.")
+            else:
+                msg = ("Dimension mismatch: array 'cov' is of shape %s,"
+                       " but 'loc' is a vector of length %d.")
+                msg = msg % (str(shape.shape), len(loc))
+            raise ValueError(msg)
+        elif shape.ndim > 2:
+            raise ValueError("Array 'cov' must be at most two-dimensional,"
+                             " but cov.ndim = %d" % shape.ndim)
+
+        # Process degrees of freedom.
+        if df is None:
+            df = 1
+        elif df <= 0:
+            raise ValueError("'df' must be greater than zero.")
+        elif np.isnan(df):
+            raise ValueError("'df' is 'nan' but must be greater than zero or 'np.inf'.")
+
+        return dim, loc, shape, df
+
+
+class multivariate_t_frozen(multi_rv_frozen):
+
+    def __init__(self, loc=None, shape=1, df=1, allow_singular=False,
+                 seed=None):
+        """Create a frozen multivariate t distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import multivariate_t
+        >>> loc = np.zeros(3)
+        >>> shape = np.eye(3)
+        >>> df = 10
+        >>> dist = multivariate_t(loc, shape, df)
+        >>> dist.rvs()
+        array([[ 0.81412036, -1.53612361,  0.42199647]])
+        >>> dist.pdf([1, 1, 1])
+        array([0.01237803])
+
+        """
+        self._dist = multivariate_t_gen(seed)
+        dim, loc, shape, df = self._dist._process_parameters(loc, shape, df)
+        self.dim, self.loc, self.shape, self.df = dim, loc, shape, df
+        self.shape_info = _PSD(shape, allow_singular=allow_singular)
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        U = self.shape_info.U
+        log_pdet = self.shape_info.log_pdet
+        return self._dist._logpdf(x, self.loc, U, log_pdet, self.df, self.dim,
+                                  self.shape_info.rank)
+
+    def cdf(self, x, *, maxpts=None, lower_limit=None, random_state=None):
+        x = self._dist._process_quantiles(x, self.dim)
+        return self._dist._cdf(x, self.loc, self.shape, self.df, self.dim,
+                               maxpts, lower_limit, random_state)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(loc=self.loc,
+                              shape=self.shape,
+                              df=self.df,
+                              size=size,
+                              random_state=random_state)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.shape)
+
+
+multivariate_t = multivariate_t_gen()
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_t_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'cdf', 'entropy']:
+    method = multivariate_t_gen.__dict__[name]
+    method_frozen = multivariate_t_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvt_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvt_docdict_params)
+
+
+_mhg_doc_default_callparams = """\
+m : array_like
+    The number of each type of object in the population.
+    That is, :math:`m[i]` is the number of objects of
+    type :math:`i`.
+n : array_like
+    The number of samples taken from the population.
+"""
+
+_mhg_doc_callparams_note = """\
+`m` must be an array of positive integers. If the quantile
+:math:`i` contains values out of the range :math:`[0, m_i]`
+where :math:`m_i` is the number of objects of type :math:`i`
+in the population or if the parameters are inconsistent with one
+another (e.g. ``x.sum() != n``), methods return the appropriate
+value (e.g. ``0`` for ``pmf``). If `m` or `n` contain negative
+values, the result will contain ``nan`` there.
+"""
+
+_mhg_doc_frozen_callparams = ""
+
+_mhg_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mhg_docdict_params = {
+    '_doc_default_callparams': _mhg_doc_default_callparams,
+    '_doc_callparams_note': _mhg_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mhg_docdict_noparams = {
+    '_doc_default_callparams': _mhg_doc_frozen_callparams,
+    '_doc_callparams_note': _mhg_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_hypergeom_gen(multi_rv_generic):
+    r"""A multivariate hypergeometric random variable.
+
+    Methods
+    -------
+    pmf(x, m, n)
+        Probability mass function.
+    logpmf(x, m, n)
+        Log of the probability mass function.
+    rvs(m, n, size=1, random_state=None)
+        Draw random samples from a multivariate hypergeometric
+        distribution.
+    mean(m, n)
+        Mean of the multivariate hypergeometric distribution.
+    var(m, n)
+        Variance of the multivariate hypergeometric distribution.
+    cov(m, n)
+        Compute the covariance matrix of the multivariate
+        hypergeometric distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The probability mass function for `multivariate_hypergeom` is
+
+    .. math::
+
+        P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{\binom{m_1}{x_1}
+        \binom{m_2}{x_2} \cdots \binom{m_k}{x_k}}{\binom{M}{n}}, \\ \quad
+        (x_1, x_2, \ldots, x_k) \in \mathbb{N}^k \text{ with }
+        \sum_{i=1}^k x_i = n
+
+    where :math:`m_i` are the number of objects of type :math:`i`, :math:`M`
+    is the total number of objects in the population (sum of all the
+    :math:`m_i`), and :math:`n` is the size of the sample to be taken
+    from the population.
+
+    .. versionadded:: 1.6.0
+
+    Examples
+    --------
+    To evaluate the probability mass function of the multivariate
+    hypergeometric distribution, with a dichotomous population of size
+    :math:`10` and :math:`20`, at a sample of size :math:`12` with
+    :math:`8` objects of the first type and :math:`4` objects of the
+    second type, use:
+
+    >>> from scipy.stats import multivariate_hypergeom
+    >>> multivariate_hypergeom.pmf(x=[8, 4], m=[10, 20], n=12)
+    0.0025207176631464523
+
+    The `multivariate_hypergeom` distribution is identical to the
+    corresponding `hypergeom` distribution (tiny numerical differences
+    notwithstanding) when only two types (good and bad) of objects
+    are present in the population as in the example above. Consider
+    another example for a comparison with the hypergeometric distribution:
+
+    >>> from scipy.stats import hypergeom
+    >>> multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4)
+    0.4395604395604395
+    >>> hypergeom.pmf(k=3, M=15, n=4, N=10)
+    0.43956043956044005
+
+    The functions ``pmf``, ``logpmf``, ``mean``, ``var``, ``cov``, and ``rvs``
+    support broadcasting, under the convention that the vector parameters
+    (``x``, ``m``, and ``n``) are interpreted as if each row along the last
+    axis is a single object. For instance, we can combine the previous two
+    calls to `multivariate_hypergeom` as
+
+    >>> multivariate_hypergeom.pmf(x=[[8, 4], [3, 1]], m=[[10, 20], [10, 5]],
+    ...                            n=[12, 4])
+    array([0.00252072, 0.43956044])
+
+    This broadcasting also works for ``cov``, where the output objects are
+    square matrices of size ``m.shape[-1]``. For example:
+
+    >>> multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12])
+    array([[[ 1.05, -1.05],
+            [-1.05,  1.05]],
+           [[ 1.56, -1.56],
+            [-1.56,  1.56]]])
+
+    That is, ``result[0]`` is equal to
+    ``multivariate_hypergeom.cov(m=[7, 9], n=8)`` and ``result[1]`` is equal
+    to ``multivariate_hypergeom.cov(m=[10, 15], n=12)``.
+
+    Alternatively, the object may be called (as a function) to fix the `m`
+    and `n` parameters, returning a "frozen" multivariate hypergeometric
+    random variable.
+
+    >>> rv = multivariate_hypergeom(m=[10, 20], n=12)
+    >>> rv.pmf(x=[8, 4])
+    0.0025207176631464523
+
+    See Also
+    --------
+    scipy.stats.hypergeom : The hypergeometric distribution.
+    scipy.stats.multinomial : The multinomial distribution.
+
+    References
+    ----------
+    .. [1] The Multivariate Hypergeometric Distribution,
+           http://www.randomservices.org/random/urn/MultiHypergeometric.html
+    .. [2] Thomas J. Sargent and John Stachurski, 2020,
+           Multivariate Hypergeometric Distribution
+           https://python.quantecon.org/multi_hyper.html
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mhg_docdict_params)
+
+    def __call__(self, m, n, seed=None):
+        """Create a frozen multivariate_hypergeom distribution.
+
+        See `multivariate_hypergeom_frozen` for more information.
+        """
+        return multivariate_hypergeom_frozen(m, n, seed=seed)
+
+    def _process_parameters(self, m, n):
+        m = np.asarray(m)
+        n = np.asarray(n)
+        if m.size == 0:
+            m = m.astype(int)
+        if n.size == 0:
+            n = n.astype(int)
+        if not np.issubdtype(m.dtype, np.integer):
+            raise TypeError("'m' must an array of integers.")
+        if not np.issubdtype(n.dtype, np.integer):
+            raise TypeError("'n' must an array of integers.")
+        if m.ndim == 0:
+            raise ValueError("'m' must be an array with"
+                             " at least one dimension.")
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., np.newaxis]
+
+        m, n = np.broadcast_arrays(m, n)
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., 0]
+
+        mcond = m < 0
+
+        M = m.sum(axis=-1)
+
+        ncond = (n < 0) | (n > M)
+        return M, m, n, mcond, ncond, np.any(mcond, axis=-1) | ncond
+
+    def _process_quantiles(self, x, M, m, n):
+        x = np.asarray(x)
+        if not np.issubdtype(x.dtype, np.integer):
+            raise TypeError("'x' must an array of integers.")
+        if x.ndim == 0:
+            raise ValueError("'x' must be an array with"
+                             " at least one dimension.")
+        if not x.shape[-1] == m.shape[-1]:
+            raise ValueError(f"Size of each quantile must be size of 'm': "
+                             f"received {x.shape[-1]}, "
+                             f"but expected {m.shape[-1]}.")
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., np.newaxis]
+            M = M[..., np.newaxis]
+
+        x, m, n, M = np.broadcast_arrays(x, m, n, M)
+
+        # check for empty arrays
+        if m.size != 0:
+            n, M = n[..., 0], M[..., 0]
+
+        xcond = (x < 0) | (x > m)
+        return (x, M, m, n, xcond,
+                np.any(xcond, axis=-1) | (x.sum(axis=-1) != n))
+
+    def _checkresult(self, result, cond, bad_value):
+        result = np.asarray(result)
+        if cond.ndim != 0:
+            result[cond] = bad_value
+        elif cond:
+            return bad_value
+        if result.ndim == 0:
+            return result[()]
+        return result
+
+    def _logpmf(self, x, M, m, n, mxcond, ncond):
+        # This equation of the pmf comes from the relation,
+        # n combine r = beta(n+1, 1) / beta(r+1, n-r+1)
+        num = np.zeros_like(m, dtype=np.float64)
+        den = np.zeros_like(n, dtype=np.float64)
+        m, x = m[~mxcond], x[~mxcond]
+        M, n = M[~ncond], n[~ncond]
+        num[~mxcond] = (betaln(m+1, 1) - betaln(x+1, m-x+1))
+        den[~ncond] = (betaln(M+1, 1) - betaln(n+1, M-n+1))
+        num[mxcond] = np.nan
+        den[ncond] = np.nan
+        num = num.sum(axis=-1)
+        return num - den
+
+    def logpmf(self, x, m, n):
+        """Log of the multivariate hypergeometric probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        M, m, n, mcond, ncond, mncond = self._process_parameters(m, n)
+        (x, M, m, n, xcond,
+         xcond_reduced) = self._process_quantiles(x, M, m, n)
+        mxcond = mcond | xcond
+        ncond = ncond | np.zeros(n.shape, dtype=np.bool_)
+
+        result = self._logpmf(x, M, m, n, mxcond, ncond)
+
+        # replace values for which x was out of the domain; broadcast
+        # xcond to the right shape
+        xcond_ = xcond_reduced | np.zeros(mncond.shape, dtype=np.bool_)
+        result = self._checkresult(result, xcond_, -np.inf)
+
+        # replace values bad for n or m; broadcast
+        # mncond to the right shape
+        mncond_ = mncond | np.zeros(xcond_reduced.shape, dtype=np.bool_)
+        return self._checkresult(result, mncond_, np.nan)
+
+    def pmf(self, x, m, n):
+        """Multivariate hypergeometric probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        out = np.exp(self.logpmf(x, m, n))
+        return out
+
+    def mean(self, m, n):
+        """Mean of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : array_like or scalar
+            The mean of the distribution
+        """
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., np.newaxis], n[..., np.newaxis]
+        cond = (M == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        mu = n*(m/M)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis] |
+                      np.zeros(mu.shape, dtype=np.bool_))
+        return self._checkresult(mu, mncond, np.nan)
+
+    def var(self, m, n):
+        """Variance of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        array_like
+            The variances of the components of the distribution.  This is
+            the diagonal of the covariance matrix of the distribution
+        """
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., np.newaxis], n[..., np.newaxis]
+        cond = (M == 0) & (M-1 == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        output = n * m/M * (M-m)/M * (M-n)/(M-1)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis] |
+                      np.zeros(output.shape, dtype=np.bool_))
+        return self._checkresult(output, mncond, np.nan)
+
+    def cov(self, m, n):
+        """Covariance matrix of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : array_like
+            The covariance matrix of the distribution
+        """
+        # see [1]_ for the formula and [2]_ for implementation
+        # cov( x_i,x_j ) = -n * (M-n)/(M-1) * (K_i*K_j) / (M**2)
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M = M[..., np.newaxis, np.newaxis]
+            n = n[..., np.newaxis, np.newaxis]
+        cond = (M == 0) & (M-1 == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        output = (-n * (M-n)/(M-1) *
+                  np.einsum("...i,...j->...ij", m, m) / (M**2))
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., 0, 0], n[..., 0, 0]
+            cond = cond[..., 0, 0]
+        dim = m.shape[-1]
+        # diagonal entries need to be computed differently
+        for i in range(dim):
+            output[..., i, i] = (n * (M-n) * m[..., i]*(M-m[..., i]))
+            output[..., i, i] = output[..., i, i] / (M-1)
+            output[..., i, i] = output[..., i, i] / (M**2)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis, np.newaxis] |
+                      np.zeros(output.shape, dtype=np.bool_))
+        return self._checkresult(output, mncond, np.nan)
+
+    def rvs(self, m, n, size=None, random_state=None):
+        """Draw random samples from a multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw. Default is ``None``, in which case a
+            single variate is returned as an array with shape ``m.shape``.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : array_like
+            Random variates of shape ``size`` or ``m.shape``
+            (if ``size=None``).
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        Also note that NumPy's `multivariate_hypergeometric` sampler is not
+        used as it doesn't support broadcasting.
+        """
+        M, m, n, _, _, _ = self._process_parameters(m, n)
+
+        random_state = self._get_random_state(random_state)
+
+        if size is not None and isinstance(size, int):
+            size = (size, )
+
+        if size is None:
+            rvs = np.empty(m.shape, dtype=m.dtype)
+        else:
+            rvs = np.empty(size + (m.shape[-1], ), dtype=m.dtype)
+        rem = M
+
+        # This sampler has been taken from numpy gh-13794
+        # https://github.com/numpy/numpy/pull/13794
+        for c in range(m.shape[-1] - 1):
+            rem = rem - m[..., c]
+            n0mask = n == 0
+            rvs[..., c] = (~n0mask *
+                           random_state.hypergeometric(m[..., c],
+                                                       rem + n0mask,
+                                                       n + n0mask,
+                                                       size=size))
+            n = n - rvs[..., c]
+        rvs[..., m.shape[-1] - 1] = n
+
+        return rvs
+
+
+multivariate_hypergeom = multivariate_hypergeom_gen()
+
+
+class multivariate_hypergeom_frozen(multi_rv_frozen):
+    def __init__(self, m, n, seed=None):
+        self._dist = multivariate_hypergeom_gen(seed)
+        (self.M, self.m, self.n,
+         self.mcond, self.ncond,
+         self.mncond) = self._dist._process_parameters(m, n)
+
+        # monkey patch self._dist
+        def _process_parameters(m, n):
+            return (self.M, self.m, self.n,
+                    self.mcond, self.ncond,
+                    self.mncond)
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.m, self.n)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.m, self.n)
+
+    def mean(self):
+        return self._dist.mean(self.m, self.n)
+
+    def var(self):
+        return self._dist.var(self.m, self.n)
+
+    def cov(self):
+        return self._dist.cov(self.m, self.n)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.m, self.n,
+                              size=size,
+                              random_state=random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_hypergeom and fill in default strings in class docstrings
+for name in ['logpmf', 'pmf', 'mean', 'var', 'cov', 'rvs']:
+    method = multivariate_hypergeom_gen.__dict__[name]
+    method_frozen = multivariate_hypergeom_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, mhg_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      mhg_docdict_params)
+
+
+class random_table_gen(multi_rv_generic):
+    r"""Contingency tables from independent samples with fixed marginal sums.
+
+    This is the distribution of random tables with given row and column vector
+    sums. This distribution represents the set of random tables under the null
+    hypothesis that rows and columns are independent. It is used in hypothesis
+    tests of independence.
+
+    Because of assumed independence, the expected frequency of each table
+    element can be computed from the row and column sums, so that the
+    distribution is completely determined by these two vectors.
+
+    Methods
+    -------
+    logpmf(x)
+        Log-probability of table `x` to occur in the distribution.
+    pmf(x)
+        Probability of table `x` to occur in the distribution.
+    mean(row, col)
+        Mean table.
+    rvs(row, col, size=None, method=None, random_state=None)
+        Draw random tables with given row and column vector sums.
+
+    Parameters
+    ----------
+    %(_doc_row_col)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_row_col_note)s
+
+    Random elements from the distribution are generated either with Boyett's
+    [1]_ or Patefield's algorithm [2]_. Boyett's algorithm has
+    O(N) time and space complexity, where N is the total sum of entries in the
+    table. Patefield's algorithm has O(K x log(N)) time complexity, where K is
+    the number of cells in the table and requires only a small constant work
+    space. By default, the `rvs` method selects the fastest algorithm based on
+    the input, but you can specify the algorithm with the keyword `method`.
+    Allowed values are "boyett" and "patefield".
+
+    .. versionadded:: 1.10.0
+
+    Examples
+    --------
+    >>> from scipy.stats import random_table
+
+    >>> row = [1, 5]
+    >>> col = [2, 3, 1]
+    >>> random_table.mean(row, col)
+    array([[0.33333333, 0.5       , 0.16666667],
+           [1.66666667, 2.5       , 0.83333333]])
+
+    Alternatively, the object may be called (as a function) to fix the row
+    and column vector sums, returning a "frozen" distribution.
+
+    >>> dist = random_table(row, col)
+    >>> dist.rvs(random_state=123)
+    array([[1, 0, 0],
+           [1, 3, 1]])
+
+    References
+    ----------
+    .. [1] J. Boyett, AS 144 Appl. Statist. 28 (1979) 329-332
+    .. [2] W.M. Patefield, AS 159 Appl. Statist. 30 (1981) 91-97
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+
+    def __call__(self, row, col, *, seed=None):
+        """Create a frozen distribution of tables with given marginals.
+
+        See `random_table_frozen` for more information.
+        """
+        return random_table_frozen(row, col, seed=seed)
+
+    def logpmf(self, x, row, col):
+        """Log-probability of table to occur in the distribution.
+
+        Parameters
+        ----------
+        %(_doc_x)s
+        %(_doc_row_col)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        If row and column marginals of `x` do not match `row` and `col`,
+        negative infinity is returned.
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+        >>> import numpy as np
+
+        >>> x = [[1, 5, 1], [2, 3, 1]]
+        >>> row = np.sum(x, axis=1)
+        >>> col = np.sum(x, axis=0)
+        >>> random_table.logpmf(x, row, col)
+        -1.6306401200847027
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.logpmf(x)
+        -1.6306401200847027
+        """
+        r, c, n = self._process_parameters(row, col)
+        x = np.asarray(x)
+
+        if x.ndim < 2:
+            raise ValueError("`x` must be at least two-dimensional")
+
+        dtype_is_int = np.issubdtype(x.dtype, np.integer)
+        with np.errstate(invalid='ignore'):
+            if not dtype_is_int and not np.all(x.astype(int) == x):
+                raise ValueError("`x` must contain only integral values")
+
+        # x does not contain NaN if we arrive here
+        if np.any(x < 0):
+            raise ValueError("`x` must contain only non-negative values")
+
+        r2 = np.sum(x, axis=-1)
+        c2 = np.sum(x, axis=-2)
+
+        if r2.shape[-1] != len(r):
+            raise ValueError("shape of `x` must agree with `row`")
+
+        if c2.shape[-1] != len(c):
+            raise ValueError("shape of `x` must agree with `col`")
+
+        res = np.empty(x.shape[:-2])
+
+        mask = np.all(r2 == r, axis=-1) & np.all(c2 == c, axis=-1)
+
+        def lnfac(x):
+            return gammaln(x + 1)
+
+        res[mask] = (np.sum(lnfac(r), axis=-1) + np.sum(lnfac(c), axis=-1)
+                     - lnfac(n) - np.sum(lnfac(x[mask]), axis=(-1, -2)))
+        res[~mask] = -np.inf
+
+        return res[()]
+
+    def pmf(self, x, row, col):
+        """Probability of table to occur in the distribution.
+
+        Parameters
+        ----------
+        %(_doc_x)s
+        %(_doc_row_col)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability mass function evaluated at `x`.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        If row and column marginals of `x` do not match `row` and `col`,
+        zero is returned.
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+        >>> import numpy as np
+
+        >>> x = [[1, 5, 1], [2, 3, 1]]
+        >>> row = np.sum(x, axis=1)
+        >>> col = np.sum(x, axis=0)
+        >>> random_table.pmf(x, row, col)
+        0.19580419580419592
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.pmf(x)
+        0.19580419580419592
+        """
+        return np.exp(self.logpmf(x, row, col))
+
+    def mean(self, row, col):
+        """Mean of distribution of conditional tables.
+        %(_doc_mean_params)s
+
+        Returns
+        -------
+        mean: ndarray
+            Mean of the distribution.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+
+        >>> row = [1, 5]
+        >>> col = [2, 3, 1]
+        >>> random_table.mean(row, col)
+        array([[0.33333333, 0.5       , 0.16666667],
+               [1.66666667, 2.5       , 0.83333333]])
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.mean()
+        array([[0.33333333, 0.5       , 0.16666667],
+               [1.66666667, 2.5       , 0.83333333]])
+        """
+        r, c, n = self._process_parameters(row, col)
+        return np.outer(r, c) / n
+
+    def rvs(self, row, col, *, size=None, method=None, random_state=None):
+        """Draw random tables with fixed column and row marginals.
+
+        Parameters
+        ----------
+        %(_doc_row_col)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        method : str, optional
+            Which method to use, "boyett" or "patefield". If None (default),
+            selects the fastest method for this input.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random 2D tables of shape (`size`, `len(row)`, `len(col)`).
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+
+        >>> row = [1, 5]
+        >>> col = [2, 3, 1]
+        >>> random_table.rvs(row, col, random_state=123)
+        array([[1., 0., 0.],
+               [1., 3., 1.]])
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.rvs(random_state=123)
+        array([[1., 0., 0.],
+               [1., 3., 1.]])
+        """
+        r, c, n = self._process_parameters(row, col)
+        size, shape = self._process_size_shape(size, r, c)
+
+        random_state = self._get_random_state(random_state)
+        meth = self._process_rvs_method(method, r, c, n)
+
+        return meth(r, c, n, size, random_state).reshape(shape)
+
+    @staticmethod
+    def _process_parameters(row, col):
+        """
+        Check that row and column vectors are one-dimensional, that they do
+        not contain negative or non-integer entries, and that the sums over
+        both vectors are equal.
+        """
+        r = np.array(row, dtype=np.int64, copy=True)
+        c = np.array(col, dtype=np.int64, copy=True)
+
+        if np.ndim(r) != 1:
+            raise ValueError("`row` must be one-dimensional")
+        if np.ndim(c) != 1:
+            raise ValueError("`col` must be one-dimensional")
+
+        if np.any(r < 0):
+            raise ValueError("each element of `row` must be non-negative")
+        if np.any(c < 0):
+            raise ValueError("each element of `col` must be non-negative")
+
+        n = np.sum(r)
+        if n != np.sum(c):
+            raise ValueError("sums over `row` and `col` must be equal")
+
+        if not np.all(r == np.asarray(row)):
+            raise ValueError("each element of `row` must be an integer")
+        if not np.all(c == np.asarray(col)):
+            raise ValueError("each element of `col` must be an integer")
+
+        return r, c, n
+
+    @staticmethod
+    def _process_size_shape(size, r, c):
+        """
+        Compute the number of samples to be drawn and the shape of the output
+        """
+        shape = (len(r), len(c))
+
+        if size is None:
+            return 1, shape
+
+        size = np.atleast_1d(size)
+        if not np.issubdtype(size.dtype, np.integer) or np.any(size < 0):
+            raise ValueError("`size` must be a non-negative integer or `None`")
+
+        return np.prod(size), tuple(size) + shape
+
+    @classmethod
+    def _process_rvs_method(cls, method, r, c, n):
+        known_methods = {
+            None: cls._rvs_select(r, c, n),
+            "boyett": cls._rvs_boyett,
+            "patefield": cls._rvs_patefield,
+        }
+        try:
+            return known_methods[method]
+        except KeyError:
+            raise ValueError(f"'{method}' not recognized, "
+                             f"must be one of {set(known_methods)}")
+
+    @classmethod
+    def _rvs_select(cls, r, c, n):
+        fac = 1.0  # benchmarks show that this value is about 1
+        k = len(r) * len(c)  # number of cells
+        # n + 1 guards against failure if n == 0
+        if n > fac * np.log(n + 1) * k:
+            return cls._rvs_patefield
+        return cls._rvs_boyett
+
+    @staticmethod
+    def _rvs_boyett(row, col, ntot, size, random_state):
+        return _rcont.rvs_rcont1(row, col, ntot, size, random_state)
+
+    @staticmethod
+    def _rvs_patefield(row, col, ntot, size, random_state):
+        return _rcont.rvs_rcont2(row, col, ntot, size, random_state)
+
+
+random_table = random_table_gen()
+
+
+class random_table_frozen(multi_rv_frozen):
+    def __init__(self, row, col, *, seed=None):
+        self._dist = random_table_gen(seed)
+        self._params = self._dist._process_parameters(row, col)
+
+        # monkey patch self._dist
+        def _process_parameters(r, c):
+            return self._params
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, None, None)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, None, None)
+
+    def mean(self):
+        return self._dist.mean(None, None)
+
+    def rvs(self, size=None, method=None, random_state=None):
+        # optimisations are possible here
+        return self._dist.rvs(None, None, size=size, method=method,
+                              random_state=random_state)
+
+
+_ctab_doc_row_col = """\
+row : array_like
+    Sum of table entries in each row.
+col : array_like
+    Sum of table entries in each column."""
+
+_ctab_doc_x = """\
+x : array-like
+   Two-dimensional table of non-negative integers, or a
+   multi-dimensional array with the last two dimensions
+   corresponding with the tables."""
+
+_ctab_doc_row_col_note = """\
+The row and column vectors must be one-dimensional, not empty,
+and each sum up to the same value. They cannot contain negative
+or noninteger entries."""
+
+_ctab_doc_mean_params = f"""
+Parameters
+----------
+{_ctab_doc_row_col}"""
+
+_ctab_doc_row_col_note_frozen = """\
+See class definition for a detailed description of parameters."""
+
+_ctab_docdict = {
+    "_doc_random_state": _doc_random_state,
+    "_doc_row_col": _ctab_doc_row_col,
+    "_doc_x": _ctab_doc_x,
+    "_doc_mean_params": _ctab_doc_mean_params,
+    "_doc_row_col_note": _ctab_doc_row_col_note,
+}
+
+_ctab_docdict_frozen = _ctab_docdict.copy()
+_ctab_docdict_frozen.update({
+    "_doc_row_col": "",
+    "_doc_mean_params": "",
+    "_doc_row_col_note": _ctab_doc_row_col_note_frozen,
+})
+
+
+def _docfill(obj, docdict, template=None):
+    obj.__doc__ = doccer.docformat(template or obj.__doc__, docdict)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# random_table and fill in default strings in class docstrings
+_docfill(random_table_gen, _ctab_docdict)
+for name in ['logpmf', 'pmf', 'mean', 'rvs']:
+    method = random_table_gen.__dict__[name]
+    method_frozen = random_table_frozen.__dict__[name]
+    _docfill(method_frozen, _ctab_docdict_frozen, method.__doc__)
+    _docfill(method, _ctab_docdict)
+
+
+class uniform_direction_gen(multi_rv_generic):
+    r"""A vector-valued uniform direction.
+
+    Return a random direction (unit vector). The `dim` keyword specifies
+    the dimensionality of the space.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random directions.
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of directions.
+    seed : {None, int, `numpy.random.Generator`,
+            `numpy.random.RandomState`}, optional
+
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This distribution generates unit vectors uniformly distributed on
+    the surface of a hypersphere. These can be interpreted as random
+    directions.
+    For example, if `dim` is 3, 3D vectors from the surface of :math:`S^2`
+    will be sampled.
+
+    References
+    ----------
+    .. [1] Marsaglia, G. (1972). "Choosing a Point from the Surface of a
+           Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import uniform_direction
+    >>> x = uniform_direction.rvs(3)
+    >>> np.linalg.norm(x)
+    1.
+
+    This generates one random direction, a vector on the surface of
+    :math:`S^2`.
+
+    Alternatively, the object may be called (as a function) to return a frozen
+    distribution with fixed `dim` parameter. Here,
+    we create a `uniform_direction` with ``dim=3`` and draw 5 observations.
+    The samples are then arranged in an array of shape 5x3.
+
+    >>> rng = np.random.default_rng()
+    >>> uniform_sphere_dist = uniform_direction(3)
+    >>> unit_vectors = uniform_sphere_dist.rvs(5, random_state=rng)
+    >>> unit_vectors
+    array([[ 0.56688642, -0.1332634 , -0.81294566],
+           [-0.427126  , -0.74779278,  0.50830044],
+           [ 0.3793989 ,  0.92346629,  0.05715323],
+           [ 0.36428383, -0.92449076, -0.11231259],
+           [-0.27733285,  0.94410968, -0.17816678]])
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen n-dimensional uniform direction distribution.
+
+        See `uniform_direction` for more information.
+        """
+        return uniform_direction_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim < 1 or dim != int(dim):
+            raise ValueError("Dimension of vector must be specified, "
+                             "and must be an integer greater than 0.")
+
+        return int(dim)
+
+    def rvs(self, dim, size=None, random_state=None):
+        """Draw random samples from S(N-1).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of space (N).
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            Pseudorandom number generator state used to generate resamples.
+
+            If `random_state` is ``None`` (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray
+            Random direction vectors
+
+        """
+        random_state = self._get_random_state(random_state)
+        if size is None:
+            size = np.array([], dtype=int)
+        size = np.atleast_1d(size)
+
+        dim = self._process_parameters(dim)
+
+        samples = _sample_uniform_direction(dim, size, random_state)
+        return samples
+
+
+uniform_direction = uniform_direction_gen()
+
+
+class uniform_direction_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen n-dimensional uniform direction distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of matrices
+        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.
+
+        Examples
+        --------
+        >>> from scipy.stats import uniform_direction
+        >>> x = uniform_direction(3)
+        >>> x.rvs()
+
+        """
+        self._dist = uniform_direction_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=None, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+def _sample_uniform_direction(dim, size, random_state):
+    """
+    Private method to generate uniform directions
+    Reference: Marsaglia, G. (1972). "Choosing a Point from the Surface of a
+               Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.
+    """
+    samples_shape = np.append(size, dim)
+    samples = random_state.standard_normal(samples_shape)
+    samples /= np.linalg.norm(samples, axis=-1, keepdims=True)
+    return samples
+
+
+_dirichlet_mn_doc_default_callparams = """\
+alpha : array_like
+    The concentration parameters. The number of entries along the last axis
+    determines the dimensionality of the distribution. Each entry must be
+    strictly positive.
+n : int or array_like
+    The number of trials. Each element must be a strictly positive integer.
+"""
+
+_dirichlet_mn_doc_frozen_callparams = ""
+
+_dirichlet_mn_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+dirichlet_mn_docdict_params = {
+    '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_default_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+dirichlet_mn_docdict_noparams = {
+    '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_frozen_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+
+def _dirichlet_multinomial_check_parameters(alpha, n, x=None):
+
+    alpha = np.asarray(alpha)
+    n = np.asarray(n)
+
+    if x is not None:
+        # Ensure that `x` and `alpha` are arrays. If the shapes are
+        # incompatible, NumPy will raise an appropriate error.
+        try:
+            x, alpha = np.broadcast_arrays(x, alpha)
+        except ValueError as e:
+            msg = "`x` and `alpha` must be broadcastable."
+            raise ValueError(msg) from e
+
+        x_int = np.floor(x)
+        if np.any(x < 0) or np.any(x != x_int):
+            raise ValueError("`x` must contain only non-negative integers.")
+        x = x_int
+
+    if np.any(alpha <= 0):
+        raise ValueError("`alpha` must contain only positive values.")
+
+    n_int = np.floor(n)
+    if np.any(n <= 0) or np.any(n != n_int):
+        raise ValueError("`n` must be a positive integer.")
+    n = n_int
+
+    sum_alpha = np.sum(alpha, axis=-1)
+    sum_alpha, n = np.broadcast_arrays(sum_alpha, n)
+
+    return (alpha, sum_alpha, n) if x is None else (alpha, sum_alpha, n, x)
+
+
+class dirichlet_multinomial_gen(multi_rv_generic):
+    r"""A Dirichlet multinomial random variable.
+
+    The Dirichlet multinomial distribution is a compound probability
+    distribution: it is the multinomial distribution with number of trials
+    `n` and class probabilities ``p`` randomly sampled from a Dirichlet
+    distribution with concentration parameters ``alpha``.
+
+    Methods
+    -------
+    logpmf(x, alpha, n):
+        Log of the probability mass function.
+    pmf(x, alpha, n):
+        Probability mass function.
+    mean(alpha, n):
+        Mean of the Dirichlet multinomial distribution.
+    var(alpha, n):
+        Variance of the Dirichlet multinomial distribution.
+    cov(alpha, n):
+        The covariance of the Dirichlet multinomial distribution.
+
+    Parameters
+    ----------
+    %(_dirichlet_mn_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    See Also
+    --------
+    scipy.stats.dirichlet : The dirichlet distribution.
+    scipy.stats.multinomial : The multinomial distribution.
+
+    References
+    ----------
+    .. [1] Dirichlet-multinomial distribution, Wikipedia,
+           https://www.wikipedia.org/wiki/Dirichlet-multinomial_distribution
+
+    Examples
+    --------
+    >>> from scipy.stats import dirichlet_multinomial
+
+    Get the PMF
+
+    >>> n = 6  # number of trials
+    >>> alpha = [3, 4, 5]  # concentration parameters
+    >>> x = [1, 2, 3]  # counts
+    >>> dirichlet_multinomial.pmf(x, alpha, n)
+    0.08484162895927604
+
+    If the sum of category counts does not equal the number of trials,
+    the probability mass is zero.
+
+    >>> dirichlet_multinomial.pmf(x, alpha, n=7)
+    0.0
+
+    Get the log of the PMF
+
+    >>> dirichlet_multinomial.logpmf(x, alpha, n)
+    -2.4669689491013327
+
+    Get the mean
+
+    >>> dirichlet_multinomial.mean(alpha, n)
+    array([1.5, 2. , 2.5])
+
+    Get the variance
+
+    >>> dirichlet_multinomial.var(alpha, n)
+    array([1.55769231, 1.84615385, 2.01923077])
+
+    Get the covariance
+
+    >>> dirichlet_multinomial.cov(alpha, n)
+    array([[ 1.55769231, -0.69230769, -0.86538462],
+           [-0.69230769,  1.84615385, -1.15384615],
+           [-0.86538462, -1.15384615,  2.01923077]])
+
+    Alternatively, the object may be called (as a function) to fix the
+    `alpha` and `n` parameters, returning a "frozen" Dirichlet multinomial
+    random variable.
+
+    >>> dm = dirichlet_multinomial(alpha, n)
+    >>> dm.pmf(x)
+    0.08484162895927579
+
+    All methods are fully vectorized. Each element of `x` and `alpha` is
+    a vector (along the last axis), each element of `n` is an
+    integer (scalar), and the result is computed element-wise.
+
+    >>> x = [[1, 2, 3], [4, 5, 6]]
+    >>> alpha = [[1, 2, 3], [4, 5, 6]]
+    >>> n = [6, 15]
+    >>> dirichlet_multinomial.pmf(x, alpha, n)
+    array([0.06493506, 0.02626937])
+
+    >>> dirichlet_multinomial.cov(alpha, n).shape  # both covariance matrices
+    (2, 3, 3)
+
+    Broadcasting according to standard NumPy conventions is supported. Here,
+    we have four sets of concentration parameters (each a two element vector)
+    for each of three numbers of trials (each a scalar).
+
+    >>> alpha = [[3, 4], [4, 5], [5, 6], [6, 7]]
+    >>> n = [[6], [7], [8]]
+    >>> dirichlet_multinomial.mean(alpha, n).shape
+    (3, 4, 2)
+
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__,
+                                        dirichlet_mn_docdict_params)
+
+    def __call__(self, alpha, n, seed=None):
+        return dirichlet_multinomial_frozen(alpha, n, seed=seed)
+
+    def logpmf(self, x, alpha, n):
+        """The log of the probability mass function.
+
+        Parameters
+        ----------
+        x: ndarray
+            Category counts (non-negative integers). Must be broadcastable
+            with shape parameter ``alpha``. If multidimensional, the last axis
+            must correspond with the categories.
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray or scalar
+            Log of the probability mass function.
+
+        """
+
+        a, Sa, n, x = _dirichlet_multinomial_check_parameters(alpha, n, x)
+
+        out = np.asarray(loggamma(Sa) + loggamma(n + 1) - loggamma(n + Sa))
+        out += (loggamma(x + a) - (loggamma(a) + loggamma(x + 1))).sum(axis=-1)
+        np.place(out, n != x.sum(axis=-1), -np.inf)
+        return out[()]
+
+    def pmf(self, x, alpha, n):
+        """Probability mass function for a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        x: ndarray
+            Category counts (non-negative integers). Must be broadcastable
+            with shape parameter ``alpha``. If multidimensional, the last axis
+            must correspond with the categories.
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray or scalar
+            Probability mass function.
+
+        """
+        return np.exp(self.logpmf(x, alpha, n))
+
+    def mean(self, alpha, n):
+        """Mean of a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray
+            Mean of a Dirichlet multinomial distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        n, Sa = n[..., np.newaxis], Sa[..., np.newaxis]
+        return n * a / Sa
+
+    def var(self, alpha, n):
+        """The variance of the Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: array_like
+            The variances of the components of the distribution. This is
+            the diagonal of the covariance matrix of the distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        n, Sa = n[..., np.newaxis], Sa[..., np.newaxis]
+        return n * a / Sa * (1 - a/Sa) * (n + Sa) / (1 + Sa)
+
+    def cov(self, alpha, n):
+        """Covariance matrix of a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out : array_like
+            The covariance matrix of the distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        var = dirichlet_multinomial.var(a, n)
+
+        n, Sa = n[..., np.newaxis, np.newaxis], Sa[..., np.newaxis, np.newaxis]
+        aiaj = a[..., :, np.newaxis] * a[..., np.newaxis, :]
+        cov = -n * aiaj / Sa ** 2 * (n + Sa) / (1 + Sa)
+
+        ii = np.arange(cov.shape[-1])
+        cov[..., ii, ii] = var
+        return cov
+
+
+dirichlet_multinomial = dirichlet_multinomial_gen()
+
+
+class dirichlet_multinomial_frozen(multi_rv_frozen):
+    def __init__(self, alpha, n, seed=None):
+        alpha, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        self.alpha = alpha
+        self.n = n
+        self._dist = dirichlet_multinomial_gen(seed)
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.alpha, self.n)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.alpha, self.n)
+
+    def mean(self):
+        return self._dist.mean(self.alpha, self.n)
+
+    def var(self):
+        return self._dist.var(self.alpha, self.n)
+
+    def cov(self):
+        return self._dist.cov(self.alpha, self.n)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# dirichlet_multinomial and fill in default strings in class docstrings.
+for name in ['logpmf', 'pmf', 'mean', 'var', 'cov']:
+    method = dirichlet_multinomial_gen.__dict__[name]
+    method_frozen = dirichlet_multinomial_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, dirichlet_mn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      dirichlet_mn_docdict_params)
+
+
+class vonmises_fisher_gen(multi_rv_generic):
+    r"""A von Mises-Fisher variable.
+
+    The `mu` keyword specifies the mean direction vector. The `kappa` keyword
+    specifies the concentration parameter.
+
+    Methods
+    -------
+    pdf(x, mu=None, kappa=1)
+        Probability density function.
+    logpdf(x, mu=None, kappa=1)
+        Log of the probability density function.
+    rvs(mu=None, kappa=1, size=1, random_state=None)
+        Draw random samples from a von Mises-Fisher distribution.
+    entropy(mu=None, kappa=1)
+        Compute the differential entropy of the von Mises-Fisher distribution.
+    fit(data)
+        Fit a von Mises-Fisher distribution to data.
+
+    Parameters
+    ----------
+    mu : array_like
+        Mean direction of the distribution. Must be a one-dimensional unit
+        vector of norm 1.
+    kappa : float
+        Concentration parameter. Must be positive.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    See Also
+    --------
+    scipy.stats.vonmises : Von-Mises Fisher distribution in 2D on a circle
+    uniform_direction : uniform distribution on the surface of a hypersphere
+
+    Notes
+    -----
+    The von Mises-Fisher distribution is a directional distribution on the
+    surface of the unit hypersphere. The probability density
+    function of a unit vector :math:`\mathbf{x}` is
+
+    .. math::
+
+        f(\mathbf{x}) = \frac{\kappa^{d/2-1}}{(2\pi)^{d/2}I_{d/2-1}(\kappa)}
+               \exp\left(\kappa \mathbf{\mu}^T\mathbf{x}\right),
+
+    where :math:`\mathbf{\mu}` is the mean direction, :math:`\kappa` the
+    concentration parameter, :math:`d` the dimension and :math:`I` the
+    modified Bessel function of the first kind. As :math:`\mu` represents
+    a direction, it must be a unit vector or in other words, a point
+    on the hypersphere: :math:`\mathbf{\mu}\in S^{d-1}`. :math:`\kappa` is a
+    concentration parameter, which means that it must be positive
+    (:math:`\kappa>0`) and that the distribution becomes more narrow with
+    increasing :math:`\kappa`. In that sense, the reciprocal value
+    :math:`1/\kappa` resembles the variance parameter of the normal
+    distribution.
+
+    The von Mises-Fisher distribution often serves as an analogue of the
+    normal distribution on the sphere. Intuitively, for unit vectors, a
+    useful distance measure is given by the angle :math:`\alpha` between
+    them. This is exactly what the scalar product
+    :math:`\mathbf{\mu}^T\mathbf{x}=\cos(\alpha)` in the
+    von Mises-Fisher probability density function describes: the angle
+    between the mean direction :math:`\mathbf{\mu}` and the vector
+    :math:`\mathbf{x}`. The larger the angle between them, the smaller the
+    probability to observe :math:`\mathbf{x}` for this particular mean
+    direction :math:`\mathbf{\mu}`.
+
+    In dimensions 2 and 3, specialized algorithms are used for fast sampling
+    [2]_, [3]_. For dimensions of 4 or higher the rejection sampling algorithm
+    described in [4]_ is utilized. This implementation is partially based on
+    the geomstats package [5]_, [6]_.
+
+    .. versionadded:: 1.11
+
+    References
+    ----------
+    .. [1] Von Mises-Fisher distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution
+    .. [2] Mardia, K., and Jupp, P. Directional statistics. Wiley, 2000.
+    .. [3] J. Wenzel. Numerically stable sampling of the von Mises Fisher
+           distribution on S2.
+           https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf
+    .. [4] Wood, A. Simulation of the von mises fisher distribution.
+           Communications in statistics-simulation and computation 23,
+           1 (1994), 157-164. https://doi.org/10.1080/03610919408813161
+    .. [5] geomstats, Github. MIT License. Accessed: 06.01.2023.
+           https://github.com/geomstats/geomstats
+    .. [6] Miolane, N. et al. Geomstats:  A Python Package for Riemannian
+           Geometry in Machine Learning. Journal of Machine Learning Research
+           21 (2020). http://jmlr.org/papers/v21/19-027.html
+
+    Examples
+    --------
+    **Visualization of the probability density**
+
+    Plot the probability density in three dimensions for increasing
+    concentration parameter. The density is calculated by the ``pdf``
+    method.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import vonmises_fisher
+    >>> from matplotlib.colors import Normalize
+    >>> n_grid = 100
+    >>> u = np.linspace(0, np.pi, n_grid)
+    >>> v = np.linspace(0, 2 * np.pi, n_grid)
+    >>> u_grid, v_grid = np.meshgrid(u, v)
+    >>> vertices = np.stack([np.cos(v_grid) * np.sin(u_grid),
+    ...                      np.sin(v_grid) * np.sin(u_grid),
+    ...                      np.cos(u_grid)],
+    ...                     axis=2)
+    >>> x = np.outer(np.cos(v), np.sin(u))
+    >>> y = np.outer(np.sin(v), np.sin(u))
+    >>> z = np.outer(np.ones_like(u), np.cos(u))
+    >>> def plot_vmf_density(ax, x, y, z, vertices, mu, kappa):
+    ...     vmf = vonmises_fisher(mu, kappa)
+    ...     pdf_values = vmf.pdf(vertices)
+    ...     pdfnorm = Normalize(vmin=pdf_values.min(), vmax=pdf_values.max())
+    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1,
+    ...                     facecolors=plt.cm.viridis(pdfnorm(pdf_values)),
+    ...                     linewidth=0)
+    ...     ax.set_aspect('equal')
+    ...     ax.view_init(azim=-130, elev=0)
+    ...     ax.axis('off')
+    ...     ax.set_title(rf"$\kappa={kappa}$")
+    >>> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 4),
+    ...                          subplot_kw={"projection": "3d"})
+    >>> left, middle, right = axes
+    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
+    >>> plot_vmf_density(left, x, y, z, vertices, mu, 5)
+    >>> plot_vmf_density(middle, x, y, z, vertices, mu, 20)
+    >>> plot_vmf_density(right, x, y, z, vertices, mu, 100)
+    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, right=1.0, wspace=0.)
+    >>> plt.show()
+
+    As we increase the concentration parameter, the points are getting more
+    clustered together around the mean direction.
+
+    **Sampling**
+
+    Draw 5 samples from the distribution using the ``rvs`` method resulting
+    in a 5x3 array.
+
+    >>> rng = np.random.default_rng()
+    >>> mu = np.array([0, 0, 1])
+    >>> samples = vonmises_fisher(mu, 20).rvs(5, random_state=rng)
+    >>> samples
+    array([[ 0.3884594 , -0.32482588,  0.86231516],
+           [ 0.00611366, -0.09878289,  0.99509023],
+           [-0.04154772, -0.01637135,  0.99900239],
+           [-0.14613735,  0.12553507,  0.98126695],
+           [-0.04429884, -0.23474054,  0.97104814]])
+
+    These samples are unit vectors on the sphere :math:`S^2`. To verify,
+    let us calculate their euclidean norms:
+
+    >>> np.linalg.norm(samples, axis=1)
+    array([1., 1., 1., 1., 1.])
+
+    Plot 20 observations drawn from the von Mises-Fisher distribution for
+    increasing concentration parameter :math:`\kappa`. The red dot highlights
+    the mean direction :math:`\mu`.
+
+    >>> def plot_vmf_samples(ax, x, y, z, mu, kappa):
+    ...     vmf = vonmises_fisher(mu, kappa)
+    ...     samples = vmf.rvs(20)
+    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0,
+    ...                     alpha=0.2)
+    ...     ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], c='k', s=5)
+    ...     ax.scatter(mu[0], mu[1], mu[2], c='r', s=30)
+    ...     ax.set_aspect('equal')
+    ...     ax.view_init(azim=-130, elev=0)
+    ...     ax.axis('off')
+    ...     ax.set_title(rf"$\kappa={kappa}$")
+    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
+    >>> fig, axes = plt.subplots(nrows=1, ncols=3,
+    ...                          subplot_kw={"projection": "3d"},
+    ...                          figsize=(9, 4))
+    >>> left, middle, right = axes
+    >>> plot_vmf_samples(left, x, y, z, mu, 5)
+    >>> plot_vmf_samples(middle, x, y, z, mu, 20)
+    >>> plot_vmf_samples(right, x, y, z, mu, 100)
+    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0,
+    ...                     right=1.0, wspace=0.)
+    >>> plt.show()
+
+    The plots show that with increasing concentration :math:`\kappa` the
+    resulting samples are centered more closely around the mean direction.
+
+    **Fitting the distribution parameters**
+
+    The distribution can be fitted to data using the ``fit`` method returning
+    the estimated parameters. As a toy example let's fit the distribution to
+    samples drawn from a known von Mises-Fisher distribution.
+
+    >>> mu, kappa = np.array([0, 0, 1]), 20
+    >>> samples = vonmises_fisher(mu, kappa).rvs(1000, random_state=rng)
+    >>> mu_fit, kappa_fit = vonmises_fisher.fit(samples)
+    >>> mu_fit, kappa_fit
+    (array([0.01126519, 0.01044501, 0.99988199]), 19.306398751730995)
+
+    We see that the estimated parameters `mu_fit` and `kappa_fit` are
+    very close to the ground truth parameters.
+
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+
+    def __call__(self, mu=None, kappa=1, seed=None):
+        """Create a frozen von Mises-Fisher distribution.
+
+        See `vonmises_fisher_frozen` for more information.
+        """
+        return vonmises_fisher_frozen(mu, kappa, seed=seed)
+
+    def _process_parameters(self, mu, kappa):
+        """
+        Infer dimensionality from mu and ensure that mu is a one-dimensional
+        unit vector and kappa positive.
+        """
+        mu = np.asarray(mu)
+        if mu.ndim > 1:
+            raise ValueError("'mu' must have one-dimensional shape.")
+        if not np.allclose(np.linalg.norm(mu), 1.):
+            raise ValueError("'mu' must be a unit vector of norm 1.")
+        if not mu.size > 1:
+            raise ValueError("'mu' must have at least two entries.")
+        kappa_error_msg = "'kappa' must be a positive scalar."
+        if not np.isscalar(kappa) or kappa < 0:
+            raise ValueError(kappa_error_msg)
+        if float(kappa) == 0.:
+            raise ValueError("For 'kappa=0' the von Mises-Fisher distribution "
+                             "becomes the uniform distribution on the sphere "
+                             "surface. Consider using "
+                             "'scipy.stats.uniform_direction' instead.")
+        dim = mu.size
+
+        return dim, mu, kappa
+
+    def _check_data_vs_dist(self, x, dim):
+        if x.shape[-1] != dim:
+            raise ValueError("The dimensionality of the last axis of 'x' must "
+                             "match the dimensionality of the "
+                             "von Mises Fisher distribution.")
+        if not np.allclose(np.linalg.norm(x, axis=-1), 1.):
+            msg = "'x' must be unit vectors of norm 1 along last dimension."
+            raise ValueError(msg)
+
+    def _log_norm_factor(self, dim, kappa):
+        # normalization factor is given by
+        # c = kappa**(dim/2-1)/((2*pi)**(dim/2)*I[dim/2-1](kappa))
+        #   = kappa**(dim/2-1)*exp(-kappa) /
+        #     ((2*pi)**(dim/2)*I[dim/2-1](kappa)*exp(-kappa)
+        #   = kappa**(dim/2-1)*exp(-kappa) /
+        #     ((2*pi)**(dim/2)*ive[dim/2-1](kappa)
+        # Then the log is given by
+        # log c = 1/2*(dim -1)*log(kappa) - kappa - -1/2*dim*ln(2*pi) -
+        #         ive[dim/2-1](kappa)
+        halfdim = 0.5 * dim
+        return (0.5 * (dim - 2)*np.log(kappa) - halfdim * _LOG_2PI -
+                np.log(ive(halfdim - 1, kappa)) - kappa)
+
+    def _logpdf(self, x, dim, mu, kappa):
+        """Log of the von Mises-Fisher probability density function.
+
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        x = np.asarray(x)
+        self._check_data_vs_dist(x, dim)
+        dotproducts = np.einsum('i,...i->...', mu, x)
+        return self._log_norm_factor(dim, kappa) + kappa * dotproducts
+
+    def logpdf(self, x, mu=None, kappa=1):
+        """Log of the von Mises-Fisher probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+        mu : array_like, default: None
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        return self._logpdf(x, dim, mu, kappa)
+
+    def pdf(self, x, mu=None, kappa=1):
+        """Von Mises-Fisher probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+        mu : array_like
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        return np.exp(self._logpdf(x, dim, mu, kappa))
+
+    def _rvs_2d(self, mu, kappa, size, random_state):
+        """
+        In 2D, the von Mises-Fisher distribution reduces to the
+        von Mises distribution which can be efficiently sampled by numpy.
+        This method is much faster than the general rejection
+        sampling based algorithm.
+
+        """
+        mean_angle = np.arctan2(mu[1], mu[0])
+        angle_samples = random_state.vonmises(mean_angle, kappa, size=size)
+        samples = np.stack([np.cos(angle_samples), np.sin(angle_samples)],
+                           axis=-1)
+        return samples
+
+    def _rvs_3d(self, kappa, size, random_state):
+        """
+        Generate samples from a von Mises-Fisher distribution
+        with mu = [1, 0, 0] and kappa. Samples then have to be
+        rotated towards the desired mean direction mu.
+        This method is much faster than the general rejection
+        sampling based algorithm.
+        Reference: https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf
+
+        """
+        if size is None:
+            sample_size = 1
+        else:
+            sample_size = size
+
+        # compute x coordinate acc. to equation from section 3.1
+        x = random_state.random(sample_size)
+        x = 1. + np.log(x + (1. - x) * np.exp(-2 * kappa))/kappa
+
+        # (y, z) are random 2D vectors that only have to be
+        # normalized accordingly. Then (x, y z) follow a VMF distribution
+        temp = np.sqrt(1. - np.square(x))
+        uniformcircle = _sample_uniform_direction(2, sample_size, random_state)
+        samples = np.stack([x, temp * uniformcircle[..., 0],
+                            temp * uniformcircle[..., 1]],
+                           axis=-1)
+        if size is None:
+            samples = np.squeeze(samples)
+        return samples
+
+    def _rejection_sampling(self, dim, kappa, size, random_state):
+        """
+        Generate samples from a n-dimensional von Mises-Fisher distribution
+        with mu = [1, 0, ..., 0] and kappa via rejection sampling.
+        Samples then have to be rotated towards the desired mean direction mu.
+        Reference: https://doi.org/10.1080/03610919408813161
+        """
+        dim_minus_one = dim - 1
+        # calculate number of requested samples
+        if size is not None:
+            if not np.iterable(size):
+                size = (size, )
+            n_samples = math.prod(size)
+        else:
+            n_samples = 1
+        # calculate envelope for rejection sampler (eq. 4)
+        sqrt = np.sqrt(4 * kappa ** 2. + dim_minus_one ** 2)
+        envelop_param = (-2 * kappa + sqrt) / dim_minus_one
+        if envelop_param == 0:
+            # the regular formula suffers from loss of precision for high
+            # kappa. This can only be detected by checking for 0 here.
+            # Workaround: expansion for sqrt variable
+            # https://www.wolframalpha.com/input?i=sqrt%284*x%5E2%2Bd%5E2%29
+            # e = (-2 * k + sqrt(k**2 + d**2)) / d
+            #   ~ (-2 * k + 2 * k + d**2/(4 * k) - d**4/(64 * k**3)) / d
+            #   = d/(4 * k) - d**3/(64 * k**3)
+            envelop_param = (dim_minus_one/4 * kappa**-1.
+                             - dim_minus_one**3/64 * kappa**-3.)
+        # reference step 0
+        node = (1. - envelop_param) / (1. + envelop_param)
+        # t = ln(1 - ((1-x)/(1+x))**2)
+        #   = ln(4 * x / (1+x)**2)
+        #   = ln(4) + ln(x) - 2*log1p(x)
+        correction = (kappa * node + dim_minus_one
+                      * (np.log(4) + np.log(envelop_param)
+                      - 2 * np.log1p(envelop_param)))
+        n_accepted = 0
+        x = np.zeros((n_samples, ))
+        halfdim = 0.5 * dim_minus_one
+        # main loop
+        while n_accepted < n_samples:
+            # generate candidates acc. to reference step 1
+            sym_beta = random_state.beta(halfdim, halfdim,
+                                         size=n_samples - n_accepted)
+            coord_x = (1 - (1 + envelop_param) * sym_beta) / (
+                1 - (1 - envelop_param) * sym_beta)
+            # accept or reject: reference step 2
+            # reformulation for numerical stability:
+            # t = ln(1 - (1-x)/(1+x) * y)
+            #   = ln((1 + x - y +x*y)/(1 +x))
+            accept_tol = random_state.random(n_samples - n_accepted)
+            criterion = (
+                kappa * coord_x
+                + dim_minus_one * (np.log((1 + envelop_param - coord_x
+                + coord_x * envelop_param) / (1 + envelop_param)))
+                - correction) > np.log(accept_tol)
+            accepted_iter = np.sum(criterion)
+            x[n_accepted:n_accepted + accepted_iter] = coord_x[criterion]
+            n_accepted += accepted_iter
+        # concatenate x and remaining coordinates: step 3
+        coord_rest = _sample_uniform_direction(dim_minus_one, n_accepted,
+                                               random_state)
+        coord_rest = np.einsum(
+            '...,...i->...i', np.sqrt(1 - x ** 2), coord_rest)
+        samples = np.concatenate([x[..., None], coord_rest], axis=1)
+        # reshape output to (size, dim)
+        if size is not None:
+            samples = samples.reshape(size + (dim, ))
+        else:
+            samples = np.squeeze(samples)
+        return samples
+
+    def _rotate_samples(self, samples, mu, dim):
+        """A QR decomposition is used to find the rotation that maps the
+        north pole (1, 0,...,0) to the vector mu. This rotation is then
+        applied to all samples.
+
+        Parameters
+        ----------
+        samples: array_like, shape = [..., n]
+        mu : array-like, shape=[n, ]
+            Point to parametrise the rotation.
+
+        Returns
+        -------
+        samples : rotated samples
+
+        """
+        base_point = np.zeros((dim, ))
+        base_point[0] = 1.
+        embedded = np.concatenate([mu[None, :], np.zeros((dim - 1, dim))])
+        rotmatrix, _ = np.linalg.qr(np.transpose(embedded))
+        if np.allclose(np.matmul(rotmatrix, base_point[:, None])[:, 0], mu):
+            rotsign = 1
+        else:
+            rotsign = -1
+
+        # apply rotation
+        samples = np.einsum('ij,...j->...i', rotmatrix, samples) * rotsign
+        return samples
+
+    def _rvs(self, dim, mu, kappa, size, random_state):
+        if dim == 2:
+            samples = self._rvs_2d(mu, kappa, size, random_state)
+        elif dim == 3:
+            samples = self._rvs_3d(kappa, size, random_state)
+        else:
+            samples = self._rejection_sampling(dim, kappa, size,
+                                               random_state)
+
+        if dim != 2:
+            samples = self._rotate_samples(samples, mu, dim)
+        return samples
+
+    def rvs(self, mu=None, kappa=1, size=1, random_state=None):
+        """Draw random samples from a von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        mu : array_like
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float
+            Concentration parameter. Must be positive.
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {None, int, np.random.RandomState, np.random.Generator},
+                        optional
+            Used for drawing random variates.
+            If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used, seeded
+            with seed.
+            If `seed` is already a ``RandomState`` or ``Generator`` instance,
+            then that object is used.
+            Default is `None`.
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`, `N`), where `N` is the
+            dimension of the distribution.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        random_state = self._get_random_state(random_state)
+        samples = self._rvs(dim, mu, kappa, size, random_state)
+        return samples
+
+    def _entropy(self, dim, kappa):
+        halfdim = 0.5 * dim
+        return (-self._log_norm_factor(dim, kappa) - kappa *
+                ive(halfdim, kappa) / ive(halfdim - 1, kappa))
+
+    def entropy(self, mu=None, kappa=1):
+        """Compute the differential entropy of the von Mises-Fisher
+        distribution.
+
+        Parameters
+        ----------
+        mu : array_like, default: None
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the von Mises-Fisher distribution.
+
+        """
+        dim, _, kappa = self._process_parameters(mu, kappa)
+        return self._entropy(dim, kappa)
+
+    def fit(self, x):
+        """Fit the von Mises-Fisher distribution to data.
+
+        Parameters
+        ----------
+        x : array-like
+            Data the distribution is fitted to. Must be two dimensional.
+            The second axis of `x` must be unit vectors of norm 1 and
+            determine the dimensionality of the fitted
+            von Mises-Fisher distribution.
+
+        Returns
+        -------
+        mu : ndarray
+            Estimated mean direction.
+        kappa : float
+            Estimated concentration parameter.
+
+        """
+        # validate input data
+        x = np.asarray(x)
+        if x.ndim != 2:
+            raise ValueError("'x' must be two dimensional.")
+        if not np.allclose(np.linalg.norm(x, axis=-1), 1.):
+            msg = "'x' must be unit vectors of norm 1 along last dimension."
+            raise ValueError(msg)
+        dim = x.shape[-1]
+
+        # mu is simply the directional mean
+        dirstats = directional_stats(x)
+        mu = dirstats.mean_direction
+        r = dirstats.mean_resultant_length
+
+        # kappa is the solution to the equation:
+        # r = I[dim/2](kappa) / I[dim/2 -1](kappa)
+        #   = I[dim/2](kappa) * exp(-kappa) / I[dim/2 -1](kappa) * exp(-kappa)
+        #   = ive(dim/2, kappa) / ive(dim/2 -1, kappa)
+
+        halfdim = 0.5 * dim
+
+        def solve_for_kappa(kappa):
+            bessel_vals = ive([halfdim, halfdim - 1], kappa)
+            return bessel_vals[0]/bessel_vals[1] - r
+
+        root_res = root_scalar(solve_for_kappa, method="brentq",
+                               bracket=(1e-8, 1e9))
+        kappa = root_res.root
+        return mu, kappa
+
+
+vonmises_fisher = vonmises_fisher_gen()
+
+
+class vonmises_fisher_frozen(multi_rv_frozen):
+    def __init__(self, mu=None, kappa=1, seed=None):
+        """Create a frozen von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        mu : array_like, default: None
+            Mean direction of the distribution.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+        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.
+
+        """
+        self._dist = vonmises_fisher_gen(seed)
+        self.dim, self.mu, self.kappa = (
+            self._dist._process_parameters(mu, kappa)
+        )
+
+    def logpdf(self, x):
+        """
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of probability density function evaluated at `x`.
+
+        """
+        return self._dist._logpdf(x, self.dim, self.mu, self.kappa)
+
+    def pdf(self, x):
+        """
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`.
+
+        """
+        return np.exp(self.logpdf(x))
+
+    def rvs(self, size=1, random_state=None):
+        """Draw random variates from the Von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {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
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the distribution.
+
+        """
+        random_state = self._dist._get_random_state(random_state)
+        return self._dist._rvs(self.dim, self.mu, self.kappa, size,
+                               random_state)
+
+    def entropy(self):
+        """
+        Calculate the differential entropy of the von Mises-Fisher
+        distribution.
+
+        Returns
+        -------
+        h: float
+            Entropy of the Von Mises-Fisher distribution.
+
+        """
+        return self._dist._entropy(self.dim, self.kappa)
+
+
+class normal_inverse_gamma_gen(multi_rv_generic):
+    r"""Normal-inverse-gamma distribution.
+
+    The normal-inverse-gamma distribution is the conjugate prior of a normal
+    distribution with unknown mean and variance.
+
+    Methods
+    -------
+    pdf(x, s2, mu=0, lmbda=1, a=1, b=1)
+        Probability density function.
+    logpdf(x, s2, mu=0, lmbda=1, a=1, b=1)
+        Log of the probability density function.
+    mean(mu=0, lmbda=1, a=1, b=1)
+        Distribution mean.
+    var(mu=0, lmbda=1, a=1, b=1)
+        Distribution variance.
+    rvs(mu=0, lmbda=1, a=1, b=1, size=None, random_state=None)
+        Draw random samples.
+
+    Parameters
+    ----------
+    mu, lmbda, a, b  : array_like
+        Shape parameters of the distribution. See notes.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    See Also
+    --------
+    norm
+    invgamma
+
+    Notes
+    -----
+
+    The probability density function of `normal_inverse_gamma` is:
+
+    .. math::
+
+        f(x, \sigma^2; \mu, \lambda, \alpha, \beta) =
+            \frac{\sqrt{\lambda}}{\sqrt{2 \pi \sigma^2}}
+            \frac{\beta^\alpha}{\Gamma(\alpha)}
+            \left( \frac{1}{\sigma^2} \right)^{\alpha + 1}
+            \exp \left(- \frac{2 \beta + \lambda (x - \mu)^2} {2 \sigma^2} \right)
+
+    where all parameters are real and finite, and :math:`\sigma^2 > 0`,
+    :math:`\lambda > 0`, :math:`\alpha > 0`, and :math:`\beta > 0`.
+
+    Methods ``normal_inverse_gamma.pdf`` and ``normal_inverse_gamma.logpdf``
+    accept `x` and `s2` for arguments :math:`x` and :math:`\sigma^2`.
+    All methods accept `mu`, `lmbda`, `a`, and `b` for shape parameters
+    :math:`\mu`, :math:`\lambda`, :math:`\alpha`, and :math:`\beta`,
+    respectively.
+
+    .. versionadded:: 1.15
+
+    References
+    ----------
+    .. [1] Normal-inverse-gamma distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution
+
+    Examples
+    --------
+    Suppose we wish to investigate the relationship between the
+    normal-inverse-gamma distribution and the inverse gamma distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(527484872345)
+    >>> mu, lmbda, a, b = 0, 1, 20, 20
+    >>> norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b)
+    >>> inv_gamma = stats.invgamma(a, scale=b)
+
+    One approach is to compare the distribution of the `s2` elements of
+    random variates against the PDF of an inverse gamma distribution.
+
+    >>> _, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng)
+    >>> bins = np.linspace(s2.min(), s2.max(), 50)
+    >>> plt.hist(s2, bins=bins, density=True, label='Frequency density')
+    >>> s2 = np.linspace(s2.min(), s2.max(), 300)
+    >>> plt.plot(s2, inv_gamma.pdf(s2), label='PDF')
+    >>> plt.xlabel(r'$\sigma^2$')
+    >>> plt.ylabel('Frequency density / PMF')
+    >>> plt.show()
+
+    Similarly, we can compare the marginal distribution of `s2` against
+    an inverse gamma distribution.
+
+    >>> from scipy.integrate import quad_vec
+    >>> from scipy import integrate
+    >>> s2 = np.linspace(0.5, 3, 6)
+    >>> res = quad_vec(lambda x: norm_inv_gamma.pdf(x, s2), -np.inf, np.inf)[0]
+    >>> np.allclose(res, inv_gamma.pdf(s2))
+    True
+
+    The sample mean is comparable to the mean of the distribution.
+
+    >>> x, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng)
+    >>> x.mean(), s2.mean()
+    (np.float64(-0.005254750127304425), np.float64(1.050438111436508))
+    >>> norm_inv_gamma.mean()
+    (np.float64(0.0), np.float64(1.0526315789473684))
+
+    Similarly, for the variance:
+
+    >>> x.var(ddof=1), s2.var(ddof=1)
+    (np.float64(1.0546150578185023), np.float64(0.061829865266330754))
+    >>> norm_inv_gamma.var()
+    (np.float64(1.0526315789473684), np.float64(0.061557402277623886))
+
+    """
+    def rvs(self, mu=0, lmbda=1, a=1, b=1, size=None, random_state=None):
+        """Draw random samples from the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+        size : int or tuple of ints, optional
+            Shape of samples to draw.
+        random_state : {None, int, np.random.RandomState, np.random.Generator}, optional
+            Used for drawing random variates.
+            If `random_state` is `None`, the `~np.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is used, seeded
+            with `random_state`.
+            If `random_state` is already a ``RandomState`` or ``Generator`` instance,
+            then that object is used.
+            Default is `None`.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            Random variates.
+
+        """
+        random_state = self._get_random_state(random_state)
+        s2 = invgamma(a, scale=b).rvs(size=size, random_state=random_state)
+        scale = (s2 / lmbda)**0.5
+        x = norm(loc=mu, scale=scale).rvs(size=size, random_state=random_state)
+        dtype = np.result_type(1.0, mu, lmbda, a, b)
+        return x.astype(dtype), s2.astype(dtype)
+
+    def _logpdf(self, x, s2, mu, lmbda, a, b):
+        t1 = 0.5 * (np.log(lmbda) - np.log(2 * np.pi * s2))
+        t2 = a*np.log(b) - special.gammaln(a).astype(a.dtype)
+        t3 = -(a + 1) * np.log(s2)
+        t4 = -(2*b + lmbda*(x - mu)**2) / (2*s2)
+        return t1 + t2 + t3 + t4
+
+    def logpdf(self, x, s2, mu=0, lmbda=1, a=1, b=1):
+        """Log of the probability density function.
+
+        Parameters
+        ----------
+        x, s2 : array_like
+            Arguments. `s2` must be greater than zero.
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of the probability density function.
+
+        """
+        invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b)
+        s2 = args[1]
+        # Keep it simple for now; lazyselect later, perhaps.
+        with np.errstate(all='ignore'):
+            logpdf = np.asarray(self._logpdf(*args))
+        logpdf[s2 <= 0] = -np.inf
+        logpdf[invalid] = np.nan
+        return logpdf[()]
+
+    def _pdf(self, x, s2, mu, lmbda, a, b):
+        t1 = np.sqrt(lmbda / (2 * np.pi * s2))
+        t2 = b**a / special.gamma(a).astype(a.dtype)
+        t3 = (1 / s2)**(a + 1)
+        t4 = np.exp(-(2*b + lmbda*(x - mu)**2) / (2*s2))
+        return t1 * t2 * t3 * t4
+
+    def pdf(self, x, s2, mu=0, lmbda=1, a=1, b=1):
+        """The probability density function.
+
+        Parameters
+        ----------
+        x, s2 : array_like
+            Arguments. `s2` must be greater than zero.
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            The probability density function.
+
+        """
+        invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b)
+        s2 = args[1]
+        # Keep it simple for now; lazyselect later, perhaps.
+        with np.errstate(all='ignore'):
+            pdf = np.asarray(self._pdf(*args))
+        pdf[s2 <= 0] = 0
+        pdf[invalid] = np.nan
+        return pdf[()]
+
+    def mean(self, mu=0, lmbda=1, a=1, b=1):
+        """The mean of the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda` and `b` must be greater
+            than zero, and `a` must be greater than one.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            The mean of the distribution.
+
+        """
+        invalid, args = self._process_shapes(mu, lmbda, a, b)
+        mu, lmbda, a, b = args
+        invalid |= ~(a > 1)
+        mean_x = np.asarray(mu).copy()
+        mean_s2 = np.asarray(b / (a - 1))
+        mean_x[invalid] = np.nan
+        mean_s2[invalid] = np.nan
+        return mean_x[()], mean_s2[()]
+
+    def var(self, mu=0, lmbda=1, a=1, b=1):
+        """The variance of the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda` and `b` must be greater
+            than zero, and `a` must be greater than two.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            The variance of the distribution.
+
+        """
+        invalid, args = self._process_shapes(mu, lmbda, a, b)
+        mu, lmbda, a, b = args
+        invalid_x = invalid | ~(a > 1)
+        invalid_s2 = invalid | ~(a > 2)
+        var_x = b / ((a - 1) * lmbda)
+        var_s2 = b**2 / ((a - 1)**2 * (a - 2))
+        var_x, var_s2 = np.asarray(var_x), np.asarray(var_s2)
+        var_x[invalid_x] = np.nan
+        var_s2[invalid_s2] = np.nan
+        return var_x[()], var_s2[()]
+
+    def _process_parameters_pdf(self, x, s2, mu, lmbda, a, b):
+        args = np.broadcast_arrays(x, s2, mu, lmbda, a, b)
+        dtype = np.result_type(1.0, *(arg.dtype for arg in args))
+        args = [arg.astype(dtype, copy=False) for arg in args]
+        x, s2, mu, lmbda, a, b = args
+        invalid = ~((lmbda > 0) & (a > 0) & (b > 0))
+        return invalid, args
+
+    def _process_shapes(self, mu, lmbda, a, b):
+        args = np.broadcast_arrays(mu, lmbda, a, b)
+        dtype = np.result_type(1.0, *(arg.dtype for arg in args))
+        args = [arg.astype(dtype, copy=False) for arg in args]
+        mu, lmbda, a, b = args
+        invalid = ~((lmbda > 0) & (a > 0) & (b > 0))
+        return invalid, args
+
+    def __call__(self, mu=0, lmbda=1, a=1, b=1, seed=None):
+        return normal_inverse_gamma_frozen(mu, lmbda, a, b, seed=seed)
+
+
+normal_inverse_gamma = normal_inverse_gamma_gen()
+
+
+class normal_inverse_gamma_frozen(multi_rv_frozen):
+
+    def __init__(self, mu=0, lmbda=1, a=1, b=1, seed=None):
+        self._dist = normal_inverse_gamma_gen(seed)
+        self._shapes = mu, lmbda, a, b
+
+    def logpdf(self, x, s2):
+        return self._dist.logpdf(x, s2, *self._shapes)
+
+    def pdf(self, x, s2):
+        return self._dist.pdf(x, s2, *self._shapes)
+
+    def mean(self):
+        return self._dist.mean(*self._shapes)
+
+    def var(self):
+        return self._dist.var(*self._shapes)
+
+    def rvs(self, size=None, random_state=None):
+        return self._dist.rvs(*self._shapes, size=size, random_state=random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# normal_inverse_gamma_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'var', 'rvs']:
+    method = normal_inverse_gamma_gen.__dict__[name]
+    method_frozen = normal_inverse_gamma_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_mvn.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_mvn.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..dfb2fda7ebd60c3aba78900043c6f86fd601dc18
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_mvn.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_new_distributions.py b/python_embeded/Lib/site-packages/scipy/stats/_new_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..03b98754d94555ca8c1976eef60747cb5cb30a89
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_new_distributions.py
@@ -0,0 +1,375 @@
+import sys
+
+import numpy as np
+from numpy import inf
+
+from scipy import special
+from scipy.stats._distribution_infrastructure import (
+    ContinuousDistribution, _RealDomain, _RealParameter, _Parameterization,
+    _combine_docs)
+
+__all__ = ['Normal', 'Uniform']
+
+
+class Normal(ContinuousDistribution):
+    r"""Normal distribution with prescribed mean and standard deviation.
+
+    The probability density function of the normal distribution is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sigma \sqrt{2 \pi}} \exp {
+            \left( -\frac{1}{2}\left( \frac{x - \mu}{\sigma} \right)^2 \right)}
+
+    """
+    # `ShiftedScaledDistribution` allows this to be generated automatically from
+    # an instance of `StandardNormal`, but the normal distribution is so frequently
+    # used that it's worth a bit of code duplication to get better performance.
+    _mu_domain = _RealDomain(endpoints=(-inf, inf))
+    _sigma_domain = _RealDomain(endpoints=(0, inf))
+    _x_support = _RealDomain(endpoints=(-inf, inf))
+
+    _mu_param = _RealParameter('mu',  symbol=r'\mu', domain=_mu_domain,
+                               typical=(-1, 1))
+    _sigma_param = _RealParameter('sigma', symbol=r'\sigma', domain=_sigma_domain,
+                                  typical=(0.5, 1.5))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1))
+
+    _parameterizations = [_Parameterization(_mu_param, _sigma_param)]
+
+    _variable = _x_param
+    _normalization = 1/np.sqrt(2*np.pi)
+    _log_normalization = np.log(2*np.pi)/2
+
+    def __new__(cls, mu=None, sigma=None, **kwargs):
+        if mu is None and sigma is None:
+            return super().__new__(StandardNormal)
+        return super().__new__(cls)
+
+    def __init__(self, *, mu=0., sigma=1., **kwargs):
+        super().__init__(mu=mu, sigma=sigma, **kwargs)
+
+    def _logpdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logpdf_formula(self, (x - mu)/sigma) - np.log(sigma)
+
+    def _pdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._pdf_formula(self, (x - mu)/sigma) / sigma
+
+    def _logcdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logcdf_formula(self, (x - mu)/sigma)
+
+    def _cdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._cdf_formula(self, (x - mu)/sigma)
+
+    def _logccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logccdf_formula(self, (x - mu)/sigma)
+
+    def _ccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ccdf_formula(self, (x - mu)/sigma)
+
+    def _icdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._icdf_formula(self, x) * sigma + mu
+
+    def _ilogcdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ilogcdf_formula(self, x) * sigma + mu
+
+    def _iccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._iccdf_formula(self, x) * sigma + mu
+
+    def _ilogccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ilogccdf_formula(self, x) * sigma + mu
+
+    def _entropy_formula(self, *, mu, sigma, **kwargs):
+        return StandardNormal._entropy_formula(self) + np.log(abs(sigma))
+
+    def _logentropy_formula(self, *, mu, sigma, **kwargs):
+        lH0 = StandardNormal._logentropy_formula(self)
+        with np.errstate(divide='ignore'):
+            # sigma = 1 -> log(sigma) = 0 -> log(log(sigma)) = -inf
+            # Silence the unnecessary runtime warning
+            lls = np.log(np.log(abs(sigma))+0j)
+        return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0)
+
+    def _median_formula(self, *, mu, sigma, **kwargs):
+        return mu
+
+    def _mode_formula(self, *, mu, sigma, **kwargs):
+        return mu
+
+    def _moment_raw_formula(self, order, *, mu, sigma, **kwargs):
+        if order == 0:
+            return np.ones_like(mu)
+        elif order == 1:
+            return mu
+        else:
+            return None
+    _moment_raw_formula.orders = [0, 1]  # type: ignore[attr-defined]
+
+    def _moment_central_formula(self, order, *, mu, sigma, **kwargs):
+        if order == 0:
+            return np.ones_like(mu)
+        elif order % 2:
+            return np.zeros_like(mu)
+        else:
+            # exact is faster (and obviously more accurate) for reasonable orders
+            return sigma**order * special.factorial2(int(order) - 1, exact=True)
+
+    def _sample_formula(self, sample_shape, full_shape, rng, *, mu, sigma, **kwargs):
+        return rng.normal(loc=mu, scale=sigma, size=full_shape)[()]
+
+
+def _log_diff(log_p, log_q):
+    return special.logsumexp([log_p, log_q+np.pi*1j], axis=0)
+
+
+class StandardNormal(Normal):
+    r"""Standard normal distribution.
+
+    The probability density function of the standard normal distribution is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2 \pi}} \exp \left( -\frac{1}{2} x^2 \right)
+
+    """
+    _x_support = _RealDomain(endpoints=(-inf, inf))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-5, 5))
+    _variable = _x_param
+    _parameterizations = []
+    _normalization = 1/np.sqrt(2*np.pi)
+    _log_normalization = np.log(2*np.pi)/2
+    mu = np.float64(0.)
+    sigma = np.float64(1.)
+
+    def __init__(self, **kwargs):
+        ContinuousDistribution.__init__(self, **kwargs)
+
+    def _logpdf_formula(self, x, **kwargs):
+        return -(self._log_normalization + x**2/2)
+
+    def _pdf_formula(self, x, **kwargs):
+        return self._normalization * np.exp(-x**2/2)
+
+    def _logcdf_formula(self, x, **kwargs):
+        return special.log_ndtr(x)
+
+    def _cdf_formula(self, x, **kwargs):
+        return special.ndtr(x)
+
+    def _logccdf_formula(self, x, **kwargs):
+        return special.log_ndtr(-x)
+
+    def _ccdf_formula(self, x, **kwargs):
+        return special.ndtr(-x)
+
+    def _icdf_formula(self, x, **kwargs):
+        return special.ndtri(x)
+
+    def _ilogcdf_formula(self, x, **kwargs):
+        return special.ndtri_exp(x)
+
+    def _iccdf_formula(self, x, **kwargs):
+        return -special.ndtri(x)
+
+    def _ilogccdf_formula(self, x, **kwargs):
+        return -special.ndtri_exp(x)
+
+    def _entropy_formula(self, **kwargs):
+        return (1 + np.log(2*np.pi))/2
+
+    def _logentropy_formula(self, **kwargs):
+        return np.log1p(np.log(2*np.pi)) - np.log(2)
+
+    def _median_formula(self, **kwargs):
+        return 0
+
+    def _mode_formula(self, **kwargs):
+        return 0
+
+    def _moment_raw_formula(self, order, **kwargs):
+        raw_moments = {0: 1, 1: 0, 2: 1, 3: 0, 4: 3, 5: 0}
+        return raw_moments.get(order, None)
+
+    def _moment_central_formula(self, order, **kwargs):
+        return self._moment_raw_formula(order, **kwargs)
+
+    def _moment_standardized_formula(self, order, **kwargs):
+        return self._moment_raw_formula(order, **kwargs)
+
+    def _sample_formula(self, sample_shape, full_shape, rng, **kwargs):
+        return rng.normal(size=full_shape)[()]
+
+
+# currently for testing only
+class _LogUniform(ContinuousDistribution):
+    r"""Log-uniform distribution.
+
+    The probability density function of the log-uniform distribution is:
+
+    .. math::
+
+        f(x; a, b) = \frac{1}
+                          {x (\log(b) - \log(a))}
+
+    If :math:`\log(X)` is a random variable that follows a uniform distribution
+    between :math:`\log(a)` and :math:`\log(b)`, then :math:`X` is log-uniformly
+    distributed with shape parameters :math:`a` and :math:`b`.
+
+    """
+
+    _a_domain = _RealDomain(endpoints=(0, inf))
+    _b_domain = _RealDomain(endpoints=('a', inf))
+    _log_a_domain = _RealDomain(endpoints=(-inf, inf))
+    _log_b_domain = _RealDomain(endpoints=('log_a', inf))
+    _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
+    _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
+    _log_a_param = _RealParameter('log_a', symbol=r'\log(a)',
+                                  domain=_log_a_domain, typical=(-3, -0.1))
+    _log_b_param = _RealParameter('log_b', symbol=r'\log(b)',
+                                  domain=_log_b_domain, typical=(0.1, 3))
+    _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
+
+    _b_domain.define_parameters(_a_param)
+    _log_b_domain.define_parameters(_log_a_param)
+    _x_support.define_parameters(_a_param, _b_param)
+
+    _parameterizations = [_Parameterization(_log_a_param, _log_b_param),
+                          _Parameterization(_a_param, _b_param)]
+    _variable = _x_param
+
+    def __init__(self, *, a=None, b=None, log_a=None, log_b=None, **kwargs):
+        super().__init__(a=a, b=b, log_a=log_a, log_b=log_b, **kwargs)
+
+    def _process_parameters(self, a=None, b=None, log_a=None, log_b=None, **kwargs):
+        a = np.exp(log_a) if a is None else a
+        b = np.exp(log_b) if b is None else b
+        log_a = np.log(a) if log_a is None else log_a
+        log_b = np.log(b) if log_b is None else log_b
+        kwargs.update(dict(a=a, b=b, log_a=log_a, log_b=log_b))
+        return kwargs
+
+    # def _logpdf_formula(self, x, *, log_a, log_b, **kwargs):
+    #     return -np.log(x) - np.log(log_b - log_a)
+
+    def _pdf_formula(self, x, *, log_a, log_b, **kwargs):
+        return ((log_b - log_a)*x)**-1
+
+    # def _cdf_formula(self, x, *, log_a, log_b, **kwargs):
+    #     return (np.log(x) - log_a)/(log_b - log_a)
+
+    def _moment_raw_formula(self, order, log_a, log_b, **kwargs):
+        if order == 0:
+            return self._one
+        t1 = self._one / (log_b - log_a) / order
+        t2 = np.real(np.exp(_log_diff(order * log_b, order * log_a)))
+        return t1 * t2
+
+
+class Uniform(ContinuousDistribution):
+    r"""Uniform distribution.
+
+    The probability density function of the uniform distribution is:
+
+    .. math::
+
+        f(x; a, b) = \frac{1}
+                          {b - a}
+
+    """
+
+    _a_domain = _RealDomain(endpoints=(-inf, inf))
+    _b_domain = _RealDomain(endpoints=('a', inf))
+    _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
+    _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
+    _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
+
+    _b_domain.define_parameters(_a_param)
+    _x_support.define_parameters(_a_param, _b_param)
+
+    _parameterizations = [_Parameterization(_a_param, _b_param)]
+    _variable = _x_param
+
+    def __init__(self, *, a=None, b=None, **kwargs):
+        super().__init__(a=a, b=b, **kwargs)
+
+    def _process_parameters(self, a=None, b=None, ab=None, **kwargs):
+        ab = b - a
+        kwargs.update(dict(a=a, b=b, ab=ab))
+        return kwargs
+
+    def _logpdf_formula(self, x, *, ab, **kwargs):
+        return np.where(np.isnan(x), np.nan, -np.log(ab))
+
+    def _pdf_formula(self, x, *, ab, **kwargs):
+        return np.where(np.isnan(x), np.nan, 1/ab)
+
+    def _logcdf_formula(self, x, *, a, ab, **kwargs):
+        with np.errstate(divide='ignore'):
+            return np.log(x - a) - np.log(ab)
+
+    def _cdf_formula(self, x, *, a, ab, **kwargs):
+        return (x - a) / ab
+
+    def _logccdf_formula(self, x, *, b, ab, **kwargs):
+        with np.errstate(divide='ignore'):
+            return np.log(b - x) - np.log(ab)
+
+    def _ccdf_formula(self, x, *, b, ab, **kwargs):
+        return (b - x) / ab
+
+    def _icdf_formula(self, p, *, a, ab, **kwargs):
+        return a + ab*p
+
+    def _iccdf_formula(self, p, *, b, ab, **kwargs):
+        return b - ab*p
+
+    def _entropy_formula(self, *, ab, **kwargs):
+        return np.log(ab)
+
+    def _mode_formula(self, *, a, b, ab, **kwargs):
+        return a + 0.5*ab
+
+    def _median_formula(self, *, a, b, ab, **kwargs):
+        return a + 0.5*ab
+
+    def _moment_raw_formula(self, order, a, b, ab, **kwargs):
+        np1 = order + 1
+        return (b**np1 - a**np1) / (np1 * ab)
+
+    def _moment_central_formula(self, order, ab, **kwargs):
+        return ab**2/12 if order == 2 else None
+
+    _moment_central_formula.orders = [2]  # type: ignore[attr-defined]
+
+    def _sample_formula(self, sample_shape, full_shape, rng, a, b, ab, **kwargs):
+        try:
+            return rng.uniform(a, b, size=full_shape)[()]
+        except OverflowError:  # happens when there are NaNs
+            return rng.uniform(0, 1, size=full_shape)*ab + a
+
+
+class _Gamma(ContinuousDistribution):
+    # Gamma distribution for testing only
+    _a_domain = _RealDomain(endpoints=(0, inf))
+    _x_support = _RealDomain(endpoints=(0, inf), inclusive=(False, False))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(0.1, 10))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(0.1, 10))
+
+    _parameterizations = [_Parameterization(_a_param)]
+    _variable = _x_param
+
+    def _pdf_formula(self, x, *, a, **kwargs):
+        return x ** (a - 1) * np.exp(-x) / special.gamma(a)
+
+
+# Distribution classes need only define the summary and beginning of the extended
+# summary portion of the class documentation. All other documentation, including
+# examples, is generated automatically.
+_module = sys.modules[__name__].__dict__
+for dist_name in __all__:
+    _module[dist_name].__doc__ = _combine_docs(_module[dist_name])
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_odds_ratio.py b/python_embeded/Lib/site-packages/scipy/stats/_odds_ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8baf14d3c75102d9ab8cf121d23ab5067d7596f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_odds_ratio.py
@@ -0,0 +1,466 @@
+import numpy as np
+
+from scipy.special import ndtri
+from scipy.optimize import brentq
+from ._discrete_distns import nchypergeom_fisher
+from ._common import ConfidenceInterval
+
+
+def _sample_odds_ratio(table):
+    """
+    Given a table [[a, b], [c, d]], compute a*d/(b*c).
+
+    Return nan if the numerator and denominator are 0.
+    Return inf if just the denominator is 0.
+    """
+    # table must be a 2x2 numpy array.
+    if table[1, 0] > 0 and table[0, 1] > 0:
+        oddsratio = table[0, 0] * table[1, 1] / (table[1, 0] * table[0, 1])
+    elif table[0, 0] == 0 or table[1, 1] == 0:
+        oddsratio = np.nan
+    else:
+        oddsratio = np.inf
+    return oddsratio
+
+
+def _solve(func):
+    """
+    Solve func(nc) = 0.  func must be an increasing function.
+    """
+    # We could just as well call the variable `x` instead of `nc`, but we
+    # always call this function with functions for which nc (the noncentrality
+    # parameter) is the variable for which we are solving.
+    nc = 1.0
+    value = func(nc)
+    if value == 0:
+        return nc
+
+    # Multiplicative factor by which to increase or decrease nc when
+    # searching for a bracketing interval.
+    factor = 2.0
+    # Find a bracketing interval.
+    if value > 0:
+        nc /= factor
+        while func(nc) > 0:
+            nc /= factor
+        lo = nc
+        hi = factor*nc
+    else:
+        nc *= factor
+        while func(nc) < 0:
+            nc *= factor
+        lo = nc/factor
+        hi = nc
+
+    # lo and hi bracket the solution for nc.
+    nc = brentq(func, lo, hi, xtol=1e-13)
+    return nc
+
+
+def _nc_hypergeom_mean_inverse(x, M, n, N):
+    """
+    For the given noncentral hypergeometric parameters x, M, n,and N
+    (table[0,0], total, row 0 sum and column 0 sum, resp., of a 2x2
+    contingency table), find the noncentrality parameter of Fisher's
+    noncentral hypergeometric distribution whose mean is x.
+    """
+    nc = _solve(lambda nc: nchypergeom_fisher.mean(M, n, N, nc) - x)
+    return nc
+
+
+def _hypergeom_params_from_table(table):
+    # The notation M, n and N is consistent with stats.hypergeom and
+    # stats.nchypergeom_fisher.
+    x = table[0, 0]
+    M = table.sum()
+    n = table[0].sum()
+    N = table[:, 0].sum()
+    return x, M, n, N
+
+
+def _ci_upper(table, alpha):
+    """
+    Compute the upper end of the confidence interval.
+    """
+    if _sample_odds_ratio(table) == np.inf:
+        return np.inf
+
+    x, M, n, N = _hypergeom_params_from_table(table)
+
+    # nchypergeom_fisher.cdf is a decreasing function of nc, so we negate
+    # it in the lambda expression.
+    nc = _solve(lambda nc: -nchypergeom_fisher.cdf(x, M, n, N, nc) + alpha)
+    return nc
+
+
+def _ci_lower(table, alpha):
+    """
+    Compute the lower end of the confidence interval.
+    """
+    if _sample_odds_ratio(table) == 0:
+        return 0
+
+    x, M, n, N = _hypergeom_params_from_table(table)
+
+    nc = _solve(lambda nc: nchypergeom_fisher.sf(x - 1, M, n, N, nc) - alpha)
+    return nc
+
+
+def _conditional_oddsratio(table):
+    """
+    Conditional MLE of the odds ratio for the 2x2 contingency table.
+    """
+    x, M, n, N = _hypergeom_params_from_table(table)
+    # Get the bounds of the support.  The support of the noncentral
+    # hypergeometric distribution with parameters M, n, and N is the same
+    # for all values of the noncentrality parameter, so we can use 1 here.
+    lo, hi = nchypergeom_fisher.support(M, n, N, 1)
+
+    # Check if x is at one of the extremes of the support.  If so, we know
+    # the odds ratio is either 0 or inf.
+    if x == lo:
+        # x is at the low end of the support.
+        return 0
+    if x == hi:
+        # x is at the high end of the support.
+        return np.inf
+
+    nc = _nc_hypergeom_mean_inverse(x, M, n, N)
+    return nc
+
+
+def _conditional_oddsratio_ci(table, confidence_level=0.95,
+                              alternative='two-sided'):
+    """
+    Conditional exact confidence interval for the odds ratio.
+    """
+    if alternative == 'two-sided':
+        alpha = 0.5*(1 - confidence_level)
+        lower = _ci_lower(table, alpha)
+        upper = _ci_upper(table, alpha)
+    elif alternative == 'less':
+        lower = 0.0
+        upper = _ci_upper(table, 1 - confidence_level)
+    else:
+        # alternative == 'greater'
+        lower = _ci_lower(table, 1 - confidence_level)
+        upper = np.inf
+
+    return lower, upper
+
+
+def _sample_odds_ratio_ci(table, confidence_level=0.95,
+                          alternative='two-sided'):
+    oddsratio = _sample_odds_ratio(table)
+    log_or = np.log(oddsratio)
+    se = np.sqrt((1/table).sum())
+    if alternative == 'less':
+        z = ndtri(confidence_level)
+        loglow = -np.inf
+        loghigh = log_or + z*se
+    elif alternative == 'greater':
+        z = ndtri(confidence_level)
+        loglow = log_or - z*se
+        loghigh = np.inf
+    else:
+        # alternative is 'two-sided'
+        z = ndtri(0.5*confidence_level + 0.5)
+        loglow = log_or - z*se
+        loghigh = log_or + z*se
+
+    return np.exp(loglow), np.exp(loghigh)
+
+
+class OddsRatioResult:
+    """
+    Result of `scipy.stats.contingency.odds_ratio`.  See the
+    docstring for `odds_ratio` for more details.
+
+    Attributes
+    ----------
+    statistic : float
+        The computed odds ratio.
+
+        * If `kind` is ``'sample'``, this is sample (or unconditional)
+          estimate, given by
+          ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
+        * If `kind` is ``'conditional'``, this is the conditional
+          maximum likelihood estimate for the odds ratio. It is
+          the noncentrality parameter of Fisher's noncentral
+          hypergeometric distribution with the same hypergeometric
+          parameters as `table` and whose mean is ``table[0, 0]``.
+
+    Methods
+    -------
+    confidence_interval :
+        Confidence interval for the odds ratio.
+    """
+
+    def __init__(self, _table, _kind, statistic):
+        # for now, no need to make _table and _kind public, since this sort of
+        # information is returned in very few `scipy.stats` results
+        self._table = _table
+        self._kind = _kind
+        self.statistic = statistic
+
+    def __repr__(self):
+        return f"OddsRatioResult(statistic={self.statistic})"
+
+    def confidence_interval(self, confidence_level=0.95,
+                            alternative='two-sided'):
+        """
+        Confidence interval for the odds ratio.
+
+        Parameters
+        ----------
+        confidence_level: float
+            Desired confidence level for the confidence interval.
+            The value must be given as a fraction between 0 and 1.
+            Default is 0.95 (meaning 95%).
+
+        alternative : {'two-sided', 'less', 'greater'}, optional
+            The alternative hypothesis of the hypothesis test to which the
+            confidence interval corresponds. That is, suppose the null
+            hypothesis is that the true odds ratio equals ``OR`` and the
+            confidence interval is ``(low, high)``. Then the following options
+            for `alternative` are available (default is 'two-sided'):
+
+            * 'two-sided': the true odds ratio is not equal to ``OR``. There
+              is evidence against the null hypothesis at the chosen
+              `confidence_level` if ``high < OR`` or ``low > OR``.
+            * 'less': the true odds ratio is less than ``OR``. The ``low`` end
+              of the confidence interval is 0, and there is evidence against
+              the null hypothesis at  the chosen `confidence_level` if
+              ``high < OR``.
+            * 'greater': the true odds ratio is greater than ``OR``.  The
+              ``high`` end of the confidence interval is ``np.inf``, and there
+              is evidence against the null hypothesis at the chosen
+              `confidence_level` if ``low > OR``.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` instance
+            The confidence interval, represented as an object with
+            attributes ``low`` and ``high``.
+
+        Notes
+        -----
+        When `kind` is ``'conditional'``, the limits of the confidence
+        interval are the conditional "exact confidence limits" as described
+        by Fisher [1]_. The conditional odds ratio and confidence interval are
+        also discussed in Section 4.1.2 of the text by Sahai and Khurshid [2]_.
+
+        When `kind` is ``'sample'``, the confidence interval is computed
+        under the assumption that the logarithm of the odds ratio is normally
+        distributed with standard error given by::
+
+            se = sqrt(1/a + 1/b + 1/c + 1/d)
+
+        where ``a``, ``b``, ``c`` and ``d`` are the elements of the
+        contingency table.  (See, for example, [2]_, section 3.1.3.2,
+        or [3]_, section 2.3.3).
+
+        References
+        ----------
+        .. [1] R. A. Fisher (1935), The logic of inductive inference,
+               Journal of the Royal Statistical Society, Vol. 98, No. 1,
+               pp. 39-82.
+        .. [2] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
+               Methods, Techniques, and Applications, CRC Press LLC, Boca
+               Raton, Florida.
+        .. [3] Alan Agresti, An Introduction to Categorical Data Analysis
+               (second edition), Wiley, Hoboken, NJ, USA (2007).
+        """
+        if alternative not in ['two-sided', 'less', 'greater']:
+            raise ValueError("`alternative` must be 'two-sided', 'less' or "
+                             "'greater'.")
+
+        if confidence_level < 0 or confidence_level > 1:
+            raise ValueError('confidence_level must be between 0 and 1')
+
+        if self._kind == 'conditional':
+            ci = self._conditional_odds_ratio_ci(confidence_level, alternative)
+        else:
+            ci = self._sample_odds_ratio_ci(confidence_level, alternative)
+        return ci
+
+    def _conditional_odds_ratio_ci(self, confidence_level=0.95,
+                                   alternative='two-sided'):
+        """
+        Confidence interval for the conditional odds ratio.
+        """
+
+        table = self._table
+        if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
+            # If both values in a row or column are zero, the p-value is 1,
+            # the odds ratio is NaN and the confidence interval is (0, inf).
+            ci = (0, np.inf)
+        else:
+            ci = _conditional_oddsratio_ci(table,
+                                           confidence_level=confidence_level,
+                                           alternative=alternative)
+        return ConfidenceInterval(low=ci[0], high=ci[1])
+
+    def _sample_odds_ratio_ci(self, confidence_level=0.95,
+                              alternative='two-sided'):
+        """
+        Confidence interval for the sample odds ratio.
+        """
+        if confidence_level < 0 or confidence_level > 1:
+            raise ValueError('confidence_level must be between 0 and 1')
+
+        table = self._table
+        if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
+            # If both values in a row or column are zero, the p-value is 1,
+            # the odds ratio is NaN and the confidence interval is (0, inf).
+            ci = (0, np.inf)
+        else:
+            ci = _sample_odds_ratio_ci(table,
+                                       confidence_level=confidence_level,
+                                       alternative=alternative)
+        return ConfidenceInterval(low=ci[0], high=ci[1])
+
+
+def odds_ratio(table, *, kind='conditional'):
+    r"""
+    Compute the odds ratio for a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements must be non-negative integers.
+    kind : str, optional
+        Which kind of odds ratio to compute, either the sample
+        odds ratio (``kind='sample'``) or the conditional odds ratio
+        (``kind='conditional'``).  Default is ``'conditional'``.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.OddsRatioResult` instance
+        The returned object has two computed attributes:
+
+        statistic : float
+            * If `kind` is ``'sample'``, this is sample (or unconditional)
+              estimate, given by
+              ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
+            * If `kind` is ``'conditional'``, this is the conditional
+              maximum likelihood estimate for the odds ratio. It is
+              the noncentrality parameter of Fisher's noncentral
+              hypergeometric distribution with the same hypergeometric
+              parameters as `table` and whose mean is ``table[0, 0]``.
+
+        The object has the method `confidence_interval` that computes
+        the confidence interval of the odds ratio.
+
+    See Also
+    --------
+    scipy.stats.fisher_exact
+    relative_risk
+    :ref:`hypothesis_odds_ratio` : Extended example
+
+    Notes
+    -----
+    The conditional odds ratio was discussed by Fisher (see "Example 1"
+    of [1]_).  Texts that cover the odds ratio include [2]_ and [3]_.
+
+    .. versionadded:: 1.10.0
+
+    References
+    ----------
+    .. [1] R. A. Fisher (1935), The logic of inductive inference,
+           Journal of the Royal Statistical Society, Vol. 98, No. 1,
+           pp. 39-82.
+    .. [2] Breslow NE, Day NE (1980). Statistical methods in cancer research.
+           Volume I - The analysis of case-control studies. IARC Sci Publ.
+           (32):5-338. PMID: 7216345. (See section 4.2.)
+    .. [3] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
+           Methods, Techniques, and Applications, CRC Press LLC, Boca
+           Raton, Florida.
+
+    Examples
+    --------
+    In epidemiology, individuals are classified as "exposed" or
+    "unexposed" to some factor or treatment. If the occurrence of some
+    illness is under study, those who have the illness are often
+    classified as "cases", and those without it are "noncases".  The
+    counts of the occurrences of these classes gives a contingency
+    table::
+
+                    exposed    unexposed
+        cases          a           b
+        noncases       c           d
+
+    The sample odds ratio may be written ``(a/c) / (b/d)``.  ``a/c`` can
+    be interpreted as the odds of a case occurring in the exposed group,
+    and ``b/d`` as the odds of a case occurring in the unexposed group.
+    The sample odds ratio is the ratio of these odds.  If the odds ratio
+    is greater than 1, it suggests that there is a positive association
+    between being exposed and being a case.
+
+    Interchanging the rows or columns of the contingency table inverts
+    the odds ratio, so it is important to understand the meaning of labels
+    given to the rows and columns of the table when interpreting the
+    odds ratio.
+
+    Consider a hypothetical example where it is hypothesized that exposure to a
+    certain chemical is associated with increased occurrence of a certain
+    disease. Suppose we have the following table for a collection of 410 people::
+
+                exposed unexposed
+        cases        7       15
+        noncases    58      472
+
+    The question we ask is "Is exposure to the chemical associated with
+    increased risk of the disease?"
+
+    Compute the odds ratio:
+
+    >>> from scipy.stats.contingency import odds_ratio
+    >>> res = odds_ratio([[7, 15], [58, 472]])
+    >>> res.statistic
+    3.7836687705553493
+
+    For this sample, the odds of getting the disease for those who have been
+    exposed to the chemical are almost 3.8 times that of those who have not been
+    exposed.
+
+    We can compute the 95% confidence interval for the odds ratio:
+
+    >>> res.confidence_interval(confidence_level=0.95)
+    ConfidenceInterval(low=1.2514829132266785, high=10.363493716701269)
+
+    The 95% confidence interval for the conditional odds ratio is approximately
+    (1.25, 10.4).
+
+    For a more detailed example, see :ref:`hypothesis_odds_ratio`.
+    """
+    if kind not in ['conditional', 'sample']:
+        raise ValueError("`kind` must be 'conditional' or 'sample'.")
+
+    c = np.asarray(table)
+
+    if c.shape != (2, 2):
+        raise ValueError(f"Invalid shape {c.shape}. The input `table` must be "
+                         "of shape (2, 2).")
+
+    if not np.issubdtype(c.dtype, np.integer):
+        raise ValueError("`table` must be an array of integers, but got "
+                         f"type {c.dtype}")
+    c = c.astype(np.int64)
+
+    if np.any(c < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
+        # If both values in a row or column are zero, the p-value is NaN and
+        # the odds ratio is NaN.
+        result = OddsRatioResult(_table=c, _kind=kind, statistic=np.nan)
+        return result
+
+    if kind == 'sample':
+        oddsratio = _sample_odds_ratio(c)
+    else:  # kind is 'conditional'
+        oddsratio = _conditional_oddsratio(c)
+
+    result = OddsRatioResult(_table=c, _kind=kind, statistic=oddsratio)
+    return result
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_page_trend_test.py b/python_embeded/Lib/site-packages/scipy/stats/_page_trend_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..aceeedc51c901073603ea43e521c4fc3c926e7de
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_page_trend_test.py
@@ -0,0 +1,479 @@
+from itertools import permutations
+import numpy as np
+import math
+from ._continuous_distns import norm
+import scipy.stats
+from dataclasses import dataclass
+
+
+@dataclass
+class PageTrendTestResult:
+    statistic: float
+    pvalue: float
+    method: str
+
+
+def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'):
+    r"""
+    Perform Page's Test, a measure of trend in observations between treatments.
+
+    Page's Test (also known as Page's :math:`L` test) is useful when:
+
+    * there are :math:`n \geq 3` treatments,
+    * :math:`m \geq 2` subjects are observed for each treatment, and
+    * the observations are hypothesized to have a particular order.
+
+    Specifically, the test considers the null hypothesis that
+
+    .. math::
+
+        m_1 = m_2 = m_3 \cdots = m_n,
+
+    where :math:`m_j` is the mean of the observed quantity under treatment
+    :math:`j`, against the alternative hypothesis that
+
+    .. math::
+
+        m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n,
+
+    where at least one inequality is strict.
+
+    As noted by [4]_, Page's :math:`L` test has greater statistical power than
+    the Friedman test against the alternative that there is a difference in
+    trend, as Friedman's test only considers a difference in the means of the
+    observations without considering their order. Whereas Spearman :math:`\rho`
+    considers the correlation between the ranked observations of two variables
+    (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it
+    carries), Page's :math:`L` is concerned with a trend in an observation
+    (e.g. the airspeed velocity of a swallow) across several distinct
+    treatments (e.g. carrying each of five coconuts of different weight) even
+    as the observation is repeated with multiple subjects (e.g. one European
+    swallow and one African swallow).
+
+    Parameters
+    ----------
+    data : array-like
+        A :math:`m \times n` array; the element in row :math:`i` and
+        column :math:`j` is the observation corresponding with subject
+        :math:`i` and treatment :math:`j`. By default, the columns are
+        assumed to be arranged in order of increasing predicted mean.
+
+    ranked : boolean, optional
+        By default, `data` is assumed to be observations rather than ranks;
+        it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If
+        `data` is provided in the form of ranks, pass argument ``True``.
+
+    predicted_ranks : array-like, optional
+        The predicted ranks of the column means. If not specified,
+        the columns are assumed to be arranged in order of increasing
+        predicted mean, so the default `predicted_ranks` are
+        :math:`[1, 2, \dots, n-1, n]`.
+
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Selects the method used to calculate the *p*-value. The following
+        options are available.
+
+        * 'auto': selects between 'exact' and 'asymptotic' to
+          achieve reasonably accurate results in reasonable time (default)
+        * 'asymptotic': compares the standardized test statistic against
+          the normal distribution
+        * 'exact': computes the exact *p*-value by comparing the observed
+          :math:`L` statistic against those realized by all possible
+          permutations of ranks (under the null hypothesis that each
+          permutation is equally likely)
+
+    Returns
+    -------
+    res : PageTrendTestResult
+        An object containing attributes:
+
+        statistic : float
+            Page's :math:`L` test statistic.
+        pvalue : float
+            The associated *p*-value
+        method : {'asymptotic', 'exact'}
+            The method used to compute the *p*-value
+
+    See Also
+    --------
+    rankdata, friedmanchisquare, spearmanr
+
+    Notes
+    -----
+    As noted in [1]_, "the :math:`n` 'treatments' could just as well represent
+    :math:`n` objects or events or performances or persons or trials ranked."
+    Similarly, the :math:`m` 'subjects' could equally stand for :math:`m`
+    "groupings by ability or some other control variable, or judges doing
+    the ranking, or random replications of some other sort."
+
+    The procedure for calculating the :math:`L` statistic, adapted from
+    [1]_, is:
+
+    1. "Predetermine with careful logic the appropriate hypotheses
+       concerning the predicted ordering of the experimental results.
+       If no reasonable basis for ordering any treatments is known, the
+       :math:`L` test is not appropriate."
+    2. "As in other experiments, determine at what level of confidence
+       you will reject the null hypothesis that there is no agreement of
+       experimental results with the monotonic hypothesis."
+    3. "Cast the experimental material into a two-way table of :math:`n`
+       columns (treatments, objects ranked, conditions) and :math:`m`
+       rows (subjects, replication groups, levels of control variables)."
+    4. "When experimental observations are recorded, rank them across each
+       row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``.
+    5. "Add the ranks in each column", e.g.
+       ``colsums = np.sum(ranks, axis=0)``.
+    6. "Multiply each sum of ranks by the predicted rank for that same
+       column", e.g. ``products = predicted_ranks * colsums``.
+    7. "Sum all such products", e.g. ``L = products.sum()``.
+
+    [1]_ continues by suggesting use of the standardized statistic
+
+    .. math::
+
+        \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)}
+
+    "which is distributed approximately as chi-square with 1 degree of
+    freedom. The ordinary use of :math:`\chi^2` tables would be
+    equivalent to a two-sided test of agreement. If a one-sided test
+    is desired, *as will almost always be the case*, the probability
+    discovered in the chi-square table should be *halved*."
+
+    However, this standardized statistic does not distinguish between the
+    observed values being well correlated with the predicted ranks and being
+    _anti_-correlated with the predicted ranks. Instead, we follow [2]_
+    and calculate the standardized statistic
+
+    .. math::
+
+        \Lambda = \frac{L - E_0}{\sqrt{V_0}},
+
+    where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and
+    :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically
+    normal under the null hypothesis".
+
+    The *p*-value for ``method='exact'`` is generated by comparing the observed
+    value of :math:`L` against the :math:`L` values generated for all
+    :math:`(n!)^m` possible permutations of ranks. The calculation is performed
+    using the recursive method of [5].
+
+    The *p*-values are not adjusted for the possibility of ties. When
+    ties are present, the reported  ``'exact'`` *p*-values may be somewhat
+    larger (i.e. more conservative) than the true *p*-value [2]_. The
+    ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less
+    conservative) than the ``'exact'`` *p*-values.
+
+    References
+    ----------
+    .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments:
+       a significant test for linear ranks", *Journal of the American
+       Statistical Association* 58(301), p. 216--230, 1963.
+
+    .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational
+       approach*, CRC Press, p. 150--152, 2012.
+
+    .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext -
+       Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php,
+       Accessed July 12, 2020.
+
+    .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation,
+       https://en.wikipedia.org/wiki/Page%27s_trend_test,
+       Accessed July 12, 2020.
+
+    .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in
+       the two-way layout", *Communications in Statistics - Simulation and
+       Computation*,  6(1), p. 49--61, 1977.
+
+    Examples
+    --------
+    We use the example from [3]_: 10 students are asked to rate three
+    teaching methods - tutorial, lecture, and seminar - on a scale of 1-5,
+    with 1 being the lowest and 5 being the highest. We have decided that
+    a confidence level of 99% is required to reject the null hypothesis in
+    favor of our alternative: that the seminar will have the highest ratings
+    and the tutorial will have the lowest. Initially, the data have been
+    tabulated with each row representing an individual student's ratings of
+    the three methods in the following order: tutorial, lecture, seminar.
+
+    >>> table = [[3, 4, 3],
+    ...          [2, 2, 4],
+    ...          [3, 3, 5],
+    ...          [1, 3, 2],
+    ...          [2, 3, 2],
+    ...          [2, 4, 5],
+    ...          [1, 2, 4],
+    ...          [3, 4, 4],
+    ...          [2, 4, 5],
+    ...          [1, 3, 4]]
+
+    Because the tutorial is hypothesized to have the lowest ratings, the
+    column corresponding with tutorial rankings should be first; the seminar
+    is hypothesized to have the highest ratings, so its column should be last.
+    Since the columns are already arranged in this order of increasing
+    predicted mean, we can pass the table directly into `page_trend_test`.
+
+    >>> from scipy.stats import page_trend_test
+    >>> res = page_trend_test(table)
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    This *p*-value indicates that there is a 0.1819% chance that
+    the :math:`L` statistic would reach such an extreme value under the null
+    hypothesis. Because 0.1819% is less than 1%, we have evidence to reject
+    the null hypothesis in favor of our alternative at a 99% confidence level.
+
+    The value of the :math:`L` statistic is 133.5. To check this manually,
+    we rank the data such that high scores correspond with high ranks, settling
+    ties with an average rank:
+
+    >>> from scipy.stats import rankdata
+    >>> ranks = rankdata(table, axis=1)
+    >>> ranks
+    array([[1.5, 3. , 1.5],
+           [1.5, 1.5, 3. ],
+           [1.5, 1.5, 3. ],
+           [1. , 3. , 2. ],
+           [1.5, 3. , 1.5],
+           [1. , 2. , 3. ],
+           [1. , 2. , 3. ],
+           [1. , 2.5, 2.5],
+           [1. , 2. , 3. ],
+           [1. , 2. , 3. ]])
+
+    We add the ranks within each column, multiply the sums by the
+    predicted ranks, and sum the products.
+
+    >>> import numpy as np
+    >>> m, n = ranks.shape
+    >>> predicted_ranks = np.arange(1, n+1)
+    >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum()
+    >>> res.statistic == L
+    True
+
+    As presented in [3]_, the asymptotic approximation of the *p*-value is the
+    survival function of the normal distribution evaluated at the standardized
+    test statistic:
+
+    >>> from scipy.stats import norm
+    >>> E0 = (m*n*(n+1)**2)/4
+    >>> V0 = (m*n**2*(n+1)*(n**2-1))/144
+    >>> Lambda = (L-E0)/np.sqrt(V0)
+    >>> p = norm.sf(Lambda)
+    >>> p
+    0.0012693433690751756
+
+    This does not precisely match the *p*-value reported by `page_trend_test`
+    above. The asymptotic distribution is not very accurate, nor conservative,
+    for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to
+    use ``method='exact'`` based on the dimensions of the table and the
+    recommendations in Page's original paper [1]_. To override
+    `page_trend_test`'s choice, provide the `method` argument.
+
+    >>> res = page_trend_test(table, method="asymptotic")
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756,
+                        method='asymptotic')
+
+    If the data are already ranked, we can pass in the ``ranks`` instead of
+    the ``table`` to save computation time.
+
+    >>> res = page_trend_test(ranks,             # ranks of data
+    ...                       ranked=True,       # data is already ranked
+    ...                       )
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    Suppose the raw data had been tabulated in an order different from the
+    order of predicted means, say lecture, seminar, tutorial.
+
+    >>> table = np.asarray(table)[:, [1, 2, 0]]
+
+    Since the arrangement of this table is not consistent with the assumed
+    ordering, we can either rearrange the table or provide the
+    `predicted_ranks`. Remembering that the lecture is predicted
+    to have the middle rank, the seminar the highest, and tutorial the lowest,
+    we pass:
+
+    >>> res = page_trend_test(table,             # data as originally tabulated
+    ...                       predicted_ranks=[2, 3, 1],  # our predicted order
+    ...                       )
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    """
+
+    # Possible values of the method parameter and the corresponding function
+    # used to evaluate the p value
+    methods = {"asymptotic": _l_p_asymptotic,
+               "exact": _l_p_exact,
+               "auto": None}
+    if method not in methods:
+        raise ValueError(f"`method` must be in {set(methods)}")
+
+    ranks = np.asarray(data)
+    if ranks.ndim != 2:  # TODO: relax this to accept 3d arrays?
+        raise ValueError("`data` must be a 2d array.")
+
+    m, n = ranks.shape
+    if m < 2 or n < 3:
+        raise ValueError("Page's L is only appropriate for data with two "
+                         "or more rows and three or more columns.")
+
+    if np.any(np.isnan(data)):
+        raise ValueError("`data` contains NaNs, which cannot be ranked "
+                         "meaningfully")
+
+    # ensure NumPy array and rank the data if it's not already ranked
+    if ranked:
+        # Only a basic check on whether data is ranked. Checking that the data
+        # is properly ranked could take as much time as ranking it.
+        if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]):
+            raise ValueError("`data` is not properly ranked. Rank the data or "
+                             "pass `ranked=False`.")
+    else:
+        ranks = scipy.stats.rankdata(data, axis=-1)
+
+    # generate predicted ranks if not provided, ensure valid NumPy array
+    if predicted_ranks is None:
+        predicted_ranks = np.arange(1, n+1)
+    else:
+        predicted_ranks = np.asarray(predicted_ranks)
+        if (predicted_ranks.ndim < 1 or
+                (set(predicted_ranks) != set(range(1, n+1)) or
+                 len(predicted_ranks) != n)):
+            raise ValueError(f"`predicted_ranks` must include each integer "
+                             f"from 1 to {n} (the number of columns in "
+                             f"`data`) exactly once.")
+
+    if not isinstance(ranked, bool):
+        raise TypeError("`ranked` must be boolean.")
+
+    # Calculate the L statistic
+    L = _l_vectorized(ranks, predicted_ranks)
+
+    # Calculate the p-value
+    if method == "auto":
+        method = _choose_method(ranks)
+    p_fun = methods[method]  # get the function corresponding with the method
+    p = p_fun(L, m, n)
+
+    page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method)
+    return page_result
+
+
+def _choose_method(ranks):
+    '''Choose method for computing p-value automatically'''
+    m, n = ranks.shape
+    if n > 8 or (m > 12 and n > 3) or m > 20:  # as in [1], [4]
+        method = "asymptotic"
+    else:
+        method = "exact"
+    return method
+
+
+def _l_vectorized(ranks, predicted_ranks):
+    '''Calculate's Page's L statistic for each page of a 3d array'''
+    colsums = ranks.sum(axis=-2, keepdims=True)
+    products = predicted_ranks * colsums
+    Ls = products.sum(axis=-1)
+    Ls = Ls[0] if Ls.size == 1 else Ls.ravel()
+    return Ls
+
+
+def _l_p_asymptotic(L, m, n):
+    '''Calculate the p-value of Page's L from the asymptotic distribution'''
+    # Using [1] as a reference, the asymptotic p-value would be calculated as:
+    # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1))
+    # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2
+    # but this is insensitive to the direction of the hypothesized ranking
+
+    # See [2] page 151
+    E0 = (m*n*(n+1)**2)/4
+    V0 = (m*n**2*(n+1)*(n**2-1))/144
+    Lambda = (L-E0)/np.sqrt(V0)
+    # This is a one-sided "greater" test - calculate the probability that the
+    # L statistic under H0 would be greater than the observed L statistic
+    p = norm.sf(Lambda)
+    return p
+
+
+def _l_p_exact(L, m, n):
+    '''Calculate the p-value of Page's L exactly'''
+    # [1] uses m, n; [5] uses n, k.
+    # Switch convention here because exact calculation code references [5].
+    L, n, k = int(L), int(m), int(n)
+    _pagel_state.set_k(k)
+    return _pagel_state.sf(L, n)
+
+
+class _PageL:
+    '''Maintains state between `page_trend_test` executions'''
+
+    def __init__(self):
+        '''Lightweight initialization'''
+        self.all_pmfs = {}
+
+    def set_k(self, k):
+        '''Calculate lower and upper limits of L for single row'''
+        self.k = k
+        # See [5] top of page 52
+        self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6
+
+    def sf(self, l, n):
+        '''Survival function of Page's L statistic'''
+        ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)]
+        return np.sum(ps)
+
+    def p_l_k_1(self):
+        '''Relative frequency of each L value over all possible single rows'''
+
+        # See [5] Equation (6)
+        ranks = range(1, self.k+1)
+        # generate all possible rows of length k
+        rank_perms = np.array(list(permutations(ranks)))
+        # compute Page's L for all possible rows
+        Ls = (ranks*rank_perms).sum(axis=1)
+        # count occurrences of each L value
+        counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0]
+        # factorial(k) is number of possible permutations
+        return counts/math.factorial(self.k)
+
+    def pmf(self, l, n):
+        '''Recursive function to evaluate p(l, k, n); see [5] Equation 1'''
+
+        if n not in self.all_pmfs:
+            self.all_pmfs[n] = {}
+        if self.k not in self.all_pmfs[n]:
+            self.all_pmfs[n][self.k] = {}
+
+        # Cache results to avoid repeating calculation. Initially this was
+        # written with lru_cache, but this seems faster? Also, we could add
+        # an option to save this for future lookup.
+        if l in self.all_pmfs[n][self.k]:
+            return self.all_pmfs[n][self.k][l]
+
+        if n == 1:
+            ps = self.p_l_k_1()  # [5] Equation 6
+            ls = range(self.a, self.b+1)
+            # not fast, but we'll only be here once
+            self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)}
+            return self.all_pmfs[n][self.k][l]
+
+        p = 0
+        low = max(l-(n-1)*self.b, self.a)  # [5] Equation 2
+        high = min(l-(n-1)*self.a, self.b)
+
+        # [5] Equation 1
+        for t in range(low, high+1):
+            p1 = self.pmf(l-t, n-1)
+            p2 = self.pmf(t, 1)
+            p += p1*p2
+        self.all_pmfs[n][self.k][l] = p
+        return p
+
+
+# Maintain state for faster repeat calls to page_trend_test w/ method='exact'
+_pagel_state = _PageL()
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_probability_distribution.py b/python_embeded/Lib/site-packages/scipy/stats/_probability_distribution.py
new file mode 100644
index 0000000000000000000000000000000000000000..c717f2991df8a1e24fea1900faf9b0ab7a24c21b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_probability_distribution.py
@@ -0,0 +1,1742 @@
+# Temporary file separated from _distribution_infrastructure.py
+# to simplify the diff during PR review.
+from abc import ABC, abstractmethod
+
+class _ProbabilityDistribution(ABC):
+    @abstractmethod
+    def support(self):
+        r"""Support of the random variable
+
+        The support of a random variable is set of all possible outcomes;
+        i.e., the subset of the domain of argument :math:`x` for which
+        the probability density function :math:`f(x)` is nonzero.
+
+        This function returns lower and upper bounds of the support.
+
+        Returns
+        -------
+        out : tuple of Array
+            The lower and upper bounds of the support.
+
+        See Also
+        --------
+        pdf
+
+        References
+        ----------
+        .. [1] Support (mathematics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Support_(mathematics)
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support ``(l, r)``.
+        The following table summarizes the value returned by methods
+        of ``ContinuousDistribution`` for arguments outside the support.
+
+        +----------------+---------------------+---------------------+
+        | Method         | Value for ``x < l`` | Value for ``x > r`` |
+        +================+=====================+=====================+
+        | ``pdf(x)``     | 0                   | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``logpdf(x)``  | -inf                | -inf                |
+        +----------------+---------------------+---------------------+
+        | ``cdf(x)``     | 0                   | 1                   |
+        +----------------+---------------------+---------------------+
+        | ``logcdf(x)``  | -inf                | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``ccdf(x)``    | 1                   | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``logccdf(x)`` | 0                   | -inf                |
+        +----------------+---------------------+---------------------+
+
+        For the ``cdf`` and related methods, the inequality need not be
+        strict; i.e. the tabulated value is returned when the method is
+        evaluated *at* the corresponding boundary.
+
+        The following table summarizes the value returned by the inverse
+        methods of ``ContinuousDistribution`` for arguments at the boundaries
+        of the domain ``0`` to ``1``.
+
+        +-------------+-----------+-----------+
+        | Method      | ``x = 0`` | ``x = 1`` |
+        +=============+===========+===========+
+        | ``icdf(x)`` | ``l``     | ``r``     |
+        +-------------+-----------+-----------+
+        | ``icdf(x)`` | ``r``     | ``l``     |
+        +-------------+-----------+-----------+
+
+        For the inverse log-functions, the same values are returned for
+        for ``x = log(0)`` and ``x = log(1)``. All inverse functions return
+        ``nan`` when evaluated at an argument outside the domain ``0`` to ``1``.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Retrieve the support of the distribution:
+
+        >>> X.support()
+        (-0.5, 0.5)
+
+        For a distribution with infinite support,
+
+        >>> X = stats.Normal()
+        >>> X.support()
+        (-inf, inf)
+
+        Due to underflow, the numerical value returned by the PDF may be zero
+        even for arguments within the support, even if the true value is
+        nonzero. In such cases, the log-PDF may be useful.
+
+        >>> X.pdf([-100., 100.])
+        array([0., 0.])
+        >>> X.logpdf([-100., 100.])
+        array([-5000.91893853, -5000.91893853])
+
+        Use cases for the log-CDF and related methods are analogous.
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def sample(self, shape, *, method, rng):
+        r"""Random sample from the distribution.
+
+        Parameters
+        ----------
+        shape : tuple of ints, default: ()
+            The shape of the sample to draw. If the parameters of the distribution
+            underlying the random variable are arrays of shape ``param_shape``,
+            the output array will be of shape ``shape + param_shape``.
+        method : {None, 'formula', 'inverse_transform'}
+            The strategy used to produce the sample. By default (``None``),
+            the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'formula'``: an implementation specific to the distribution
+            - ``'inverse_transform'``: generate a uniformly distributed sample and
+              return the inverse CDF at these arguments.
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a `NotImplementedError``
+            will be raised.
+        rng : `numpy.random.Generator` or `scipy.stats.QMCEngine`, optional
+            Pseudo- or quasi-random 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` and
+            `scipy.stats.QMCEngine` are passed to `numpy.random.default_rng`
+            to instantiate a ``Generator``.
+
+            If `rng` is an instance of `scipy.stats.QMCEngine` configured to use
+            scrambling and `shape` is not empty, then each slice along the zeroth
+            axis of the result is a "quasi-independent", low-discrepancy sequence;
+            that is, they are distinct sequences that can be treated as statistically
+            independent for most practical purposes. Separate calls to `sample`
+            produce new quasi-independent, low-discrepancy sequences.
+
+        References
+        ----------
+        .. [1] Sampling (statistics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Sampling_(statistics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=0., b=1.)
+
+        Generate a pseudorandom sample:
+
+        >>> x = X.sample((1000, 1))
+        >>> octiles = (np.arange(8) + 1) / 8
+        >>> np.count_nonzero(x <= octiles, axis=0)
+        array([ 148,  263,  387,  516,  636,  751,  865, 1000])  # may vary
+
+        >>> X = stats.Uniform(a=np.zeros((3, 1)), b=np.ones(2))
+        >>> X.a.shape,
+        (3, 2)
+        >>> x = X.sample(shape=(5, 4))
+        >>> x.shape
+        (5, 4, 3, 2)
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def moment(self, order, kind, *, method):
+        r"""Raw, central, or standard moment of positive integer order.
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the "raw" moment (about the origin) of order :math:`n` of
+        a random variable :math:`X` is:
+
+        .. math::
+
+            \mu'_n(X) = \int_{\chi} x^n f(x) dx
+
+        The "central" moment is the raw moment taken about the mean,
+        :math:`\mu = \mu'_1`:
+
+        .. math::
+
+            \mu_n(X) = \int_{\chi} (x - \mu) ^n f(x) dx
+
+        The "standardized" moment is the central moment normalized by the
+        :math:`n^\text{th}` power of the standard deviation
+        :math:`\sigma = \sqrt{\mu_2}` to produce a scale invariant quantity:
+
+        .. math::
+
+            \tilde{\mu}_n(X) = \frac{\mu_n(X)}
+                                    {\sigma^n}
+
+        Parameters
+        ----------
+        order : int
+            The integer order of the moment; i.e. :math:`n` in the formulae above.
+        kind : {'raw', 'central', 'standardized'}
+            Whether to return the raw (default), central, or standardized moment
+            defined above.
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'quadrature', 'cache'}
+            The strategy used to evaluate the moment. By default (``None``),
+            the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'cache'``: use the value of the moment most recently calculated
+              via another method
+            - ``'formula'``: use a formula for the moment itself
+            - ``'general'``: use a general result that is true for all distributions
+              with finite moments; for instance, the zeroth raw moment is
+              identically 1
+            - ``'transform'``: transform a raw moment to a central moment or
+              vice versa (see Notes)
+            - ``'normalize'``: normalize a central moment to get a standardized
+              or vice versa
+            - ``'quadrature'``: numerically integrate according to the definition
+
+            Not all `method` options are available for all orders, kinds, and
+            distributions. If the selected `method` is not available, a
+            ``NotImplementedError`` will be raised.
+
+        Returns
+        -------
+        out : array
+            The moment of the random variable of the specified order and kind.
+
+        See Also
+        --------
+        pdf
+        mean
+        variance
+        standard_deviation
+        skewness
+        kurtosis
+
+        Notes
+        -----
+        Not all distributions have finite moments of all orders; moments of some
+        orders may be undefined or infinite. If a formula for the moment is not
+        specifically implemented for the chosen distribution, SciPy will attempt
+        to compute the moment via a generic method, which may yield a finite
+        result where none exists. This is not a critical bug, but an opportunity
+        for an enhancement.
+
+        The definition of a raw moment in the summary is specific to the raw moment
+        about the origin. The raw moment about any point :math:`a` is:
+
+        .. math::
+
+            E[(X-a)^n] = \int_{\chi} (x-a)^n f(x) dx
+
+        In this notation, a raw moment about the origin is :math:`\mu'_n = E[x^n]`,
+        and a central moment is :math:`\mu_n = E[(x-\mu)^n]`, where :math:`\mu`
+        is the first raw moment; i.e. the mean.
+
+        The ``'transform'`` method takes advantage of the following relationships
+        between moments taken about different points :math:`a` and :math:`b`.
+
+        .. math::
+
+            E[(X-b)^n] =  \sum_{i=0}^n E[(X-a)^i] {n \choose i} (a - b)^{n-i}
+
+        For instance, to transform the raw moment to the central moment, we let
+        :math:`b = \mu` and :math:`a = 0`.
+
+        The distribution infrastructure provides flexibility for distribution
+        authors to implement separate formulas for raw moments, central moments,
+        and standardized moments of any order. By default, the moment of the
+        desired order and kind is evaluated from the formula if such a formula
+        is available; if not, the infrastructure uses any formulas that are
+        available rather than resorting directly to numerical integration.
+        For instance, if formulas for the first three raw moments are
+        available and the third standardized moments is desired, the
+        infrastructure will evaluate the raw moments and perform the transforms
+        and standardization required. The decision tree is somewhat complex,
+        but the strategy for obtaining a moment of a given order and kind
+        (possibly as an intermediate step due to the recursive nature of the
+        transform formula above) roughly follows this order of priority:
+
+        #. Use cache (if order of same moment and kind has been calculated)
+        #. Use formula (if available)
+        #. Transform between raw and central moment and/or normalize to convert
+           between central and standardized moments (if efficient)
+        #. Use a generic result true for most distributions (if available)
+        #. Use quadrature
+
+        References
+        ----------
+        .. [1] Moment, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Moment_(mathematics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the first raw moment:
+
+        >>> X.moment(order=1, kind='raw')
+        1.0
+        >>> X.moment(order=1, kind='raw') == X.mean() == X.mu
+        True
+
+        Evaluate the second central moment:
+
+        >>> X.moment(order=2, kind='central')
+        4.0
+        >>> X.moment(order=2, kind='central') == X.variance() == X.sigma**2
+        True
+
+        Evaluate the fourth standardized moment:
+
+        >>> X.moment(order=4, kind='standardized')
+        3.0
+        >>> X.moment(order=4, kind='standardized') == X.kurtosis(convention='non-excess')
+        True
+
+        """  # noqa:E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def mean(self, *, method):
+        r"""Mean (raw first moment about the origin)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'quadrature', 'cache'}
+            Method used to calculate the raw first moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        median
+        mode
+
+        References
+        ----------
+        .. [1] Mean, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Mean#Mean_of_a_probability_distribution
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the variance:
+
+        >>> X.mean()
+        1.0
+        >>> X.mean() == X.moment(order=1, kind='raw') == X.mu
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def median(self, *, method):
+        r"""Median (50th percentil)
+
+        If a continuous random variable :math:`X` has probability :math:`0.5` of
+        taking on a value less than :math:`m`, then :math:`m` is the median.
+        That is, the median is the value :math:`m` for which:
+
+        .. math::
+
+            P(X ≤ m) = 0.5 = P(X ≥ m)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'icdf'}
+            The strategy used to evaluate the median.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the median
+            - ``'icdf'``: evaluate the inverse CDF of 0.5
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The median
+
+        See Also
+        --------
+        mean
+        mode
+        icdf
+
+        References
+        ----------
+        .. [1] Median, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Median#Probability_distributions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=0., b=10.)
+
+        Compute the median:
+
+        >>> X.median()
+        np.float64(5.0)
+        >>> X.median() == X.icdf(0.5) == X.iccdf(0.5)
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def mode(self, *, method):
+        r"""Mode (most likely value)
+
+        Informally, the mode is a value that a random variable has the highest
+        probability (density) of assuming. That is, the mode is the element of
+        the support :math:`\chi` that maximizes the probability density
+        function :math:`f(x)`:
+
+        .. math::
+
+            \text{mode} = \arg\max_{x \in \chi} f(x)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'optimization'}
+            The strategy used to evaluate the mode.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the median
+            - ``'optimization'``: numerically maximize the PDF
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The mode
+
+        See Also
+        --------
+        mean
+        median
+        pdf
+
+        Notes
+        -----
+        For some distributions
+
+        #. the mode is not unique (e.g. the uniform distribution);
+        #. the PDF has one or more singularities, and it is debateable whether
+           a singularity is considered to be in the domain and called the mode
+           (e.g. the gamma distribution with shape parameter less than 1); and/or
+        #. the probability density function may have one or more local maxima
+           that are not a global maximum (e.g. mixture distributions).
+
+        In such cases, `mode` will
+
+        #. return a single value,
+        #. consider the mode to occur at a singularity, and/or
+        #. return a local maximum which may or may not be a global maximum.
+
+        If a formula for the mode is not specifically implemented for the
+        chosen distribution, SciPy will attempt to compute the mode
+        numerically, which may not meet the user's preferred definition of a
+        mode. In such cases, the user is encouraged to subclass the
+        distribution and override ``mode``.
+
+        References
+        ----------
+        .. [1] Mode (statistics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Mode_(statistics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the mode:
+
+        >>> X.mode()
+        1.0
+
+        If the mode is not uniquely defined, ``mode`` nonetheless returns a
+        single value.
+
+        >>> X = stats.Uniform(a=0., b=1.)
+        >>> X.mode()
+        0.5
+
+        If this choice does not satisfy your requirements, subclass the
+        distribution and override ``mode``:
+
+        >>> class BetterUniform(stats.Uniform):
+        ...     def mode(self):
+        ...         return self.b
+        >>> X = BetterUniform(a=0., b=1.)
+        >>> X.mode()
+        1.0
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def variance(self, *, method):
+        r"""Variance (central second moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
+            Method used to calculate the central second moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        standard_deviation
+        mean
+
+        References
+        ----------
+        .. [1] Variance, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Variance#Absolutely_continuous_random_variable
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the variance:
+
+        >>> X.variance()
+        4.0
+        >>> X.variance() == X.moment(order=2, kind='central') == X.sigma**2
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def standard_deviation(self, *, method):
+        r"""Standard deviation (square root of the second central moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
+            Method used to calculate the central second moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        variance
+        mean
+        moment
+
+        References
+        ----------
+        .. [1] Standard deviation, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the standard deviation:
+
+        >>> X.standard_deviation()
+        2.0
+        >>> X.standard_deviation() == X.moment(order=2, kind='central')**0.5 == X.sigma
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def skewness(self, *, method):
+        r"""Skewness (standardized third moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
+            Method used to calculate the standardized third moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        mean
+        variance
+
+        References
+        ----------
+        .. [1] Skewness, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Skewness
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the skewness:
+
+        >>> X.skewness()
+        0.0
+        >>> X.skewness() == X.moment(order=3, kind='standardized')
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def kurtosis(self, *, method):
+        r"""Kurtosis (standardized fourth moment)
+
+        By default, this is the standardized fourth moment, also known as the
+        "non-excess" or "Pearson" kurtosis (e.g. the kurtosis of the normal
+        distribution is 3). The "excess" or "Fisher" kurtosis (the standardized
+        fourth moment minus 3) is available via the `convention` parameter.
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
+            Method used to calculate the standardized fourth moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+        convention : {'non-excess', 'excess'}
+            Two distinct conventions are available:
+
+            - ``'non-excess'``: the standardized fourth moment (Pearson's kurtosis)
+            - ``'excess'``: the standardized fourth moment minus 3 (Fisher's kurtosis)
+
+            The default is ``'non-excess'``.
+
+        See Also
+        --------
+        moment
+        mean
+        variance
+
+        References
+        ----------
+        .. [1] Kurtosis, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Kurtosis
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the kurtosis:
+
+        >>> X.kurtosis()
+        3.0
+        >>> (X.kurtosis()
+        ...  == X.kurtosis(convention='excess') + 3.
+        ...  == X.moment(order=4, kind='standardized'))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def pdf(self, x, /, *, method):
+        r"""Probability density function
+
+        The probability density function ("PDF"), denoted :math:`f(x)`, is the
+        probability *per unit length* that the random variable will assume the
+        value :math:`x`. Mathematically, it can be defined as the derivative
+        of the cumulative distribution function :math:`F(x)`:
+
+        .. math::
+
+            f(x) = \frac{d}{dx} F(x)
+
+        `pdf` accepts `x` for :math:`x`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the PDF.
+        method : {None, 'formula', 'logexp'}
+            The strategy used to evaluate the PDF. By default (``None``), the
+            infrastructure chooses between the following options, listed in
+            order of precedence.
+
+            - ``'formula'``: use a formula for the PDF itself
+            - ``'logexp'``: evaluate the log-PDF and exponentiate
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The PDF evaluated at the argument `x`.
+
+        See Also
+        --------
+        cdf
+        logpdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        By definition of the support, the PDF evaluates to its minimum value
+        of :math:`0` outside the support; i.e. for :math:`x < l` or
+        :math:`x > r`. The maximum of the PDF may be less than or greater than
+        :math:`1`; since the valus is a probability *density*, only its integral
+        over the support must equal :math:`1`.
+
+        References
+        ----------
+        .. [1] Probability density function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Probability_density_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the PDF at the desired argument:
+
+        >>> X.pdf(0.25)
+        0.5
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logpdf(self, x, /, *, method):
+        r"""Log of the probability density function
+
+        The probability density function ("PDF"), denoted :math:`f(x)`, is the
+        probability *per unit length* that the random variable will assume the
+        value :math:`x`. Mathematically, it can be defined as the derivative
+        of the cumulative distribution function :math:`F(x)`:
+
+        .. math::
+
+            f(x) = \frac{d}{dx} F(x)
+
+        `logpdf` computes the logarithm of the probability density function
+        ("log-PDF"), :math:`\log(f(x))`, but it may be numerically favorable
+        compared to the naive implementation (computing :math:`f(x)` and
+        taking the logarithm).
+
+        `logpdf` accepts `x` for :math:`x`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the log-PDF.
+        method : {None, 'formula', 'logexp'}
+            The strategy used to evaluate the log-PDF. By default (``None``), the
+            infrastructure chooses between the following options, listed in order
+            of precedence.
+
+            - ``'formula'``: use a formula for the log-PDF itself
+            - ``'logexp'``: evaluate the PDF and takes its logarithm
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-PDF evaluated at the argument `x`.
+
+        See Also
+        --------
+        pdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        By definition of the support, the log-PDF evaluates to its minimum value
+        of :math:`-\infty` (i.e. :math:`\log(0)`) outside the support; i.e. for
+        :math:`x < l` or :math:`x > r`. The maximum of the log-PDF may be less
+        than or greater than :math:`\log(1) = 0` because the maximum of the PDF
+        can be any positive real.
+
+        For distributions with infinite support, it is common for `pdf` to return
+        a value of ``0`` when the argument is theoretically within the support;
+        this can occur because the true value of the PDF is too small to be
+        represented by the chosen dtype. The log-PDF, however, will often be finite
+        (not ``-inf``) over a much larger domain. Consequently, it may be preferred
+        to work with the logarithms of probabilities and probability densities to
+        avoid underflow.
+
+        References
+        ----------
+        .. [1] Probability density function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Probability_density_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1.0, b=1.0)
+
+        Evaluate the log-PDF at the desired argument:
+
+        >>> X.logpdf(0.5)
+        -0.6931471805599453
+        >>> np.allclose(X.logpdf(0.5), np.log(X.pdf(0.5)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def cdf(self, x, y, /, *, method):
+        r"""Cumulative distribution function
+
+        The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
+        the probability the random variable :math:`X` will assume a value
+        less than or equal to :math:`x`:
+
+        .. math::
+
+            F(x) = P(X ≤ x)
+
+        A two-argument variant of this function is also defined as the
+        probability the random variable :math:`X` will assume a value between
+        :math:`x` and :math:`y`.
+
+        .. math::
+
+            F(x, y) = P(x ≤ X ≤ y)
+
+        `cdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the CDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
+            The strategy used to evaluate the CDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the CDF itself
+            - ``'logexp'``: evaluate the log-CDF and exponentiate
+            - ``'complement'``: evaluate the CCDF and take the complement
+            - ``'quadrature'``: numerically integrate the PDF
+
+            In place of ``'complement'``, the two-argument form accepts:
+
+            - ``'subtraction'``: compute the CDF at each argument and take
+              the difference.
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The CDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        logcdf
+        ccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The CDF :math:`F(x)` is related to the probability density function
+        :math:`f(x)` by:
+
+        .. math::
+
+            F(x) = \int_l^x f(u) du
+
+        The two argument version is:
+
+        .. math::
+
+            F(x, y) = \int_x^y f(u) du = F(y) - F(x)
+
+        The CDF evaluates to its minimum value of :math:`0` for :math:`x ≤ l`
+        and its maximum value of :math:`1` for :math:`x ≥ r`.
+
+        The CDF is also known simply as the "distribution function".
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the CDF at the desired argument:
+
+        >>> X.cdf(0.25)
+        0.75
+
+        Evaluate the cumulative probability between two arguments:
+
+        >>> X.cdf(-0.25, 0.25) == X.cdf(0.25) - X.cdf(-0.25)
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def icdf(self, p, /, *, method):
+        r"""Inverse of the cumulative distribution function.
+
+        The inverse of the cumulative distribution function ("inverse CDF"),
+        denoted :math:`F^{-1}(p)`, is the argument :math:`x` for which the
+        cumulative distribution function :math:`F(x)` evaluates to :math:`p`.
+
+        .. math::
+
+            F^{-1}(p) = x \quad \text{s.t.} \quad F(x) = p
+
+        `icdf` accepts `p` for :math:`p \in [0, 1]`.
+
+        Parameters
+        ----------
+        p : array_like
+            The argument of the inverse CDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse CDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse CDF itself
+            - ``'complement'``: evaluate the inverse CCDF at the
+              complement of `p`
+            - ``'inversion'``: solve numerically for the argument at which the
+              CDF is equal to `p`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse CDF evaluated at the provided argument.
+
+        See Also
+        --------
+        cdf
+        ilogcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse CDF returns its minimum value of :math:`l` at :math:`p = 0`
+        and its maximum value of :math:`r` at :math:`p = 1`. Because the CDF
+        has range :math:`[0, 1]`, the inverse CDF is only defined on the
+        domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, `icdf`
+        returns ``nan``.
+
+        The inverse CDF is also known as the quantile function, percentile function,
+        and percent-point function.
+
+        References
+        ----------
+        .. [1] Quantile function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Quantile_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse CDF at the desired argument:
+
+        >>> X.icdf(0.25)
+        -0.25
+        >>> np.allclose(X.cdf(X.icdf(0.25)), 0.25)
+        True
+
+        This function returns NaN when the argument is outside the domain.
+
+        >>> X.icdf([-0.1, 0, 1, 1.1])
+        array([ nan, -0.5,  0.5,  nan])
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ccdf(self, x, y, /, *, method):
+        r"""Complementary cumulative distribution function
+
+        The complementary cumulative distribution function ("CCDF"), denoted
+        :math:`G(x)`, is the complement of the cumulative distribution function
+        :math:`F(x)`; i.e., probability the random variable :math:`X` will
+        assume a value greater than :math:`x`:
+
+        .. math::
+
+            G(x) = 1 - F(x) = P(X > x)
+
+        A two-argument variant of this function is:
+
+        .. math::
+
+            G(x, y) = 1 - F(x, y) = P(X < x \text{ or } X > y)
+
+        `ccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the CCDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
+            The strategy used to evaluate the CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the CCDF itself
+            - ``'logexp'``: evaluate the log-CCDF and exponentiate
+            - ``'complement'``: evaluate the CDF and take the complement
+            - ``'quadrature'``: numerically integrate the PDF
+
+            The two-argument form chooses between:
+
+            - ``'formula'``: use a formula for the CCDF itself
+            - ``'addition'``: compute the CDF at `x` and the CCDF at `y`, then add
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The CCDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        cdf
+        logccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The CCDF :math:`G(x)` is related to the probability density function
+        :math:`f(x)` by:
+
+        .. math::
+
+            G(x) = \int_x^r f(u) du
+
+        The two argument version is:
+
+        .. math::
+
+            G(x, y) = \int_l^x f(u) du + \int_y^r f(u) du
+
+        The CCDF returns its minimum value of :math:`0` for :math:`x ≥ r`
+        and its maximum value of :math:`1` for :math:`x ≤ l`.
+
+        The CCDF is also known as the "survival function".
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the CCDF at the desired argument:
+
+        >>> X.ccdf(0.25)
+        0.25
+        >>> np.allclose(X.ccdf(0.25), 1-X.cdf(0.25))
+        True
+
+        Evaluate the complement of the cumulative probability between two arguments:
+
+        >>> X.ccdf(-0.25, 0.25) == X.cdf(-0.25) + X.ccdf(0.25)
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def iccdf(self, p, /, *, method):
+        r"""Inverse complementary cumulative distribution function.
+
+        The inverse complementary cumulative distribution function ("inverse CCDF"),
+        denoted :math:`G^{-1}(p)`, is the argument :math:`x` for which the
+        complementary cumulative distribution function :math:`G(x)` evaluates to
+        :math:`p`.
+
+        .. math::
+
+            G^{-1}(p) = x \quad \text{s.t.} \quad G(x) = p
+
+        `iccdf` accepts `p` for :math:`p \in [0, 1]`.
+
+        Parameters
+        ----------
+        p : array_like
+            The argument of the inverse CCDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse CCDF itself
+            - ``'complement'``: evaluate the inverse CDF at the
+              complement of `p`
+            - ``'inversion'``: solve numerically for the argument at which the
+              CCDF is equal to `p`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse CCDF evaluated at the provided argument.
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse CCDF returns its minimum value of :math:`l` at :math:`p = 1`
+        and its maximum value of :math:`r` at :math:`p = 0`. Because the CCDF
+        has range :math:`[0, 1]`, the inverse CCDF is only defined on the
+        domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, ``iccdf``
+        returns ``nan``.
+
+        See Also
+        --------
+        icdf
+        ilogccdf
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse CCDF at the desired argument:
+
+        >>> X.iccdf(0.25)
+        0.25
+        >>> np.allclose(X.iccdf(0.25), X.icdf(1-0.25))
+        True
+
+        This function returns NaN when the argument is outside the domain.
+
+        >>> X.iccdf([-0.1, 0, 1, 1.1])
+        array([ nan,  0.5, -0.5,  nan])
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logcdf(self, x, y, /, *, method):
+        r"""Log of the cumulative distribution function
+
+        The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
+        the probability the random variable :math:`X` will assume a value
+        less than or equal to :math:`x`:
+
+        .. math::
+
+            F(x) = P(X ≤ x)
+
+        A two-argument variant of this function is also defined as the
+        probability the random variable :math:`X` will assume a value between
+        :math:`x` and :math:`y`.
+
+        .. math::
+
+            F(x, y) = P(x ≤ X ≤ y)
+
+        `logcdf` computes the logarithm of the cumulative distribution function
+        ("log-CDF"), :math:`\log(F(x))`/:math:`\log(F(x, y))`, but it may be
+        numerically favorable compared to the naive implementation (computing
+        the CDF and taking the logarithm).
+
+        `logcdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the log-CDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
+            The strategy used to evaluate the log-CDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log-CDF itself
+            - ``'logexp'``: evaluate the CDF and take the logarithm
+            - ``'complement'``: evaluate the log-CCDF and take the
+              logarithmic complement (see Notes)
+            - ``'quadrature'``: numerically log-integrate the log-PDF
+
+            In place of ``'complement'``, the two-argument form accepts:
+
+            - ``'subtraction'``: compute the log-CDF at each argument and take
+              the logarithmic difference (see Notes)
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-CDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        cdf
+        logccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The log-CDF evaluates to its minimum value of :math:`\log(0) = -\infty`
+        for :math:`x ≤ l` and its maximum value of :math:`\log(1) = 0` for
+        :math:`x ≥ r`.
+
+        For distributions with infinite support, it is common for
+        `cdf` to return a value of ``0`` when the argument
+        is theoretically within the support; this can occur because the true value
+        of the CDF is too small to be represented by the chosen dtype. `logcdf`,
+        however, will often return a finite (not ``-inf``) result over a much larger
+        domain. Similarly, `logcdf` may provided a strictly negative result with
+        arguments for which `cdf` would return ``1.0``. Consequently, it may be
+        preferred to work with the logarithms of probabilities to avoid underflow
+        and related limitations of floating point numbers.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+        Similarly, the term "logarithmic difference" of :math:`w` and :math:`z`
+        is used here to mean :math:`\log(\exp(w)-\exp(z))`.
+
+        If ``y < x``, the CDF is negative, and therefore the log-CCDF
+        is complex with imaginary part :math:`\pi`. For
+        consistency, the result of this function always has complex dtype
+        when `y` is provided, regardless of the value of the imaginary part.
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the log-CDF at the desired argument:
+
+        >>> X.logcdf(0.25)
+        -0.287682072451781
+        >>> np.allclose(X.logcdf(0.), np.log(X.cdf(0.)))
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ilogcdf(self, logp, /, *, method):
+        r"""Inverse of the logarithm of the cumulative distribution function.
+
+        The inverse of the logarithm of the cumulative distribution function
+        ("inverse log-CDF") is the argument :math:`x` for which the logarithm
+        of the cumulative distribution function :math:`\log(F(x))` evaluates
+        to :math:`\log(p)`.
+
+        Mathematically, it is equivalent to :math:`F^{-1}(\exp(y))`, where
+        :math:`y = \log(p)`, but it may be numerically favorable compared to
+        the naive implementation (computing :math:`p = \exp(y)`, then
+        :math:`F^{-1}(p)`).
+
+        `ilogcdf` accepts `logp` for :math:`\log(p) ≤ 0`.
+
+        Parameters
+        ----------
+        logp : array_like
+            The argument of the inverse log-CDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse log-CDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse log-CDF itself
+            - ``'complement'``: evaluate the inverse log-CCDF at the
+              logarithmic complement of `logp` (see Notes)
+            - ``'inversion'``: solve numerically for the argument at which the
+              log-CDF is equal to `logp`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse log-CDF evaluated at the provided argument.
+
+        See Also
+        --------
+        icdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The inverse log-CDF returns its minimum value of :math:`l` at
+        :math:`\log(p) = \log(0) = -\infty` and its maximum value of :math:`r` at
+        :math:`\log(p) = \log(1) = 0`. Because the log-CDF has range
+        :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
+        negative reals; for :math:`\log(p) > 0`, `ilogcdf` returns ``nan``.
+
+        Occasionally, it is needed to find the argument of the CDF for which
+        the resulting probability is very close to ``0`` or ``1`` - too close to
+        represent accurately with floating point arithmetic. In many cases,
+        however, the *logarithm* of this resulting probability may be
+        represented in floating point arithmetic, in which case this function
+        may be used to find the argument of the CDF for which the *logarithm*
+        of the resulting probability is :math:`y = \log(p)`.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse log-CDF at the desired argument:
+
+        >>> X.ilogcdf(-0.25)
+        0.2788007830714034
+        >>> np.allclose(X.ilogcdf(-0.25), X.icdf(np.exp(-0.25)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logccdf(self, x, y, /, *, method):
+        r"""Log of the complementary cumulative distribution function
+
+        The complementary cumulative distribution function ("CCDF"), denoted
+        :math:`G(x)` is the complement of the cumulative distribution function
+        :math:`F(x)`; i.e., probability the random variable :math:`X` will
+        assume a value greater than :math:`x`:
+
+        .. math::
+
+            G(x) = 1 - F(x) = P(X > x)
+
+        A two-argument variant of this function is:
+
+        .. math::
+
+            G(x, y) = 1 - F(x, y) = P(X < x \quad \text{or} \quad X > y)
+
+        `logccdf` computes the logarithm of the complementary cumulative
+        distribution function ("log-CCDF"), :math:`\log(G(x))`/:math:`\log(G(x, y))`,
+        but it may be numerically favorable compared to the naive implementation
+        (computing the CDF and taking the logarithm).
+
+        `logccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the log-CCDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
+            The strategy used to evaluate the log-CCDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log CCDF itself
+            - ``'logexp'``: evaluate the CCDF and take the logarithm
+            - ``'complement'``: evaluate the log-CDF and take the
+              logarithmic complement (see Notes)
+            - ``'quadrature'``: numerically log-integrate the log-PDF
+
+            The two-argument form chooses between:
+
+            - ``'formula'``: use a formula for the log CCDF itself
+            - ``'addition'``: compute the log-CDF at `x` and the log-CCDF at `y`,
+              then take the logarithmic sum (see Notes)
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-CCDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        ccdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The log-CCDF returns its minimum value of :math:`\log(0)=-\infty` for
+        :math:`x ≥ r` and its maximum value of :math:`\log(1) = 0` for
+        :math:`x ≤ l`.
+
+        For distributions with infinite support, it is common for
+        `ccdf` to return a value of ``0`` when the argument
+        is theoretically within the support; this can occur because the true value
+        of the CCDF is too small to be represented by the chosen dtype. The log
+        of the CCDF, however, will often be finite (not ``-inf``) over a much larger
+        domain. Similarly, `logccdf` may provided a strictly negative result with
+        arguments for which `ccdf` would return ``1.0``. Consequently, it may be
+        preferred to work with the logarithms of probabilities to avoid underflow
+        and related limitations of floating point numbers.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+        Similarly, the term "logarithmic sum" of :math:`w` and :math:`z`
+        is used here to mean the :math:`\log(\exp(w)+\exp(z))`, AKA
+        :math:`\text{LogSumExp}(w, z)`.
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the log-CCDF at the desired argument:
+
+        >>> X.logccdf(0.25)
+        -1.3862943611198906
+        >>> np.allclose(X.logccdf(0.), np.log(X.ccdf(0.)))
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ilogccdf(self, logp, /, *, method):
+        r"""Inverse of the log of the complementary cumulative distribution function.
+
+        The inverse of the logarithm of the complementary cumulative distribution
+        function ("inverse log-CCDF") is the argument :math:`x` for which the logarithm
+        of the complementary cumulative distribution function :math:`\log(G(x))`
+        evaluates to :math:`\log(p)`.
+
+        Mathematically, it is equivalent to :math:`G^{-1}(\exp(y))`, where
+        :math:`y = \log(p)`, but it may be numerically favorable compared to the naive
+        implementation (computing :math:`p = \exp(y)`, then :math:`G^{-1}(p)`).
+
+        `ilogccdf` accepts `logp` for :math:`\log(p) ≤ 0`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the inverse log-CCDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse log-CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse log-CCDF itself
+            - ``'complement'``: evaluate the inverse log-CDF at the
+              logarithmic complement of `x` (see Notes)
+            - ``'inversion'``: solve numerically for the argument at which the
+              log-CCDF is equal to `x`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse log-CCDF evaluated at the provided argument.
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse log-CCDF returns its minimum value of :math:`l` at
+        :math:`\log(p) = \log(1) = 0` and its maximum value of :math:`r` at
+        :math:`\log(p) = \log(0) = -\infty`. Because the log-CCDF has range
+        :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
+        negative reals; for :math:`\log(p) > 0`, `ilogccdf` returns ``nan``.
+
+        Occasionally, it is needed to find the argument of the CCDF for which
+        the resulting probability is very close to ``0`` or ``1`` - too close to
+        represent accurately with floating point arithmetic. In many cases,
+        however, the *logarithm* of this resulting probability may be
+        represented in floating point arithmetic, in which case this function
+        may be used to find the argument of the CCDF for which the *logarithm*
+        of the resulting probability is `y = \log(p)`.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+
+        See Also
+        --------
+        iccdf
+        ilogccdf
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse log-CCDF at the desired argument:
+
+        >>> X.ilogccdf(-0.25)
+        -0.2788007830714034
+        >>> np.allclose(X.ilogccdf(-0.25), X.iccdf(np.exp(-0.25)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logentropy(self, *, method):
+        r"""Logarithm of the differential entropy
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the differential entropy (or simply "entropy") of a random
+        variable :math:`X` is:
+
+        .. math::
+
+            h(X) = - \int_{\chi} f(x) \log f(x) dx
+
+        `logentropy` computes the logarithm of the differential entropy
+        ("log-entropy"), :math:`log(h(X))`, but it may be numerically favorable
+        compared to the naive implementation (computing :math:`h(X)` then
+        taking the logarithm).
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'logexp', 'quadrature}
+            The strategy used to evaluate the log-entropy. By default
+            (``None``), the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log-entropy itself
+            - ``'logexp'``: evaluate the entropy and take the logarithm
+            - ``'quadrature'``: numerically log-integrate the logarithm of the
+              entropy integrand
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-entropy.
+
+        See Also
+        --------
+        entropy
+        logpdf
+
+        Notes
+        -----
+        If the entropy of a distribution is negative, then the log-entropy
+        is complex with imaginary part :math:`\pi`. For
+        consistency, the result of this function always has complex dtype,
+        regardless of the value of the imaginary part.
+
+        References
+        ----------
+        .. [1] Differential entropy, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Differential_entropy
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the log-entropy:
+
+        >>> X.logentropy()
+        (-0.3665129205816642+0j)
+        >>> np.allclose(np.exp(X.logentropy()), X.entropy())
+        True
+
+        For a random variable with negative entropy, the log-entropy has an
+        imaginary part equal to `np.pi`.
+
+        >>> X = stats.Uniform(a=-.1, b=.1)
+        >>> X.entropy(), X.logentropy()
+        (-1.6094379124341007, (0.4758849953271105+3.141592653589793j))
+
+        """
+        raise NotImplementedError()
+        
+    @abstractmethod
+    def entropy(self, *, method):
+        r"""Differential entropy
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the differential entropy (or simply "entropy") of a
+        continuous random variable :math:`X` is:
+
+        .. math::
+
+            h(X) = - \int_{\chi} f(x) \log f(x) dx
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'logexp', 'quadrature'}
+            The strategy used to evaluate the entropy. By default (``None``),
+            the infrastructure chooses between the following options, listed
+            in order of precedence.
+
+            - ``'formula'``: use a formula for the entropy itself
+            - ``'logexp'``: evaluate the log-entropy and exponentiate
+            - ``'quadrature'``: use numerical integration
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The entropy of the random variable.
+
+        See Also
+        --------
+        logentropy
+        pdf
+
+        Notes
+        -----
+        This function calculates the entropy using the natural logarithm; i.e.
+        the logarithm with base :math:`e`. Consequently, the value is expressed
+        in (dimensionless) "units" of nats. To convert the entropy to different
+        units (i.e. corresponding with a different base), divide the result by
+        the natural logarithm of the desired base.
+
+        References
+        ----------
+        .. [1] Differential entropy, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Differential_entropy
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the entropy:
+
+        >>> X.entropy()
+        0.6931471805599454
+
+        """
+        raise NotImplementedError()
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_qmc.py b/python_embeded/Lib/site-packages/scipy/stats/_qmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..794ac75506ed8acd3a3d3033200b5817a2ada797
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_qmc.py
@@ -0,0 +1,2951 @@
+"""Quasi-Monte Carlo engines and helpers."""
+import copy
+import math
+import numbers
+import os
+import warnings
+from abc import ABC, abstractmethod
+from functools import partial
+from typing import (
+    ClassVar,
+    Literal,
+    overload,
+    TYPE_CHECKING,
+)
+from collections.abc import Callable
+
+import numpy as np
+
+from scipy._lib._util import DecimalNumber, GeneratorType, IntNumber, SeedType
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+    
+import scipy.stats as stats
+from scipy._lib._util import rng_integers, _rng_spawn, _transition_to_rng
+from scipy.sparse.csgraph import minimum_spanning_tree
+from scipy.spatial import distance, Voronoi
+from scipy.special import gammainc
+from ._sobol import (
+    _initialize_v, _cscramble, _fill_p_cumulative, _draw, _fast_forward,
+    _categorize, _MAXDIM
+)
+from ._qmc_cy import (
+    _cy_wrapper_centered_discrepancy,
+    _cy_wrapper_wrap_around_discrepancy,
+    _cy_wrapper_mixture_discrepancy,
+    _cy_wrapper_l2_star_discrepancy,
+    _cy_wrapper_update_discrepancy,
+    _cy_van_der_corput_scrambled,
+    _cy_van_der_corput,
+)
+
+
+__all__ = ['scale', 'discrepancy', 'geometric_discrepancy', 'update_discrepancy',
+           'QMCEngine', 'Sobol', 'Halton', 'LatinHypercube', 'PoissonDisk',
+           'MultinomialQMC', 'MultivariateNormalQMC']
+
+
+@overload
+def check_random_state(seed: IntNumber | None = ...) -> np.random.Generator:
+    ...
+
+
+@overload
+def check_random_state(seed: GeneratorType) -> GeneratorType:
+    ...
+
+
+# Based on scipy._lib._util.check_random_state
+# This is going to be removed at the end of the SPEC 7 transition,
+# so I'll just leave the argument name `seed` alone
+def check_random_state(seed=None):
+    """Turn `seed` into a `numpy.random.Generator` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is an int or None, a new `numpy.random.Generator` is
+        created using ``np.random.default_rng(seed)``.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance, then
+        the provided instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or isinstance(seed, (numbers.Integral, np.integer)):
+        return np.random.default_rng(seed)
+    elif isinstance(seed, (np.random.RandomState, np.random.Generator)):
+        return seed
+    else:
+        raise ValueError(f'{seed!r} cannot be used to seed a'
+                         ' numpy.random.Generator instance')
+
+
+def scale(
+    sample: "npt.ArrayLike",
+    l_bounds: "npt.ArrayLike",
+    u_bounds: "npt.ArrayLike",
+    *,
+    reverse: bool = False
+) -> np.ndarray:
+    r"""Sample scaling from unit hypercube to different bounds.
+
+    To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
+    with :math:`a` the lower bounds and :math:`b` the upper bounds.
+    The following transformation is used:
+
+    .. math::
+
+        (b - a) \cdot \text{sample} + a
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        Sample to scale.
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds (resp. :math:`a`, :math:`b`) of transformed
+        data. If `reverse` is True, range of the original data to transform
+        to the unit hypercube.
+    reverse : bool, optional
+        Reverse the transformation from different bounds to the unit hypercube.
+        Default is False.
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        Scaled sample.
+
+    Examples
+    --------
+    Transform 3 samples in the unit hypercube to bounds:
+
+    >>> from scipy.stats import qmc
+    >>> l_bounds = [-2, 0]
+    >>> u_bounds = [6, 5]
+    >>> sample = [[0.5 , 0.75],
+    ...           [0.5 , 0.5],
+    ...           [0.75, 0.25]]
+    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)
+    >>> sample_scaled
+    array([[2.  , 3.75],
+           [2.  , 2.5 ],
+           [4.  , 1.25]])
+
+    And convert back to the unit hypercube:
+
+    >>> sample_ = qmc.scale(sample_scaled, l_bounds, u_bounds, reverse=True)
+    >>> sample_
+    array([[0.5 , 0.75],
+           [0.5 , 0.5 ],
+           [0.75, 0.25]])
+
+    """
+    sample = np.asarray(sample)
+
+    # Checking bounds and sample
+    if not sample.ndim == 2:
+        raise ValueError('Sample is not a 2D array')
+
+    lower, upper = _validate_bounds(
+        l_bounds=l_bounds, u_bounds=u_bounds, d=sample.shape[1]
+    )
+
+    if not reverse:
+        # Checking that sample is within the hypercube
+        if (sample.max() > 1.) or (sample.min() < 0.):
+            raise ValueError('Sample is not in unit hypercube')
+
+        return sample * (upper - lower) + lower
+    else:
+        # Checking that sample is within the bounds
+        if not (np.all(sample >= lower) and np.all(sample <= upper)):
+            raise ValueError('Sample is out of bounds')
+
+        return (sample - lower) / (upper - lower)
+
+
+def _ensure_in_unit_hypercube(sample: "npt.ArrayLike") -> np.ndarray:
+    """Ensure that sample is a 2D array and is within a unit hypercube
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        A 2D array of points.
+
+    Returns
+    -------
+    np.ndarray
+        The array interpretation of the input sample
+
+    Raises
+    ------
+    ValueError
+        If the input is not a 2D array or contains points outside of
+        a unit hypercube.
+    """
+    sample = np.asarray(sample, dtype=np.float64, order="C")
+
+    if not sample.ndim == 2:
+        raise ValueError("Sample is not a 2D array")
+
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError("Sample is not in unit hypercube")
+
+    return sample
+
+
+def discrepancy(
+        sample: "npt.ArrayLike",
+        *,
+        iterative: bool = False,
+        method: Literal["CD", "WD", "MD", "L2-star"] = "CD",
+        workers: IntNumber = 1) -> float:
+    """Discrepancy of a given sample.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to compute the discrepancy from.
+    iterative : bool, optional
+        Must be False if not using it for updating the discrepancy.
+        Default is False. Refer to the notes for more details.
+    method : str, optional
+        Type of discrepancy, can be ``CD``, ``WD``, ``MD`` or ``L2-star``.
+        Refer to the notes for more details. Default is ``CD``.
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is given all
+        CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    discrepancy : float
+        Discrepancy.
+
+    See Also
+    --------
+    geometric_discrepancy
+
+    Notes
+    -----
+    The discrepancy is a uniformity criterion used to assess the space filling
+    of a number of samples in a hypercube. A discrepancy quantifies the
+    distance between the continuous uniform distribution on a hypercube and the
+    discrete uniform distribution on :math:`n` distinct sample points.
+
+    The lower the value is, the better the coverage of the parameter space is.
+
+    For a collection of subsets of the hypercube, the discrepancy is the
+    difference between the fraction of sample points in one of those
+    subsets and the volume of that subset. There are different definitions of
+    discrepancy corresponding to different collections of subsets. Some
+    versions take a root mean square difference over subsets instead of
+    a maximum.
+
+    A measure of uniformity is reasonable if it satisfies the following
+    criteria [1]_:
+
+    1. It is invariant under permuting factors and/or runs.
+    2. It is invariant under rotation of the coordinates.
+    3. It can measure not only uniformity of the sample over the hypercube,
+       but also the projection uniformity of the sample over non-empty
+       subset of lower dimension hypercubes.
+    4. There is some reasonable geometric meaning.
+    5. It is easy to compute.
+    6. It satisfies the Koksma-Hlawka-like inequality.
+    7. It is consistent with other criteria in experimental design.
+
+    Four methods are available:
+
+    * ``CD``: Centered Discrepancy - subspace involves a corner of the
+      hypercube
+    * ``WD``: Wrap-around Discrepancy - subspace can wrap around bounds
+    * ``MD``: Mixture Discrepancy - mix between CD/WD covering more criteria
+    * ``L2-star``: L2-star discrepancy - like CD BUT variant to rotation
+
+    See [2]_ for precise definitions of each method.
+
+    Lastly, using ``iterative=True``, it is possible to compute the
+    discrepancy as if we had :math:`n+1` samples. This is useful if we want
+    to add a point to a sampling and check the candidate which would give the
+    lowest discrepancy. Then you could just update the discrepancy with
+    each candidate using `update_discrepancy`. This method is faster than
+    computing the discrepancy for a large number of candidates.
+
+    References
+    ----------
+    .. [1] Fang et al. "Design and modeling for computer experiments".
+       Computer Science and Data Analysis Series, 2006.
+    .. [2] Zhou Y.-D. et al. "Mixture discrepancy for quasi-random point sets."
+       Journal of Complexity, 29 (3-4) , pp. 283-301, 2013.
+    .. [3] T. T. Warnock. "Computational investigations of low discrepancy
+       point sets." Applications of Number Theory to Numerical
+       Analysis, Academic Press, pp. 319-343, 1972.
+
+    Examples
+    --------
+    Calculate the quality of the sample using the discrepancy:
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+    >>> l_bounds = [0.5, 0.5]
+    >>> u_bounds = [6.5, 6.5]
+    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
+    >>> space
+    array([[0.08333333, 0.41666667],
+           [0.25      , 0.91666667],
+           [0.41666667, 0.25      ],
+           [0.58333333, 0.75      ],
+           [0.75      , 0.08333333],
+           [0.91666667, 0.58333333]])
+    >>> qmc.discrepancy(space)
+    0.008142039609053464
+
+    We can also compute iteratively the ``CD`` discrepancy by using
+    ``iterative=True``.
+
+    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
+    >>> disc_init
+    0.04769081147119336
+    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
+    0.008142039609053513
+
+    """
+    sample = _ensure_in_unit_hypercube(sample)
+
+    workers = _validate_workers(workers)
+
+    methods = {
+        "CD": _cy_wrapper_centered_discrepancy,
+        "WD": _cy_wrapper_wrap_around_discrepancy,
+        "MD": _cy_wrapper_mixture_discrepancy,
+        "L2-star": _cy_wrapper_l2_star_discrepancy,
+    }
+
+    if method in methods:
+        return methods[method](sample, iterative, workers=workers)
+    else:
+        raise ValueError(f"{method!r} is not a valid method. It must be one of"
+                         f" {set(methods)!r}")
+
+
+def geometric_discrepancy(
+        sample: "npt.ArrayLike",
+        method: Literal["mindist", "mst"] = "mindist",
+        metric: str = "euclidean") -> float:
+    """Discrepancy of a given sample based on its geometric properties.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to compute the discrepancy from.
+    method : {"mindist", "mst"}, optional
+        The method to use. One of ``mindist`` for minimum distance (default)
+        or ``mst`` for minimum spanning tree.
+    metric : str or callable, optional
+        The distance metric to use. See the documentation
+        for `scipy.spatial.distance.pdist` for the available metrics and
+        the default.
+
+    Returns
+    -------
+    discrepancy : float
+        Discrepancy (higher values correspond to greater sample uniformity).
+
+    See Also
+    --------
+    discrepancy
+
+    Notes
+    -----
+    The discrepancy can serve as a simple measure of quality of a random sample.
+    This measure is based on the geometric properties of the distribution of points
+    in the sample, such as the minimum distance between any pair of points, or
+    the mean edge length in a minimum spanning tree.
+
+    The higher the value is, the better the coverage of the parameter space is.
+    Note that this is different from `scipy.stats.qmc.discrepancy`, where lower
+    values correspond to higher quality of the sample.
+
+    Also note that when comparing different sampling strategies using this function,
+    the sample size must be kept constant.
+
+    It is possible to calculate two metrics from the minimum spanning tree:
+    the mean edge length and the standard deviation of edges lengths. Using
+    both metrics offers a better picture of uniformity than either metric alone,
+    with higher mean and lower standard deviation being preferable (see [1]_
+    for a brief discussion). This function currently only calculates the mean
+    edge length.
+
+    References
+    ----------
+    .. [1] Franco J. et al. "Minimum Spanning Tree: A new approach to assess the quality
+       of the design of computer experiments." Chemometrics and Intelligent Laboratory
+       Systems, 97 (2), pp. 164-169, 2009.
+
+    Examples
+    --------
+    Calculate the quality of the sample using the minimum euclidean distance
+    (the defaults):
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> rng = np.random.default_rng(191468432622931918890291693003068437394)
+    >>> sample = qmc.LatinHypercube(d=2, rng=rng).random(50)
+    >>> qmc.geometric_discrepancy(sample)
+    0.03708161435687876
+
+    Calculate the quality using the mean edge length in the minimum
+    spanning tree:
+
+    >>> qmc.geometric_discrepancy(sample, method='mst')
+    0.1105149978798376
+
+    Display the minimum spanning tree and the points with
+    the smallest distance:
+
+    >>> import matplotlib.pyplot as plt
+    >>> from matplotlib.lines import Line2D
+    >>> from scipy.sparse.csgraph import minimum_spanning_tree
+    >>> from scipy.spatial.distance import pdist, squareform
+    >>> dist = pdist(sample)
+    >>> mst = minimum_spanning_tree(squareform(dist))
+    >>> edges = np.where(mst.toarray() > 0)
+    >>> edges = np.asarray(edges).T
+    >>> min_dist = np.min(dist)
+    >>> min_idx = np.argwhere(squareform(dist) == min_dist)[0]
+    >>> fig, ax = plt.subplots(figsize=(10, 5))
+    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
+    ...            xlim=[0, 1], ylim=[0, 1])
+    >>> for edge in edges:
+    ...     ax.plot(sample[edge, 0], sample[edge, 1], c='k')
+    >>> ax.scatter(sample[:, 0], sample[:, 1])
+    >>> ax.add_patch(plt.Circle(sample[min_idx[0]], min_dist, color='red', fill=False))
+    >>> markers = [
+    ...     Line2D([0], [0], marker='o', lw=0, label='Sample points'),
+    ...     Line2D([0], [0], color='k', label='Minimum spanning tree'),
+    ...     Line2D([0], [0], marker='o', lw=0, markerfacecolor='w', markeredgecolor='r',
+    ...            label='Minimum point-to-point distance'),
+    ... ]
+    >>> ax.legend(handles=markers, loc='center left', bbox_to_anchor=(1, 0.5));
+    >>> plt.show()
+
+    """
+    sample = _ensure_in_unit_hypercube(sample)
+    if sample.shape[0] < 2:
+        raise ValueError("Sample must contain at least two points")
+
+    distances = distance.pdist(sample, metric=metric)  # type: ignore[call-overload]
+
+    if np.any(distances == 0.0):
+        warnings.warn("Sample contains duplicate points.", stacklevel=2)
+
+    if method == "mindist":
+        return np.min(distances[distances.nonzero()])
+    elif method == "mst":
+        fully_connected_graph = distance.squareform(distances)
+        mst = minimum_spanning_tree(fully_connected_graph)
+        distances = mst[mst.nonzero()]
+        # TODO consider returning both the mean and the standard deviation
+        # see [1] for a discussion
+        return np.mean(distances)
+    else:
+        raise ValueError(f"{method!r} is not a valid method. "
+                         f"It must be one of {{'mindist', 'mst'}}")
+
+
+def update_discrepancy(
+        x_new: "npt.ArrayLike",
+        sample: "npt.ArrayLike",
+        initial_disc: DecimalNumber) -> float:
+    """Update the centered discrepancy with a new sample.
+
+    Parameters
+    ----------
+    x_new : array_like (1, d)
+        The new sample to add in `sample`.
+    sample : array_like (n, d)
+        The initial sample.
+    initial_disc : float
+        Centered discrepancy of the `sample`.
+
+    Returns
+    -------
+    discrepancy : float
+        Centered discrepancy of the sample composed of `x_new` and `sample`.
+
+    Examples
+    --------
+    We can also compute iteratively the discrepancy by using
+    ``iterative=True``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+    >>> l_bounds = [0.5, 0.5]
+    >>> u_bounds = [6.5, 6.5]
+    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
+    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
+    >>> disc_init
+    0.04769081147119336
+    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
+    0.008142039609053513
+
+    """
+    sample = np.asarray(sample, dtype=np.float64, order="C")
+    x_new = np.asarray(x_new, dtype=np.float64, order="C")
+
+    # Checking that sample is within the hypercube and 2D
+    if not sample.ndim == 2:
+        raise ValueError('Sample is not a 2D array')
+
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError('Sample is not in unit hypercube')
+
+    # Checking that x_new is within the hypercube and 1D
+    if not x_new.ndim == 1:
+        raise ValueError('x_new is not a 1D array')
+
+    if not (np.all(x_new >= 0) and np.all(x_new <= 1)):
+        raise ValueError('x_new is not in unit hypercube')
+
+    if x_new.shape[0] != sample.shape[1]:
+        raise ValueError("x_new and sample must be broadcastable")
+
+    return _cy_wrapper_update_discrepancy(x_new, sample, initial_disc)
+
+
+def _perturb_discrepancy(sample: np.ndarray, i1: int, i2: int, k: int,
+                         disc: float):
+    """Centered discrepancy after an elementary perturbation of a LHS.
+
+    An elementary perturbation consists of an exchange of coordinates between
+    two points: ``sample[i1, k] <-> sample[i2, k]``. By construction,
+    this operation conserves the LHS properties.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample (before permutation) to compute the discrepancy from.
+    i1 : int
+        The first line of the elementary permutation.
+    i2 : int
+        The second line of the elementary permutation.
+    k : int
+        The column of the elementary permutation.
+    disc : float
+        Centered discrepancy of the design before permutation.
+
+    Returns
+    -------
+    discrepancy : float
+        Centered discrepancy of the design after permutation.
+
+    References
+    ----------
+    .. [1] Jin et al. "An efficient algorithm for constructing optimal design
+       of computer experiments", Journal of Statistical Planning and
+       Inference, 2005.
+
+    """
+    n = sample.shape[0]
+
+    z_ij = sample - 0.5
+
+    # Eq (19)
+    c_i1j = (1. / n ** 2.
+             * np.prod(0.5 * (2. + abs(z_ij[i1, :])
+                              + abs(z_ij) - abs(z_ij[i1, :] - z_ij)), axis=1))
+    c_i2j = (1. / n ** 2.
+             * np.prod(0.5 * (2. + abs(z_ij[i2, :])
+                              + abs(z_ij) - abs(z_ij[i2, :] - z_ij)), axis=1))
+
+    # Eq (20)
+    c_i1i1 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i1, :]))
+              - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i1, :])
+                                 - 0.5 * z_ij[i1, :] ** 2))
+    c_i2i2 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i2, :]))
+              - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i2, :])
+                                 - 0.5 * z_ij[i2, :] ** 2))
+
+    # Eq (22), typo in the article in the denominator i2 -> i1
+    num = (2 + abs(z_ij[i2, k]) + abs(z_ij[:, k])
+           - abs(z_ij[i2, k] - z_ij[:, k]))
+    denum = (2 + abs(z_ij[i1, k]) + abs(z_ij[:, k])
+             - abs(z_ij[i1, k] - z_ij[:, k]))
+    gamma = num / denum
+
+    # Eq (23)
+    c_p_i1j = gamma * c_i1j
+    # Eq (24)
+    c_p_i2j = c_i2j / gamma
+
+    alpha = (1 + abs(z_ij[i2, k])) / (1 + abs(z_ij[i1, k]))
+    beta = (2 - abs(z_ij[i2, k])) / (2 - abs(z_ij[i1, k]))
+
+    g_i1 = np.prod(1. + abs(z_ij[i1, :]))
+    g_i2 = np.prod(1. + abs(z_ij[i2, :]))
+    h_i1 = np.prod(1. + 0.5 * abs(z_ij[i1, :]) - 0.5 * (z_ij[i1, :] ** 2))
+    h_i2 = np.prod(1. + 0.5 * abs(z_ij[i2, :]) - 0.5 * (z_ij[i2, :] ** 2))
+
+    # Eq (25), typo in the article g is missing
+    c_p_i1i1 = ((g_i1 * alpha) / (n ** 2) - 2. * alpha * beta * h_i1 / n)
+    # Eq (26), typo in the article n ** 2
+    c_p_i2i2 = ((g_i2 / ((n ** 2) * alpha)) - (2. * h_i2 / (n * alpha * beta)))
+
+    # Eq (26)
+    sum_ = c_p_i1j - c_i1j + c_p_i2j - c_i2j
+
+    mask = np.ones(n, dtype=bool)
+    mask[[i1, i2]] = False
+    sum_ = sum(sum_[mask])
+
+    disc_ep = (disc + c_p_i1i1 - c_i1i1 + c_p_i2i2 - c_i2i2 + 2 * sum_)
+
+    return disc_ep
+
+
+def primes_from_2_to(n: int) -> np.ndarray:
+    """Prime numbers from 2 to *n*.
+
+    Parameters
+    ----------
+    n : int
+        Sup bound with ``n >= 6``.
+
+    Returns
+    -------
+    primes : list(int)
+        Primes in ``2 <= p < n``.
+
+    Notes
+    -----
+    Taken from [1]_ by P.T. Roy, written consent given on 23.04.2021
+    by the original author, Bruno Astrolino, for free use in SciPy under
+    the 3-clause BSD.
+
+    References
+    ----------
+    .. [1] `StackOverflow `_.
+
+    """
+    sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool)
+    for i in range(1, int(n ** 0.5) // 3 + 1):
+        k = 3 * i + 1 | 1
+        sieve[k * k // 3::2 * k] = False
+        sieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = False
+    return np.r_[2, 3, ((3 * np.nonzero(sieve)[0][1:] + 1) | 1)]
+
+
+def n_primes(n: IntNumber) -> list[int]:
+    """List of the n-first prime numbers.
+
+    Parameters
+    ----------
+    n : int
+        Number of prime numbers wanted.
+
+    Returns
+    -------
+    primes : list(int)
+        List of primes.
+
+    """
+    primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
+              61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
+              131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
+              197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269,
+              271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
+              353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431,
+              433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
+              509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
+              601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673,
+              677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761,
+              769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857,
+              859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
+              953, 967, 971, 977, 983, 991, 997][:n]
+
+    if len(primes) < n:
+        big_number = 2000
+        while 'Not enough primes':
+            primes = primes_from_2_to(big_number)[:n]  # type: ignore
+            if len(primes) == n:
+                break
+            big_number += 1000
+
+    return primes
+
+
+def _van_der_corput_permutations(
+    base: IntNumber, *, rng: SeedType = None
+) -> np.ndarray:
+    """Permutations for scrambling a Van der Corput sequence.
+
+    Parameters
+    ----------
+    base : int
+        Base of the sequence.
+    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`, this keyword was changed from `seed` to
+            `rng`. During the transition, the behavior documented above is not
+            accurate; see `check_random_state` for actual behavior. After the
+            transition, this admonition can be removed.
+
+    Returns
+    -------
+    permutations : array_like
+        Permutation indices.
+
+    Notes
+    -----
+    In Algorithm 1 of Owen 2017, a permutation of `np.arange(base)` is
+    created for each positive integer `k` such that ``1 - base**-k < 1``
+    using floating-point arithmetic. For double precision floats, the
+    condition ``1 - base**-k < 1`` can also be written as ``base**-k >
+    2**-54``, which makes it more apparent how many permutations we need
+    to create.
+    """
+    rng = check_random_state(rng)
+    count = math.ceil(54 / math.log2(base)) - 1
+    permutations = np.repeat(np.arange(base)[None], count, axis=0)
+    for perm in permutations:
+        rng.shuffle(perm)
+
+    return permutations
+
+
+def van_der_corput(
+        n: IntNumber,
+        base: IntNumber = 2,
+        *,
+        start_index: IntNumber = 0,
+        scramble: bool = False,
+        permutations: "npt.ArrayLike | None" = None,
+        rng: SeedType = None,
+        workers: IntNumber = 1) -> np.ndarray:
+    """Van der Corput sequence.
+
+    Pseudo-random number generator based on a b-adic expansion.
+
+    Scrambling uses permutations of the remainders (see [1]_). Multiple
+    permutations are applied to construct a point. The sequence of
+    permutations has to be the same for all points of the sequence.
+
+    Parameters
+    ----------
+    n : int
+        Number of element of the sequence.
+    base : int, optional
+        Base of the sequence. Default is 2.
+    start_index : int, optional
+        Index to start the sequence from. Default is 0.
+    scramble : bool, optional
+        If True, use Owen scrambling. Otherwise no scrambling is done.
+        Default is True.
+    permutations : array_like, optional
+        Permutations used for scrambling.
+    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``.
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is
+        given all CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    sequence : list (n,)
+        Sequence of Van der Corput.
+
+    References
+    ----------
+    .. [1] A. B. Owen. "A randomized Halton algorithm in R",
+       :arxiv:`1706.02808`, 2017.
+
+    """
+    if base < 2:
+        raise ValueError("'base' must be at least 2")
+
+    if scramble:
+        if permutations is None:
+            permutations = _van_der_corput_permutations(
+                base=base, rng=rng
+            )
+        else:
+            permutations = np.asarray(permutations)
+
+        permutations = permutations.astype(np.int64)
+        return _cy_van_der_corput_scrambled(n, base, start_index,
+                                            permutations, workers)
+
+    else:
+        return _cy_van_der_corput(n, base, start_index, workers)
+
+
+class QMCEngine(ABC):
+    """A generic Quasi-Monte Carlo sampler class meant for subclassing.
+
+    QMCEngine is a base class to construct a specific Quasi-Monte Carlo
+    sampler. It cannot be used directly as a sampler.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    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`, this keyword was changed from `seed` 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 `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    By convention samples are distributed over the half-open interval
+    ``[0, 1)``. Instances of the class can access the attributes: ``d`` for
+    the dimension; and ``rng`` for the random number generator.
+
+    **Subclassing**
+
+    When subclassing `QMCEngine` to create a new sampler,  ``__init__`` and
+    ``random`` must be redefined.
+
+    * ``__init__(d, rng=None)``: at least fix the dimension. If the sampler
+      does not take advantage of a ``rng`` (deterministic methods like
+      Halton), this parameter can be omitted.
+    * ``_random(n, *, workers=1)``: draw ``n`` from the engine. ``workers``
+      is used for parallelism. See `Halton` for example.
+
+    Optionally, two other methods can be overwritten by subclasses:
+
+    * ``reset``: Reset the engine to its original state.
+    * ``fast_forward``: If the sequence is deterministic (like Halton
+      sequence), then ``fast_forward(n)`` is skipping the ``n`` first draw.
+
+    Examples
+    --------
+    To create a random sampler based on ``np.random.random``, we would do the
+    following:
+
+    >>> from scipy.stats import qmc
+    >>> class RandomEngine(qmc.QMCEngine):
+    ...     def __init__(self, d, rng=None):
+    ...         super().__init__(d=d, rng=rng)
+    ...
+    ...
+    ...     def _random(self, n=1, *, workers=1):
+    ...         return self.rng.random((n, self.d))
+    ...
+    ...
+    ...     def reset(self):
+    ...         super().__init__(d=self.d, rng=self.rng_seed)
+    ...         return self
+    ...
+    ...
+    ...     def fast_forward(self, n):
+    ...         self.random(n)
+    ...         return self
+
+    After subclassing `QMCEngine` to define the sampling strategy we want to
+    use, we can create an instance to sample from.
+
+    >>> engine = RandomEngine(2)
+    >>> engine.random(5)
+    array([[0.22733602, 0.31675834],  # random
+           [0.79736546, 0.67625467],
+           [0.39110955, 0.33281393],
+           [0.59830875, 0.18673419],
+           [0.67275604, 0.94180287]])
+
+    We can also reset the state of the generator and resample again.
+
+    >>> _ = engine.reset()
+    >>> engine.random(5)
+    array([[0.22733602, 0.31675834],  # random
+           [0.79736546, 0.67625467],
+           [0.39110955, 0.33281393],
+           [0.59830875, 0.18673419],
+           [0.67275604, 0.94180287]])
+
+    """
+
+    @abstractmethod
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        d: IntNumber,
+        *,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        self._initialize(d, optimization=optimization, rng=rng)
+
+    # During SPEC 7 transition:
+    # `__init__` has to be wrapped with @_transition_to_rng decorator
+    # because it is public. Subclasses previously called `__init__`
+    # directly, but this was problematic because arguments passed to
+    # subclass `__init__` as `seed` would get passed to superclass
+    # `__init__` as `rng`, rejecting `RandomState` arguments.
+    def _initialize(
+        self,
+        d: IntNumber,
+        *,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        if not np.issubdtype(type(d), np.integer) or d < 0:
+            raise ValueError('d must be a non-negative integer value')
+
+        self.d = d
+
+        if isinstance(rng, np.random.Generator):
+            # Spawn a Generator that we can own and reset.
+            self.rng = _rng_spawn(rng, 1)[0]
+        else:
+            # Create our instance of Generator, does not need spawning
+            # Also catch RandomState which cannot be spawned
+            self.rng = check_random_state(rng)
+        self.rng_seed = copy.deepcopy(self.rng)
+
+        self.num_generated = 0
+
+        config = {
+            # random-cd
+            "n_nochange": 100,
+            "n_iters": 10_000,
+            "rng": self.rng,
+
+            # lloyd
+            "tol": 1e-5,
+            "maxiter": 10,
+            "qhull_options": None,
+        }
+        self._optimization = optimization
+        self.optimization_method = _select_optimizer(optimization, config)
+
+    @abstractmethod
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        ...
+
+    def random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the half-open interval ``[0, 1)``.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space.
+            Default is 1.
+        workers : int, optional
+            Only supported with `Halton`.
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Default is 1. It becomes faster
+            than one worker for `n` greater than :math:`10^3`.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        sample = self._random(n, workers=workers)
+        if self.optimization_method is not None:
+            sample = self.optimization_method(sample)
+
+        self.num_generated += n
+        return sample
+
+    def integers(
+        self,
+        l_bounds: "npt.ArrayLike",
+        *,
+        u_bounds: "npt.ArrayLike | None" = None,
+        n: IntNumber = 1,
+        endpoint: bool = False,
+        workers: IntNumber = 1
+    ) -> np.ndarray:
+        r"""
+        Draw `n` integers from `l_bounds` (inclusive) to `u_bounds`
+        (exclusive), or if endpoint=True, `l_bounds` (inclusive) to
+        `u_bounds` (inclusive).
+
+        Parameters
+        ----------
+        l_bounds : int or array-like of ints
+            Lowest (signed) integers to be drawn (unless ``u_bounds=None``,
+            in which case this parameter is 0 and this value is used for
+            `u_bounds`).
+        u_bounds : int or array-like of ints, optional
+            If provided, one above the largest (signed) integer to be drawn
+            (see above for behavior if ``u_bounds=None``).
+            If array-like, must contain integer values.
+        n : int, optional
+            Number of samples to generate in the parameter space.
+            Default is 1.
+        endpoint : bool, optional
+            If true, sample from the interval ``[l_bounds, u_bounds]`` instead
+            of the default ``[l_bounds, u_bounds)``. Defaults is False.
+        workers : int, optional
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Only supported when using `Halton`
+            Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        Notes
+        -----
+        It is safe to just use the same ``[0, 1)`` to integer mapping
+        with QMC that you would use with MC. You still get unbiasedness,
+        a strong law of large numbers, an asymptotically infinite variance
+        reduction and a finite sample variance bound.
+
+        To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
+        with :math:`a` the lower bounds and :math:`b` the upper bounds,
+        the following transformation is used:
+
+        .. math::
+
+            \text{floor}((b - a) \cdot \text{sample} + a)
+
+        """
+        if u_bounds is None:
+            u_bounds = l_bounds
+            l_bounds = 0
+
+        u_bounds = np.atleast_1d(u_bounds)
+        l_bounds = np.atleast_1d(l_bounds)
+
+        if endpoint:
+            u_bounds = u_bounds + 1
+
+        if (not np.issubdtype(l_bounds.dtype, np.integer) or
+                not np.issubdtype(u_bounds.dtype, np.integer)):
+            message = ("'u_bounds' and 'l_bounds' must be integers or"
+                       " array-like of integers")
+            raise ValueError(message)
+
+        if isinstance(self, Halton):
+            sample = self.random(n=n, workers=workers)
+        else:
+            sample = self.random(n=n)
+
+        sample = scale(sample, l_bounds=l_bounds, u_bounds=u_bounds)
+        sample = np.floor(sample).astype(np.int64)
+
+        return sample
+
+    def reset(self) -> "QMCEngine":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : QMCEngine
+            Engine reset to its base state.
+
+        """
+        rng = copy.deepcopy(self.rng_seed)
+        self.rng = check_random_state(rng)
+        self.num_generated = 0
+        return self
+
+    def fast_forward(self, n: IntNumber) -> "QMCEngine":
+        """Fast-forward the sequence by `n` positions.
+
+        Parameters
+        ----------
+        n : int
+            Number of points to skip in the sequence.
+
+        Returns
+        -------
+        engine : QMCEngine
+            Engine reset to its base state.
+
+        """
+        self.random(n=n)
+        return self
+
+
+class Halton(QMCEngine):
+    """Halton sequence.
+
+    Pseudo-random number generator that generalize the Van der Corput sequence
+    for multiple dimensions. The Halton sequence uses the base-two Van der
+    Corput sequence for the first dimension, base-three for its second and
+    base-:math:`n` for its n-dimension.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    scramble : bool, optional
+        If True, use Owen scrambling. Otherwise no scrambling is done.
+        Default is True.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    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`, this keyword was changed from `seed` 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 `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    The Halton sequence has severe striping artifacts for even modestly
+    large dimensions. These can be ameliorated by scrambling. Scrambling
+    also supports replication-based error estimates and extends
+    applicability to unbounded integrands.
+
+    References
+    ----------
+    .. [1] Halton, "On the efficiency of certain quasi-random sequences of
+       points in evaluating multi-dimensional integrals", Numerische
+       Mathematik, 1960.
+    .. [2] A. B. Owen. "A randomized Halton algorithm in R",
+       :arxiv:`1706.02808`, 2017.
+
+    Examples
+    --------
+    Generate samples from a low discrepancy sequence of Halton.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.Halton(d=2, scramble=False)
+    >>> sample = sampler.random(n=5)
+    >>> sample
+    array([[0.        , 0.        ],
+           [0.5       , 0.33333333],
+           [0.25      , 0.66666667],
+           [0.75      , 0.11111111],
+           [0.125     , 0.44444444]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.088893711419753
+
+    If some wants to continue an existing design, extra points can be obtained
+    by calling again `random`. Alternatively, you can skip some points like:
+
+    >>> _ = sampler.fast_forward(5)
+    >>> sample_continued = sampler.random(n=5)
+    >>> sample_continued
+    array([[0.3125    , 0.37037037],
+           [0.8125    , 0.7037037 ],
+           [0.1875    , 0.14814815],
+           [0.6875    , 0.48148148],
+           [0.4375    , 0.81481481]])
+
+    Finally, samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
+    array([[3.125     , 3.11111111],
+           [8.125     , 4.11111111],
+           [1.875     , 2.44444444],
+           [6.875     , 3.44444444],
+           [4.375     , 4.44444444]])
+
+    """
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *, scramble: bool = True,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True,
+                           'optimization': optimization}
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+
+        # important to have ``type(bdim) == int`` for performance reason
+        self.base = [int(bdim) for bdim in n_primes(d)]
+        self.scramble = scramble
+
+        self._initialize_permutations()
+
+    def _initialize_permutations(self) -> None:
+        """Initialize permutations for all Van der Corput sequences.
+
+        Permutations are only needed for scrambling.
+        """
+        self._permutations: list = [None] * len(self.base)
+        if self.scramble:
+            for i, bdim in enumerate(self.base):
+                permutations = _van_der_corput_permutations(
+                    base=bdim, rng=self.rng
+                )
+
+                self._permutations[i] = permutations
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the half-open interval ``[0, 1)``.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+        workers : int, optional
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Default is 1. It becomes faster
+            than one worker for `n` greater than :math:`10^3`.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        workers = _validate_workers(workers)
+        # Generate a sample using a Van der Corput sequence per dimension.
+        sample = [van_der_corput(n, bdim, start_index=self.num_generated,
+                                 scramble=self.scramble,
+                                 permutations=self._permutations[i],
+                                 workers=workers)
+                  for i, bdim in enumerate(self.base)]
+
+        return np.array(sample).T.reshape(n, self.d)
+
+
+class LatinHypercube(QMCEngine):
+    r"""Latin hypercube sampling (LHS).
+
+    A Latin hypercube sample [1]_ generates :math:`n` points in
+    :math:`[0,1)^{d}`. Each univariate marginal distribution is stratified,
+    placing exactly one point in :math:`[j/n, (j+1)/n)` for
+    :math:`j=0,1,...,n-1`. They are still applicable when :math:`n << d`.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    scramble : bool, optional
+        When False, center samples within cells of a multi-dimensional grid.
+        Otherwise, samples are randomly placed within cells of the grid.
+
+        .. note::
+            Setting ``scramble=False`` does not ensure deterministic output.
+            For that, use the `rng` parameter.
+
+        Default is True.
+
+        .. versionadded:: 1.10.0
+
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.8.0
+        .. versionchanged:: 1.10.0
+            Add ``lloyd``.
+
+    strength : {1, 2}, optional
+        Strength of the LHS. ``strength=1`` produces a plain LHS while
+        ``strength=2`` produces an orthogonal array based LHS of strength 2
+        [7]_, [8]_. In that case, only ``n=p**2`` points can be sampled,
+        with ``p`` a prime number. It also constrains ``d <= p + 1``.
+        Default is 1.
+
+        .. versionadded:: 1.8.0
+
+    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`, this keyword was changed from `seed` 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 `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    See Also
+    --------
+    :ref:`quasi-monte-carlo`
+
+    Notes
+    -----
+
+    When LHS is used for integrating a function :math:`f` over :math:`n`,
+    LHS is extremely effective on integrands that are nearly additive [2]_.
+    With a LHS of :math:`n` points, the variance of the integral is always
+    lower than plain MC on :math:`n-1` points [3]_. There is a central limit
+    theorem for LHS on the mean and variance of the integral [4]_, but not
+    necessarily for optimized LHS due to the randomization.
+
+    :math:`A` is called an orthogonal array of strength :math:`t` if in each
+    n-row-by-t-column submatrix of :math:`A`: all :math:`p^t` possible
+    distinct rows occur the same number of times. The elements of :math:`A`
+    are in the set :math:`\{0, 1, ..., p-1\}`, also called symbols.
+    The constraint that :math:`p` must be a prime number is to allow modular
+    arithmetic. Increasing strength adds some symmetry to the sub-projections
+    of a sample. With strength 2, samples are symmetric along the diagonals of
+    2D sub-projections. This may be undesirable, but on the other hand, the
+    sample dispersion is improved.
+
+    Strength 1 (plain LHS) brings an advantage over strength 0 (MC) and
+    strength 2 is a useful increment over strength 1. Going to strength 3 is
+    a smaller increment and scrambled QMC like Sobol', Halton are more
+    performant [7]_.
+
+    To create a LHS of strength 2, the orthogonal array :math:`A` is
+    randomized by applying a random, bijective map of the set of symbols onto
+    itself. For example, in column 0, all 0s might become 2; in column 1,
+    all 0s might become 1, etc.
+    Then, for each column :math:`i` and symbol :math:`j`, we add a plain,
+    one-dimensional LHS of size :math:`p` to the subarray where
+    :math:`A^i = j`. The resulting matrix is finally divided by :math:`p`.
+
+    References
+    ----------
+    .. [1] Mckay et al., "A Comparison of Three Methods for Selecting Values
+       of Input Variables in the Analysis of Output from a Computer Code."
+       Technometrics, 1979.
+    .. [2] M. Stein, "Large sample properties of simulations using Latin
+       hypercube sampling." Technometrics 29, no. 2: 143-151, 1987.
+    .. [3] A. B. Owen, "Monte Carlo variance of scrambled net quadrature."
+       SIAM Journal on Numerical Analysis 34, no. 5: 1884-1910, 1997
+    .. [4]  Loh, W.-L. "On Latin hypercube sampling." The annals of statistics
+       24, no. 5: 2058-2080, 1996.
+    .. [5] Fang et al. "Design and modeling for computer experiments".
+       Computer Science and Data Analysis Series, 2006.
+    .. [6] Damblin et al., "Numerical studies of space filling designs:
+       optimization of Latin Hypercube Samples and subprojection properties."
+       Journal of Simulation, 2013.
+    .. [7] A. B. Owen , "Orthogonal arrays for computer experiments,
+       integration and visualization." Statistica Sinica, 1992.
+    .. [8] B. Tang, "Orthogonal Array-Based Latin Hypercubes."
+       Journal of the American Statistical Association, 1993.
+    .. [9] Seaholm, Susan K. et al. (1988). Latin hypercube sampling and the
+       sensitivity analysis of a Monte Carlo epidemic model. Int J Biomed
+       Comput, 23(1-2), 97-112. :doi:`10.1016/0020-7101(88)90067-0`
+
+    Examples
+    --------
+    Generate samples from a Latin hypercube generator.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.LatinHypercube(d=2)
+    >>> sample = sampler.random(n=5)
+    >>> sample
+    array([[0.1545328 , 0.53664833], # random
+            [0.84052691, 0.06474907],
+            [0.52177809, 0.93343721],
+            [0.68033825, 0.36265316],
+            [0.26544879, 0.61163943]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.0196... # random
+
+    Samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample, l_bounds, u_bounds)
+    array([[1.54532796, 3.609945 ], # random
+            [8.40526909, 2.1942472 ],
+            [5.2177809 , 4.80031164],
+            [6.80338249, 3.08795949],
+            [2.65448791, 3.83491828]])
+
+    Below are other examples showing alternative ways to construct LHS with
+    even better coverage of the space.
+
+    Using a base LHS as a baseline.
+
+    >>> sampler = qmc.LatinHypercube(d=2)
+    >>> sample = sampler.random(n=5)
+    >>> qmc.discrepancy(sample)
+    0.0196...  # random
+
+    Use the `optimization` keyword argument to produce a LHS with
+    lower discrepancy at higher computational cost.
+
+    >>> sampler = qmc.LatinHypercube(d=2, optimization="random-cd")
+    >>> sample = sampler.random(n=5)
+    >>> qmc.discrepancy(sample)
+    0.0176...  # random
+
+    Use the `strength` keyword argument to produce an orthogonal array based
+    LHS of strength 2. In this case, the number of sample points must be the
+    square of a prime number.
+
+    >>> sampler = qmc.LatinHypercube(d=2, strength=2)
+    >>> sample = sampler.random(n=9)
+    >>> qmc.discrepancy(sample)
+    0.00526...  # random
+
+    Options could be combined to produce an optimized centered
+    orthogonal array based LHS. After optimization, the result would not
+    be guaranteed to be of strength 2.
+
+    **Real-world example**
+
+    In [9]_, a Latin Hypercube sampling (LHS) strategy was used to sample a
+    parameter space to study the importance of each parameter of an epidemic
+    model. Such analysis is also called a sensitivity analysis.
+
+    Since the dimensionality of the problem is high (6), it is computationally
+    expensive to cover the space. When numerical experiments are costly, QMC
+    enables analysis that may not be possible if using a grid.
+
+    The six parameters of the model represented the probability of illness,
+    the probability of withdrawal, and four contact probabilities. The
+    authors assumed uniform distributions for all parameters and generated
+    50 samples.
+
+    Using `scipy.stats.qmc.LatinHypercube` to replicate the protocol,
+    the first step is to create a sample in the unit hypercube:
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.LatinHypercube(d=6)
+    >>> sample = sampler.random(n=50)
+
+    Then the sample can be scaled to the appropriate bounds:
+
+    >>> l_bounds = [0.000125, 0.01, 0.0025, 0.05, 0.47, 0.7]
+    >>> u_bounds = [0.000375, 0.03, 0.0075, 0.15, 0.87, 0.9]
+    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)
+
+    Such a sample was used to run the model 50 times, and a polynomial
+    response surface was constructed. This allowed the authors to study the
+    relative importance of each parameter across the range of possibilities
+    of every other parameter.
+
+    In this computer experiment, they showed a 14-fold reduction in the
+    number of samples required to maintain an error below 2% on their
+    response surface when compared to a grid sampling.
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *,
+        scramble: bool = True,
+        strength: int = 1,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True, 'strength': strength,
+                           'optimization': optimization}
+        super()._initialize(d=d, rng=rng, optimization=optimization)
+        self.scramble = scramble
+
+        lhs_method_strength = {
+            1: self._random_lhs,
+            2: self._random_oa_lhs
+        }
+
+        try:
+            self.lhs_method: Callable = lhs_method_strength[strength]
+        except KeyError as exc:
+            message = (f"{strength!r} is not a valid strength. It must be one"
+                       f" of {set(lhs_method_strength)!r}")
+            raise ValueError(message) from exc
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        lhs = self.lhs_method(n)
+        return lhs
+
+    def _random_lhs(self, n: IntNumber = 1) -> np.ndarray:
+        """Base LHS algorithm."""
+        if not self.scramble:
+            samples: np.ndarray | float = 0.5
+        else:
+            samples = self.rng.uniform(size=(n, self.d))
+
+        perms = np.tile(np.arange(1, n + 1),
+                        (self.d, 1))  # type: ignore[arg-type]
+        for i in range(self.d):
+            self.rng.shuffle(perms[i, :])
+        perms = perms.T
+
+        samples = (perms - samples) / n
+        return samples
+
+    def _random_oa_lhs(self, n: IntNumber = 4) -> np.ndarray:
+        """Orthogonal array based LHS of strength 2."""
+        p = np.sqrt(n).astype(int)
+        n_row = p**2
+        n_col = p + 1
+
+        primes = primes_from_2_to(p + 1)
+        if p not in primes or n != n_row:
+            raise ValueError(
+                "n is not the square of a prime number. Close"
+                f" values are {primes[-2:]**2}"
+            )
+        if self.d > p + 1:
+            raise ValueError("n is too small for d. Must be n > (d-1)**2")
+
+        oa_sample = np.zeros(shape=(n_row, n_col), dtype=int)
+
+        # OA of strength 2
+        arrays = np.tile(np.arange(p), (2, 1))
+        oa_sample[:, :2] = np.stack(np.meshgrid(*arrays),
+                                    axis=-1).reshape(-1, 2)
+        for p_ in range(1, p):
+            oa_sample[:, 2+p_-1] = np.mod(oa_sample[:, 0]
+                                          + p_*oa_sample[:, 1], p)
+
+        # scramble the OA
+        oa_sample_ = np.empty(shape=(n_row, n_col), dtype=int)
+        for j in range(n_col):
+            perms = self.rng.permutation(p)
+            oa_sample_[:, j] = perms[oa_sample[:, j]]
+        
+        oa_sample = oa_sample_
+        # following is making a scrambled OA into an OA-LHS
+        oa_lhs_sample = np.zeros(shape=(n_row, n_col))
+        lhs_engine = LatinHypercube(d=1, scramble=self.scramble, strength=1,
+                                    rng=self.rng)  # type: QMCEngine
+        for j in range(n_col):
+            for k in range(p):
+                idx = oa_sample[:, j] == k
+                lhs = lhs_engine.random(p).flatten()
+                oa_lhs_sample[:, j][idx] = lhs + oa_sample[:, j][idx]
+
+        oa_lhs_sample /= p
+
+        return oa_lhs_sample[:, :self.d]
+
+
+class Sobol(QMCEngine):
+    """Engine for generating (scrambled) Sobol' sequences.
+
+    Sobol' sequences are low-discrepancy, quasi-random numbers. Points
+    can be drawn using two methods:
+
+    * `random_base2`: safely draw :math:`n=2^m` points. This method
+      guarantees the balance properties of the sequence.
+    * `random`: draw an arbitrary number of points from the
+      sequence. See warning below.
+
+    Parameters
+    ----------
+    d : int
+        Dimensionality of the sequence. Max dimensionality is 21201.
+    scramble : bool, optional
+        If True, use LMS+shift scrambling. Otherwise, no scrambling is done.
+        Default is True.
+    bits : int, optional
+        Number of bits of the generator. Control the maximum number of points
+        that can be generated, which is ``2**bits``. Maximal value is 64.
+        It does not correspond to the return type, which is always
+        ``np.float64`` to prevent points from repeating themselves.
+        Default is None, which for backward compatibility, corresponds to 30.
+
+        .. versionadded:: 1.9.0
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    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`, this keyword was changed from `seed` 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 `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    Sobol' sequences [1]_ provide :math:`n=2^m` low discrepancy points in
+    :math:`[0,1)^{d}`. Scrambling them [3]_ makes them suitable for singular
+    integrands, provides a means of error estimation, and can improve their
+    rate of convergence. The scrambling strategy which is implemented is a
+    (left) linear matrix scramble (LMS) followed by a digital random shift
+    (LMS+shift) [2]_.
+
+    There are many versions of Sobol' sequences depending on their
+    'direction numbers'. This code uses direction numbers from [4]_. Hence,
+    the maximum number of dimension is 21201. The direction numbers have been
+    precomputed with search criterion 6 and can be retrieved at
+    https://web.maths.unsw.edu.au/~fkuo/sobol/.
+
+    .. warning::
+
+       Sobol' sequences are a quadrature rule and they lose their balance
+       properties if one uses a sample size that is not a power of 2, or skips
+       the first point, or thins the sequence [5]_.
+
+       If :math:`n=2^m` points are not enough then one should take :math:`2^M`
+       points for :math:`M>m`. When scrambling, the number R of independent
+       replicates does not have to be a power of 2.
+
+       Sobol' sequences are generated to some number :math:`B` of bits.
+       After :math:`2^B` points have been generated, the sequence would
+       repeat. Hence, an error is raised.
+       The number of bits can be controlled with the parameter `bits`.
+
+    References
+    ----------
+    .. [1] I. M. Sobol', "The distribution of points in a cube and the accurate
+       evaluation of integrals." Zh. Vychisl. Mat. i Mat. Phys., 7:784-802,
+       1967.
+    .. [2] J. Matousek, "On the L2-discrepancy for anchored boxes."
+       J. of Complexity 14, 527-556, 1998.
+    .. [3] Art B. Owen, "Scrambling Sobol and Niederreiter-Xing points."
+       Journal of Complexity, 14(4):466-489, December 1998.
+    .. [4] S. Joe and F. Y. Kuo, "Constructing sobol sequences with better
+       two-dimensional projections." SIAM Journal on Scientific Computing,
+       30(5):2635-2654, 2008.
+    .. [5] Art B. Owen, "On dropping the first Sobol' point."
+       :arxiv:`2008.08051`, 2020.
+
+    Examples
+    --------
+    Generate samples from a low discrepancy sequence of Sobol'.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.Sobol(d=2, scramble=False)
+    >>> sample = sampler.random_base2(m=3)
+    >>> sample
+    array([[0.   , 0.   ],
+           [0.5  , 0.5  ],
+           [0.75 , 0.25 ],
+           [0.25 , 0.75 ],
+           [0.375, 0.375],
+           [0.875, 0.875],
+           [0.625, 0.125],
+           [0.125, 0.625]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.013882107204860938
+
+    To continue an existing design, extra points can be obtained
+    by calling again `random_base2`. Alternatively, you can skip some
+    points like:
+
+    >>> _ = sampler.reset()
+    >>> _ = sampler.fast_forward(4)
+    >>> sample_continued = sampler.random_base2(m=2)
+    >>> sample_continued
+    array([[0.375, 0.375],
+           [0.875, 0.875],
+           [0.625, 0.125],
+           [0.125, 0.625]])
+
+    Finally, samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
+    array([[3.75 , 3.125],
+           [8.75 , 4.625],
+           [6.25 , 2.375],
+           [1.25 , 3.875]])
+
+    """
+
+    MAXDIM: ClassVar[int] = _MAXDIM
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *, scramble: bool = True,
+        bits: IntNumber | None = None, rng: SeedType = None,
+        optimization: Literal["random-cd", "lloyd"] | None = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True, 'bits': bits,
+                           'optimization': optimization}
+
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+        if d > self.MAXDIM:
+            raise ValueError(
+                f"Maximum supported dimensionality is {self.MAXDIM}."
+            )
+
+        self.bits = bits
+        self.dtype_i: type
+        self.scramble = scramble
+
+        if self.bits is None:
+            self.bits = 30
+
+        if self.bits <= 32:
+            self.dtype_i = np.uint32
+        elif 32 < self.bits <= 64:
+            self.dtype_i = np.uint64
+        else:
+            raise ValueError("Maximum supported 'bits' is 64")
+
+        self.maxn = 2**self.bits
+
+        # v is d x maxbit matrix
+        self._sv: np.ndarray = np.zeros((d, self.bits), dtype=self.dtype_i)
+        _initialize_v(self._sv, dim=d, bits=self.bits)
+
+        if not scramble:
+            self._shift: np.ndarray = np.zeros(d, dtype=self.dtype_i)
+        else:
+            # scramble self._shift and self._sv
+            self._scramble()
+
+        self._quasi = self._shift.copy()
+
+        # normalization constant with the largest possible number
+        # calculate in Python to not overflow int with 2**64
+        self._scale = 1.0 / 2 ** self.bits
+
+        self._first_point = (self._quasi * self._scale).reshape(1, -1)
+        # explicit casting to float64
+        self._first_point = self._first_point.astype(np.float64)
+
+    def _scramble(self) -> None:
+        """Scramble the sequence using LMS+shift."""
+        # Generate shift vector
+        self._shift = np.dot(
+            rng_integers(self.rng, 2, size=(self.d, self.bits),
+                         dtype=self.dtype_i),
+            2 ** np.arange(self.bits, dtype=self.dtype_i),
+        )
+        # Generate lower triangular matrices (stacked across dimensions)
+        ltm = np.tril(rng_integers(self.rng, 2,
+                                   size=(self.d, self.bits, self.bits),
+                                   dtype=self.dtype_i))
+        _cscramble(
+            dim=self.d, bits=self.bits,  # type: ignore[arg-type]
+            ltm=ltm, sv=self._sv
+        )
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw next point(s) in the Sobol' sequence.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sobol' sample.
+
+        """
+        sample: np.ndarray = np.empty((n, self.d), dtype=np.float64)
+
+        if n == 0:
+            return sample
+
+        total_n = self.num_generated + n
+        if total_n > self.maxn:
+            msg = (
+                f"At most 2**{self.bits}={self.maxn} distinct points can be "
+                f"generated. {self.num_generated} points have been previously "
+                f"generated, then: n={self.num_generated}+{n}={total_n}. "
+            )
+            if self.bits != 64:
+                msg += "Consider increasing `bits`."
+            raise ValueError(msg)
+
+        if self.num_generated == 0:
+            # verify n is 2**n
+            if not (n & (n - 1) == 0):
+                warnings.warn("The balance properties of Sobol' points require"
+                              " n to be a power of 2.", stacklevel=2)
+
+            if n == 1:
+                sample = self._first_point
+            else:
+                _draw(
+                    n=n - 1, num_gen=self.num_generated, dim=self.d,
+                    scale=self._scale, sv=self._sv, quasi=self._quasi,
+                    sample=sample
+                )
+                sample = np.concatenate(
+                    [self._first_point, sample]
+                )[:n]
+        else:
+            _draw(
+                n=n, num_gen=self.num_generated - 1, dim=self.d,
+                scale=self._scale, sv=self._sv, quasi=self._quasi,
+                sample=sample
+            )
+
+        return sample
+
+    def random_base2(self, m: IntNumber) -> np.ndarray:
+        """Draw point(s) from the Sobol' sequence.
+
+        This function draws :math:`n=2^m` points in the parameter space
+        ensuring the balance properties of the sequence.
+
+        Parameters
+        ----------
+        m : int
+            Logarithm in base 2 of the number of samples; i.e., n = 2^m.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sobol' sample.
+
+        """
+        n = 2 ** m
+
+        total_n = self.num_generated + n
+        if not (total_n & (total_n - 1) == 0):
+            raise ValueError('The balance properties of Sobol\' points require '
+                             f'n to be a power of 2. {self.num_generated} points '
+                             'have been previously generated, then: '
+                             f'n={self.num_generated}+2**{m}={total_n}. '
+                             'If you still want to do this, the function '
+                             '\'Sobol.random()\' can be used.'
+                             )
+
+        return self.random(n)
+
+    def reset(self) -> "Sobol":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : Sobol
+            Engine reset to its base state.
+
+        """
+        super().reset()
+        self._quasi = self._shift.copy()
+        return self
+
+    def fast_forward(self, n: IntNumber) -> "Sobol":
+        """Fast-forward the sequence by `n` positions.
+
+        Parameters
+        ----------
+        n : int
+            Number of points to skip in the sequence.
+
+        Returns
+        -------
+        engine : Sobol
+            The fast-forwarded engine.
+
+        """
+        if self.num_generated == 0:
+            _fast_forward(
+                n=n - 1, num_gen=self.num_generated, dim=self.d,
+                sv=self._sv, quasi=self._quasi
+            )
+        else:
+            _fast_forward(
+                n=n, num_gen=self.num_generated - 1, dim=self.d,
+                sv=self._sv, quasi=self._quasi
+            )
+        self.num_generated += n
+        return self
+
+
+class PoissonDisk(QMCEngine):
+    """Poisson disk sampling.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    radius : float
+        Minimal distance to keep between points when sampling new candidates.
+    hypersphere : {"volume", "surface"}, optional
+        Sampling strategy to generate potential candidates to be added in the
+        final sample. Default is "volume".
+
+        * ``volume``: original Bridson algorithm as described in [1]_.
+          New candidates are sampled *within* the hypersphere.
+        * ``surface``: only sample the surface of the hypersphere.
+    ncandidates : int
+        Number of candidates to sample per iteration. More candidates result
+        in a denser sampling as more candidates can be accepted per iteration.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    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`, this keyword was changed from `seed` 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 `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds of target sample data.
+
+    Notes
+    -----
+    Poisson disk sampling is an iterative sampling strategy. Starting from
+    a seed sample, `ncandidates` are sampled in the hypersphere
+    surrounding the seed. Candidates below a certain `radius` or outside the
+    domain are rejected. New samples are added in a pool of sample seed. The
+    process stops when the pool is empty or when the number of required
+    samples is reached.
+
+    The maximum number of point that a sample can contain is directly linked
+    to the `radius`. As the dimension of the space increases, a higher radius
+    spreads the points further and help overcome the curse of dimensionality.
+    See the :ref:`quasi monte carlo tutorial ` for more
+    details.
+
+    .. warning::
+
+       The algorithm is more suitable for low dimensions and sampling size
+       due to its iterative nature and memory requirements.
+       Selecting a small radius with a high dimension would
+       mean that the space could contain more samples than using lower
+       dimension or a bigger radius.
+
+    Some code taken from [2]_, written consent given on 31.03.2021
+    by the original author, Shamis, for free use in SciPy under
+    the 3-clause BSD.
+
+    References
+    ----------
+    .. [1] Robert Bridson, "Fast Poisson Disk Sampling in Arbitrary
+       Dimensions." SIGGRAPH, 2007.
+    .. [2] `StackOverflow `__.
+
+    Examples
+    --------
+    Generate a 2D sample using a `radius` of 0.2.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from matplotlib.collections import PatchCollection
+    >>> from scipy.stats import qmc
+    >>>
+    >>> rng = np.random.default_rng()
+    >>> radius = 0.2
+    >>> engine = qmc.PoissonDisk(d=2, radius=radius, rng=rng)
+    >>> sample = engine.random(20)
+
+    Visualizing the 2D sample and showing that no points are closer than
+    `radius`. ``radius/2`` is used to visualize non-intersecting circles.
+    If two samples are exactly at `radius` from each other, then their circle
+    of radius ``radius/2`` will touch.
+
+    >>> fig, ax = plt.subplots()
+    >>> _ = ax.scatter(sample[:, 0], sample[:, 1])
+    >>> circles = [plt.Circle((xi, yi), radius=radius/2, fill=False)
+    ...            for xi, yi in sample]
+    >>> collection = PatchCollection(circles, match_original=True)
+    >>> ax.add_collection(collection)
+    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
+    ...            xlim=[0, 1], ylim=[0, 1])
+    >>> plt.show()
+
+    Such visualization can be seen as circle packing: how many circle can
+    we put in the space. It is a np-hard problem. The method `fill_space`
+    can be used to add samples until no more samples can be added. This is
+    a hard problem and parameters may need to be adjusted manually. Beware of
+    the dimension: as the dimensionality increases, the number of samples
+    required to fill the space increases exponentially
+    (curse-of-dimensionality).
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        d: IntNumber,
+        *,
+        radius: DecimalNumber = 0.05,
+        hypersphere: Literal["volume", "surface"] = "volume",
+        ncandidates: IntNumber = 30,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None,
+        l_bounds: "npt.ArrayLike | None" = None,
+        u_bounds: "npt.ArrayLike | None" = None,
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'radius': radius,
+                           'hypersphere': hypersphere,
+                           'ncandidates': ncandidates,
+                           'optimization': optimization}
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+
+        hypersphere_sample = {
+            "volume": self._hypersphere_volume_sample,
+            "surface": self._hypersphere_surface_sample
+        }
+
+        try:
+            self.hypersphere_method = hypersphere_sample[hypersphere]
+        except KeyError as exc:
+            message = (
+                f"{hypersphere!r} is not a valid hypersphere sampling"
+                f" method. It must be one of {set(hypersphere_sample)!r}")
+            raise ValueError(message) from exc
+
+        # size of the sphere from which the samples are drawn relative to the
+        # size of a disk (radius)
+        # for the surface sampler, all new points are almost exactly 1 radius
+        # away from at least one existing sample +eps to avoid rejection
+        self.radius_factor = 2 if hypersphere == "volume" else 1.001
+        self.radius = radius
+        self.radius_squared = self.radius**2
+
+        # sample to generate per iteration in the hypersphere around center
+        self.ncandidates = ncandidates
+        
+        if u_bounds is None:
+            u_bounds = np.ones(d)
+        if l_bounds is None:
+            l_bounds = np.zeros(d)
+        self.l_bounds, self.u_bounds = _validate_bounds(
+            l_bounds=l_bounds, u_bounds=u_bounds, d=int(d)
+        )
+
+        with np.errstate(divide='ignore'):
+            self.cell_size = self.radius / np.sqrt(self.d)
+            self.grid_size = (
+                np.ceil((self.u_bounds - self.l_bounds) / self.cell_size)
+            ).astype(int)
+
+        self._initialize_grid_pool()
+
+    def _initialize_grid_pool(self):
+        """Sampling pool and sample grid."""
+        self.sample_pool = []
+        # Positions of cells
+        # n-dim value for each grid cell
+        self.sample_grid = np.empty(
+            np.append(self.grid_size, self.d),
+            dtype=np.float32
+        )
+        # Initialise empty cells with NaNs
+        self.sample_grid.fill(np.nan)
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the interval ``[l_bounds, u_bounds]``.
+
+        Note that it can return fewer samples if the space is full.
+        See the note section of the class.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        if n == 0 or self.d == 0:
+            return np.empty((n, self.d))
+
+        def in_limits(sample: np.ndarray) -> bool:
+            for i in range(self.d):
+                if (sample[i] > self.u_bounds[i] or sample[i] < self.l_bounds[i]):
+                    return False
+            return True
+
+        def in_neighborhood(candidate: np.ndarray, n: int = 2) -> bool:
+            """
+            Check if there are samples closer than ``radius_squared`` to the
+            `candidate` sample.
+            """
+            indices = ((candidate - self.l_bounds) / self.cell_size).astype(int)
+            ind_min = np.maximum(indices - n, self.l_bounds.astype(int))
+            ind_max = np.minimum(indices + n + 1, self.grid_size)
+
+            # Check if the center cell is empty
+            if not np.isnan(self.sample_grid[tuple(indices)][0]):
+                return True
+
+            a = [slice(ind_min[i], ind_max[i]) for i in range(self.d)]
+
+            # guards against: invalid value encountered in less as we are
+            # comparing with nan and returns False. Which is wanted.
+            with np.errstate(invalid='ignore'):
+                if np.any(
+                    np.sum(
+                        np.square(candidate - self.sample_grid[tuple(a)]),
+                        axis=self.d
+                    ) < self.radius_squared
+                ):
+                    return True
+
+            return False
+
+        def add_sample(candidate: np.ndarray) -> None:
+            self.sample_pool.append(candidate)
+            indices = ((candidate - self.l_bounds) / self.cell_size).astype(int)
+            self.sample_grid[tuple(indices)] = candidate
+            curr_sample.append(candidate)
+
+        curr_sample: list[np.ndarray] = []
+
+        if len(self.sample_pool) == 0:
+            # the pool is being initialized with a single random sample
+            add_sample(self.rng.uniform(self.l_bounds, self.u_bounds))
+            num_drawn = 1
+        else:
+            num_drawn = 0
+
+        # exhaust sample pool to have up to n sample
+        while len(self.sample_pool) and num_drawn < n:
+            # select a sample from the available pool
+            idx_center = rng_integers(self.rng, len(self.sample_pool))
+            center = self.sample_pool[idx_center]
+            del self.sample_pool[idx_center]
+
+            # generate candidates around the center sample
+            candidates = self.hypersphere_method(
+                center, self.radius * self.radius_factor, self.ncandidates
+            )
+
+            # keep candidates that satisfy some conditions
+            for candidate in candidates:
+                if in_limits(candidate) and not in_neighborhood(candidate):
+                    add_sample(candidate)
+
+                    num_drawn += 1
+                    if num_drawn >= n:
+                        break
+
+        self.num_generated += num_drawn
+        return np.array(curr_sample)
+
+    def fill_space(self) -> np.ndarray:
+        """Draw ``n`` samples in the interval ``[l_bounds, u_bounds]``.
+
+        Unlike `random`, this method will try to add points until
+        the space is full. Depending on ``candidates`` (and to a lesser extent
+        other parameters), some empty areas can still be present in the sample.
+
+        .. warning::
+
+           This can be extremely slow in high dimensions or if the
+           ``radius`` is very small-with respect to the dimensionality.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        return self.random(np.inf)  # type: ignore[arg-type]
+
+    def reset(self) -> "PoissonDisk":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : PoissonDisk
+            Engine reset to its base state.
+
+        """
+        super().reset()
+        self._initialize_grid_pool()
+        return self
+
+    def _hypersphere_volume_sample(
+        self, center: np.ndarray, radius: DecimalNumber,
+        candidates: IntNumber = 1
+    ) -> np.ndarray:
+        """Uniform sampling within hypersphere."""
+        # should remove samples within r/2
+        x = self.rng.standard_normal(size=(candidates, self.d))
+        ssq = np.sum(x**2, axis=1)
+        fr = radius * gammainc(self.d/2, ssq/2)**(1/self.d) / np.sqrt(ssq)
+        fr_tiled = np.tile(
+            fr.reshape(-1, 1), (1, self.d)  # type: ignore[arg-type]
+        )
+        p = center + np.multiply(x, fr_tiled)
+        return p
+
+    def _hypersphere_surface_sample(
+        self, center: np.ndarray, radius: DecimalNumber,
+        candidates: IntNumber = 1
+    ) -> np.ndarray:
+        """Uniform sampling on the hypersphere's surface."""
+        vec = self.rng.standard_normal(size=(candidates, self.d))
+        vec /= np.linalg.norm(vec, axis=1)[:, None]
+        p = center + np.multiply(vec, radius)
+        return p
+
+
+class MultivariateNormalQMC:
+    r"""QMC sampling from a multivariate Normal :math:`N(\mu, \Sigma)`.
+
+    Parameters
+    ----------
+    mean : array_like (d,)
+        The mean vector. Where ``d`` is the dimension.
+    cov : array_like (d, d), optional
+        The covariance matrix. If omitted, use `cov_root` instead.
+        If both `cov` and `cov_root` are omitted, use the identity matrix.
+    cov_root : array_like (d, d'), optional
+        A root decomposition of the covariance matrix, where ``d'`` may be less
+        than ``d`` if the covariance is not full rank. If omitted, use `cov`.
+    inv_transform : bool, optional
+        If True, use inverse transform instead of Box-Muller. Default is True.
+    engine : QMCEngine, optional
+        Quasi-Monte Carlo engine sampler. If None, `Sobol` is 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``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Examples
+    --------
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import qmc
+    >>> dist = qmc.MultivariateNormalQMC(mean=[0, 5], cov=[[1, 0], [0, 1]])
+    >>> sample = dist.random(512)
+    >>> _ = plt.scatter(sample[:, 0], sample[:, 1])
+    >>> plt.show()
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+            self,
+            mean: "npt.ArrayLike",
+            cov: "npt.ArrayLike | None" = None,
+            *,
+            cov_root: "npt.ArrayLike | None" = None,
+            inv_transform: bool = True,
+            engine: QMCEngine | None = None,
+            rng: SeedType = None,
+    ) -> None:
+        mean = np.asarray(np.atleast_1d(mean))
+        d = mean.shape[0]
+        if cov is not None:
+            # covariance matrix provided
+            cov = np.asarray(np.atleast_2d(cov))
+            # check for square/symmetric cov matrix and mean vector has the
+            # same d
+            if not mean.shape[0] == cov.shape[0]:
+                raise ValueError("Dimension mismatch between mean and "
+                                 "covariance.")
+            if not np.allclose(cov, cov.transpose()):
+                raise ValueError("Covariance matrix is not symmetric.")
+            # compute Cholesky decomp; if it fails, do the eigen decomposition
+            try:
+                cov_root = np.linalg.cholesky(cov).transpose()
+            except np.linalg.LinAlgError:
+                eigval, eigvec = np.linalg.eigh(cov)
+                if not np.all(eigval >= -1.0e-8):
+                    raise ValueError("Covariance matrix not PSD.")
+                eigval = np.clip(eigval, 0.0, None)
+                cov_root = (eigvec * np.sqrt(eigval)).transpose()
+        elif cov_root is not None:
+            # root decomposition provided
+            cov_root = np.atleast_2d(cov_root)
+            if not mean.shape[0] == cov_root.shape[0]:
+                raise ValueError("Dimension mismatch between mean and "
+                                 "covariance.")
+        else:
+            # corresponds to identity covariance matrix
+            cov_root = None
+
+        self._inv_transform = inv_transform
+
+        if not inv_transform:
+            # to apply Box-Muller, we need an even number of dimensions
+            engine_dim = 2 * math.ceil(d / 2)
+        else:
+            engine_dim = d
+        if engine is None:
+            # Need this during SPEC 7 transition to prevent `RandomState`
+            # from being passed via `rng`.
+            kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng"
+            kwargs = {kwarg: rng}
+            self.engine = Sobol(
+                d=engine_dim, scramble=True, bits=30, **kwargs
+            )  # type: QMCEngine
+        elif isinstance(engine, QMCEngine):
+            if engine.d != engine_dim:
+                raise ValueError("Dimension of `engine` must be consistent"
+                                 " with dimensions of mean and covariance."
+                                 " If `inv_transform` is False, it must be"
+                                 " an even number.")
+            self.engine = engine
+        else:
+            raise ValueError("`engine` must be an instance of "
+                             "`scipy.stats.qmc.QMCEngine` or `None`.")
+
+        self._mean = mean
+        self._corr_matrix = cov_root
+
+        self._d = d
+
+    def random(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the multivariate Normal.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sample.
+
+        """
+        base_samples = self._standard_normal_samples(n)
+        return self._correlate(base_samples)
+
+    def _correlate(self, base_samples: np.ndarray) -> np.ndarray:
+        if self._corr_matrix is not None:
+            return base_samples @ self._corr_matrix + self._mean
+        else:
+            # avoid multiplying with identity here
+            return base_samples + self._mean
+
+    def _standard_normal_samples(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the standard Normal :math:`N(0, I_d)`.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sample.
+
+        """
+        # get base samples
+        samples = self.engine.random(n)
+        if self._inv_transform:
+            # apply inverse transform
+            # (values to close to 0/1 result in inf values)
+            return stats.norm.ppf(0.5 + (1 - 1e-10) * (samples - 0.5))  # type: ignore[attr-defined]  # noqa: E501
+        else:
+            # apply Box-Muller transform (note: indexes starting from 1)
+            even = np.arange(0, samples.shape[-1], 2)
+            Rs = np.sqrt(-2 * np.log(samples[:, even]))
+            thetas = 2 * math.pi * samples[:, 1 + even]
+            cos = np.cos(thetas)
+            sin = np.sin(thetas)
+            transf_samples = np.stack([Rs * cos, Rs * sin],
+                                      -1).reshape(n, -1)
+            # make sure we only return the number of dimension requested
+            return transf_samples[:, : self._d]
+
+
+class MultinomialQMC:
+    r"""QMC sampling from a multinomial distribution.
+
+    Parameters
+    ----------
+    pvals : array_like (k,)
+        Vector of probabilities of size ``k``, where ``k`` is the number
+        of categories. Elements must be non-negative and sum to 1.
+    n_trials : int
+        Number of trials.
+    engine : QMCEngine, optional
+        Quasi-Monte Carlo engine sampler. If None, `Sobol` is 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``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Examples
+    --------
+    Let's define 3 categories and for a given sample, the sum of the trials
+    of each category is 8. The number of trials per category is determined
+    by the `pvals` associated to each category.
+    Then, we sample this distribution 64 times.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import qmc
+    >>> dist = qmc.MultinomialQMC(
+    ...     pvals=[0.2, 0.4, 0.4], n_trials=10, engine=qmc.Halton(d=1)
+    ... )
+    >>> sample = dist.random(64)
+
+    We can plot the sample and verify that the median of number of trials
+    for each category is following the `pvals`. That would be
+    ``pvals * n_trials = [2, 4, 4]``.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.yaxis.get_major_locator().set_params(integer=True)
+    >>> _ = ax.boxplot(sample)
+    >>> ax.set(xlabel="Categories", ylabel="Trials")
+    >>> plt.show()
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        pvals: "npt.ArrayLike",
+        n_trials: IntNumber,
+        *,
+        engine: QMCEngine | None = None,
+        rng: SeedType = None,
+    ) -> None:
+        self.pvals = np.atleast_1d(np.asarray(pvals))
+        if np.min(pvals) < 0:
+            raise ValueError('Elements of pvals must be non-negative.')
+        if not np.isclose(np.sum(pvals), 1):
+            raise ValueError('Elements of pvals must sum to 1.')
+        self.n_trials = n_trials
+        if engine is None:
+            # Need this during SPEC 7 transition to prevent `RandomState`
+            # from being passed via `rng`.
+            kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng"
+            kwargs = {kwarg: rng}
+            self.engine = Sobol(
+                d=1, scramble=True, bits=30, **kwargs
+            )  # type: QMCEngine
+        elif isinstance(engine, QMCEngine):
+            if engine.d != 1:
+                raise ValueError("Dimension of `engine` must be 1.")
+            self.engine = engine
+        else:
+            raise ValueError("`engine` must be an instance of "
+                             "`scipy.stats.qmc.QMCEngine` or `None`.")
+
+    def random(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the multinomial distribution.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        samples : array_like (n, pvals)
+            Sample.
+
+        """
+        sample = np.empty((n, len(self.pvals)))
+        for i in range(n):
+            base_draws = self.engine.random(self.n_trials).ravel()
+            p_cumulative = np.empty_like(self.pvals, dtype=float)
+            _fill_p_cumulative(np.array(self.pvals, dtype=float), p_cumulative)
+            sample_ = np.zeros_like(self.pvals, dtype=np.intp)
+            _categorize(base_draws, p_cumulative, sample_)
+            sample[i] = sample_
+        return sample
+
+
+def _select_optimizer(
+    optimization: Literal["random-cd", "lloyd"] | None, config: dict
+) -> Callable | None:
+    """A factory for optimization methods."""
+    optimization_method: dict[str, Callable] = {
+        "random-cd": _random_cd,
+        "lloyd": _lloyd_centroidal_voronoi_tessellation
+    }
+
+    optimizer: partial | None
+    if optimization is not None:
+        try:
+            optimization = optimization.lower()  # type: ignore[assignment]
+            optimizer_ = optimization_method[optimization]
+        except KeyError as exc:
+            message = (f"{optimization!r} is not a valid optimization"
+                       f" method. It must be one of"
+                       f" {set(optimization_method)!r}")
+            raise ValueError(message) from exc
+
+        # config
+        optimizer = partial(optimizer_, **config)
+    else:
+        optimizer = None
+
+    return optimizer
+
+
+def _random_cd(
+    best_sample: np.ndarray, n_iters: int, n_nochange: int, rng: GeneratorType,
+    **kwargs: dict
+) -> np.ndarray:
+    """Optimal LHS on CD.
+
+    Create a base LHS and do random permutations of coordinates to
+    lower the centered discrepancy.
+    Because it starts with a normal LHS, it also works with the
+    `scramble` keyword argument.
+
+    Two stopping criterion are used to stop the algorithm: at most,
+    `n_iters` iterations are performed; or if there is no improvement
+    for `n_nochange` consecutive iterations.
+    """
+    del kwargs  # only use keywords which are defined, needed by factory
+
+    n, d = best_sample.shape
+
+    if d == 0 or n == 0:
+        return np.empty((n, d))
+
+    if d == 1 or n == 1:
+        # discrepancy measures are invariant under permuting factors and runs
+        return best_sample
+
+    best_disc = discrepancy(best_sample)
+
+    bounds = ([0, d - 1],
+              [0, n - 1],
+              [0, n - 1])
+
+    n_nochange_ = 0
+    n_iters_ = 0
+    while n_nochange_ < n_nochange and n_iters_ < n_iters:
+        n_iters_ += 1
+
+        col = rng_integers(rng, *bounds[0], endpoint=True)  # type: ignore[misc]
+        row_1 = rng_integers(rng, *bounds[1], endpoint=True)  # type: ignore[misc]
+        row_2 = rng_integers(rng, *bounds[2], endpoint=True)  # type: ignore[misc]
+        disc = _perturb_discrepancy(best_sample,
+                                    row_1, row_2, col,
+                                    best_disc)
+        if disc < best_disc:
+            best_sample[row_1, col], best_sample[row_2, col] = (
+                best_sample[row_2, col], best_sample[row_1, col])
+
+            best_disc = disc
+            n_nochange_ = 0
+        else:
+            n_nochange_ += 1
+
+    return best_sample
+
+
+def _l1_norm(sample: np.ndarray) -> float:
+    return distance.pdist(sample, 'cityblock').min()
+
+
+def _lloyd_iteration(
+    sample: np.ndarray,
+    decay: float,
+    qhull_options: str
+) -> np.ndarray:
+    """Lloyd-Max algorithm iteration.
+
+    Based on the implementation of Stéfan van der Walt:
+
+    https://github.com/stefanv/lloyd
+
+    which is:
+
+        Copyright (c) 2021-04-21 Stéfan van der Walt
+        https://github.com/stefanv/lloyd
+        MIT License
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to iterate on.
+    decay : float
+        Relaxation decay. A positive value would move the samples toward
+        their centroid, and negative value would move them away.
+        1 would move the samples to their centroid.
+    qhull_options : str
+        Additional options to pass to Qhull. See Qhull manual
+        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
+        "Qbb Qc Qz Qj" otherwise.)
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        The sample after an iteration of Lloyd's algorithm.
+
+    """
+    new_sample = np.empty_like(sample)
+
+    voronoi = Voronoi(sample, qhull_options=qhull_options)
+
+    for ii, idx in enumerate(voronoi.point_region):
+        # the region is a series of indices into self.voronoi.vertices
+        # remove samples at infinity, designated by index -1
+        region = [i for i in voronoi.regions[idx] if i != -1]
+
+        # get the vertices for this region
+        verts = voronoi.vertices[region]
+
+        # clipping would be wrong, we need to intersect
+        # verts = np.clip(verts, 0, 1)
+
+        # move samples towards centroids:
+        # Centroid in n-D is the mean for uniformly distributed nodes
+        # of a geometry.
+        centroid = np.mean(verts, axis=0)
+        new_sample[ii] = sample[ii] + (centroid - sample[ii]) * decay
+
+    # only update sample to centroid within the region
+    is_valid = np.all(np.logical_and(new_sample >= 0, new_sample <= 1), axis=1)
+    sample[is_valid] = new_sample[is_valid]
+
+    return sample
+
+
+def _lloyd_centroidal_voronoi_tessellation(
+    sample: "npt.ArrayLike",
+    *,
+    tol: DecimalNumber = 1e-5,
+    maxiter: IntNumber = 10,
+    qhull_options: str | None = None,
+    **kwargs: dict
+) -> np.ndarray:
+    """Approximate Centroidal Voronoi Tessellation.
+
+    Perturb samples in N-dimensions using Lloyd-Max algorithm.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to iterate on. With ``n`` the number of samples and ``d``
+        the dimension. Samples must be in :math:`[0, 1]^d`, with ``d>=2``.
+    tol : float, optional
+        Tolerance for termination. If the min of the L1-norm over the samples
+        changes less than `tol`, it stops the algorithm. Default is 1e-5.
+    maxiter : int, optional
+        Maximum number of iterations. It will stop the algorithm even if
+        `tol` is above the threshold.
+        Too many iterations tend to cluster the samples as a hypersphere.
+        Default is 10.
+    qhull_options : str, optional
+        Additional options to pass to Qhull. See Qhull manual
+        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
+        "Qbb Qc Qz Qj" otherwise.)
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        The sample after being processed by Lloyd-Max algorithm.
+
+    Notes
+    -----
+    Lloyd-Max algorithm is an iterative process with the purpose of improving
+    the dispersion of samples. For given sample: (i) compute a Voronoi
+    Tessellation; (ii) find the centroid of each Voronoi cell; (iii) move the
+    samples toward the centroid of their respective cell. See [1]_, [2]_.
+
+    A relaxation factor is used to control how fast samples can move at each
+    iteration. This factor is starting at 2 and ending at 1 after `maxiter`
+    following an exponential decay.
+
+    The process converges to equally spaced samples. It implies that measures
+    like the discrepancy could suffer from too many iterations. On the other
+    hand, L1 and L2 distances should improve. This is especially true with
+    QMC methods which tend to favor the discrepancy over other criteria.
+
+    .. note::
+
+        The current implementation does not intersect the Voronoi Tessellation
+        with the boundaries. This implies that for a low number of samples,
+        empirically below 20, no Voronoi cell is touching the boundaries.
+        Hence, samples cannot be moved close to the boundaries.
+
+        Further improvements could consider the samples at infinity so that
+        all boundaries are segments of some Voronoi cells. This would fix
+        the computation of the centroid position.
+
+    .. warning::
+
+       The Voronoi Tessellation step is expensive and quickly becomes
+       intractable with dimensions as low as 10 even for a sample
+       of size as low as 1000.
+
+    .. versionadded:: 1.9.0
+
+    References
+    ----------
+    .. [1] Lloyd. "Least Squares Quantization in PCM".
+       IEEE Transactions on Information Theory, 1982.
+    .. [2] Max J. "Quantizing for minimum distortion".
+       IEEE Transactions on Information Theory, 1960.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial import distance
+    >>> from scipy.stats._qmc import _lloyd_centroidal_voronoi_tessellation
+    >>> rng = np.random.default_rng()
+    >>> sample = rng.random((128, 2))
+
+    .. note::
+
+        The samples need to be in :math:`[0, 1]^d`. `scipy.stats.qmc.scale`
+        can be used to scale the samples from their
+        original bounds to :math:`[0, 1]^d`. And back to their original bounds.
+
+    Compute the quality of the sample using the L1 criterion.
+
+    >>> def l1_norm(sample):
+    ...    return distance.pdist(sample, 'cityblock').min()
+
+    >>> l1_norm(sample)
+    0.00161...  # random
+
+    Now process the sample using Lloyd's algorithm and check the improvement
+    on the L1. The value should increase.
+
+    >>> sample = _lloyd_centroidal_voronoi_tessellation(sample)
+    >>> l1_norm(sample)
+    0.0278...  # random
+
+    """
+    del kwargs  # only use keywords which are defined, needed by factory
+
+    sample = np.asarray(sample).copy()
+
+    if not sample.ndim == 2:
+        raise ValueError('`sample` is not a 2D array')
+
+    if not sample.shape[1] >= 2:
+        raise ValueError('`sample` dimension is not >= 2')
+
+    # Checking that sample is within the hypercube
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError('`sample` is not in unit hypercube')
+
+    if qhull_options is None:
+        qhull_options = 'Qbb Qc Qz QJ'
+
+        if sample.shape[1] >= 5:
+            qhull_options += ' Qx'
+
+    # Fit an exponential to be 2 at 0 and 1 at `maxiter`.
+    # The decay is used for relaxation.
+    # analytical solution for y=exp(-maxiter/x) - 0.1
+    root = -maxiter / np.log(0.1)
+    decay = [np.exp(-x / root)+0.9 for x in range(maxiter)]
+
+    l1_old = _l1_norm(sample=sample)
+    for i in range(maxiter):
+        sample = _lloyd_iteration(
+                sample=sample, decay=decay[i],
+                qhull_options=qhull_options,
+        )
+
+        l1_new = _l1_norm(sample=sample)
+
+        if abs(l1_new - l1_old) < tol:
+            break
+        else:
+            l1_old = l1_new
+
+    return sample
+
+
+def _validate_workers(workers: IntNumber = 1) -> IntNumber:
+    """Validate `workers` based on platform and value.
+
+    Parameters
+    ----------
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is
+        given all CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    Workers : int
+        Number of CPU used by the algorithm
+
+    """
+    workers = int(workers)
+    if workers == -1:
+        workers = os.cpu_count()  # type: ignore[assignment]
+        if workers is None:
+            raise NotImplementedError(
+                "Cannot determine the number of cpus using os.cpu_count(), "
+                "cannot use -1 for the number of workers"
+            )
+    elif workers <= 0:
+        raise ValueError(f"Invalid number of workers: {workers}, must be -1 "
+                         "or > 0")
+
+    return workers
+
+
+def _validate_bounds(
+    l_bounds: "npt.ArrayLike", u_bounds: "npt.ArrayLike", d: int
+) -> "tuple[npt.NDArray[np.generic], npt.NDArray[np.generic]]":
+    """Bounds input validation.
+
+    Parameters
+    ----------
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds.
+    d : int
+        Dimension to use for broadcasting.
+
+    Returns
+    -------
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds.
+
+    """
+    try:
+        lower = np.broadcast_to(l_bounds, d)
+        upper = np.broadcast_to(u_bounds, d)
+    except ValueError as exc:
+        msg = ("'l_bounds' and 'u_bounds' must be broadcastable and respect"
+               " the sample dimension")
+        raise ValueError(msg) from exc
+
+    if not np.all(lower < upper):
+        raise ValueError("Bounds are not consistent 'l_bounds' < 'u_bounds'")
+
+    return lower, upper
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..5e5af2ac01b5a8b05fa7e25089739c79da3e0352
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.pyi b/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c154ead5f1d93572a41e30bbdd68a082ec774af7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_qmc_cy.pyi
@@ -0,0 +1,54 @@
+import numpy as np
+from scipy._lib._util import DecimalNumber, IntNumber
+
+
+def _cy_wrapper_centered_discrepancy(
+        sample: np.ndarray, 
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_wrap_around_discrepancy(
+        sample: np.ndarray,
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_mixture_discrepancy(
+        sample: np.ndarray,
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_l2_star_discrepancy(
+        sample: np.ndarray,
+        iterative: bool,
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_update_discrepancy(
+        x_new_view: np.ndarray,
+        sample_view: np.ndarray,
+        initial_disc: DecimalNumber,
+) -> float: ...
+
+
+def _cy_van_der_corput(
+        n: IntNumber,
+        base: IntNumber,
+        start_index: IntNumber,
+        workers: IntNumber,
+) -> np.ndarray: ...
+
+
+def _cy_van_der_corput_scrambled(
+        n: IntNumber,
+        base: IntNumber,
+        start_index: IntNumber,
+        permutations: np.ndarray,
+        workers: IntNumber,
+) -> np.ndarray: ...
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_qmvnt.py b/python_embeded/Lib/site-packages/scipy/stats/_qmvnt.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4066b594c9de7732e6fa528407852acf934b80c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_qmvnt.py
@@ -0,0 +1,533 @@
+# Integration of multivariate normal and t distributions.
+
+# Adapted from the MATLAB original implementations by Dr. Alan Genz.
+
+#     http://www.math.wsu.edu/faculty/genz/software/software.html
+
+# Copyright (C) 2013, Alan Genz,  All rights reserved.
+# Python implementation is copyright (C) 2022, Robert Kern,  All rights
+# reserved.
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided 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 contributor name(s) may not 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 USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+import numpy as np
+
+from scipy.fft import fft, ifft
+from scipy.special import gammaincinv, ndtr, ndtri
+from scipy.stats._qmc import primes_from_2_to
+
+
+phi = ndtr
+phinv = ndtri
+
+
+def _factorize_int(n):
+    """Return a sorted list of the unique prime factors of a positive integer.
+    """
+    # NOTE: There are lots faster ways to do this, but this isn't terrible.
+    factors = set()
+    for p in primes_from_2_to(int(np.sqrt(n)) + 1):
+        while not (n % p):
+            factors.add(p)
+            n //= p
+        if n == 1:
+            break
+    if n != 1:
+        factors.add(n)
+    return sorted(factors)
+
+
+def _primitive_root(p):
+    """Compute a primitive root of the prime number `p`.
+
+    Used in the CBC lattice construction.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n
+    """
+    # p is prime
+    pm = p - 1
+    factors = _factorize_int(pm)
+    n = len(factors)
+    r = 2
+    k = 0
+    while k < n:
+        d = pm // factors[k]
+        # pow() doesn't like numpy scalar types.
+        rd = pow(int(r), int(d), int(p))
+        if rd == 1:
+            r += 1
+            k = 0
+        else:
+            k += 1
+    return r
+
+
+def _cbc_lattice(n_dim, n_qmc_samples):
+    """Compute a QMC lattice generator using a Fast CBC construction.
+
+    Parameters
+    ----------
+    n_dim : int > 0
+        The number of dimensions for the lattice.
+    n_qmc_samples : int > 0
+        The desired number of QMC samples. This will be rounded down to the
+        nearest prime to enable the CBC construction.
+
+    Returns
+    -------
+    q : float array : shape=(n_dim,)
+        The lattice generator vector. All values are in the open interval
+        ``(0, 1)``.
+    actual_n_qmc_samples : int
+        The prime number of QMC samples that must be used with this lattice,
+        no more, no less.
+
+    References
+    ----------
+    .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction,
+           a Reprise for Different Kernels", In H. Niederreiter and D. Talay,
+           editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004,
+           Springer-Verlag, 2006, 371-385.
+    """
+    # Round down to the nearest prime number.
+    primes = primes_from_2_to(n_qmc_samples + 1)
+    n_qmc_samples = primes[-1]
+
+    bt = np.ones(n_dim)
+    gm = np.hstack([1.0, 0.8 ** np.arange(n_dim - 1)])
+    q = 1
+    w = 0
+    z = np.arange(1, n_dim + 1)
+    m = (n_qmc_samples - 1) // 2
+    g = _primitive_root(n_qmc_samples)
+    # Slightly faster way to compute perm[j] = pow(g, j, n_qmc_samples)
+    # Shame that we don't have modulo pow() implemented as a ufunc.
+    perm = np.ones(m, dtype=int)
+    for j in range(m - 1):
+        perm[j + 1] = (g * perm[j]) % n_qmc_samples
+    perm = np.minimum(n_qmc_samples - perm, perm)
+    pn = perm / n_qmc_samples
+    c = pn * pn - pn + 1.0 / 6
+    fc = fft(c)
+    for s in range(1, n_dim):
+        reordered = np.hstack([
+            c[:w+1][::-1],
+            c[w+1:m][::-1],
+        ])
+        q = q * (bt[s-1] + gm[s-1] * reordered)
+        w = ifft(fc * fft(q)).real.argmin()
+        z[s] = perm[w]
+    q = z / n_qmc_samples
+    return q, n_qmc_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the development of a parameter for users
+# to set the desired CDF accuracy, but must be reviewed and tested before use.
+def _qauto(func, covar, low, high, rng, error=1e-3, limit=10_000, **kwds):
+    """Automatically rerun the integration to get the required error bound.
+
+    Parameters
+    ----------
+    func : callable
+        Either :func:`_qmvn` or :func:`_qmvt`.
+    covar, low, high : array
+        As specified in :func:`_qmvn` and :func:`_qmvt`.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    error : float > 0
+        The desired error bound.
+    limit : int > 0:
+        The rough limit of the number of integration points to consider. The
+        integration will stop looping once this limit has been *exceeded*.
+    **kwds :
+        Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be
+        sure to include ``nu=`` as one of these.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    n_samples : int
+        The number of integration points actually used.
+    """
+    n = len(covar)
+    n_samples = 0
+    if n == 1:
+        prob = phi(high) - phi(low)
+        # More or less
+        est_error = 1e-15
+    else:
+        mi = min(limit, n * 1000)
+        prob = 0.0
+        est_error = 1.0
+        ei = 0.0
+        while est_error > error and n_samples < limit:
+            mi = round(np.sqrt(2) * mi)
+            pi, ei, ni = func(mi, covar, low, high, rng=rng, **kwds)
+            n_samples += ni
+            wt = 1.0 / (1 + (ei / est_error)**2)
+            prob += wt * (pi - prob)
+            est_error = np.sqrt(wt) * ei
+    return prob, est_error, n_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the resolution of gh-8367, gh-16142, and
+# possibly gh-14286, but must be reviewed and tested before use.
+def _qmvn(m, covar, low, high, rng, lattice='cbc', n_batches=10):
+    """Multivariate normal integration over box bounds.
+
+    Parameters
+    ----------
+    m : int > n_batches
+        The number of points to sample. This number will be divided into
+        `n_batches` batches that apply random offsets of the sampling lattice
+        for each batch in order to estimate the error.
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    lattice : 'cbc' or callable
+        The type of lattice rule to use to construct the integration points.
+    n_batches : int > 0, optional
+        The number of QMC batches to apply.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    """
+    cho, lo, hi = _permuted_cholesky(covar, low, high)
+    n = cho.shape[0]
+    ct = cho[0, 0]
+    c = phi(lo[0] / ct)
+    d = phi(hi[0] / ct)
+    ci = c
+    dci = d - ci
+    prob = 0.0
+    error_var = 0.0
+    q, n_qmc_samples = _cbc_lattice(n - 1, max(m // n_batches, 1))
+    y = np.zeros((n - 1, n_qmc_samples))
+    i_samples = np.arange(n_qmc_samples) + 1
+    for j in range(n_batches):
+        c = np.full(n_qmc_samples, ci)
+        dc = np.full(n_qmc_samples, dci)
+        pv = dc.copy()
+        for i in range(1, n):
+            # Pseudorandomly-shifted lattice coordinate.
+            z = q[i - 1] * i_samples + rng.random()
+            # Fast remainder(z, 1.0)
+            z -= z.astype(int)
+            # Tent periodization transform.
+            x = abs(2 * z - 1)
+            y[i - 1, :] = phinv(c + x * dc)
+            s = cho[i, :i] @ y[:i, :]
+            ct = cho[i, i]
+            c = phi((lo[i] - s) / ct)
+            d = phi((hi[i] - s) / ct)
+            dc = d - c
+            pv = pv * dc
+        # Accumulate the mean and error variances with online formulations.
+        d = (pv.mean() - prob) / (j + 1)
+        prob += d
+        error_var = (j - 1) * error_var / (j + 1) + d * d
+    # Error bounds are 3 times the standard error of the estimates.
+    est_error = 3 * np.sqrt(error_var)
+    n_samples = n_qmc_samples * n_batches
+    return prob, est_error, n_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the resolution of gh-8367, gh-16142, and
+# possibly gh-14286, but must be reviewed and tested before use.
+def _mvn_qmc_integrand(covar, low, high, use_tent=False):
+    """Transform the multivariate normal integration into a QMC integrand over
+    a unit hypercube.
+
+    The dimensionality of the resulting hypercube integration domain is one
+    less than the dimensionality of the original integrand. Note that this
+    transformation subsumes the integration bounds in order to account for
+    infinite bounds. The QMC integration one does with the returned integrand
+    should be on the unit hypercube.
+
+    Parameters
+    ----------
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    use_tent : bool, optional
+        If True, then use tent periodization. Only helpful for lattice rules.
+
+    Returns
+    -------
+    integrand : Callable[[NDArray], NDArray]
+        The QMC-integrable integrand. It takes an
+        ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit
+        hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these
+        QMC points.
+    ndim_integrand : int
+        The dimensionality of the integrand. Equal to ``n-1``.
+    """
+    cho, lo, hi = _permuted_cholesky(covar, low, high)
+    n = cho.shape[0]
+    ndim_integrand = n - 1
+    ct = cho[0, 0]
+    c = phi(lo[0] / ct)
+    d = phi(hi[0] / ct)
+    ci = c
+    dci = d - ci
+
+    def integrand(*zs):
+        ndim_qmc = len(zs)
+        n_qmc_samples = len(np.atleast_1d(zs[0]))
+        assert ndim_qmc == ndim_integrand
+        y = np.zeros((ndim_qmc, n_qmc_samples))
+        c = np.full(n_qmc_samples, ci)
+        dc = np.full(n_qmc_samples, dci)
+        pv = dc.copy()
+        for i in range(1, n):
+            if use_tent:
+                # Tent periodization transform.
+                x = abs(2 * zs[i-1] - 1)
+            else:
+                x = zs[i-1]
+            y[i - 1, :] = phinv(c + x * dc)
+            s = cho[i, :i] @ y[:i, :]
+            ct = cho[i, i]
+            c = phi((lo[i] - s) / ct)
+            d = phi((hi[i] - s) / ct)
+            dc = d - c
+            pv = pv * dc
+        return pv
+
+    return integrand, ndim_integrand
+
+
+def _qmvt(m, nu, covar, low, high, rng, lattice='cbc', n_batches=10):
+    """Multivariate t integration over box bounds.
+
+    Parameters
+    ----------
+    m : int > n_batches
+        The number of points to sample. This number will be divided into
+        `n_batches` batches that apply random offsets of the sampling lattice
+        for each batch in order to estimate the error.
+    nu : float >= 0
+        The shape parameter of the multivariate t distribution.
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    lattice : 'cbc' or callable
+        The type of lattice rule to use to construct the integration points.
+    n_batches : int > 0, optional
+        The number of QMC batches to apply.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    n_samples : int
+        The number of samples actually used.
+    """
+    sn = max(1.0, np.sqrt(nu))
+    low = np.asarray(low, dtype=np.float64)
+    high = np.asarray(high, dtype=np.float64)
+    cho, lo, hi = _permuted_cholesky(covar, low / sn, high / sn)
+    n = cho.shape[0]
+    prob = 0.0
+    error_var = 0.0
+    q, n_qmc_samples = _cbc_lattice(n, max(m // n_batches, 1))
+    i_samples = np.arange(n_qmc_samples) + 1
+    for j in range(n_batches):
+        pv = np.ones(n_qmc_samples)
+        s = np.zeros((n, n_qmc_samples))
+        for i in range(n):
+            # Pseudorandomly-shifted lattice coordinate.
+            z = q[i] * i_samples + rng.random()
+            # Fast remainder(z, 1.0)
+            z -= z.astype(int)
+            # Tent periodization transform.
+            x = abs(2 * z - 1)
+            # FIXME: Lift the i==0 case out of the loop to make the logic
+            # easier to follow.
+            if i == 0:
+                # We'll use one of the QR variates to pull out the
+                # t-distribution scaling.
+                if nu > 0:
+                    r = np.sqrt(2 * gammaincinv(nu / 2, x))
+                else:
+                    r = np.ones_like(x)
+            else:
+                y = phinv(c + x * dc)  # noqa: F821
+                with np.errstate(invalid='ignore'):
+                    s[i:, :] += cho[i:, i - 1][:, np.newaxis] * y
+            si = s[i, :]
+
+            c = np.ones(n_qmc_samples)
+            d = np.ones(n_qmc_samples)
+            with np.errstate(invalid='ignore'):
+                lois = lo[i] * r - si
+                hiis = hi[i] * r - si
+            c[lois < -9] = 0.0
+            d[hiis < -9] = 0.0
+            lo_mask = abs(lois) < 9
+            hi_mask = abs(hiis) < 9
+            c[lo_mask] = phi(lois[lo_mask])
+            d[hi_mask] = phi(hiis[hi_mask])
+
+            dc = d - c
+            pv *= dc
+
+        # Accumulate the mean and error variances with online formulations.
+        d = (pv.mean() - prob) / (j + 1)
+        prob += d
+        error_var = (j - 1) * error_var / (j + 1) + d * d
+    # Error bounds are 3 times the standard error of the estimates.
+    est_error = 3 * np.sqrt(error_var)
+    n_samples = n_qmc_samples * n_batches
+    return prob, est_error, n_samples
+
+
+def _permuted_cholesky(covar, low, high, tol=1e-10):
+    """Compute a scaled, permuted Cholesky factor, with integration bounds.
+
+    The scaling and permuting of the dimensions accomplishes part of the
+    transformation of the original integration problem into a more numerically
+    tractable form. The lower-triangular Cholesky factor will then be used in
+    the subsequent integration. The integration bounds will be scaled and
+    permuted as well.
+
+    Parameters
+    ----------
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    tol : float, optional
+        The singularity tolerance.
+
+    Returns
+    -------
+    cho : (n, n) float array
+        Lower Cholesky factor, scaled and permuted.
+    new_low, new_high : (n,) float array
+        The scaled and permuted low and high integration bounds.
+    """
+    # Make copies for outputting.
+    cho = np.array(covar, dtype=np.float64)
+    new_lo = np.array(low, dtype=np.float64)
+    new_hi = np.array(high, dtype=np.float64)
+    n = cho.shape[0]
+    if cho.shape != (n, n):
+        raise ValueError("expected a square symmetric array")
+    if new_lo.shape != (n,) or new_hi.shape != (n,):
+        raise ValueError(
+            "expected integration boundaries the same dimensions "
+            "as the covariance matrix"
+        )
+    # Scale by the sqrt of the diagonal.
+    dc = np.sqrt(np.maximum(np.diag(cho), 0.0))
+    # But don't divide by 0.
+    dc[dc == 0.0] = 1.0
+    new_lo /= dc
+    new_hi /= dc
+    cho /= dc
+    cho /= dc[:, np.newaxis]
+
+    y = np.zeros(n)
+    sqtp = np.sqrt(2 * np.pi)
+    for k in range(n):
+        epk = (k + 1) * tol
+        im = k
+        ck = 0.0
+        dem = 1.0
+        s = 0.0
+        lo_m = 0.0
+        hi_m = 0.0
+        for i in range(k, n):
+            if cho[i, i] > tol:
+                ci = np.sqrt(cho[i, i])
+                if i > 0:
+                    s = cho[i, :k] @ y[:k]
+                lo_i = (new_lo[i] - s) / ci
+                hi_i = (new_hi[i] - s) / ci
+                de = phi(hi_i) - phi(lo_i)
+                if de <= dem:
+                    ck = ci
+                    dem = de
+                    lo_m = lo_i
+                    hi_m = hi_i
+                    im = i
+        if im > k:
+            # Swap im and k
+            cho[im, im] = cho[k, k]
+            _swap_slices(cho, np.s_[im, :k], np.s_[k, :k])
+            _swap_slices(cho, np.s_[im + 1:, im], np.s_[im + 1:, k])
+            _swap_slices(cho, np.s_[k + 1:im, k], np.s_[im, k + 1:im])
+            _swap_slices(new_lo, k, im)
+            _swap_slices(new_hi, k, im)
+        if ck > epk:
+            cho[k, k] = ck
+            cho[k, k + 1:] = 0.0
+            for i in range(k + 1, n):
+                cho[i, k] /= ck
+                cho[i, k + 1:i + 1] -= cho[i, k] * cho[k + 1:i + 1, k]
+            if abs(dem) > tol:
+                y[k] = ((np.exp(-lo_m * lo_m / 2) - np.exp(-hi_m * hi_m / 2)) /
+                        (sqtp * dem))
+            else:
+                y[k] = (lo_m + hi_m) / 2
+                if lo_m < -10:
+                    y[k] = hi_m
+                elif hi_m > 10:
+                    y[k] = lo_m
+            cho[k, :k + 1] /= ck
+            new_lo[k] /= ck
+            new_hi[k] /= ck
+        else:
+            cho[k:, k] = 0.0
+            y[k] = (new_lo[k] + new_hi[k]) / 2
+    return cho, new_lo, new_hi
+
+
+def _swap_slices(x, slc1, slc2):
+    t = x[slc1].copy()
+    x[slc1] = x[slc2].copy()
+    x[slc2] = t
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_relative_risk.py b/python_embeded/Lib/site-packages/scipy/stats/_relative_risk.py
new file mode 100644
index 0000000000000000000000000000000000000000..9da8ac3fcaece6e0a56a70c4789a46ffa918c0a8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_relative_risk.py
@@ -0,0 +1,263 @@
+import operator
+from dataclasses import dataclass
+import numpy as np
+from scipy.special import ndtri
+from ._common import ConfidenceInterval
+
+
+def _validate_int(n, bound, name):
+    msg = f'{name} must be an integer not less than {bound}, but got {n!r}'
+    try:
+        n = operator.index(n)
+    except TypeError:
+        raise TypeError(msg) from None
+    if n < bound:
+        raise ValueError(msg)
+    return n
+
+
+@dataclass
+class RelativeRiskResult:
+    """
+    Result of `scipy.stats.contingency.relative_risk`.
+
+    Attributes
+    ----------
+    relative_risk : float
+        This is::
+
+            (exposed_cases/exposed_total) / (control_cases/control_total)
+
+    exposed_cases : int
+        The number of "cases" (i.e. occurrence of disease or other event
+        of interest) among the sample of "exposed" individuals.
+    exposed_total : int
+        The total number of "exposed" individuals in the sample.
+    control_cases : int
+        The number of "cases" among the sample of "control" or non-exposed
+        individuals.
+    control_total : int
+        The total number of "control" individuals in the sample.
+
+    Methods
+    -------
+    confidence_interval :
+        Compute the confidence interval for the relative risk estimate.
+    """
+
+    relative_risk: float
+    exposed_cases: int
+    exposed_total: int
+    control_cases: int
+    control_total: int
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Compute the confidence interval for the relative risk.
+
+        The confidence interval is computed using the Katz method
+        (i.e. "Method C" of [1]_; see also [2]_, section 3.1.2).
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            The confidence level to use for the confidence interval.
+            Default is 0.95.
+
+        Returns
+        -------
+        ci : ConfidenceInterval instance
+            The return value is an object with attributes ``low`` and
+            ``high`` that hold the confidence interval.
+
+        References
+        ----------
+        .. [1] D. Katz, J. Baptista, S. P. Azen and M. C. Pike, "Obtaining
+               confidence intervals for the risk ratio in cohort studies",
+               Biometrics, 34, 469-474 (1978).
+        .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
+               CRC Press LLC, Boca Raton, FL, USA (1996).
+
+
+        Examples
+        --------
+        >>> from scipy.stats.contingency import relative_risk
+        >>> result = relative_risk(exposed_cases=10, exposed_total=75,
+        ...                        control_cases=12, control_total=225)
+        >>> result.relative_risk
+        2.5
+        >>> result.confidence_interval()
+        ConfidenceInterval(low=1.1261564003469628, high=5.549850800541033)
+        """
+        if not 0 <= confidence_level <= 1:
+            raise ValueError('confidence_level must be in the interval '
+                             '[0, 1].')
+
+        # Handle edge cases where either exposed_cases or control_cases
+        # is zero.  We follow the convention of the R function riskratio
+        # from the epitools library.
+        if self.exposed_cases == 0 and self.control_cases == 0:
+            # relative risk is nan.
+            return ConfidenceInterval(low=np.nan, high=np.nan)
+        elif self.exposed_cases == 0:
+            # relative risk is 0.
+            return ConfidenceInterval(low=0.0, high=np.nan)
+        elif self.control_cases == 0:
+            # relative risk is inf
+            return ConfidenceInterval(low=np.nan, high=np.inf)
+
+        alpha = 1 - confidence_level
+        z = ndtri(1 - alpha/2)
+        rr = self.relative_risk
+
+        # Estimate of the variance of log(rr) is
+        # var(log(rr)) = 1/exposed_cases - 1/exposed_total +
+        #                1/control_cases - 1/control_total
+        # and the standard error is the square root of that.
+        se = np.sqrt(1/self.exposed_cases - 1/self.exposed_total +
+                     1/self.control_cases - 1/self.control_total)
+        delta = z*se
+        katz_lo = rr*np.exp(-delta)
+        katz_hi = rr*np.exp(delta)
+        return ConfidenceInterval(low=katz_lo, high=katz_hi)
+
+
+def relative_risk(exposed_cases, exposed_total, control_cases, control_total):
+    """
+    Compute the relative risk (also known as the risk ratio).
+
+    This function computes the relative risk associated with a 2x2
+    contingency table ([1]_, section 2.2.3; [2]_, section 3.1.2). Instead
+    of accepting a table as an argument, the individual numbers that are
+    used to compute the relative risk are given as separate parameters.
+    This is to avoid the ambiguity of which row or column of the contingency
+    table corresponds to the "exposed" cases and which corresponds to the
+    "control" cases.  Unlike, say, the odds ratio, the relative risk is not
+    invariant under an interchange of the rows or columns.
+
+    Parameters
+    ----------
+    exposed_cases : nonnegative int
+        The number of "cases" (i.e. occurrence of disease or other event
+        of interest) among the sample of "exposed" individuals.
+    exposed_total : positive int
+        The total number of "exposed" individuals in the sample.
+    control_cases : nonnegative int
+        The number of "cases" among the sample of "control" or non-exposed
+        individuals.
+    control_total : positive int
+        The total number of "control" individuals in the sample.
+
+    Returns
+    -------
+    result : instance of `~scipy.stats._result_classes.RelativeRiskResult`
+        The object has the float attribute ``relative_risk``, which is::
+
+            rr = (exposed_cases/exposed_total) / (control_cases/control_total)
+
+        The object also has the method ``confidence_interval`` to compute
+        the confidence interval of the relative risk for a given confidence
+        level.
+
+    See Also
+    --------
+    odds_ratio
+
+    Notes
+    -----
+    The R package epitools has the function `riskratio`, which accepts
+    a table with the following layout::
+
+                        disease=0   disease=1
+        exposed=0 (ref)    n00         n01
+        exposed=1          n10         n11
+
+    With a 2x2 table in the above format, the estimate of the CI is
+    computed by `riskratio` when the argument method="wald" is given,
+    or with the function `riskratio.wald`.
+
+    For example, in a test of the incidence of lung cancer among a
+    sample of smokers and nonsmokers, the "exposed" category would
+    correspond to "is a smoker" and the "disease" category would
+    correspond to "has or had lung cancer".
+
+    To pass the same data to ``relative_risk``, use::
+
+        relative_risk(n11, n10 + n11, n01, n00 + n01)
+
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] Alan Agresti, An Introduction to Categorical Data Analysis
+           (second edition), Wiley, Hoboken, NJ, USA (2007).
+    .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
+           CRC Press LLC, Boca Raton, FL, USA (1996).
+
+    Examples
+    --------
+    >>> from scipy.stats.contingency import relative_risk
+
+    This example is from Example 3.1 of [2]_.  The results of a heart
+    disease study are summarized in the following table::
+
+                 High CAT   Low CAT    Total
+                 --------   -------    -----
+        CHD         27         44        71
+        No CHD      95        443       538
+
+        Total      122        487       609
+
+    CHD is coronary heart disease, and CAT refers to the level of
+    circulating catecholamine.  CAT is the "exposure" variable, and
+    high CAT is the "exposed" category. So the data from the table
+    to be passed to ``relative_risk`` is::
+
+        exposed_cases = 27
+        exposed_total = 122
+        control_cases = 44
+        control_total = 487
+
+    >>> result = relative_risk(27, 122, 44, 487)
+    >>> result.relative_risk
+    2.4495156482861398
+
+    Find the confidence interval for the relative risk.
+
+    >>> result.confidence_interval(confidence_level=0.95)
+    ConfidenceInterval(low=1.5836990926700116, high=3.7886786315466354)
+
+    The interval does not contain 1, so the data supports the statement
+    that high CAT is associated with greater risk of CHD.
+    """
+    # Relative risk is a trivial calculation.  The nontrivial part is in the
+    # `confidence_interval` method of the RelativeRiskResult class.
+
+    exposed_cases = _validate_int(exposed_cases, 0, "exposed_cases")
+    exposed_total = _validate_int(exposed_total, 1, "exposed_total")
+    control_cases = _validate_int(control_cases, 0, "control_cases")
+    control_total = _validate_int(control_total, 1, "control_total")
+
+    if exposed_cases > exposed_total:
+        raise ValueError('exposed_cases must not exceed exposed_total.')
+    if control_cases > control_total:
+        raise ValueError('control_cases must not exceed control_total.')
+
+    if exposed_cases == 0 and control_cases == 0:
+        # relative risk is 0/0.
+        rr = np.nan
+    elif exposed_cases == 0:
+        # relative risk is 0/nonzero
+        rr = 0.0
+    elif control_cases == 0:
+        # relative risk is nonzero/0.
+        rr = np.inf
+    else:
+        p1 = exposed_cases / exposed_total
+        p2 = control_cases / control_total
+        rr = p1 / p2
+    return RelativeRiskResult(relative_risk=rr,
+                              exposed_cases=exposed_cases,
+                              exposed_total=exposed_total,
+                              control_cases=control_cases,
+                              control_total=control_total)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_resampling.py b/python_embeded/Lib/site-packages/scipy/stats/_resampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..930b62ec7213cf2557f938d8cbe8399648f31985
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_resampling.py
@@ -0,0 +1,2377 @@
+import warnings
+import numpy as np
+from itertools import combinations, permutations, product
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+import inspect
+
+from scipy._lib._util import (check_random_state, _rename_parameter, rng_integers,
+                              _transition_to_rng)
+from scipy._lib._array_api import array_namespace, is_numpy, xp_moveaxis_to_end
+from scipy.special import ndtr, ndtri, comb, factorial
+
+from ._common import ConfidenceInterval
+from ._axis_nan_policy import _broadcast_concatenate, _broadcast_arrays
+from ._warnings_errors import DegenerateDataWarning
+
+__all__ = ['bootstrap', 'monte_carlo_test', 'permutation_test']
+
+
+def _vectorize_statistic(statistic):
+    """Vectorize an n-sample statistic"""
+    # This is a little cleaner than np.nditer at the expense of some data
+    # copying: concatenate samples together, then use np.apply_along_axis
+    def stat_nd(*data, axis=0):
+        lengths = [sample.shape[axis] for sample in data]
+        split_indices = np.cumsum(lengths)[:-1]
+        z = _broadcast_concatenate(data, axis)
+
+        # move working axis to position 0 so that new dimensions in the output
+        # of `statistic` are _prepended_. ("This axis is removed, and replaced
+        # with new dimensions...")
+        z = np.moveaxis(z, axis, 0)
+
+        def stat_1d(z):
+            data = np.split(z, split_indices)
+            return statistic(*data)
+
+        return np.apply_along_axis(stat_1d, 0, z)[()]
+    return stat_nd
+
+
+def _jackknife_resample(sample, batch=None):
+    """Jackknife resample the sample. Only one-sample stats for now."""
+    n = sample.shape[-1]
+    batch_nominal = batch or n
+
+    for k in range(0, n, batch_nominal):
+        # col_start:col_end are the observations to remove
+        batch_actual = min(batch_nominal, n-k)
+
+        # jackknife - each row leaves out one observation
+        j = np.ones((batch_actual, n), dtype=bool)
+        np.fill_diagonal(j[:, k:k+batch_actual], False)
+        i = np.arange(n)
+        i = np.broadcast_to(i, (batch_actual, n))
+        i = i[j].reshape((batch_actual, n-1))
+
+        resamples = sample[..., i]
+        yield resamples
+
+
+def _bootstrap_resample(sample, n_resamples=None, rng=None):
+    """Bootstrap resample the sample."""
+    n = sample.shape[-1]
+
+    # bootstrap - each row is a random resample of original observations
+    i = rng_integers(rng, 0, n, (n_resamples, n))
+
+    resamples = sample[..., i]
+    return resamples
+
+
+def _percentile_of_score(a, score, axis):
+    """Vectorized, simplified `scipy.stats.percentileofscore`.
+    Uses logic of the 'mean' value of percentileofscore's kind parameter.
+
+    Unlike `stats.percentileofscore`, the percentile returned is a fraction
+    in [0, 1].
+    """
+    B = a.shape[axis]
+    return ((a < score).sum(axis=axis) + (a <= score).sum(axis=axis)) / (2 * B)
+
+
+def _percentile_along_axis(theta_hat_b, alpha):
+    """`np.percentile` with different percentile for each slice."""
+    # the difference between _percentile_along_axis and np.percentile is that
+    # np.percentile gets _all_ the qs for each axis slice, whereas
+    # _percentile_along_axis gets the q corresponding with each axis slice
+    shape = theta_hat_b.shape[:-1]
+    alpha = np.broadcast_to(alpha, shape)
+    percentiles = np.zeros_like(alpha, dtype=np.float64)
+    for indices, alpha_i in np.ndenumerate(alpha):
+        if np.isnan(alpha_i):
+            # e.g. when bootstrap distribution has only one unique element
+            msg = (
+                "The BCa confidence interval cannot be calculated."
+                " This problem is known to occur when the distribution"
+                " is degenerate or the statistic is np.min."
+            )
+            warnings.warn(DegenerateDataWarning(msg), stacklevel=3)
+            percentiles[indices] = np.nan
+        else:
+            theta_hat_b_i = theta_hat_b[indices]
+            percentiles[indices] = np.percentile(theta_hat_b_i, alpha_i)
+    return percentiles[()]  # return scalar instead of 0d array
+
+
+def _bca_interval(data, statistic, axis, alpha, theta_hat_b, batch):
+    """Bias-corrected and accelerated interval."""
+    # closely follows [1] 14.3 and 15.4 (Eq. 15.36)
+
+    # calculate z0_hat
+    theta_hat = np.asarray(statistic(*data, axis=axis))[..., None]
+    percentile = _percentile_of_score(theta_hat_b, theta_hat, axis=-1)
+    z0_hat = ndtri(percentile)
+
+    # calculate a_hat
+    theta_hat_ji = []  # j is for sample of data, i is for jackknife resample
+    for j, sample in enumerate(data):
+        # _jackknife_resample will add an axis prior to the last axis that
+        # corresponds with the different jackknife resamples. Do the same for
+        # each sample of the data to ensure broadcastability. We need to
+        # create a copy of the list containing the samples anyway, so do this
+        # in the loop to simplify the code. This is not the bottleneck...
+        samples = [np.expand_dims(sample, -2) for sample in data]
+        theta_hat_i = []
+        for jackknife_sample in _jackknife_resample(sample, batch):
+            samples[j] = jackknife_sample
+            broadcasted = _broadcast_arrays(samples, axis=-1)
+            theta_hat_i.append(statistic(*broadcasted, axis=-1))
+        theta_hat_ji.append(theta_hat_i)
+
+    theta_hat_ji = [np.concatenate(theta_hat_i, axis=-1)
+                    for theta_hat_i in theta_hat_ji]
+
+    n_j = [theta_hat_i.shape[-1] for theta_hat_i in theta_hat_ji]
+
+    theta_hat_j_dot = [theta_hat_i.mean(axis=-1, keepdims=True)
+                       for theta_hat_i in theta_hat_ji]
+
+    U_ji = [(n - 1) * (theta_hat_dot - theta_hat_i)
+            for theta_hat_dot, theta_hat_i, n
+            in zip(theta_hat_j_dot, theta_hat_ji, n_j)]
+
+    nums = [(U_i**3).sum(axis=-1)/n**3 for U_i, n in zip(U_ji, n_j)]
+    dens = [(U_i**2).sum(axis=-1)/n**2 for U_i, n in zip(U_ji, n_j)]
+    a_hat = 1/6 * sum(nums) / sum(dens)**(3/2)
+
+    # calculate alpha_1, alpha_2
+    z_alpha = ndtri(alpha)
+    z_1alpha = -z_alpha
+    num1 = z0_hat + z_alpha
+    alpha_1 = ndtr(z0_hat + num1/(1 - a_hat*num1))
+    num2 = z0_hat + z_1alpha
+    alpha_2 = ndtr(z0_hat + num2/(1 - a_hat*num2))
+    return alpha_1, alpha_2, a_hat  # return a_hat for testing
+
+
+def _bootstrap_iv(data, statistic, vectorized, paired, axis, confidence_level,
+                  alternative, n_resamples, batch, method, bootstrap_result,
+                  rng):
+    """Input validation and standardization for `bootstrap`."""
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(statistic).parameters
+
+    if not vectorized:
+        statistic = _vectorize_statistic(statistic)
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    n_samples = 0
+    try:
+        n_samples = len(data)
+    except TypeError:
+        raise ValueError("`data` must be a sequence of samples.")
+
+    if n_samples == 0:
+        raise ValueError("`data` must contain at least one sample.")
+
+    message = ("Ignoring the dimension specified by `axis`, arrays in `data` do not "
+               "have the same shape. Beginning in SciPy 1.16.0, `bootstrap` will "
+               "explicitly broadcast elements of `data` to the same shape (ignoring "
+               "`axis`) before performing the calculation. To avoid this warning in "
+               "the meantime, ensure that all samples have the same shape (except "
+               "potentially along `axis`).")
+    data = [np.atleast_1d(sample) for sample in data]
+    reduced_shapes = set()
+    for sample in data:
+        reduced_shape = list(sample.shape)
+        reduced_shape.pop(axis)
+        reduced_shapes.add(tuple(reduced_shape))
+    if len(reduced_shapes) != 1:
+        warnings.warn(message, FutureWarning, stacklevel=3)
+
+    data_iv = []
+    for sample in data:
+        if sample.shape[axis_int] <= 1:
+            raise ValueError("each sample in `data` must contain two or more "
+                             "observations along `axis`.")
+        sample = np.moveaxis(sample, axis_int, -1)
+        data_iv.append(sample)
+
+    if paired not in {True, False}:
+        raise ValueError("`paired` must be `True` or `False`.")
+
+    if paired:
+        n = data_iv[0].shape[-1]
+        for sample in data_iv[1:]:
+            if sample.shape[-1] != n:
+                message = ("When `paired is True`, all samples must have the "
+                           "same length along `axis`")
+                raise ValueError(message)
+
+        # to generate the bootstrap distribution for paired-sample statistics,
+        # resample the indices of the observations
+        def statistic(i, axis=-1, data=data_iv, unpaired_statistic=statistic):
+            data = [sample[..., i] for sample in data]
+            return unpaired_statistic(*data, axis=axis)
+
+        data_iv = [np.arange(n)]
+
+    confidence_level_float = float(confidence_level)
+
+    alternative = alternative.lower()
+    alternatives = {'two-sided', 'less', 'greater'}
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be one of {alternatives}")
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int < 0:
+        raise ValueError("`n_resamples` must be a non-negative integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    methods = {'percentile', 'basic', 'bca'}
+    method = method.lower()
+    if method not in methods:
+        raise ValueError(f"`method` must be in {methods}")
+
+    message = "`bootstrap_result` must have attribute `bootstrap_distribution'"
+    if (bootstrap_result is not None
+            and not hasattr(bootstrap_result, "bootstrap_distribution")):
+        raise ValueError(message)
+
+    message = ("Either `bootstrap_result.bootstrap_distribution.size` or "
+               "`n_resamples` must be positive.")
+    if ((not bootstrap_result or
+         not bootstrap_result.bootstrap_distribution.size)
+            and n_resamples_int == 0):
+        raise ValueError(message)
+
+    rng = check_random_state(rng)
+
+    return (data_iv, statistic, vectorized, paired, axis_int,
+            confidence_level_float, alternative, n_resamples_int, batch_iv,
+            method, bootstrap_result, rng)
+
+
+@dataclass
+class BootstrapResult:
+    """Result object returned by `scipy.stats.bootstrap`.
+
+    Attributes
+    ----------
+    confidence_interval : ConfidenceInterval
+        The bootstrap confidence interval as an instance of
+        `collections.namedtuple` with attributes `low` and `high`.
+    bootstrap_distribution : ndarray
+        The bootstrap distribution, that is, the value of `statistic` for
+        each resample. The last dimension corresponds with the resamples
+        (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
+    standard_error : float or ndarray
+        The bootstrap standard error, that is, the sample standard
+        deviation of the bootstrap distribution.
+
+    """
+    confidence_interval: ConfidenceInterval
+    bootstrap_distribution: np.ndarray
+    standard_error: float | np.ndarray
+
+
+@_transition_to_rng('random_state')
+def bootstrap(data, statistic, *, n_resamples=9999, batch=None,
+              vectorized=None, paired=False, axis=0, confidence_level=0.95,
+              alternative='two-sided', method='BCa', bootstrap_result=None,
+              rng=None):
+    r"""
+    Compute a two-sided bootstrap confidence interval of a statistic.
+
+    When `method` is ``'percentile'`` and `alternative` is ``'two-sided'``,
+    a bootstrap confidence interval is computed according to the following
+    procedure.
+
+    1. Resample the data: for each sample in `data` and for each of
+       `n_resamples`, take a random sample of the original sample
+       (with replacement) of the same size as the original sample.
+
+    2. Compute the bootstrap distribution of the statistic: for each set of
+       resamples, compute the test statistic.
+
+    3. Determine the confidence interval: find the interval of the bootstrap
+       distribution that is
+
+       - symmetric about the median and
+       - contains `confidence_level` of the resampled statistic values.
+
+    While the ``'percentile'`` method is the most intuitive, it is rarely
+    used in practice. Two more common methods are available, ``'basic'``
+    ('reverse percentile') and ``'BCa'`` ('bias-corrected and accelerated');
+    they differ in how step 3 is performed.
+
+    If the samples in `data` are  taken at random from their respective
+    distributions :math:`n` times, the confidence interval returned by
+    `bootstrap` will contain the true value of the statistic for those
+    distributions approximately `confidence_level`:math:`\, \times \, n` times.
+
+    Parameters
+    ----------
+    data : sequence of array-like
+         Each element of `data` is a sample containing scalar observations from an
+         underlying distribution. Elements of `data` must be broadcastable to the
+         same shape (with the possible exception of the dimension specified by `axis`).
+
+         .. versionchanged:: 1.14.0
+             `bootstrap` will now emit a ``FutureWarning`` if the shapes of the
+             elements of `data` are not the same (with the exception of the dimension
+             specified by `axis`).
+             Beginning in SciPy 1.16.0, `bootstrap` will explicitly broadcast the
+             elements to the same shape (except along `axis`) before performing
+             the calculation.
+
+    statistic : callable
+        Statistic for which the confidence interval is to be calculated.
+        `statistic` must be a callable that accepts ``len(data)`` samples
+        as separate arguments and returns the resulting statistic.
+        If `vectorized` is set ``True``,
+        `statistic` must also accept a keyword argument `axis` and be
+        vectorized to compute the statistic along the provided `axis`.
+    n_resamples : int, default: ``9999``
+        The number of resamples performed to form the bootstrap distribution
+        of the statistic.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        `statistic`. Memory usage is O( `batch` * ``n`` ), where ``n`` is the
+        sample size. Default is ``None``, in which case ``batch = n_resamples``
+        (or ``batch = max(n_resamples, n)`` for ``method='BCa'``).
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed an ND sample array. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
+        a vectorized statistic typically reduces computation time.
+    paired : bool, default: ``False``
+        Whether the statistic treats corresponding elements of the samples
+        in `data` as paired. If True, `bootstrap` resamples an array of
+        *indices* and uses the same indices for all arrays in `data`; otherwise,
+        `bootstrap` independently resamples the elements of each array.
+    axis : int, default: ``0``
+        The axis of the samples in `data` along which the `statistic` is
+        calculated.
+    confidence_level : float, default: ``0.95``
+        The confidence level of the confidence interval.
+    alternative : {'two-sided', 'less', 'greater'}, default: ``'two-sided'``
+        Choose ``'two-sided'`` (default) for a two-sided confidence interval,
+        ``'less'`` for a one-sided confidence interval with the lower bound
+        at ``-np.inf``, and ``'greater'`` for a one-sided confidence interval
+        with the upper bound at ``np.inf``. The other bound of the one-sided
+        confidence intervals is the same as that of a two-sided confidence
+        interval with `confidence_level` twice as far from 1.0; e.g. the upper
+        bound of a 95% ``'less'``  confidence interval is the same as the upper
+        bound of a 90% ``'two-sided'`` confidence interval.
+    method : {'percentile', 'basic', 'bca'}, default: ``'BCa'``
+        Whether to return the 'percentile' bootstrap confidence interval
+        (``'percentile'``), the 'basic' (AKA 'reverse') bootstrap confidence
+        interval (``'basic'``), or the bias-corrected and accelerated bootstrap
+        confidence interval (``'BCa'``).
+    bootstrap_result : BootstrapResult, optional
+        Provide the result object returned by a previous call to `bootstrap`
+        to include the previous bootstrap distribution in the new bootstrap
+        distribution. This can be used, for example, to change
+        `confidence_level`, change `method`, or see the effect of performing
+        additional resampling without repeating computations.
+    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 : BootstrapResult
+        An object with attributes:
+
+        confidence_interval : ConfidenceInterval
+            The bootstrap confidence interval as an instance of
+            `collections.namedtuple` with attributes `low` and `high`.
+        bootstrap_distribution : ndarray
+            The bootstrap distribution, that is, the value of `statistic` for
+            each resample. The last dimension corresponds with the resamples
+            (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
+        standard_error : float or ndarray
+            The bootstrap standard error, that is, the sample standard
+            deviation of the bootstrap distribution.
+
+    Warns
+    -----
+    `~scipy.stats.DegenerateDataWarning`
+        Generated when ``method='BCa'`` and the bootstrap distribution is
+        degenerate (e.g. all elements are identical).
+
+    Notes
+    -----
+    Elements of the confidence interval may be NaN for ``method='BCa'`` if
+    the bootstrap distribution is degenerate (e.g. all elements are identical).
+    In this case, consider using another `method` or inspecting `data` for
+    indications that other analysis may be more appropriate (e.g. all
+    observations are identical).
+
+    References
+    ----------
+    .. [1] B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap,
+       Chapman & Hall/CRC, Boca Raton, FL, USA (1993)
+    .. [2] Nathaniel E. Helwig, "Bootstrap Confidence Intervals",
+       http://users.stat.umn.edu/~helwig/notes/bootci-Notes.pdf
+    .. [3] Bootstrapping (statistics), Wikipedia,
+       https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
+
+    Examples
+    --------
+    Suppose we have sampled data from an unknown distribution.
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> from scipy.stats import norm
+    >>> dist = norm(loc=2, scale=4)  # our "unknown" distribution
+    >>> data = dist.rvs(size=100, random_state=rng)
+
+    We are interested in the standard deviation of the distribution.
+
+    >>> std_true = dist.std()      # the true value of the statistic
+    >>> print(std_true)
+    4.0
+    >>> std_sample = np.std(data)  # the sample statistic
+    >>> print(std_sample)
+    3.9460644295563863
+
+    The bootstrap is used to approximate the variability we would expect if we
+    were to repeatedly sample from the unknown distribution and calculate the
+    statistic of the sample each time. It does this by repeatedly resampling
+    values *from the original sample* with replacement and calculating the
+    statistic of each resample. This results in a "bootstrap distribution" of
+    the statistic.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import bootstrap
+    >>> data = (data,)  # samples must be in a sequence
+    >>> res = bootstrap(data, np.std, confidence_level=0.9, rng=rng)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.bootstrap_distribution, bins=25)
+    >>> ax.set_title('Bootstrap Distribution')
+    >>> ax.set_xlabel('statistic value')
+    >>> ax.set_ylabel('frequency')
+    >>> plt.show()
+
+    The standard error quantifies this variability. It is calculated as the
+    standard deviation of the bootstrap distribution.
+
+    >>> res.standard_error
+    0.24427002125829136
+    >>> res.standard_error == np.std(res.bootstrap_distribution, ddof=1)
+    True
+
+    The bootstrap distribution of the statistic is often approximately normal
+    with scale equal to the standard error.
+
+    >>> x = np.linspace(3, 5)
+    >>> pdf = norm.pdf(x, loc=std_sample, scale=res.standard_error)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.bootstrap_distribution, bins=25, density=True)
+    >>> ax.plot(x, pdf)
+    >>> ax.set_title('Normal Approximation of the Bootstrap Distribution')
+    >>> ax.set_xlabel('statistic value')
+    >>> ax.set_ylabel('pdf')
+    >>> plt.show()
+
+    This suggests that we could construct a 90% confidence interval on the
+    statistic based on quantiles of this normal distribution.
+
+    >>> norm.interval(0.9, loc=std_sample, scale=res.standard_error)
+    (3.5442759991341726, 4.3478528599786)
+
+    Due to central limit theorem, this normal approximation is accurate for a
+    variety of statistics and distributions underlying the samples; however,
+    the approximation is not reliable in all cases. Because `bootstrap` is
+    designed to work with arbitrary underlying distributions and statistics,
+    it uses more advanced techniques to generate an accurate confidence
+    interval.
+
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=3.57655333533867, high=4.382043696342881)
+
+    If we sample from the original distribution 100 times and form a bootstrap
+    confidence interval for each sample, the confidence interval
+    contains the true value of the statistic approximately 90% of the time.
+
+    >>> n_trials = 100
+    >>> ci_contains_true_std = 0
+    >>> for i in range(n_trials):
+    ...    data = (dist.rvs(size=100, random_state=rng),)
+    ...    res = bootstrap(data, np.std, confidence_level=0.9,
+    ...                    n_resamples=999, rng=rng)
+    ...    ci = res.confidence_interval
+    ...    if ci[0] < std_true < ci[1]:
+    ...        ci_contains_true_std += 1
+    >>> print(ci_contains_true_std)
+    88
+
+    Rather than writing a loop, we can also determine the confidence intervals
+    for all 100 samples at once.
+
+    >>> data = (dist.rvs(size=(n_trials, 100), random_state=rng),)
+    >>> res = bootstrap(data, np.std, axis=-1, confidence_level=0.9,
+    ...                 n_resamples=999, rng=rng)
+    >>> ci_l, ci_u = res.confidence_interval
+
+    Here, `ci_l` and `ci_u` contain the confidence interval for each of the
+    ``n_trials = 100`` samples.
+
+    >>> print(ci_l[:5])
+    [3.86401283 3.33304394 3.52474647 3.54160981 3.80569252]
+    >>> print(ci_u[:5])
+    [4.80217409 4.18143252 4.39734707 4.37549713 4.72843584]
+
+    And again, approximately 90% contain the true value, ``std_true = 4``.
+
+    >>> print(np.sum((ci_l < std_true) & (std_true < ci_u)))
+    93
+
+    `bootstrap` can also be used to estimate confidence intervals of
+    multi-sample statistics. For example, to get a confidence interval
+    for the difference between means, we write a function that accepts
+    two sample arguments and returns only the statistic. The use of the
+    ``axis`` argument ensures that all mean calculations are perform in
+    a single vectorized call, which is faster than looping over pairs
+    of resamples in Python.
+
+    >>> def my_statistic(sample1, sample2, axis=-1):
+    ...     mean1 = np.mean(sample1, axis=axis)
+    ...     mean2 = np.mean(sample2, axis=axis)
+    ...     return mean1 - mean2
+
+    Here, we use the 'percentile' method with the default 95% confidence level.
+
+    >>> sample1 = norm.rvs(scale=1, size=100, random_state=rng)
+    >>> sample2 = norm.rvs(scale=2, size=100, random_state=rng)
+    >>> data = (sample1, sample2)
+    >>> res = bootstrap(data, my_statistic, method='basic', rng=rng)
+    >>> print(my_statistic(sample1, sample2))
+    0.16661030792089523
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=-0.29087973240818693, high=0.6371338699912273)
+
+    The bootstrap estimate of the standard error is also available.
+
+    >>> print(res.standard_error)
+    0.238323948262459
+
+    Paired-sample statistics work, too. For example, consider the Pearson
+    correlation coefficient.
+
+    >>> from scipy.stats import pearsonr
+    >>> n = 100
+    >>> x = np.linspace(0, 10, n)
+    >>> y = x + rng.uniform(size=n)
+    >>> print(pearsonr(x, y)[0])  # element 0 is the statistic
+    0.9954306665125647
+
+    We wrap `pearsonr` so that it returns only the statistic, ensuring
+    that we use the `axis` argument because it is available.
+
+    >>> def my_statistic(x, y, axis=-1):
+    ...     return pearsonr(x, y, axis=axis)[0]
+
+    We call `bootstrap` using ``paired=True``.
+
+    >>> res = bootstrap((x, y), my_statistic, paired=True, rng=rng)
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=0.9941504301315878, high=0.996377412215445)
+
+    The result object can be passed back into `bootstrap` to perform additional
+    resampling:
+
+    >>> len(res.bootstrap_distribution)
+    9999
+    >>> res = bootstrap((x, y), my_statistic, paired=True,
+    ...                 n_resamples=1000, rng=rng,
+    ...                 bootstrap_result=res)
+    >>> len(res.bootstrap_distribution)
+    10999
+
+    or to change the confidence interval options:
+
+    >>> res2 = bootstrap((x, y), my_statistic, paired=True,
+    ...                  n_resamples=0, rng=rng, bootstrap_result=res,
+    ...                  method='percentile', confidence_level=0.9)
+    >>> np.testing.assert_equal(res2.bootstrap_distribution,
+    ...                         res.bootstrap_distribution)
+    >>> res.confidence_interval
+    ConfidenceInterval(low=0.9941574828235082, high=0.9963781698210212)
+
+    without repeating computation of the original bootstrap distribution.
+
+    """
+    # Input validation
+    args = _bootstrap_iv(data, statistic, vectorized, paired, axis,
+                         confidence_level, alternative, n_resamples, batch,
+                         method, bootstrap_result, rng)
+    (data, statistic, vectorized, paired, axis, confidence_level,
+     alternative, n_resamples, batch, method, bootstrap_result,
+     rng) = args
+
+    theta_hat_b = ([] if bootstrap_result is None
+                   else [bootstrap_result.bootstrap_distribution])
+
+    batch_nominal = batch or n_resamples or 1
+
+    for k in range(0, n_resamples, batch_nominal):
+        batch_actual = min(batch_nominal, n_resamples-k)
+        # Generate resamples
+        resampled_data = []
+        for sample in data:
+            resample = _bootstrap_resample(sample, n_resamples=batch_actual,
+                                           rng=rng)
+            resampled_data.append(resample)
+
+        # Compute bootstrap distribution of statistic
+        theta_hat_b.append(statistic(*resampled_data, axis=-1))
+    theta_hat_b = np.concatenate(theta_hat_b, axis=-1)
+
+    # Calculate percentile interval
+    alpha = ((1 - confidence_level)/2 if alternative == 'two-sided'
+             else (1 - confidence_level))
+    if method == 'bca':
+        interval = _bca_interval(data, statistic, axis=-1, alpha=alpha,
+                                 theta_hat_b=theta_hat_b, batch=batch)[:2]
+        percentile_fun = _percentile_along_axis
+    else:
+        interval = alpha, 1-alpha
+
+        def percentile_fun(a, q):
+            return np.percentile(a=a, q=q, axis=-1)
+
+    # Calculate confidence interval of statistic
+    ci_l = percentile_fun(theta_hat_b, interval[0]*100)
+    ci_u = percentile_fun(theta_hat_b, interval[1]*100)
+    if method == 'basic':  # see [3]
+        theta_hat = statistic(*data, axis=-1)
+        ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l
+
+    if alternative == 'less':
+        ci_l = np.full_like(ci_l, -np.inf)
+    elif alternative == 'greater':
+        ci_u = np.full_like(ci_u, np.inf)
+
+    return BootstrapResult(confidence_interval=ConfidenceInterval(ci_l, ci_u),
+                           bootstrap_distribution=theta_hat_b,
+                           standard_error=np.std(theta_hat_b, ddof=1, axis=-1))
+
+
+def _monte_carlo_test_iv(data, rvs, statistic, vectorized, n_resamples,
+                         batch, alternative, axis):
+    """Input validation for `monte_carlo_test`."""
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if not isinstance(rvs, Sequence):
+        rvs = (rvs,)
+        data = (data,)
+    for rvs_i in rvs:
+        if not callable(rvs_i):
+            raise TypeError("`rvs` must be callable or sequence of callables.")
+
+    # At this point, `data` should be a sequence
+    # If it isn't, the user passed a sequence for `rvs` but not `data`
+    message = "If `rvs` is a sequence, `len(rvs)` must equal `len(data)`."
+    try:
+        len(data)
+    except TypeError as e:
+        raise ValueError(message) from e
+    if not len(rvs) == len(data):
+        raise ValueError(message)
+
+    if not callable(statistic):
+        raise TypeError("`statistic` must be callable.")
+
+    if vectorized is None:
+        try:
+            signature = inspect.signature(statistic).parameters
+        except ValueError as e:
+            message = (f"Signature inspection of {statistic=} failed; "
+                       "pass `vectorize` explicitly.")
+            raise ValueError(message) from e
+        vectorized = 'axis' in signature
+
+    xp = array_namespace(*data)
+
+    if not vectorized:
+        if is_numpy(xp):
+            statistic_vectorized = _vectorize_statistic(statistic)
+        else:
+            message = ("`statistic` must be vectorized (i.e. support an `axis` "
+                       f"argument) when `data` contains {xp.__name__} arrays.")
+            raise ValueError(message)
+    else:
+        statistic_vectorized = statistic
+
+    data = _broadcast_arrays(data, axis, xp=xp)
+    data_iv = []
+    for sample in data:
+        sample = xp.broadcast_to(sample, (1,)) if sample.ndim == 0 else sample
+        sample = xp_moveaxis_to_end(sample, axis_int, xp=xp)
+        data_iv.append(sample)
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    alternatives = {'two-sided', 'greater', 'less'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be in {alternatives}")
+
+    # Infer the desired p-value dtype based on the input types
+    min_float = getattr(xp, 'float16', xp.float32)
+    dtype = xp.result_type(*data_iv, min_float)
+
+    return (data_iv, rvs, statistic_vectorized, vectorized, n_resamples_int,
+            batch_iv, alternative, axis_int, dtype, xp)
+
+
+@dataclass
+class MonteCarloTestResult:
+    """Result object returned by `scipy.stats.monte_carlo_test`.
+
+    Attributes
+    ----------
+    statistic : float or ndarray
+        The observed test statistic of the sample.
+    pvalue : float or ndarray
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null
+        hypothesis.
+    """
+    statistic: float | np.ndarray
+    pvalue: float | np.ndarray
+    null_distribution: np.ndarray
+
+
+@_rename_parameter('sample', 'data')
+def monte_carlo_test(data, rvs, statistic, *, vectorized=None,
+                     n_resamples=9999, batch=None, alternative="two-sided",
+                     axis=0):
+    r"""Perform a Monte Carlo hypothesis test.
+
+    `data` contains a sample or a sequence of one or more samples. `rvs`
+    specifies the distribution(s) of the sample(s) in `data` under the null
+    hypothesis. The value of `statistic` for the given `data` is compared
+    against a Monte Carlo null distribution: the value of the statistic for
+    each of `n_resamples` sets of samples generated using `rvs`. This gives
+    the p-value, the probability of observing such an extreme value of the
+    test statistic under the null hypothesis.
+
+    Parameters
+    ----------
+    data : array-like or sequence of array-like
+        An array or sequence of arrays of observations.
+    rvs : callable or tuple of callables
+        A callable or sequence of callables that generates random variates
+        under the null hypothesis. Each element of `rvs` must be a callable
+        that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
+        returns an N-d array sample of that shape. If `rvs` is a sequence, the
+        number of callables in `rvs` must match the number of samples in
+        `data`, i.e. ``len(rvs) == len(data)``. If `rvs` is a single callable,
+        `data` is treated as a single sample.
+    statistic : callable
+        Statistic for which the p-value of the hypothesis test is to be
+        calculated. `statistic` must be a callable that accepts a sample
+        (e.g. ``statistic(sample)``) or ``len(rvs)`` separate samples (e.g.
+        ``statistic(samples1, sample2)`` if `rvs` contains two callables and
+        `data` contains two samples) and returns the resulting statistic.
+        If `vectorized` is set ``True``, `statistic` must also accept a keyword
+        argument `axis` and be vectorized to compute the statistic along the
+        provided `axis` of the samples in `data`.
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed ND sample arrays. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
+        a vectorized statistic typically reduces computation time.
+    n_resamples : int, default: 9999
+        Number of samples drawn from each of the callables of `rvs`.
+        Equivalently, the number statistic values under the null hypothesis
+        used as the Monte Carlo null distribution.
+    batch : int, optional
+        The number of Monte Carlo samples to process in each call to
+        `statistic`. Memory usage is O( `batch` * ``sample.size[axis]`` ). Default
+        is ``None``, in which case `batch` equals `n_resamples`.
+    alternative : {'two-sided', 'less', 'greater'}
+        The alternative hypothesis for which the p-value is calculated.
+        For each alternative, the p-value is defined as follows.
+
+        - ``'greater'`` : the percentage of the null distribution that is
+          greater than or equal to the observed value of the test statistic.
+        - ``'less'`` : the percentage of the null distribution that is
+          less than or equal to the observed value of the test statistic.
+        - ``'two-sided'`` : twice the smaller of the p-values above.
+
+    axis : int, default: 0
+        The axis of `data` (or each sample within `data`) over which to
+        calculate the statistic.
+
+    Returns
+    -------
+    res : MonteCarloTestResult
+        An object with attributes:
+
+        statistic : float or ndarray
+            The test statistic of the observed `data`.
+        pvalue : float or ndarray
+            The p-value for the given alternative.
+        null_distribution : ndarray
+            The values of the test statistic generated under the null
+            hypothesis.
+
+    .. warning::
+        The p-value is calculated by counting the elements of the null
+        distribution that are as extreme or more extreme than the observed
+        value of the statistic. Due to the use of finite precision arithmetic,
+        some statistic functions return numerically distinct values when the
+        theoretical values would be exactly equal. In some cases, this could
+        lead to a large error in the calculated p-value. `monte_carlo_test`
+        guards against this by considering elements in the null distribution
+        that are "close" (within a relative tolerance of 100 times the
+        floating point epsilon of inexact dtypes) to the observed
+        value of the test statistic as equal to the observed value of the
+        test statistic. However, the user is advised to inspect the null
+        distribution to assess whether this method of comparison is
+        appropriate, and if not, calculate the p-value manually.
+
+    References
+    ----------
+
+    .. [1] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
+       Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
+       Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
+
+    Examples
+    --------
+
+    Suppose we wish to test whether a small sample has been drawn from a normal
+    distribution. We decide that we will use the skew of the sample as a
+    test statistic, and we will consider a p-value of 0.05 to be statistically
+    significant.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> def statistic(x, axis):
+    ...     return stats.skew(x, axis)
+
+    After collecting our data, we calculate the observed value of the test
+    statistic.
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.skewnorm.rvs(a=1, size=50, random_state=rng)
+    >>> statistic(x, axis=0)
+    0.12457412450240658
+
+    To determine the probability of observing such an extreme value of the
+    skewness by chance if the sample were drawn from the normal distribution,
+    we can perform a Monte Carlo hypothesis test. The test will draw many
+    samples at random from their normal distribution, calculate the skewness
+    of each sample, and compare our original skewness against this
+    distribution to determine an approximate p-value.
+
+    >>> from scipy.stats import monte_carlo_test
+    >>> # because our statistic is vectorized, we pass `vectorized=True`
+    >>> rvs = lambda size: stats.norm.rvs(size=size, random_state=rng)
+    >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
+    >>> print(res.statistic)
+    0.12457412450240658
+    >>> print(res.pvalue)
+    0.7012
+
+    The probability of obtaining a test statistic less than or equal to the
+    observed value under the null hypothesis is ~70%. This is greater than
+    our chosen threshold of 5%, so we cannot consider this to be significant
+    evidence against the null hypothesis.
+
+    Note that this p-value essentially matches that of
+    `scipy.stats.skewtest`, which relies on an asymptotic distribution of a
+    test statistic based on the sample skewness.
+
+    >>> stats.skewtest(x).pvalue
+    0.6892046027110614
+
+    This asymptotic approximation is not valid for small sample sizes, but
+    `monte_carlo_test` can be used with samples of any size.
+
+    >>> x = stats.skewnorm.rvs(a=1, size=7, random_state=rng)
+    >>> # stats.skewtest(x) would produce an error due to small sample
+    >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
+
+    The Monte Carlo distribution of the test statistic is provided for
+    further investigation.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.null_distribution, bins=50)
+    >>> ax.set_title("Monte Carlo distribution of test statistic")
+    >>> ax.set_xlabel("Value of Statistic")
+    >>> ax.set_ylabel("Frequency")
+    >>> plt.show()
+
+    """
+    args = _monte_carlo_test_iv(data, rvs, statistic, vectorized,
+                                n_resamples, batch, alternative, axis)
+    (data, rvs, statistic, vectorized, n_resamples,
+     batch, alternative, axis, dtype, xp) = args
+
+    # Some statistics return plain floats; ensure they're at least a NumPy float
+    observed = xp.asarray(statistic(*data, axis=-1))
+    observed = observed[()] if observed.ndim == 0 else observed
+
+    n_observations = [sample.shape[-1] for sample in data]
+    batch_nominal = batch or n_resamples
+    null_distribution = []
+    for k in range(0, n_resamples, batch_nominal):
+        batch_actual = min(batch_nominal, n_resamples - k)
+        resamples = [rvs_i(size=(batch_actual, n_observations_i))
+                     for rvs_i, n_observations_i in zip(rvs, n_observations)]
+        null_distribution.append(statistic(*resamples, axis=-1))
+    null_distribution = xp.concat(null_distribution)
+    null_distribution = xp.reshape(null_distribution, [-1] + [1]*observed.ndim)
+
+    # relative tolerance for detecting numerically distinct but
+    # theoretically equal values in the null distribution
+    eps =  (0 if not xp.isdtype(observed.dtype, ('real floating'))
+            else xp.finfo(observed.dtype).eps*100)
+    gamma = xp.abs(eps * observed)
+
+    def less(null_distribution, observed):
+        cmps = null_distribution <= observed + gamma
+        cmps = xp.asarray(cmps, dtype=dtype)
+        pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
+        return pvalues
+
+    def greater(null_distribution, observed):
+        cmps = null_distribution >= observed - gamma
+        cmps = xp.asarray(cmps, dtype=dtype)
+        pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
+        return pvalues
+
+    def two_sided(null_distribution, observed):
+        pvalues_less = less(null_distribution, observed)
+        pvalues_greater = greater(null_distribution, observed)
+        pvalues = xp.minimum(pvalues_less, pvalues_greater) * 2
+        return pvalues
+
+    compare = {"less": less,
+               "greater": greater,
+               "two-sided": two_sided}
+
+    pvalues = compare[alternative](null_distribution, observed)
+    pvalues = xp.clip(pvalues, 0., 1.)
+
+    return MonteCarloTestResult(observed, pvalues, null_distribution)
+
+
+@dataclass
+class PowerResult:
+    """Result object returned by `scipy.stats.power`.
+
+    Attributes
+    ----------
+    power : float or ndarray
+        The estimated power.
+    pvalues : float or ndarray
+        The simulated p-values.
+    """
+    power: float | np.ndarray
+    pvalues: float | np.ndarray
+
+
+def _wrap_kwargs(fun):
+    """Wrap callable to accept arbitrary kwargs and ignore unused ones"""
+
+    try:
+        keys = set(inspect.signature(fun).parameters.keys())
+    except ValueError:
+        # NumPy Generator methods can't be inspected
+        keys = {'size'}
+
+    # Set keys=keys/fun=fun to avoid late binding gotcha
+    def wrapped_rvs_i(*args, keys=keys, fun=fun, **all_kwargs):
+        kwargs = {key: val for key, val in all_kwargs.items()
+                  if key in keys}
+        return fun(*args, **kwargs)
+    return wrapped_rvs_i
+
+
+def _power_iv(rvs, test, n_observations, significance, vectorized,
+              n_resamples, batch, kwargs):
+    """Input validation for `monte_carlo_test`."""
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if not isinstance(rvs, Sequence):
+        rvs = (rvs,)
+        n_observations = (n_observations,)
+    for rvs_i in rvs:
+        if not callable(rvs_i):
+            raise TypeError("`rvs` must be callable or sequence of callables.")
+
+    if not len(rvs) == len(n_observations):
+        message = ("If `rvs` is a sequence, `len(rvs)` "
+                   "must equal `len(n_observations)`.")
+        raise ValueError(message)
+
+    significance = np.asarray(significance)[()]
+    if (not np.issubdtype(significance.dtype, np.floating)
+            or np.min(significance) < 0 or np.max(significance) > 1):
+        raise ValueError("`significance` must contain floats between 0 and 1.")
+
+    kwargs = dict() if kwargs is None else kwargs
+    if not isinstance(kwargs, dict):
+        raise TypeError("`kwargs` must be a dictionary that maps keywords to arrays.")
+
+    vals = kwargs.values()
+    keys = kwargs.keys()
+
+    # Wrap callables to ignore unused keyword arguments
+    wrapped_rvs = [_wrap_kwargs(rvs_i) for rvs_i in rvs]
+
+    # Broadcast, then ravel nobs/kwarg combinations. In the end,
+    # `nobs` and `vals` have shape (# of combinations, number of variables)
+    tmp = np.asarray(np.broadcast_arrays(*n_observations, *vals))
+    shape = tmp.shape
+    if tmp.ndim == 1:
+        tmp = tmp[np.newaxis, :]
+    else:
+        tmp = tmp.reshape((shape[0], -1)).T
+    nobs, vals = tmp[:, :len(rvs)], tmp[:, len(rvs):]
+    nobs = nobs.astype(int)
+
+    if not callable(test):
+        raise TypeError("`test` must be callable.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(test).parameters
+
+    if not vectorized:
+        test_vectorized = _vectorize_statistic(test)
+    else:
+        test_vectorized = test
+    # Wrap `test` function to ignore unused kwargs
+    test_vectorized = _wrap_kwargs(test_vectorized)
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    return (wrapped_rvs, test_vectorized, nobs, significance, vectorized,
+            n_resamples_int, batch_iv, vals, keys, shape[1:])
+
+
+def power(test, rvs, n_observations, *, significance=0.01, vectorized=None,
+          n_resamples=10000, batch=None, kwargs=None):
+    r"""Simulate the power of a hypothesis test under an alternative hypothesis.
+
+    Parameters
+    ----------
+    test : callable
+        Hypothesis test for which the power is to be simulated.
+        `test` must be a callable that accepts a sample (e.g. ``test(sample)``)
+        or ``len(rvs)`` separate samples (e.g. ``test(samples1, sample2)`` if
+        `rvs` contains two callables and `n_observations` contains two values)
+        and returns the p-value of the test.
+        If `vectorized` is set to ``True``, `test` must also accept a keyword
+        argument `axis` and be vectorized to perform the test along the
+        provided `axis` of the samples.
+        Any callable from `scipy.stats` with an `axis` argument that returns an
+        object with a `pvalue` attribute is also acceptable.
+    rvs : callable or tuple of callables
+        A callable or sequence of callables that generate(s) random variates
+        under the alternative hypothesis. Each element of `rvs` must accept
+        keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and return an
+        N-d array of that shape. If `rvs` is a sequence, the number of callables
+        in `rvs` must match the number of elements of `n_observations`, i.e.
+        ``len(rvs) == len(n_observations)``. If `rvs` is a single callable,
+        `n_observations` is treated as a single element.
+    n_observations : tuple of ints or tuple of integer arrays
+        If a sequence of ints, each is the sizes of a sample to be passed to `test`.
+        If a sequence of integer arrays, the power is simulated for each
+        set of corresponding sample sizes. See Examples.
+    significance : float or array_like of floats, default: 0.01
+        The threshold for significance; i.e., the p-value below which the
+        hypothesis test results will be considered as evidence against the null
+        hypothesis. Equivalently, the acceptable rate of Type I error under
+        the null hypothesis. If an array, the power is simulated for each
+        significance threshold.
+    kwargs : dict, optional
+        Keyword arguments to be passed to `rvs` and/or `test` callables.
+        Introspection is used to determine which keyword arguments may be
+        passed to each callable.
+        The value corresponding with each keyword must be an array.
+        Arrays must be broadcastable with one another and with each array in
+        `n_observations`. The power is simulated for each set of corresponding
+        sample sizes and arguments. See Examples.
+    vectorized : bool, optional
+        If `vectorized` is set to ``False``, `test` will not be passed keyword
+        argument `axis` and is expected to perform the test only for 1D samples.
+        If ``True``, `test` will be passed keyword argument `axis` and is
+        expected to perform the test along `axis` when passed N-D sample arrays.
+        If ``None`` (default), `vectorized` will be set ``True`` if ``axis`` is
+        a parameter of `test`. Use of a vectorized test typically reduces
+        computation time.
+    n_resamples : int, default: 10000
+        Number of samples drawn from each of the callables of `rvs`.
+        Equivalently, the number tests performed under the alternative
+        hypothesis to approximate the power.
+    batch : int, optional
+        The number of samples to process in each call to `test`. Memory usage is
+        proportional to the product of `batch` and the largest sample size. Default
+        is ``None``, in which case `batch` equals `n_resamples`.
+
+    Returns
+    -------
+    res : PowerResult
+        An object with attributes:
+
+        power : float or ndarray
+            The estimated power against the alternative.
+        pvalues : ndarray
+            The p-values observed under the alternative hypothesis.
+
+    Notes
+    -----
+    The power is simulated as follows:
+
+    - Draw many random samples (or sets of samples), each of the size(s)
+      specified by `n_observations`, under the alternative specified by
+      `rvs`.
+    - For each sample (or set of samples), compute the p-value according to
+      `test`. These p-values are recorded in the ``pvalues`` attribute of
+      the result object.
+    - Compute the proportion of p-values that are less than the `significance`
+      level. This is the power recorded in the ``power`` attribute of the
+      result object.
+
+    Suppose that `significance` is an array with shape ``shape1``, the elements
+    of `kwargs` and `n_observations` are mutually broadcastable to shape ``shape2``,
+    and `test` returns an array of p-values of shape ``shape3``. Then the result
+    object ``power`` attribute will be of shape ``shape1 + shape2 + shape3``, and
+    the ``pvalues`` attribute will be of shape ``shape2 + shape3 + (n_resamples,)``.
+
+    Examples
+    --------
+    Suppose we wish to simulate the power of the independent sample t-test
+    under the following conditions:
+
+    - The first sample has 10 observations drawn from a normal distribution
+      with mean 0.
+    - The second sample has 12 observations drawn from a normal distribution
+      with mean 1.0.
+    - The threshold on p-values for significance is 0.05.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(2549598345528)
+    >>>
+    >>> test = stats.ttest_ind
+    >>> n_observations = (10, 12)
+    >>> rvs1 = rng.normal
+    >>> rvs2 = lambda size: rng.normal(loc=1, size=size)
+    >>> rvs = (rvs1, rvs2)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> res.power
+    0.6116
+
+    With samples of size 10 and 12, respectively, the power of the t-test
+    with a significance threshold of 0.05 is approximately 60% under the chosen
+    alternative. We can investigate the effect of sample size on the power
+    by passing sample size arrays.
+
+    >>> import matplotlib.pyplot as plt
+    >>> nobs_x = np.arange(5, 21)
+    >>> nobs_y = nobs_x
+    >>> n_observations = (nobs_x, nobs_y)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> ax = plt.subplot()
+    >>> ax.plot(nobs_x, res.power)
+    >>> ax.set_xlabel('Sample Size')
+    >>> ax.set_ylabel('Simulated Power')
+    >>> ax.set_title('Simulated Power of `ttest_ind` with Equal Sample Sizes')
+    >>> plt.show()
+
+    Alternatively, we can investigate the impact that effect size has on the power.
+    In this case, the effect size is the location of the distribution underlying
+    the second sample.
+
+    >>> n_observations = (10, 12)
+    >>> loc = np.linspace(0, 1, 20)
+    >>> rvs2 = lambda size, loc: rng.normal(loc=loc, size=size)
+    >>> rvs = (rvs1, rvs2)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05,
+    ...                   kwargs={'loc': loc})
+    >>> ax = plt.subplot()
+    >>> ax.plot(loc, res.power)
+    >>> ax.set_xlabel('Effect Size')
+    >>> ax.set_ylabel('Simulated Power')
+    >>> ax.set_title('Simulated Power of `ttest_ind`, Varying Effect Size')
+    >>> plt.show()
+
+    We can also use `power` to estimate the Type I error rate (also referred to by the
+    ambiguous term "size") of a test and assess whether it matches the nominal level.
+    For example, the null hypothesis of `jarque_bera` is that the sample was drawn from
+    a distribution with the same skewness and kurtosis as the normal distribution. To
+    estimate the Type I error rate, we can consider the null hypothesis to be a true
+    *alternative* hypothesis and calculate the power.
+
+    >>> test = stats.jarque_bera
+    >>> n_observations = 10
+    >>> rvs = rng.normal
+    >>> significance = np.linspace(0.0001, 0.1, 1000)
+    >>> res = stats.power(test, rvs, n_observations, significance=significance)
+    >>> size = res.power
+
+    As shown below, the Type I error rate of the test is far below the nominal level
+    for such a small sample, as mentioned in its documentation.
+
+    >>> ax = plt.subplot()
+    >>> ax.plot(significance, size)
+    >>> ax.plot([0, 0.1], [0, 0.1], '--')
+    >>> ax.set_xlabel('nominal significance level')
+    >>> ax.set_ylabel('estimated test size (Type I error rate)')
+    >>> ax.set_title('Estimated test size vs nominal significance level')
+    >>> ax.set_aspect('equal', 'box')
+    >>> ax.legend(('`ttest_1samp`', 'ideal test'))
+    >>> plt.show()
+
+    As one might expect from such a conservative test, the power is quite low with
+    respect to some alternatives. For example, the power of the test under the
+    alternative that the sample was drawn from the Laplace distribution may not
+    be much greater than the Type I error rate.
+
+    >>> rvs = rng.laplace
+    >>> significance = np.linspace(0.0001, 0.1, 1000)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> print(res.power)
+    0.0587
+
+    This is not a mistake in SciPy's implementation; it is simply due to the fact
+    that the null distribution of the test statistic is derived under the assumption
+    that the sample size is large (i.e. approaches infinity), and this asymptotic
+    approximation is not accurate for small samples. In such cases, resampling
+    and Monte Carlo methods (e.g. `permutation_test`, `goodness_of_fit`,
+    `monte_carlo_test`) may be more appropriate.
+
+    """
+    tmp = _power_iv(rvs, test, n_observations, significance,
+                    vectorized, n_resamples, batch, kwargs)
+    (rvs, test, nobs, significance,
+     vectorized, n_resamples, batch, args, kwds, shape)= tmp
+
+    batch_nominal = batch or n_resamples
+    pvalues = []  # results of various nobs/kwargs combinations
+    for nobs_i, args_i in zip(nobs, args):
+        kwargs_i = dict(zip(kwds, args_i))
+        pvalues_i = []  # results of batches; fixed nobs/kwargs combination
+        for k in range(0, n_resamples, batch_nominal):
+            batch_actual = min(batch_nominal, n_resamples - k)
+            resamples = [rvs_j(size=(batch_actual, nobs_ij), **kwargs_i)
+                         for rvs_j, nobs_ij in zip(rvs, nobs_i)]
+            res = test(*resamples, **kwargs_i, axis=-1)
+            p = getattr(res, 'pvalue', res)
+            pvalues_i.append(p)
+        # Concatenate results from batches
+        pvalues_i = np.concatenate(pvalues_i, axis=-1)
+        pvalues.append(pvalues_i)
+    # `test` can return result with array of p-values
+    shape += pvalues_i.shape[:-1]
+    # Concatenate results from various nobs/kwargs combinations
+    pvalues = np.concatenate(pvalues, axis=0)
+    # nobs/kwargs arrays were raveled to single axis; unravel
+    pvalues = pvalues.reshape(shape + (-1,))
+    if significance.ndim > 0:
+        newdims = tuple(range(significance.ndim, pvalues.ndim + significance.ndim))
+        significance = np.expand_dims(significance, newdims)
+    powers = np.mean(pvalues < significance, axis=-1)
+
+    return PowerResult(power=powers, pvalues=pvalues)
+
+
+@dataclass
+class PermutationTestResult:
+    """Result object returned by `scipy.stats.permutation_test`.
+
+    Attributes
+    ----------
+    statistic : float or ndarray
+        The observed test statistic of the data.
+    pvalue : float or ndarray
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null
+        hypothesis.
+    """
+    statistic: float | np.ndarray
+    pvalue: float | np.ndarray
+    null_distribution: np.ndarray
+
+
+def _all_partitions_concatenated(ns):
+    """
+    Generate all partitions of indices of groups of given sizes, concatenated
+
+    `ns` is an iterable of ints.
+    """
+    def all_partitions(z, n):
+        for c in combinations(z, n):
+            x0 = set(c)
+            x1 = z - x0
+            yield [x0, x1]
+
+    def all_partitions_n(z, ns):
+        if len(ns) == 0:
+            yield [z]
+            return
+        for c in all_partitions(z, ns[0]):
+            for d in all_partitions_n(c[1], ns[1:]):
+                yield c[0:1] + d
+
+    z = set(range(np.sum(ns)))
+    for partitioning in all_partitions_n(z, ns[:]):
+        x = np.concatenate([list(partition)
+                            for partition in partitioning]).astype(int)
+        yield x
+
+
+def _batch_generator(iterable, batch):
+    """A generator that yields batches of elements from an iterable"""
+    iterator = iter(iterable)
+    if batch <= 0:
+        raise ValueError("`batch` must be positive.")
+    z = [item for i, item in zip(range(batch), iterator)]
+    while z:  # we don't want StopIteration without yielding an empty list
+        yield z
+        z = [item for i, item in zip(range(batch), iterator)]
+
+
+def _pairings_permutations_gen(n_permutations, n_samples, n_obs_sample, batch,
+                               rng):
+    # Returns a generator that yields arrays of size
+    # `(batch, n_samples, n_obs_sample)`.
+    # Each row is an independent permutation of indices 0 to `n_obs_sample`.
+    batch = min(batch, n_permutations)
+
+    if hasattr(rng, 'permuted'):
+        def batched_perm_generator():
+            indices = np.arange(n_obs_sample)
+            indices = np.tile(indices, (batch, n_samples, 1))
+            for k in range(0, n_permutations, batch):
+                batch_actual = min(batch, n_permutations-k)
+                # Don't permute in place, otherwise results depend on `batch`
+                permuted_indices = rng.permuted(indices, axis=-1)
+                yield permuted_indices[:batch_actual]
+    else:  # RandomState and early Generators don't have `permuted`
+        def batched_perm_generator():
+            for k in range(0, n_permutations, batch):
+                batch_actual = min(batch, n_permutations-k)
+                size = (batch_actual, n_samples, n_obs_sample)
+                x = rng.random(size=size)
+                yield np.argsort(x, axis=-1)[:batch_actual]
+
+    return batched_perm_generator()
+
+
+def _calculate_null_both(data, statistic, n_permutations, batch,
+                         rng=None):
+    """
+    Calculate null distribution for independent sample tests.
+    """
+    n_samples = len(data)
+
+    # compute number of permutations
+    # (distinct partitions of data into samples of these sizes)
+    n_obs_i = [sample.shape[-1] for sample in data]  # observations per sample
+    n_obs_ic = np.cumsum(n_obs_i)
+    n_obs = n_obs_ic[-1]  # total number of observations
+    n_max = np.prod([comb(n_obs_ic[i], n_obs_ic[i-1])
+                     for i in range(n_samples-1, 0, -1)])
+
+    # perm_generator is an iterator that produces permutations of indices
+    # from 0 to n_obs. We'll concatenate the samples, use these indices to
+    # permute the data, then split the samples apart again.
+    if n_permutations >= n_max:
+        exact_test = True
+        n_permutations = n_max
+        perm_generator = _all_partitions_concatenated(n_obs_i)
+    else:
+        exact_test = False
+        # Neither RandomState.permutation nor Generator.permutation
+        # can permute axis-slices independently. If this feature is
+        # added in the future, batches of the desired size should be
+        # generated in a single call.
+        perm_generator = (rng.permutation(n_obs)
+                          for i in range(n_permutations))
+
+    batch = batch or int(n_permutations)
+    null_distribution = []
+
+    # First, concatenate all the samples. In batches, permute samples with
+    # indices produced by the `perm_generator`, split them into new samples of
+    # the original sizes, compute the statistic for each batch, and add these
+    # statistic values to the null distribution.
+    data = np.concatenate(data, axis=-1)
+    for indices in _batch_generator(perm_generator, batch=batch):
+        indices = np.array(indices)
+
+        # `indices` is 2D: each row is a permutation of the indices.
+        # We use it to index `data` along its last axis, which corresponds
+        # with observations.
+        # After indexing, the second to last axis of `data_batch` corresponds
+        # with permutations, and the last axis corresponds with observations.
+        data_batch = data[..., indices]
+
+        # Move the permutation axis to the front: we'll concatenate a list
+        # of batched statistic values along this zeroth axis to form the
+        # null distribution.
+        data_batch = np.moveaxis(data_batch, -2, 0)
+        data_batch = np.split(data_batch, n_obs_ic[:-1], axis=-1)
+        null_distribution.append(statistic(*data_batch, axis=-1))
+    null_distribution = np.concatenate(null_distribution, axis=0)
+
+    return null_distribution, n_permutations, exact_test
+
+
+def _calculate_null_pairings(data, statistic, n_permutations, batch,
+                             rng=None):
+    """
+    Calculate null distribution for association tests.
+    """
+    n_samples = len(data)
+
+    # compute number of permutations (factorial(n) permutations of each sample)
+    n_obs_sample = data[0].shape[-1]  # observations per sample; same for each
+    n_max = factorial(n_obs_sample)**n_samples
+
+    # `perm_generator` is an iterator that produces a list of permutations of
+    # indices from 0 to n_obs_sample, one for each sample.
+    if n_permutations >= n_max:
+        exact_test = True
+        n_permutations = n_max
+        batch = batch or int(n_permutations)
+        # Cartesian product of the sets of all permutations of indices
+        perm_generator = product(*(permutations(range(n_obs_sample))
+                                   for i in range(n_samples)))
+        batched_perm_generator = _batch_generator(perm_generator, batch=batch)
+    else:
+        exact_test = False
+        batch = batch or int(n_permutations)
+        # Separate random permutations of indices for each sample.
+        # Again, it would be nice if RandomState/Generator.permutation
+        # could permute each axis-slice separately.
+        args = n_permutations, n_samples, n_obs_sample, batch, rng
+        batched_perm_generator = _pairings_permutations_gen(*args)
+
+    null_distribution = []
+
+    for indices in batched_perm_generator:
+        indices = np.array(indices)
+
+        # `indices` is 3D: the zeroth axis is for permutations, the next is
+        # for samples, and the last is for observations. Swap the first two
+        # to make the zeroth axis correspond with samples, as it does for
+        # `data`.
+        indices = np.swapaxes(indices, 0, 1)
+
+        # When we're done, `data_batch` will be a list of length `n_samples`.
+        # Each element will be a batch of random permutations of one sample.
+        # The zeroth axis of each batch will correspond with permutations,
+        # and the last will correspond with observations. (This makes it
+        # easy to pass into `statistic`.)
+        data_batch = [None]*n_samples
+        for i in range(n_samples):
+            data_batch[i] = data[i][..., indices[i]]
+            data_batch[i] = np.moveaxis(data_batch[i], -2, 0)
+
+        null_distribution.append(statistic(*data_batch, axis=-1))
+    null_distribution = np.concatenate(null_distribution, axis=0)
+
+    return null_distribution, n_permutations, exact_test
+
+
+def _calculate_null_samples(data, statistic, n_permutations, batch,
+                            rng=None):
+    """
+    Calculate null distribution for paired-sample tests.
+    """
+    n_samples = len(data)
+
+    # By convention, the meaning of the "samples" permutations type for
+    # data with only one sample is to flip the sign of the observations.
+    # Achieve this by adding a second sample - the negative of the original.
+    if n_samples == 1:
+        data = [data[0], -data[0]]
+
+    # The "samples" permutation strategy is the same as the "pairings"
+    # strategy except the roles of samples and observations are flipped.
+    # So swap these axes, then we'll use the function for the "pairings"
+    # strategy to do all the work!
+    data = np.swapaxes(data, 0, -1)
+
+    # (Of course, the user's statistic doesn't know what we've done here,
+    # so we need to pass it what it's expecting.)
+    def statistic_wrapped(*data, axis):
+        data = np.swapaxes(data, 0, -1)
+        if n_samples == 1:
+            data = data[0:1]
+        return statistic(*data, axis=axis)
+
+    return _calculate_null_pairings(data, statistic_wrapped, n_permutations,
+                                    batch, rng)
+
+
+def _permutation_test_iv(data, statistic, permutation_type, vectorized,
+                         n_resamples, batch, alternative, axis, rng):
+    """Input validation for `permutation_test`."""
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    permutation_types = {'samples', 'pairings', 'independent'}
+    permutation_type = permutation_type.lower()
+    if permutation_type not in permutation_types:
+        raise ValueError(f"`permutation_type` must be in {permutation_types}.")
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(statistic).parameters
+
+    if not vectorized:
+        statistic = _vectorize_statistic(statistic)
+
+    message = "`data` must be a tuple containing at least two samples"
+    try:
+        if len(data) < 2 and permutation_type == 'independent':
+            raise ValueError(message)
+    except TypeError:
+        raise TypeError(message)
+
+    data = _broadcast_arrays(data, axis)
+    data_iv = []
+    for sample in data:
+        sample = np.atleast_1d(sample)
+        if sample.shape[axis] <= 1:
+            raise ValueError("each sample in `data` must contain two or more "
+                             "observations along `axis`.")
+        sample = np.moveaxis(sample, axis_int, -1)
+        data_iv.append(sample)
+
+    n_resamples_int = (int(n_resamples) if not np.isinf(n_resamples)
+                       else np.inf)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    alternatives = {'two-sided', 'greater', 'less'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be in {alternatives}")
+
+    rng = check_random_state(rng)
+
+    return (data_iv, statistic, permutation_type, vectorized, n_resamples_int,
+            batch_iv, alternative, axis_int, rng)
+
+
+@_transition_to_rng('random_state')
+def permutation_test(data, statistic, *, permutation_type='independent',
+                     vectorized=None, n_resamples=9999, batch=None,
+                     alternative="two-sided", axis=0, rng=None):
+    r"""
+    Performs a permutation test of a given statistic on provided data.
+
+    For independent sample statistics, the null hypothesis is that the data are
+    randomly sampled from the same distribution.
+    For paired sample statistics, two null hypothesis can be tested:
+    that the data are paired at random or that the data are assigned to samples
+    at random.
+
+    Parameters
+    ----------
+    data : iterable of array-like
+        Contains the samples, each of which is an array of observations.
+        Dimensions of sample arrays must be compatible for broadcasting except
+        along `axis`.
+    statistic : callable
+        Statistic for which the p-value of the hypothesis test is to be
+        calculated. `statistic` must be a callable that accepts samples
+        as separate arguments (e.g. ``statistic(*data)``) and returns the
+        resulting statistic.
+        If `vectorized` is set ``True``, `statistic` must also accept a keyword
+        argument `axis` and be vectorized to compute the statistic along the
+        provided `axis` of the sample arrays.
+    permutation_type : {'independent', 'samples', 'pairings'}, optional
+        The type of permutations to be performed, in accordance with the
+        null hypothesis. The first two permutation types are for paired sample
+        statistics, in which all samples contain the same number of
+        observations and observations with corresponding indices along `axis`
+        are considered to be paired; the third is for independent sample
+        statistics.
+
+        - ``'samples'`` : observations are assigned to different samples
+          but remain paired with the same observations from other samples.
+          This permutation type is appropriate for paired sample hypothesis
+          tests such as the Wilcoxon signed-rank test and the paired t-test.
+        - ``'pairings'`` : observations are paired with different observations,
+          but they remain within the same sample. This permutation type is
+          appropriate for association/correlation tests with statistics such
+          as Spearman's :math:`\rho`, Kendall's :math:`\tau`, and Pearson's
+          :math:`r`.
+        - ``'independent'`` (default) : observations are assigned to different
+          samples. Samples may contain different numbers of observations. This
+          permutation type is appropriate for independent sample hypothesis
+          tests such as the Mann-Whitney :math:`U` test and the independent
+          sample t-test.
+
+          Please see the Notes section below for more detailed descriptions
+          of the permutation types.
+
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed an ND sample array. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use
+        of a vectorized statistic typically reduces computation time.
+    n_resamples : int or np.inf, default: 9999
+        Number of random permutations (resamples) used to approximate the null
+        distribution. If greater than or equal to the number of distinct
+        permutations, the exact null distribution will be computed.
+        Note that the number of distinct permutations grows very rapidly with
+        the sizes of samples, so exact tests are feasible only for very small
+        data sets.
+    batch : int, optional
+        The number of permutations to process in each call to `statistic`.
+        Memory usage is O( `batch` * ``n`` ), where ``n`` is the total size
+        of all samples, regardless of the value of `vectorized`. Default is
+        ``None``, in which case ``batch`` is the number of permutations.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        The alternative hypothesis for which the p-value is calculated.
+        For each alternative, the p-value is defined for exact tests as
+        follows.
+
+        - ``'greater'`` : the percentage of the null distribution that is
+          greater than or equal to the observed value of the test statistic.
+        - ``'less'`` : the percentage of the null distribution that is
+          less than or equal to the observed value of the test statistic.
+        - ``'two-sided'`` (default) : twice the smaller of the p-values above.
+
+        Note that p-values for randomized tests are calculated according to the
+        conservative (over-estimated) approximation suggested in [2]_ and [3]_
+        rather than the unbiased estimator suggested in [4]_. That is, when
+        calculating the proportion of the randomized null distribution that is
+        as extreme as the observed value of the test statistic, the values in
+        the numerator and denominator are both increased by one. An
+        interpretation of this adjustment is that the observed value of the
+        test statistic is always included as an element of the randomized
+        null distribution.
+        The convention used for two-sided p-values is not universal;
+        the observed test statistic and null distribution are returned in
+        case a different definition is preferred.
+
+    axis : int, default: 0
+        The axis of the (broadcasted) samples over which to calculate the
+        statistic. If samples have a different number of dimensions,
+        singleton dimensions are prepended to samples with fewer dimensions
+        before `axis` is considered.
+    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 : PermutationTestResult
+        An object with attributes:
+
+        statistic : float or ndarray
+            The observed test statistic of the data.
+        pvalue : float or ndarray
+            The p-value for the given alternative.
+        null_distribution : ndarray
+            The values of the test statistic generated under the null
+            hypothesis.
+
+    Notes
+    -----
+
+    The three types of permutation tests supported by this function are
+    described below.
+
+    **Unpaired statistics** (``permutation_type='independent'``):
+
+    The null hypothesis associated with this permutation type is that all
+    observations are sampled from the same underlying distribution and that
+    they have been assigned to one of the samples at random.
+
+    Suppose ``data`` contains two samples; e.g. ``a, b = data``.
+    When ``1 < n_resamples < binom(n, k)``, where
+
+    * ``k`` is the number of observations in ``a``,
+    * ``n`` is the total number of observations in ``a`` and ``b``, and
+    * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
+
+    the data are pooled (concatenated), randomly assigned to either the first
+    or second sample, and the statistic is calculated. This process is
+    performed repeatedly, `permutation` times, generating a distribution of the
+    statistic under the null hypothesis. The statistic of the original
+    data is compared to this distribution to determine the p-value.
+
+    When ``n_resamples >= binom(n, k)``, an exact test is performed: the data
+    are *partitioned* between the samples in each distinct way exactly once,
+    and the exact null distribution is formed.
+    Note that for a given partitioning of the data between the samples,
+    only one ordering/permutation of the data *within* each sample is
+    considered. For statistics that do not depend on the order of the data
+    within samples, this dramatically reduces computational cost without
+    affecting the shape of the null distribution (because the frequency/count
+    of each value is affected by the same factor).
+
+    For ``a = [a1, a2, a3, a4]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``x = [b3, a1, a2, b2]`` and ``y = [a4, b1, a3]``.
+    Because only one ordering/permutation of the data *within* each sample
+    is considered in an exact test, a resampling like ``x = [b3, a1, b2, a2]``
+    and ``y = [a4, a3, b1]`` would *not* be considered distinct from the
+    example above.
+
+    ``permutation_type='independent'`` does not support one-sample statistics,
+    but it can be applied to statistics with more than two samples. In this
+    case, if ``n`` is an array of the number of observations within each
+    sample, the number of distinct partitions is::
+
+        np.prod([binom(sum(n[i:]), sum(n[i+1:])) for i in range(len(n)-1)])
+
+    **Paired statistics, permute pairings** (``permutation_type='pairings'``):
+
+    The null hypothesis associated with this permutation type is that
+    observations within each sample are drawn from the same underlying
+    distribution and that pairings with elements of other samples are
+    assigned at random.
+
+    Suppose ``data`` contains only one sample; e.g. ``a, = data``, and we
+    wish to consider all possible pairings of elements of ``a`` with elements
+    of a second sample, ``b``. Let ``n`` be the number of observations in
+    ``a``, which must also equal the number of observations in ``b``.
+
+    When ``1 < n_resamples < factorial(n)``, the elements of ``a`` are
+    randomly permuted. The user-supplied statistic accepts one data argument,
+    say ``a_perm``, and calculates the statistic considering ``a_perm`` and
+    ``b``. This process is performed repeatedly, `permutation` times,
+    generating a distribution of the statistic under the null hypothesis.
+    The statistic of the original data is compared to this distribution to
+    determine the p-value.
+
+    When ``n_resamples >= factorial(n)``, an exact test is performed:
+    ``a`` is permuted in each distinct way exactly once. Therefore, the
+    `statistic` is computed for each unique pairing of samples between ``a``
+    and ``b`` exactly once.
+
+    For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``a_perm = [a3, a1, a2]`` while ``b`` is left
+    in its original order.
+
+    ``permutation_type='pairings'`` supports ``data`` containing any number
+    of samples, each of which must contain the same number of observations.
+    All samples provided in ``data`` are permuted *independently*. Therefore,
+    if ``m`` is the number of samples and ``n`` is the number of observations
+    within each sample, then the number of permutations in an exact test is::
+
+        factorial(n)**m
+
+    Note that if a two-sample statistic, for example, does not inherently
+    depend on the order in which observations are provided - only on the
+    *pairings* of observations - then only one of the two samples should be
+    provided in ``data``. This dramatically reduces computational cost without
+    affecting the shape of the null distribution (because the frequency/count
+    of each value is affected by the same factor).
+
+    **Paired statistics, permute samples** (``permutation_type='samples'``):
+
+    The null hypothesis associated with this permutation type is that
+    observations within each pair are drawn from the same underlying
+    distribution and that the sample to which they are assigned is random.
+
+    Suppose ``data`` contains two samples; e.g. ``a, b = data``.
+    Let ``n`` be the number of observations in ``a``, which must also equal
+    the number of observations in ``b``.
+
+    When ``1 < n_resamples < 2**n``, the elements of ``a`` are ``b`` are
+    randomly swapped between samples (maintaining their pairings) and the
+    statistic is calculated. This process is performed repeatedly,
+    `permutation` times,  generating a distribution of the statistic under the
+    null hypothesis. The statistic of the original data is compared to this
+    distribution to determine the p-value.
+
+    When ``n_resamples >= 2**n``, an exact test is performed: the observations
+    are assigned to the two samples in each distinct way (while maintaining
+    pairings) exactly once.
+
+    For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``x = [b1, a2, b3]`` and ``y = [a1, b2, a3]``.
+
+    ``permutation_type='samples'`` supports ``data`` containing any number
+    of samples, each of which must contain the same number of observations.
+    If ``data`` contains more than one sample, paired observations within
+    ``data`` are exchanged between samples *independently*. Therefore, if ``m``
+    is the number of samples and ``n`` is the number of observations within
+    each sample, then the number of permutations in an exact test is::
+
+        factorial(m)**n
+
+    Several paired-sample statistical tests, such as the Wilcoxon signed rank
+    test and paired-sample t-test, can be performed considering only the
+    *difference* between two paired elements. Accordingly, if ``data`` contains
+    only one sample, then the null distribution is formed by independently
+    changing the *sign* of each observation.
+
+    .. warning::
+        The p-value is calculated by counting the elements of the null
+        distribution that are as extreme or more extreme than the observed
+        value of the statistic. Due to the use of finite precision arithmetic,
+        some statistic functions return numerically distinct values when the
+        theoretical values would be exactly equal. In some cases, this could
+        lead to a large error in the calculated p-value. `permutation_test`
+        guards against this by considering elements in the null distribution
+        that are "close" (within a relative tolerance of 100 times the
+        floating point epsilon of inexact dtypes) to the observed
+        value of the test statistic as equal to the observed value of the
+        test statistic. However, the user is advised to inspect the null
+        distribution to assess whether this method of comparison is
+        appropriate, and if not, calculate the p-value manually. See example
+        below.
+
+    References
+    ----------
+
+    .. [1] R. A. Fisher. The Design of Experiments, 6th Ed (1951).
+    .. [2] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
+       Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
+       Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
+    .. [3] M. D. Ernst. "Permutation Methods: A Basis for Exact Inference".
+       Statistical Science (2004).
+    .. [4] B. Efron and R. J. Tibshirani. An Introduction to the Bootstrap
+       (1993).
+
+    Examples
+    --------
+
+    Suppose we wish to test whether two samples are drawn from the same
+    distribution. Assume that the underlying distributions are unknown to us,
+    and that before observing the data, we hypothesized that the mean of the
+    first sample would be less than that of the second sample. We decide that
+    we will use the difference between the sample means as a test statistic,
+    and we will consider a p-value of 0.05 to be statistically significant.
+
+    For efficiency, we write the function defining the test statistic in a
+    vectorized fashion: the samples ``x`` and ``y`` can be ND arrays, and the
+    statistic will be calculated for each axis-slice along `axis`.
+
+    >>> import numpy as np
+    >>> def statistic(x, y, axis):
+    ...     return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+
+    After collecting our data, we calculate the observed value of the test
+    statistic.
+
+    >>> from scipy.stats import norm
+    >>> rng = np.random.default_rng()
+    >>> x = norm.rvs(size=5, random_state=rng)
+    >>> y = norm.rvs(size=6, loc = 3, random_state=rng)
+    >>> statistic(x, y, 0)
+    -3.5411688580987266
+
+    Indeed, the test statistic is negative, suggesting that the true mean of
+    the distribution underlying ``x`` is less than that of the distribution
+    underlying ``y``. To determine the probability of this occurring by chance
+    if the two samples were drawn from the same distribution, we perform
+    a permutation test.
+
+    >>> from scipy.stats import permutation_test
+    >>> # because our statistic is vectorized, we pass `vectorized=True`
+    >>> # `n_resamples=np.inf` indicates that an exact test is to be performed
+    >>> res = permutation_test((x, y), statistic, vectorized=True,
+    ...                        n_resamples=np.inf, alternative='less')
+    >>> print(res.statistic)
+    -3.5411688580987266
+    >>> print(res.pvalue)
+    0.004329004329004329
+
+    The probability of obtaining a test statistic less than or equal to the
+    observed value under the null hypothesis is 0.4329%. This is less than our
+    chosen threshold of 5%, so we consider this to be significant evidence
+    against the null hypothesis in favor of the alternative.
+
+    Because the size of the samples above was small, `permutation_test` could
+    perform an exact test. For larger samples, we resort to a randomized
+    permutation test.
+
+    >>> x = norm.rvs(size=100, random_state=rng)
+    >>> y = norm.rvs(size=120, loc=0.2, random_state=rng)
+    >>> res = permutation_test((x, y), statistic, n_resamples=9999,
+    ...                        vectorized=True, alternative='less',
+    ...                        rng=rng)
+    >>> print(res.statistic)
+    -0.4230459671240913
+    >>> print(res.pvalue)
+    0.0015
+
+    The approximate probability of obtaining a test statistic less than or
+    equal to the observed value under the null hypothesis is 0.0225%. This is
+    again less than our chosen threshold of 5%, so again we have significant
+    evidence to reject the null hypothesis in favor of the alternative.
+
+    For large samples and number of permutations, the result is comparable to
+    that of the corresponding asymptotic test, the independent sample t-test.
+
+    >>> from scipy.stats import ttest_ind
+    >>> res_asymptotic = ttest_ind(x, y, alternative='less')
+    >>> print(res_asymptotic.pvalue)
+    0.0014669545224902675
+
+    The permutation distribution of the test statistic is provided for
+    further investigation.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.hist(res.null_distribution, bins=50)
+    >>> plt.title("Permutation distribution of test statistic")
+    >>> plt.xlabel("Value of Statistic")
+    >>> plt.ylabel("Frequency")
+    >>> plt.show()
+
+    Inspection of the null distribution is essential if the statistic suffers
+    from inaccuracy due to limited machine precision. Consider the following
+    case:
+
+    >>> from scipy.stats import pearsonr
+    >>> x = [1, 2, 4, 3]
+    >>> y = [2, 4, 6, 8]
+    >>> def statistic(x, y, axis=-1):
+    ...     return pearsonr(x, y, axis=axis).statistic
+    >>> res = permutation_test((x, y), statistic, vectorized=True,
+    ...                        permutation_type='pairings',
+    ...                        alternative='greater')
+    >>> r, pvalue, null = res.statistic, res.pvalue, res.null_distribution
+
+    In this case, some elements of the null distribution differ from the
+    observed value of the correlation coefficient ``r`` due to numerical noise.
+    We manually inspect the elements of the null distribution that are nearly
+    the same as the observed value of the test statistic.
+
+    >>> r
+    0.7999999999999999
+    >>> unique = np.unique(null)
+    >>> unique
+    array([-1. , -1. , -0.8, -0.8, -0.8, -0.6, -0.4, -0.4, -0.2, -0.2, -0.2,
+        0. ,  0.2,  0.2,  0.2,  0.4,  0.4,  0.6,  0.8,  0.8,  0.8,  1. ,
+        1. ])  # may vary
+    >>> unique[np.isclose(r, unique)].tolist()
+    [0.7999999999999998, 0.7999999999999999, 0.8]  # may vary
+
+    If `permutation_test` were to perform the comparison naively, the
+    elements of the null distribution with value ``0.7999999999999998`` would
+    not be considered as extreme or more extreme as the observed value of the
+    statistic, so the calculated p-value would be too small.
+
+    >>> incorrect_pvalue = np.count_nonzero(null >= r) / len(null)
+    >>> incorrect_pvalue
+    0.14583333333333334  # may vary
+
+    Instead, `permutation_test` treats elements of the null distribution that
+    are within ``max(1e-14, abs(r)*1e-14)`` of the observed value of the
+    statistic ``r`` to be equal to ``r``.
+
+    >>> correct_pvalue = np.count_nonzero(null >= r - 1e-14) / len(null)
+    >>> correct_pvalue
+    0.16666666666666666
+    >>> res.pvalue == correct_pvalue
+    True
+
+    This method of comparison is expected to be accurate in most practical
+    situations, but the user is advised to assess this by inspecting the
+    elements of the null distribution that are close to the observed value
+    of the statistic. Also, consider the use of statistics that can be
+    calculated using exact arithmetic (e.g. integer statistics).
+
+    """
+    args = _permutation_test_iv(data, statistic, permutation_type, vectorized,
+                                n_resamples, batch, alternative, axis,
+                                rng)
+    (data, statistic, permutation_type, vectorized, n_resamples, batch,
+     alternative, axis, rng) = args
+
+    observed = statistic(*data, axis=-1)
+
+    null_calculators = {"pairings": _calculate_null_pairings,
+                        "samples": _calculate_null_samples,
+                        "independent": _calculate_null_both}
+    null_calculator_args = (data, statistic, n_resamples,
+                            batch, rng)
+    calculate_null = null_calculators[permutation_type]
+    null_distribution, n_resamples, exact_test = (
+        calculate_null(*null_calculator_args))
+
+    # See References [2] and [3]
+    adjustment = 0 if exact_test else 1
+
+    # relative tolerance for detecting numerically distinct but
+    # theoretically equal values in the null distribution
+    eps =  (0 if not np.issubdtype(observed.dtype, np.inexact)
+            else np.finfo(observed.dtype).eps*100)
+    gamma = np.abs(eps * observed)
+
+    def less(null_distribution, observed):
+        cmps = null_distribution <= observed + gamma
+        pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment)
+        return pvalues
+
+    def greater(null_distribution, observed):
+        cmps = null_distribution >= observed - gamma
+        pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment)
+        return pvalues
+
+    def two_sided(null_distribution, observed):
+        pvalues_less = less(null_distribution, observed)
+        pvalues_greater = greater(null_distribution, observed)
+        pvalues = np.minimum(pvalues_less, pvalues_greater) * 2
+        return pvalues
+
+    compare = {"less": less,
+               "greater": greater,
+               "two-sided": two_sided}
+
+    pvalues = compare[alternative](null_distribution, observed)
+    pvalues = np.clip(pvalues, 0, 1)
+
+    return PermutationTestResult(observed, pvalues, null_distribution)
+
+
+@dataclass
+class ResamplingMethod:
+    """Configuration information for a statistical resampling method.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a resampling or Monte Carlo version
+    of the hypothesis test.
+
+    Attributes
+    ----------
+    n_resamples : int
+        The number of resamples to perform or Monte Carlo samples to draw.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+
+    """
+    n_resamples: int = 9999
+    batch: int = None  # type: ignore[assignment]
+
+
+@dataclass
+class MonteCarloMethod(ResamplingMethod):
+    """Configuration information for a Monte Carlo hypothesis test.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a Monte Carlo version of the
+    hypothesis tests.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of Monte Carlo samples to draw. Default is 9999.
+    batch : int, optional
+        The number of Monte Carlo samples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all samples in a single batch.
+    rvs : callable or tuple of callables, optional
+        A callable or sequence of callables that generates random variates
+        under the null hypothesis. Each element of `rvs` must be a callable
+        that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
+        returns an N-d array sample of that shape. If `rvs` is a sequence, the
+        number of callables in `rvs` must match the number of samples passed
+        to the hypothesis test in which the `MonteCarloMethod` is used. Default
+        is ``None``, in which case the hypothesis test function chooses values
+        to match the standard version of the hypothesis test. For example,
+        the null hypothesis of `scipy.stats.pearsonr` is typically that the
+        samples are drawn from the standard normal distribution, so
+        ``rvs = (rng.normal, rng.normal)`` where
+        ``rng = np.random.default_rng()``.
+    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``.
+
+    """
+    rvs: object = None
+    rng: object = None
+
+    def __init__(self, n_resamples=9999, batch=None, rvs=None, rng=None):
+        if (rvs is not None) and (rng is not None):
+            message = 'Use of `rvs` and `rng` are mutually exclusive.'
+            raise ValueError(message)
+
+        self.n_resamples = n_resamples
+        self.batch = batch
+        self.rvs = rvs
+        self.rng = rng
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        return dict(n_resamples=self.n_resamples, batch=self.batch,
+                    rvs=self.rvs, rng=self.rng)
+
+
+_rs_deprecation = ("Use of attribute `random_state` is deprecated and replaced by "
+                   "`rng`. Support for `random_state` will be removed in SciPy 1.19.0. "
+                   "To silence this warning and ensure consistent behavior in SciPy "
+                   "1.19.0, control the RNG using attribute `rng`. Values set using "
+                   "attribute `rng` will be validated by `np.random.default_rng`, so "
+                   "the behavior corresponding with a given value may change compared "
+                   "to use of `random_state`. 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.")
+
+
+@dataclass
+class PermutationMethod(ResamplingMethod):
+    """Configuration information for a permutation hypothesis test.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a permutation version of the
+    hypothesis tests.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of resamples to perform. Default is 9999.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator used to perform resampling.
+
+        If `rng` is passed by keyword to the initializer or the `rng` attribute is used
+        directly, types other than `numpy.random.Generator` are passed to
+        `numpy.random.default_rng` to instantiate a ``Generator`` before use.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable behavior.
+
+        If this argument is passed by position, if `random_state` is passed by keyword
+        into the initializer, or if the `random_state` attribute is used directly,
+        legacy behavior for `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` 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 attribute name was changed from
+            `random_state` to `rng`. For an interim period, both names will continue to
+            work, although only one may be specified at a time. After the interim
+            period, uses of `random_state` will emit warnings. The behavior of both
+            `random_state` and `rng` are outlined above, but only `rng` should be used
+            in new code.
+
+    """
+    rng: object  # type: ignore[misc]
+    _rng: object = field(init=False, repr=False, default=None)  # type: ignore[assignment]
+
+    @property
+    def random_state(self):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, val):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        self._random_state = val
+
+    @property  # type: ignore[no-redef]
+    def rng(self):  # noqa: F811
+        return self._rng
+
+    def __init__(self, n_resamples=9999, batch=None, random_state=None, *, rng=None):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
+        #               DeprecationWarning, stacklevel=2)
+        self._rng = rng
+        self._random_state = random_state
+        super().__init__(n_resamples=n_resamples, batch=batch)
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        d = dict(n_resamples=self.n_resamples, batch=self.batch)
+        if self.rng is not None:
+            d['rng'] = self.rng
+        if self.random_state is not None:
+            d['random_state'] = self.random_state
+        return d
+
+
+@dataclass
+class BootstrapMethod(ResamplingMethod):
+    """Configuration information for a bootstrap confidence interval.
+
+    Instances of this class can be passed into the `method` parameter of some
+    confidence interval methods to generate a bootstrap confidence interval.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of resamples to perform. Default is 9999.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator used to perform resampling.
+
+        If `rng` is passed by keyword to the initializer or the `rng` attribute is used
+        directly, types other than `numpy.random.Generator` are passed to
+        `numpy.random.default_rng` to instantiate a ``Generator``  before use.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable behavior.
+
+        If this argument is passed by position, if `random_state` is passed by keyword
+        into the initializer, or if the `random_state` attribute is used directly,
+        legacy behavior for `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` 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 attribute name was changed from
+            `random_state` to `rng`. For an interim period, both names will continue to
+            work, although only one may be specified at a time. After the interim
+            period, uses of `random_state` will emit warnings. The behavior of both
+            `random_state` and `rng` are outlined above, but only `rng` should be used
+            in new code.
+
+    method : {'BCa', 'percentile', 'basic'}
+        Whether to use the 'percentile' bootstrap ('percentile'), the 'basic'
+        (AKA 'reverse') bootstrap ('basic'), or the bias-corrected and
+        accelerated bootstrap ('BCa', default).
+
+    """
+    rng: object  # type: ignore[misc]
+    _rng: object = field(init=False, repr=False, default=None)  # type: ignore[assignment]
+    method: str = 'BCa'
+
+    @property
+    def random_state(self):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, val):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        self._random_state = val
+
+    @property  # type: ignore[no-redef]
+    def rng(self):  # noqa: F811
+        return self._rng
+
+    def __init__(self, n_resamples=9999, batch=None, random_state=None,
+                 method='BCa', *, rng=None):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
+        #               DeprecationWarning, stacklevel=2)
+        self._rng = rng  # don't validate with `default_rng`
+        self._random_state = random_state
+        self.method = method
+        super().__init__(n_resamples=n_resamples, batch=batch)
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        d = dict(n_resamples=self.n_resamples, batch=self.batch,
+                 method=self.method)
+        if self.rng is not None:
+            d['rng'] = self.rng
+        if self.random_state is not None:
+            d['random_state'] = self.random_state
+        return d
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_result_classes.py b/python_embeded/Lib/site-packages/scipy/stats/_result_classes.py
new file mode 100644
index 0000000000000000000000000000000000000000..58b1eb2487dec575c47012e2dbebae75749687c8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_result_classes.py
@@ -0,0 +1,40 @@
+# This module exists only to allow Sphinx to generate docs
+# for the result objects returned by some functions in stats
+# _without_ adding them to the main stats documentation page.
+
+"""
+Result classes
+--------------
+
+.. currentmodule:: scipy.stats._result_classes
+
+.. autosummary::
+   :toctree: generated/
+
+   RelativeRiskResult
+   BinomTestResult
+   TukeyHSDResult
+   DunnettResult
+   PearsonRResult
+   FitResult
+   OddsRatioResult
+   TtestResult
+   ECDFResult
+   EmpiricalDistributionFunction
+
+"""
+
+__all__ = ['BinomTestResult', 'RelativeRiskResult', 'TukeyHSDResult',
+           'PearsonRResult', 'FitResult', 'OddsRatioResult',
+           'TtestResult', 'DunnettResult', 'ECDFResult',
+           'EmpiricalDistributionFunction']
+
+
+from ._binomtest import BinomTestResult
+from ._odds_ratio import OddsRatioResult
+from ._relative_risk import RelativeRiskResult
+from ._hypotests import TukeyHSDResult
+from ._multicomp import DunnettResult
+from ._stats_py import PearsonRResult, TtestResult
+from ._fit import FitResult
+from ._survival import ECDFResult, EmpiricalDistributionFunction
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_sampling.py b/python_embeded/Lib/site-packages/scipy/stats/_sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..143ad644b1d13b6fc09acbbf3914d1741431682e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_sampling.py
@@ -0,0 +1,1314 @@
+import math
+import numbers
+import numpy as np
+from scipy import stats
+from scipy import special as sc
+from ._qmc import (check_random_state as check_random_state_qmc,
+                   Halton, QMCEngine)
+from ._unuran.unuran_wrapper import NumericalInversePolynomial
+from scipy._lib._util import check_random_state
+
+
+__all__ = ['FastGeneratorInversion', 'RatioUniforms']
+
+
+# define pdfs and other helper functions to create the generators
+
+def argus_pdf(x, chi):
+    # approach follows Baumgarten/Hoermann: Generating ARGUS random variates
+    # for chi > 5, use relationship of the ARGUS distribution to Gamma(1.5)
+    if chi <= 5:
+        y = 1 - x * x
+        return x * math.sqrt(y) * math.exp(-0.5 * chi**2 * y)
+    return math.sqrt(x) * math.exp(-x)
+
+
+def argus_gamma_trf(x, chi):
+    if chi <= 5:
+        return x
+    return np.sqrt(1.0 - 2 * x / chi**2)
+
+
+def argus_gamma_inv_trf(x, chi):
+    if chi <= 5:
+        return x
+    return 0.5 * chi**2 * (1 - x**2)
+
+
+def betaprime_pdf(x, a, b):
+    if x > 0:
+        logf = (a - 1) * math.log(x) - (a + b) * math.log1p(x) - sc.betaln(a, b)
+        return math.exp(logf)
+    else:
+        # return pdf at x == 0 separately to avoid runtime warnings
+        if a > 1:
+            return 0
+        elif a < 1:
+            return np.inf
+        else:
+            return 1 / sc.beta(a, b)
+
+
+def beta_valid_params(a, b):
+    return (min(a, b) >= 0.1) and (max(a, b) <= 700)
+
+
+def gamma_pdf(x, a):
+    if x > 0:
+        return math.exp(-math.lgamma(a) + (a - 1.0) * math.log(x) - x)
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def invgamma_pdf(x, a):
+    if x > 0:
+        return math.exp(-(a + 1.0) * math.log(x) - math.lgamma(a) - 1 / x)
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def burr_pdf(x, cc, dd):
+    # note: we use np.exp instead of math.exp, otherwise an overflow
+    # error can occur in the setup, e.g., for parameters
+    # 1.89128135, 0.30195177, see test test_burr_overflow
+    if x > 0:
+        lx = math.log(x)
+        return np.exp(-(cc + 1) * lx - (dd + 1) * math.log1p(np.exp(-cc * lx)))
+    else:
+        return 0
+
+
+def burr12_pdf(x, cc, dd):
+    if x > 0:
+        lx = math.log(x)
+        logterm = math.log1p(math.exp(cc * lx))
+        return math.exp((cc - 1) * lx - (dd + 1) * logterm + math.log(cc * dd))
+    else:
+        return 0
+
+
+def chi_pdf(x, a):
+    if x > 0:
+        return math.exp(
+            (a - 1) * math.log(x)
+            - 0.5 * (x * x)
+            - (a / 2 - 1) * math.log(2)
+            - math.lgamma(0.5 * a)
+        )
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def chi2_pdf(x, df):
+    if x > 0:
+        return math.exp(
+            (df / 2 - 1) * math.log(x)
+            - 0.5 * x
+            - (df / 2) * math.log(2)
+            - math.lgamma(0.5 * df)
+        )
+    else:
+        return 0 if df >= 1 else np.inf
+
+
+def alpha_pdf(x, a):
+    if x > 0:
+        return math.exp(-2.0 * math.log(x) - 0.5 * (a - 1.0 / x) ** 2)
+    return 0.0
+
+
+def bradford_pdf(x, c):
+    if 0 <= x <= 1:
+        return 1.0 / (1.0 + c * x)
+    return 0.0
+
+
+def crystalball_pdf(x, b, m):
+    if x > -b:
+        return math.exp(-0.5 * x * x)
+    return math.exp(m * math.log(m / b) - 0.5 * b * b - m * math.log(m / b - b - x))
+
+
+def weibull_min_pdf(x, c):
+    if x > 0:
+        return c * math.exp((c - 1) * math.log(x) - x**c)
+    return 0.0
+
+
+def weibull_max_pdf(x, c):
+    if x < 0:
+        return c * math.exp((c - 1) * math.log(-x) - ((-x) ** c))
+    return 0.0
+
+
+def invweibull_pdf(x, c):
+    if x > 0:
+        return c * math.exp(-(c + 1) * math.log(x) - x ** (-c))
+    return 0.0
+
+
+def wald_pdf(x):
+    if x > 0:
+        return math.exp(-((x - 1) ** 2) / (2 * x)) / math.sqrt(x**3)
+    return 0.0
+
+
+def geninvgauss_mode(p, b):
+    if p > 1:  # equivalent mode formulas numerical more stable versions
+        return (math.sqrt((1 - p) ** 2 + b**2) - (1 - p)) / b
+    return b / (math.sqrt((1 - p) ** 2 + b**2) + (1 - p))
+
+
+def geninvgauss_pdf(x, p, b):
+    m = geninvgauss_mode(p, b)
+    lfm = (p - 1) * math.log(m) - 0.5 * b * (m + 1 / m)
+    if x > 0:
+        return math.exp((p - 1) * math.log(x) - 0.5 * b * (x + 1 / x) - lfm)
+    return 0.0
+
+
+def invgauss_mode(mu):
+    return 1.0 / (math.sqrt(1.5 * 1.5 + 1 / (mu * mu)) + 1.5)
+
+
+def invgauss_pdf(x, mu):
+    m = invgauss_mode(mu)
+    lfm = -1.5 * math.log(m) - (m - mu) ** 2 / (2 * m * mu**2)
+    if x > 0:
+        return math.exp(-1.5 * math.log(x) - (x - mu) ** 2 / (2 * x * mu**2) - lfm)
+    return 0.0
+
+
+def powerlaw_pdf(x, a):
+    if x > 0:
+        return x ** (a - 1)
+    return 0.0
+
+
+# Define a dictionary: for a given distribution (keys), another dictionary
+# (values) specifies the parameters for NumericalInversePolynomial (PINV).
+# The keys of the latter dictionary are:
+# - pdf: the pdf of the distribution (callable). The signature of the pdf
+#   is float -> float (i.e., the function does not have to be vectorized).
+#   If possible, functions like log or exp from the module math should be
+#   preferred over functions from numpy since the PINV setup will be faster
+#   in that case.
+# - check_pinv_params: callable f that returns true if the shape parameters
+#   (args) are recommended parameters for PINV (i.e., the u-error does
+#   not exceed the default tolerance)
+# - center: scalar if the center does not depend on args, otherwise
+#   callable that returns the center as a function of the shape parameters
+# - rvs_transform: a callable that can be used to transform the rvs that
+#   are distributed according to the pdf to the target distribution
+#   (as an example, see the entry for the beta distribution)
+# - rvs_transform_inv: the inverse of rvs_transform (it is required
+#   for the transformed ppf)
+# - mirror_uniform: boolean or a callable that returns true or false
+#   depending on the shape parameters. If True, the ppf is applied
+#   to 1-u instead of u to generate rvs, where u is a uniform rv.
+#   While both u and 1-u are uniform, it can be required to use 1-u
+#   to compute the u-error correctly. This is only relevant for the argus
+#   distribution.
+# The only required keys are "pdf" and "check_pinv_params".
+# All other keys are optional.
+
+PINV_CONFIG = {
+    "alpha": {
+        "pdf": alpha_pdf,
+        "check_pinv_params": lambda a: 1.0e-11 <= a < 2.1e5,
+        "center": lambda a: 0.25 * (math.sqrt(a * a + 8.0) - a),
+    },
+    "anglit": {
+        "pdf": lambda x: math.cos(2 * x) + 1.0e-13,
+        # +1.e-13 is necessary, otherwise PINV has strange problems as
+        # f(upper border) is very close to 0
+        "center": 0,
+    },
+    "argus": {
+        "pdf": argus_pdf,
+        "center": lambda chi: 0.7 if chi <= 5 else 0.5,
+        "check_pinv_params": lambda chi: 1e-20 < chi < 901,
+        "rvs_transform": argus_gamma_trf,
+        "rvs_transform_inv": argus_gamma_inv_trf,
+        "mirror_uniform": lambda chi: chi > 5,
+    },
+    "beta": {
+        "pdf": betaprime_pdf,
+        "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
+        "check_pinv_params": beta_valid_params,
+        "rvs_transform": lambda x, *args: x / (1 + x),
+        "rvs_transform_inv": lambda x, *args: x / (1 - x) if x < 1 else np.inf,
+    },
+    "betaprime": {
+        "pdf": betaprime_pdf,
+        "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
+        "check_pinv_params": beta_valid_params,
+    },
+    "bradford": {
+        "pdf": bradford_pdf,
+        "check_pinv_params": lambda a: 1.0e-6 <= a <= 1e9,
+        "center": 0.5,
+    },
+    "burr": {
+        "pdf": burr_pdf,
+        "center": lambda a, b: (2 ** (1 / b) - 1) ** (-1 / a),
+        "check_pinv_params": lambda a, b: (min(a, b) >= 0.3) and (max(a, b) <= 50),
+    },
+    "burr12": {
+        "pdf": burr12_pdf,
+        "center": lambda a, b: (2 ** (1 / b) - 1) ** (1 / a),
+        "check_pinv_params": lambda a, b: (min(a, b) >= 0.2) and (max(a, b) <= 50),
+    },
+    "cauchy": {
+        "pdf": lambda x: 1 / (1 + (x * x)),
+        "center": 0,
+    },
+    "chi": {
+        "pdf": chi_pdf,
+        "check_pinv_params": lambda df: 0.05 <= df <= 1.0e6,
+        "center": lambda a: math.sqrt(a),
+    },
+    "chi2": {
+        "pdf": chi2_pdf,
+        "check_pinv_params": lambda df: 0.07 <= df <= 1e6,
+        "center": lambda a: a,
+    },
+    "cosine": {
+        "pdf": lambda x: 1 + math.cos(x),
+        "center": 0,
+    },
+    "crystalball": {
+        "pdf": crystalball_pdf,
+        "check_pinv_params": lambda b, m: (0.01 <= b <= 5.5)
+        and (1.1 <= m <= 75.1),
+        "center": 0.0,
+    },
+    "expon": {
+        "pdf": lambda x: math.exp(-x),
+        "center": 1.0,
+    },
+    "gamma": {
+        "pdf": gamma_pdf,
+        "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
+        "center": lambda a: a,
+    },
+    "gennorm": {
+        "pdf": lambda x, b: math.exp(-abs(x) ** b),
+        "check_pinv_params": lambda b: 0.081 <= b <= 45.0,
+        "center": 0.0,
+    },
+    "geninvgauss": {
+        "pdf": geninvgauss_pdf,
+        "check_pinv_params": lambda p, b: (abs(p) <= 1200.0)
+        and (1.0e-10 <= b <= 1200.0),
+        "center": geninvgauss_mode,
+    },
+    "gumbel_l": {
+        "pdf": lambda x: math.exp(x - math.exp(x)),
+        "center": -0.6,
+    },
+    "gumbel_r": {
+        "pdf": lambda x: math.exp(-x - math.exp(-x)),
+        "center": 0.6,
+    },
+    "hypsecant": {
+        "pdf": lambda x: 1.0 / (math.exp(x) + math.exp(-x)),
+        "center": 0.0,
+    },
+    "invgamma": {
+        "pdf": invgamma_pdf,
+        "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
+        "center": lambda a: 1 / a,
+    },
+    "invgauss": {
+        "pdf": invgauss_pdf,
+        "check_pinv_params": lambda mu: 1.0e-10 <= mu <= 1.0e9,
+        "center": invgauss_mode,
+    },
+    "invweibull": {
+        "pdf": invweibull_pdf,
+        "check_pinv_params": lambda a: 0.12 <= a <= 512,
+        "center": 1.0,
+    },
+    "laplace": {
+        "pdf": lambda x: math.exp(-abs(x)),
+        "center": 0.0,
+    },
+    "logistic": {
+        "pdf": lambda x: math.exp(-x) / (1 + math.exp(-x)) ** 2,
+        "center": 0.0,
+    },
+    "maxwell": {
+        "pdf": lambda x: x * x * math.exp(-0.5 * x * x),
+        "center": 1.41421,
+    },
+    "moyal": {
+        "pdf": lambda x: math.exp(-(x + math.exp(-x)) / 2),
+        "center": 1.2,
+    },
+    "norm": {
+        "pdf": lambda x: math.exp(-x * x / 2),
+        "center": 0.0,
+    },
+    "pareto": {
+        "pdf": lambda x, b: x ** -(b + 1),
+        "center": lambda b: b / (b - 1) if b > 2 else 1.5,
+        "check_pinv_params": lambda b: 0.08 <= b <= 400000,
+    },
+    "powerlaw": {
+        "pdf": powerlaw_pdf,
+        "center": 1.0,
+        "check_pinv_params": lambda a: 0.06 <= a <= 1.0e5,
+    },
+    "t": {
+        "pdf": lambda x, df: (1 + x * x / df) ** (-0.5 * (df + 1)),
+        "check_pinv_params": lambda a: 0.07 <= a <= 1e6,
+        "center": 0.0,
+    },
+    "rayleigh": {
+        "pdf": lambda x: x * math.exp(-0.5 * (x * x)),
+        "center": 1.0,
+    },
+    "semicircular": {
+        "pdf": lambda x: math.sqrt(1.0 - (x * x)),
+        "center": 0,
+    },
+    "wald": {
+        "pdf": wald_pdf,
+        "center": 1.0,
+    },
+    "weibull_max": {
+        "pdf": weibull_max_pdf,
+        "check_pinv_params": lambda a: 0.25 <= a <= 512,
+        "center": -1.0,
+    },
+    "weibull_min": {
+        "pdf": weibull_min_pdf,
+        "check_pinv_params": lambda a: 0.25 <= a <= 512,
+        "center": 1.0,
+    },
+}
+
+
+def _validate_qmc_input(qmc_engine, d, seed):
+    # Input validation for `qmc_engine` and `d`
+    # Error messages for invalid `d` are raised by QMCEngine
+    # we could probably use a stats.qmc.check_qrandom_state
+    if isinstance(qmc_engine, QMCEngine):
+        if d is not None and qmc_engine.d != d:
+            message = "`d` must be consistent with dimension of `qmc_engine`."
+            raise ValueError(message)
+        d = qmc_engine.d if d is None else d
+    elif qmc_engine is None:
+        d = 1 if d is None else d
+        qmc_engine = Halton(d, seed=seed)
+    else:
+        message = (
+            "`qmc_engine` must be an instance of "
+            "`scipy.stats.qmc.QMCEngine` or `None`."
+        )
+        raise ValueError(message)
+
+    return qmc_engine, d
+
+
+class CustomDistPINV:
+    def __init__(self, pdf, args):
+        self._pdf = lambda x: pdf(x, *args)
+
+    def pdf(self, x):
+        return self._pdf(x)
+
+
+class FastGeneratorInversion:
+    """
+    Fast sampling by numerical inversion of the CDF for a large class of
+    continuous distributions in `scipy.stats`.
+
+    Parameters
+    ----------
+    dist : rv_frozen object
+        Frozen distribution object from `scipy.stats`. The list of supported
+        distributions can be found in the Notes section. The shape parameters,
+        `loc` and `scale` used to create the distributions must be scalars.
+        For example, for the Gamma distribution with shape parameter `p`,
+        `p` has to be a float, and for the beta distribution with shape
+        parameters (a, b), both a and b have to be floats.
+    domain : tuple of floats, optional
+        If one wishes to sample from a truncated/conditional distribution,
+        the domain has to be specified.
+        The default is None. In that case, the random variates are not
+        truncated, and the domain is inferred from the support of the
+        distribution.
+    ignore_shape_range : boolean, optional.
+        If False, shape parameters that are outside of the valid range
+        of values to ensure that the numerical accuracy (see Notes) is
+        high, raise a ValueError. If True, any shape parameters that are valid
+        for the distribution are accepted. This can be useful for testing.
+        The default is False.
+    random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            A NumPy random number generator or seed for the underlying NumPy
+            random number generator used to generate the stream of uniform
+            random numbers.
+            If `random_state` is None, it uses ``self.random_state``.
+            If `random_state` is an int,
+            ``np.random.default_rng(random_state)`` is used.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+    Attributes
+    ----------
+    loc : float
+        The location parameter.
+    random_state : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        The random state used in relevant methods like `rvs` (unless
+        another `random_state` is passed as an argument to these methods).
+    scale : float
+        The scale parameter.
+
+    Methods
+    -------
+    cdf
+    evaluate_error
+    ppf
+    qrvs
+    rvs
+    support
+
+    Notes
+    -----
+    The class creates an object for continuous distributions specified
+    by `dist`. The method `rvs` uses a generator from
+    `scipy.stats.sampling` that is created when the object is instantiated.
+    In addition, the methods `qrvs` and `ppf` are added.
+    `qrvs` generate samples based on quasi-random numbers from
+    `scipy.stats.qmc`. `ppf` is the PPF based on the
+    numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is
+    used to generate random variates.
+
+    Supported distributions (`distname`) are:
+    ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``,
+    ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``,
+    ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``,
+    ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``,
+    ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``,
+    ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``,
+    ``wald``, ``weibull_max``, ``weibull_min``.
+
+    `rvs` relies on the accuracy of the numerical inversion. If very extreme
+    shape parameters are used, the numerical inversion might not work. However,
+    for all implemented distributions, the admissible shape parameters have
+    been tested, and an error will be raised if the user supplies values
+    outside of the allowed range. The u-error should not exceed 1e-10 for all
+    valid parameters. Note that warnings might be raised even if parameters
+    are within the valid range when the object is instantiated.
+    To check numerical accuracy, the method `evaluate_error` can be used.
+
+    Note that all implemented distributions are also part of `scipy.stats`, and
+    the object created by `FastGeneratorInversion` relies on methods like
+    `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this
+    class can be summarized as follows: Once the generator to sample random
+    variates is created in the setup step, sampling and evaluation of
+    the PPF using `ppf` are very fast,
+    and performance is essentially independent of the distribution. Therefore,
+    a substantial speed-up can be achieved for many distributions if large
+    numbers of random variates are required. It is important to know that this
+    fast sampling is achieved by inversion of the CDF. Thus, one uniform
+    random variate is transformed into a non-uniform variate, which is an
+    advantage for several simulation methods, e.g., when
+    the variance reduction methods of common random variates or
+    antithetic variates are be used ([2]_).
+
+    In addition, inversion makes it possible to
+    - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`),
+    - to generate random variates truncated to an interval. For example, if
+    one aims to sample standard normal random variates from
+    the interval (2, 4), this can be easily achieved by using the parameter
+    `domain`.
+
+    The location and scale that are initially defined by `dist`
+    can be reset without having to rerun the setup
+    step to create the generator that is used for sampling. The relation
+    of the distribution `Y` with `loc` and `scale` to the standard
+    distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by
+    ``Y = loc + scale * X``.
+
+    References
+    ----------
+    .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
+           "Random variate  generation by numerical inversion when only the
+           density is known." ACM Transactions on Modeling and Computer
+           Simulation (TOMACS) 20.4 (2010): 1-25.
+    .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger.
+           "Automatic nonuniform random number generation."
+           Springer, 2004.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats.sampling import FastGeneratorInversion
+
+    Let's start with a simple example to illustrate the main features:
+
+    >>> gamma_frozen = stats.gamma(1.5)
+    >>> gamma_dist = FastGeneratorInversion(gamma_frozen)
+    >>> r = gamma_dist.rvs(size=1000)
+
+    The mean should be approximately equal to the shape parameter 1.5:
+
+    >>> r.mean()
+    1.52423591130436  # may vary
+
+    Similarly, we can draw a sample based on quasi-random numbers:
+
+    >>> r = gamma_dist.qrvs(size=1000)
+    >>> r.mean()
+    1.4996639255942914  # may vary
+
+    Compare the PPF against approximation `ppf`.
+
+    >>> q = [0.001, 0.2, 0.5, 0.8, 0.999]
+    >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q)))
+    4.313394796895409e-08
+
+    To confirm that the numerical inversion is accurate, we evaluate the
+    approximation error (u-error), which should be below 1e-10 (for more
+    details, refer to the documentation of `evaluate_error`):
+
+    >>> gamma_dist.evaluate_error()
+    (7.446320551265581e-11, nan)  # may vary
+
+    Note that the location and scale can be changed without instantiating a
+    new generator:
+
+    >>> gamma_dist.loc = 2
+    >>> gamma_dist.scale = 3
+    >>> r = gamma_dist.rvs(size=1000)
+
+    The mean should be approximately 2 + 3*1.5 = 6.5.
+
+    >>> r.mean()
+    6.399549295242894  # may vary
+
+    Let us also illustrate how truncation can be applied:
+
+    >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4))
+    >>> r = trunc_norm.rvs(size=1000)
+    >>> 3 < r.min() < r.max() < 4
+    True
+
+    Check the mean:
+
+    >>> r.mean()
+    3.250433367078603  # may vary
+
+    >>> stats.norm.expect(lb=3, ub=4, conditional=True)
+    3.260454285589997
+
+    In this particular, case, `scipy.stats.truncnorm` could also be used to
+    generate truncated normal random variates.
+
+    """
+
+    def __init__(
+        self,
+        dist,
+        *,
+        domain=None,
+        ignore_shape_range=False,
+        random_state=None,
+    ):
+
+        if isinstance(dist, stats.distributions.rv_frozen):
+            distname = dist.dist.name
+            if distname not in PINV_CONFIG.keys():
+                raise ValueError(
+                    f"Distribution '{distname}' is not supported."
+                    f"It must be one of {list(PINV_CONFIG.keys())}"
+                    )
+        else:
+            raise ValueError("`dist` must be a frozen distribution object")
+
+        loc = dist.kwds.get("loc", 0)
+        scale = dist.kwds.get("scale", 1)
+        args = dist.args
+        if not np.isscalar(loc):
+            raise ValueError("loc must be scalar.")
+        if not np.isscalar(scale):
+            raise ValueError("scale must be scalar.")
+
+        self._frozendist = getattr(stats, distname)(
+            *args,
+            loc=loc,
+            scale=scale,
+        )
+        self._distname = distname
+
+        nargs = np.broadcast_arrays(args)[0].size
+        nargs_expected = self._frozendist.dist.numargs
+        if nargs != nargs_expected:
+            raise ValueError(
+                f"Each of the {nargs_expected} shape parameters must be a "
+                f"scalar, but {nargs} values are provided."
+            )
+
+        self.random_state = random_state
+
+        if domain is None:
+            self._domain = self._frozendist.support()
+            self._p_lower = 0.0
+            self._p_domain = 1.0
+        else:
+            self._domain = domain
+            self._p_lower = self._frozendist.cdf(self._domain[0])
+            _p_domain = self._frozendist.cdf(self._domain[1]) - self._p_lower
+            self._p_domain = _p_domain
+        self._set_domain_adj()
+        self._ignore_shape_range = ignore_shape_range
+
+        # the domain to be passed to NumericalInversePolynomial
+        # define a separate variable since in case of a transformation,
+        # domain_pinv will not be the same as self._domain
+        self._domain_pinv = self._domain
+
+        # get information about the distribution from the config to set up
+        # the generator
+        dist = self._process_config(distname, args)
+
+        if self._rvs_transform_inv is not None:
+            d0 = self._rvs_transform_inv(self._domain[0], *args)
+            d1 = self._rvs_transform_inv(self._domain[1], *args)
+            if d0 > d1:
+                # swap values if transformation if decreasing
+                d0, d1 = d1, d0
+            # only update _domain_pinv and not _domain
+            # _domain refers to the original distribution, _domain_pinv
+            # to the transformed distribution
+            self._domain_pinv = d0, d1
+
+        # self._center has been set by the call self._process_config
+        # check if self._center is inside the transformed domain
+        # _domain_pinv, otherwise move it to the endpoint that is closer
+        if self._center is not None:
+            if self._center < self._domain_pinv[0]:
+                self._center = self._domain_pinv[0]
+            elif self._center > self._domain_pinv[1]:
+                self._center = self._domain_pinv[1]
+
+        self._rng = NumericalInversePolynomial(
+            dist,
+            random_state=self.random_state,
+            domain=self._domain_pinv,
+            center=self._center,
+            )
+
+    @property
+    def random_state(self):
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, random_state):
+        self._random_state = check_random_state_qmc(random_state)
+
+    @property
+    def loc(self):
+        return self._frozendist.kwds.get("loc", 0)
+
+    @loc.setter
+    def loc(self, loc):
+        if not np.isscalar(loc):
+            raise ValueError("loc must be scalar.")
+        self._frozendist.kwds["loc"] = loc
+        # update the adjusted domain that depends on loc and scale
+        self._set_domain_adj()
+
+    @property
+    def scale(self):
+        return self._frozendist.kwds.get("scale", 0)
+
+    @scale.setter
+    def scale(self, scale):
+        if not np.isscalar(scale):
+            raise ValueError("scale must be scalar.")
+        self._frozendist.kwds["scale"] = scale
+        # update the adjusted domain that depends on loc and scale
+        self._set_domain_adj()
+
+    def _set_domain_adj(self):
+        """ Adjust the domain based on loc and scale. """
+        loc = self.loc
+        scale = self.scale
+        lb = self._domain[0] * scale + loc
+        ub = self._domain[1] * scale + loc
+        self._domain_adj = (lb, ub)
+
+    def _process_config(self, distname, args):
+        cfg = PINV_CONFIG[distname]
+        if "check_pinv_params" in cfg:
+            if not self._ignore_shape_range:
+                if not cfg["check_pinv_params"](*args):
+                    msg = ("No generator is defined for the shape parameters "
+                           f"{args}. Use ignore_shape_range to proceed "
+                           "with the selected values.")
+                    raise ValueError(msg)
+
+        if "center" in cfg.keys():
+            if not np.isscalar(cfg["center"]):
+                self._center = cfg["center"](*args)
+            else:
+                self._center = cfg["center"]
+        else:
+            self._center = None
+        self._rvs_transform = cfg.get("rvs_transform", None)
+        self._rvs_transform_inv = cfg.get("rvs_transform_inv", None)
+        _mirror_uniform = cfg.get("mirror_uniform", None)
+        if _mirror_uniform is None:
+            self._mirror_uniform = False
+        else:
+            self._mirror_uniform = _mirror_uniform(*args)
+
+        return CustomDistPINV(cfg["pdf"], args)
+
+    def rvs(self, size=None):
+        """
+        Sample from the distribution by inversion.
+
+        Parameters
+        ----------
+        size : int or tuple, optional
+            The shape of samples. Default is ``None`` in which case a scalar
+            sample is returned.
+
+        Returns
+        -------
+        rvs : array_like
+            A NumPy array of random variates.
+
+        Notes
+        -----
+        Random variates are generated by numerical inversion of the CDF, i.e.,
+        `ppf` computed by `NumericalInversePolynomial` when the class
+        is instantiated. Note that the
+        default ``rvs`` method of the rv_continuous class is
+        overwritten. Hence, a different stream of random numbers is generated
+        even if the same seed is used.
+        """
+        # note: we cannot use self._rng.rvs directly in case
+        # self._mirror_uniform is true
+        u = self.random_state.uniform(size=size)
+        if self._mirror_uniform:
+            u = 1 - u
+        r = self._rng.ppf(u)
+        if self._rvs_transform is not None:
+            r = self._rvs_transform(r, *self._frozendist.args)
+        return self.loc + self.scale * r
+
+    def ppf(self, q):
+        """
+        Very fast PPF (inverse CDF) of the distribution which
+        is a very close approximation of the exact PPF values.
+
+        Parameters
+        ----------
+        u : array_like
+            Array with probabilities.
+
+        Returns
+        -------
+        ppf : array_like
+            Quantiles corresponding to the values in `u`.
+
+        Notes
+        -----
+        The evaluation of the PPF is very fast but it may have a large
+        relative error in the far tails. The numerical precision of the PPF
+        is controlled by the u-error, that is,
+        ``max |u - CDF(PPF(u))|`` where the max is taken over points in
+        the interval [0,1], see `evaluate_error`.
+
+        Note that this PPF is designed to generate random samples.
+        """
+        q = np.asarray(q)
+        if self._mirror_uniform:
+            x = self._rng.ppf(1 - q)
+        else:
+            x = self._rng.ppf(q)
+        if self._rvs_transform is not None:
+            x = self._rvs_transform(x, *self._frozendist.args)
+        return self.scale * x + self.loc
+
+    def qrvs(self, size=None, d=None, qmc_engine=None):
+        """
+        Quasi-random variates of the given distribution.
+
+        The `qmc_engine` is used to draw uniform quasi-random variates, and
+        these are converted to quasi-random variates of the given distribution
+        using inverse transform sampling.
+
+        Parameters
+        ----------
+        size : int, tuple of ints, or None; optional
+            Defines shape of random variates array. Default is ``None``.
+        d : int or None, optional
+            Defines dimension of uniform quasi-random variates to be
+            transformed. Default is ``None``.
+        qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional
+            Defines the object to use for drawing
+            quasi-random variates. Default is ``None``, which uses
+            `scipy.stats.qmc.Halton(1)`.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Quasi-random variates. See Notes for shape information.
+
+        Notes
+        -----
+        The shape of the output array depends on `size`, `d`, and `qmc_engine`.
+        The intent is for the interface to be natural, but the detailed rules
+        to achieve this are complicated.
+
+        - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is
+          created with dimension `d`. If `d` is not provided, ``d=1``.
+        - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is
+          determined from the dimension of the `qmc_engine`.
+        - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the
+          dimensions are inconsistent, a ``ValueError`` is raised.
+        - After `d` is determined according to the rules above, the output
+          shape is ``tuple_shape + d_shape``, where:
+
+              - ``tuple_shape = tuple()`` if `size` is ``None``,
+              - ``tuple_shape = (size,)`` if `size` is an ``int``,
+              - ``tuple_shape = size`` if `size` is a sequence,
+              - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and
+              - ``d_shape = (d,)`` if `d` is greater than 1.
+
+        The elements of the returned array are part of a low-discrepancy
+        sequence. If `d` is 1, this means that none of the samples are truly
+        independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a
+        quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for
+        details. Note that when `d` > 1, the samples returned are still those
+        of the provided univariate distribution, not a multivariate
+        generalization of that distribution.
+
+        """
+        qmc_engine, d = _validate_qmc_input(qmc_engine, d, self.random_state)
+        # mainly copied from unuran_wrapper.pyx.templ
+        # `rvs` is flexible about whether `size` is an int or tuple, so this
+        # should be, too.
+        try:
+            if size is None:
+                tuple_size = (1,)
+            else:
+                tuple_size = tuple(size)
+        except TypeError:
+            tuple_size = (size,)
+        # we do not use rng.qrvs directly since we need to be
+        # able to apply the ppf to 1 - u
+        N = 1 if size is None else np.prod(size)
+        u = qmc_engine.random(N)
+        if self._mirror_uniform:
+            u = 1 - u
+        qrvs = self._ppf(u)
+        if self._rvs_transform is not None:
+            qrvs = self._rvs_transform(qrvs, *self._frozendist.args)
+        if size is None:
+            qrvs = qrvs.squeeze()[()]
+        else:
+            if d == 1:
+                qrvs = qrvs.reshape(tuple_size)
+            else:
+                qrvs = qrvs.reshape(tuple_size + (d,))
+        return self.loc + self.scale * qrvs
+
+    def evaluate_error(self, size=100000, random_state=None, x_error=False):
+        """
+        Evaluate the numerical accuracy of the inversion (u- and x-error).
+
+        Parameters
+        ----------
+        size : int, optional
+            The number of random points over which the error is estimated.
+            Default is ``100000``.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            A NumPy random number generator or seed for the underlying NumPy
+            random number generator used to generate the stream of uniform
+            random numbers.
+            If `random_state` is None, use ``self.random_state``.
+            If `random_state` is an int,
+            ``np.random.default_rng(random_state)`` is used.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+        Returns
+        -------
+        u_error, x_error : tuple of floats
+            A NumPy array of random variates.
+
+        Notes
+        -----
+        The numerical precision of the inverse CDF `ppf` is controlled by
+        the u-error. It is computed as follows:
+        ``max |u - CDF(PPF(u))|`` where the max is taken `size` random
+        points in the interval [0,1]. `random_state` determines the random
+        sample. Note that if `ppf` was exact, the u-error would be zero.
+
+        The x-error measures the direct distance between the exact PPF
+        and `ppf`. If ``x_error`` is set to ``True`, it is
+        computed as the maximum of the minimum of the relative and absolute
+        x-error:
+        ``max(min(x_error_abs[i], x_error_rel[i]))`` where
+        ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``,
+        ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``.
+        Note that it is important to consider the relative x-error in the case
+        that ``PPF(u)`` is close to zero or very large.
+
+        By default, only the u-error is evaluated and the x-error is set to
+        ``np.nan``. Note that the evaluation of the x-error will be very slow
+        if the implementation of the PPF is slow.
+
+        Further information about these error measures can be found in [1]_.
+
+        References
+        ----------
+        .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
+               "Random variate  generation by numerical inversion when only the
+               density is known." ACM Transactions on Modeling and Computer
+               Simulation (TOMACS) 20.4 (2010): 1-25.
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> from scipy.stats.sampling import FastGeneratorInversion
+
+        Create an object for the normal distribution:
+
+        >>> d_norm_frozen = stats.norm()
+        >>> d_norm = FastGeneratorInversion(d_norm_frozen)
+
+        To confirm that the numerical inversion is accurate, we evaluate the
+        approximation error (u-error and x-error).
+
+        >>> u_error, x_error = d_norm.evaluate_error(x_error=True)
+
+        The u-error should be below 1e-10:
+
+        >>> u_error
+        8.785783212061915e-11  # may vary
+
+        Compare the PPF against approximation `ppf`:
+
+        >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999]
+        >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q))
+        >>> x_error_abs = np.max(diff)
+        >>> x_error_abs
+        1.2937954707581412e-08
+
+        This is the absolute x-error evaluated at the points q. The relative
+        error is given by
+
+        >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q)))
+        >>> x_error_rel
+        4.186725600453555e-09
+
+        The x_error computed above is derived in a very similar way over a
+        much larger set of random values q. At each value q[i], the minimum
+        of the relative and absolute error is taken. The final value is then
+        derived as the maximum of these values. In our example, we get the
+        following value:
+
+        >>> x_error
+        4.507068014335139e-07  # may vary
+
+        """
+        if not isinstance(size, (numbers.Integral, np.integer)):
+            raise ValueError("size must be an integer.")
+        # urng will be used to draw the samples for testing the error
+        # it must not interfere with self.random_state. therefore, do not
+        # call self.rvs, but draw uniform random numbers and apply
+        # self.ppf (note: like in rvs, consider self._mirror_uniform)
+        urng = check_random_state_qmc(random_state)
+        u = urng.uniform(size=size)
+        if self._mirror_uniform:
+            u = 1 - u
+        x = self.ppf(u)
+        uerr = np.max(np.abs(self._cdf(x) - u))
+        if not x_error:
+            return uerr, np.nan
+        ppf_u = self._ppf(u)
+        x_error_abs = np.abs(self.ppf(u)-ppf_u)
+        x_error_rel = x_error_abs / np.abs(ppf_u)
+        x_error_combined = np.array([x_error_abs, x_error_rel]).min(axis=0)
+        return uerr, np.max(x_error_combined)
+
+    def support(self):
+        """Support of the distribution.
+
+        Returns
+        -------
+        a, b : float
+            end-points of the distribution's support.
+
+        Notes
+        -----
+
+        Note that the support of the distribution depends on `loc`,
+        `scale` and `domain`.
+
+        Examples
+        --------
+
+        >>> from scipy import stats
+        >>> from scipy.stats.sampling import FastGeneratorInversion
+
+        Define a truncated normal distribution:
+
+        >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1))
+        >>> d_norm.support()
+        (0, 1)
+
+        Shift the distribution:
+
+        >>> d_norm.loc = 2.5
+        >>> d_norm.support()
+        (2.5, 3.5)
+
+        """
+        return self._domain_adj
+
+    def _cdf(self, x):
+        """Cumulative distribution function (CDF)
+
+        Parameters
+        ----------
+        x : array_like
+            The values where the CDF is evaluated
+
+        Returns
+        -------
+        y : ndarray
+            CDF evaluated at x
+
+        """
+        y = self._frozendist.cdf(x)
+        if self._p_domain == 1.0:
+            return y
+        return np.clip((y - self._p_lower) / self._p_domain, 0, 1)
+
+    def _ppf(self, q):
+        """Percent point function (inverse of `cdf`)
+
+        Parameters
+        ----------
+        q : array_like
+            lower tail probability
+
+        Returns
+        -------
+        x : array_like
+            quantile corresponding to the lower tail probability q.
+
+        """
+        if self._p_domain == 1.0:
+            return self._frozendist.ppf(q)
+        x = self._frozendist.ppf(self._p_domain * np.array(q) + self._p_lower)
+        return np.clip(x, self._domain_adj[0], self._domain_adj[1])
+
+
+class RatioUniforms:
+    """
+    Generate random samples from a probability density function using the
+    ratio-of-uniforms method.
+
+    Parameters
+    ----------
+    pdf : callable
+        A function with signature `pdf(x)` that is proportional to the
+        probability density function of the distribution.
+    umax : float
+        The upper bound of the bounding rectangle in the u-direction.
+    vmin : float
+        The lower bound of the bounding rectangle in the v-direction.
+    vmax : float
+        The upper bound of the bounding rectangle in the v-direction.
+    c : float, optional.
+        Shift parameter of ratio-of-uniforms method, see Notes. Default is 0.
+    random_state : {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.
+
+    Methods
+    -------
+    rvs
+
+    Notes
+    -----
+    Given a univariate probability density function `pdf` and a constant `c`,
+    define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``.
+    If ``(U, V)`` is a random vector uniformly distributed over ``A``,
+    then ``V/U + c`` follows a distribution according to `pdf`.
+
+    The above result (see [1]_, [2]_) can be used to sample random variables
+    using only the PDF, i.e. no inversion of the CDF is required. Typical
+    choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of
+    the rectangle ``R = [0, umax] x [vmin, vmax]`` where
+
+    - ``umax = sup sqrt(pdf(x))``
+    - ``vmin = inf (x - c) sqrt(pdf(x))``
+    - ``vmax = sup (x - c) sqrt(pdf(x))``
+
+    In particular, these values are finite if `pdf` is bounded and
+    ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails).
+    One can generate ``(U, V)`` uniformly on ``R`` and return
+    ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly
+    verified.
+
+    The algorithm is not changed if one replaces `pdf` by k * `pdf` for any
+    constant k > 0. Thus, it is often convenient to work with a function
+    that is proportional to the probability density function by dropping
+    unnecessary normalization factors.
+
+    Intuitively, the method works well if ``A`` fills up most of the
+    enclosing rectangle such that the probability is high that ``(U, V)``
+    lies in ``A`` whenever it lies in ``R`` as the number of required
+    iterations becomes too large otherwise. To be more precise, note that
+    the expected number of iterations to draw ``(U, V)`` uniformly
+    distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by
+    the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``,
+    where `area(pdf)` is the integral of `pdf` (which is equal to one if the
+    probability density function is used but can take on other values if a
+    function proportional to the density is used). The equality holds since
+    the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_).
+    If the sampling fails to generate a single random variate after 50000
+    iterations (i.e. not a single draw is in ``A``), an exception is raised.
+
+    If the bounding rectangle is not correctly specified (i.e. if it does not
+    contain ``A``), the algorithm samples from a distribution different from
+    the one given by `pdf`. It is therefore recommended to perform a
+    test such as `~scipy.stats.kstest` as a check.
+
+    References
+    ----------
+    .. [1] L. Devroye, "Non-Uniform Random Variate Generation",
+       Springer-Verlag, 1986.
+
+    .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
+       random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
+
+    .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random
+       Variables Using the Ratio of Uniform Deviates",
+       ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+
+    >>> from scipy.stats.sampling import RatioUniforms
+    >>> rng = np.random.default_rng()
+
+    Simulate normally distributed random variables. It is easy to compute the
+    bounding rectangle explicitly in that case. For simplicity, we drop the
+    normalization factor of the density.
+
+    >>> f = lambda x: np.exp(-x**2 / 2)
+    >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
+    >>> umax = np.sqrt(f(0))
+    >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng)
+    >>> r = gen.rvs(size=2500)
+
+    The K-S test confirms that the random variates are indeed normally
+    distributed (normality is not rejected at 5% significance level):
+
+    >>> stats.kstest(r, 'norm')[1]
+    0.250634764150542
+
+    The exponential distribution provides another example where the bounding
+    rectangle can be determined explicitly.
+
+    >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0,
+    ...                     vmax=2*np.exp(-1), random_state=rng)
+    >>> r = gen.rvs(1000)
+    >>> stats.kstest(r, 'expon')[1]
+    0.21121052054580314
+
+    """
+    
+    def __init__(self, pdf, *, umax, vmin, vmax, c=0, random_state=None):
+        if vmin >= vmax:
+            raise ValueError("vmin must be smaller than vmax.")
+
+        if umax <= 0:
+            raise ValueError("umax must be positive.")
+        
+        self._pdf = pdf
+        self._umax = umax
+        self._vmin = vmin
+        self._vmax = vmax
+        self._c = c
+        self._rng = check_random_state(random_state)
+
+    def rvs(self, size=1):
+        """Sampling of random variates
+
+        Parameters
+        ----------
+        size : int or tuple of ints, optional
+            Number of random variates to be generated (default is 1).
+
+        Returns
+        -------
+        rvs : ndarray
+            The random variates distributed according to the probability
+            distribution defined by the pdf.
+
+        """
+        size1d = tuple(np.atleast_1d(size))
+        N = np.prod(size1d)  # number of rvs needed, reshape upon return
+
+        # start sampling using ratio of uniforms method
+        x = np.zeros(N)
+        simulated, i = 0, 1
+
+        # loop until N rvs have been generated: expected runtime is finite.
+        # to avoid infinite loop, raise exception if not a single rv has been
+        # generated after 50000 tries. even if the expected number of iterations
+        # is 1000, the probability of this event is (1-1/1000)**50000
+        # which is of order 10e-22
+        while simulated < N:
+            k = N - simulated
+            # simulate uniform rvs on [0, umax] and [vmin, vmax]
+            u1 = self._umax * self._rng.uniform(size=k)
+            v1 = self._rng.uniform(self._vmin, self._vmax, size=k)
+            # apply rejection method
+            rvs = v1 / u1 + self._c
+            accept = (u1**2 <= self._pdf(rvs))
+            num_accept = np.sum(accept)
+            if num_accept > 0:
+                x[simulated:(simulated + num_accept)] = rvs[accept]
+                simulated += num_accept
+
+            if (simulated == 0) and (i*N >= 50000):
+                msg = (
+                    f"Not a single random variate could be generated in {i*N} "
+                    "attempts. The ratio of uniforms method does not appear "
+                    "to work for the provided parameters. Please check the "
+                    "pdf and the bounds."
+                )
+                raise RuntimeError(msg)
+            i += 1
+
+        return np.reshape(x, size1d)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_sensitivity_analysis.py b/python_embeded/Lib/site-packages/scipy/stats/_sensitivity_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a82b7430e298335efb46b7a6a40dfe4ae8d089
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_sensitivity_analysis.py
@@ -0,0 +1,713 @@
+import inspect
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+from collections.abc import Callable
+
+import numpy as np
+
+from scipy.stats._common import ConfidenceInterval
+from scipy.stats._qmc import check_random_state
+from scipy.stats._resampling import BootstrapResult
+from scipy.stats import qmc, bootstrap
+from scipy._lib._util import _transition_to_rng
+
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+    from scipy._lib._util import DecimalNumber, IntNumber
+
+
+__all__ = [
+    'sobol_indices'
+]
+
+
+def f_ishigami(x: "npt.ArrayLike") -> "npt.NDArray[np.inexact[Any]]":
+    r"""Ishigami function.
+
+    .. math::
+
+        Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1
+
+    with :math:`\mathbf{x} \in [-\pi, \pi]^3`.
+
+    Parameters
+    ----------
+    x : array_like ([x1, x2, x3], n)
+
+    Returns
+    -------
+    f : array_like (n,)
+        Function evaluation.
+
+    References
+    ----------
+    .. [1] Ishigami, T. and T. Homma. "An importance quantification technique
+       in uncertainty analysis for computer models." IEEE,
+       :doi:`10.1109/ISUMA.1990.151285`, 1990.
+    """
+    x = np.atleast_2d(x)
+    f_eval = (
+        np.sin(x[0])
+        + 7 * np.sin(x[1])**2
+        + 0.1 * (x[2]**4) * np.sin(x[0])
+    )
+    return f_eval
+
+
+def sample_A_B(
+    n,
+    dists,
+    rng=None
+):
+    """Sample two matrices A and B.
+
+    Uses a Sobol' sequence with 2`d` columns to have 2 uncorrelated matrices.
+    This is more efficient than using 2 random draw of Sobol'.
+    See sec. 5 from [1]_.
+
+    Output shape is (d, n).
+
+    References
+    ----------
+    .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    """
+    d = len(dists)
+    A_B = qmc.Sobol(d=2*d, seed=rng, bits=64).random(n).T
+    A_B = A_B.reshape(2, d, -1)
+    try:
+        for d_, dist in enumerate(dists):
+            A_B[:, d_] = dist.ppf(A_B[:, d_])
+    except AttributeError as exc:
+        message = "Each distribution in `dists` must have method `ppf`."
+        raise ValueError(message) from exc
+    return A_B
+
+
+def sample_AB(A: np.ndarray, B: np.ndarray) -> np.ndarray:
+    """AB matrix.
+
+    AB: rows of B into A. Shape (d, d, n).
+    - Copy A into d "pages"
+    - In the first page, replace 1st rows of A with 1st row of B.
+    ...
+    - In the dth page, replace dth row of A with dth row of B.
+    - return the stack of pages
+    """
+    d, n = A.shape
+    AB = np.tile(A, (d, 1, 1))
+    i = np.arange(d)
+    AB[i, i] = B[i]
+    return AB
+
+
+def saltelli_2010(
+    f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+    r"""Saltelli2010 formulation.
+
+    .. math::
+
+        S_i = \frac{1}{N} \sum_{j=1}^N
+        f(\mathbf{B})_j (f(\mathbf{AB}^{(i)})_j - f(\mathbf{A})_j)
+
+    .. math::
+
+        S_{T_i} = \frac{1}{N} \sum_{j=1}^N
+        (f(\mathbf{A})_j - f(\mathbf{AB}^{(i)})_j)^2
+
+    Parameters
+    ----------
+    f_A, f_B : array_like (s, n)
+        Function values at A and B, respectively
+    f_AB : array_like (d, s, n)
+        Function values at each of the AB pages
+
+    Returns
+    -------
+    s, st : array_like (s, d)
+        First order and total order Sobol' indices.
+
+    References
+    ----------
+    .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    """
+    # Empirical variance calculated using output from A and B which are
+    # independent. Output of AB is not independent and cannot be used
+    var = np.var([f_A, f_B], axis=(0, -1))
+
+    # We divide by the variance to have a ratio of variance
+    # this leads to eq. 2
+    s = np.mean(f_B * (f_AB - f_A), axis=-1) / var  # Table 2 (b)
+    st = 0.5 * np.mean((f_A - f_AB) ** 2, axis=-1) / var  # Table 2 (f)
+
+    return s.T, st.T
+
+
+@dataclass
+class BootstrapSobolResult:
+    first_order: BootstrapResult
+    total_order: BootstrapResult
+
+
+@dataclass
+class SobolResult:
+    first_order: np.ndarray
+    total_order: np.ndarray
+    _indices_method: Callable
+    _f_A: np.ndarray
+    _f_B: np.ndarray
+    _f_AB: np.ndarray
+    _A: np.ndarray | None = None
+    _B: np.ndarray | None = None
+    _AB: np.ndarray | None = None
+    _bootstrap_result: BootstrapResult | None = None
+
+    def bootstrap(
+        self,
+        confidence_level: "DecimalNumber" = 0.95,
+        n_resamples: "IntNumber" = 999
+    ) -> BootstrapSobolResult:
+        """Bootstrap Sobol' indices to provide confidence intervals.
+
+        Parameters
+        ----------
+        confidence_level : float, default: ``0.95``
+            The confidence level of the confidence intervals.
+        n_resamples : int, default: ``999``
+            The number of resamples performed to form the bootstrap
+            distribution of the indices.
+
+        Returns
+        -------
+        res : BootstrapSobolResult
+            Bootstrap result containing the confidence intervals and the
+            bootstrap distribution of the indices.
+
+            An object with attributes:
+
+            first_order : BootstrapResult
+                Bootstrap result of the first order indices.
+            total_order : BootstrapResult
+                Bootstrap result of the total order indices.
+            See `BootstrapResult` for more details.
+
+        """
+        def statistic(idx):
+            f_A_ = self._f_A[:, idx]
+            f_B_ = self._f_B[:, idx]
+            f_AB_ = self._f_AB[..., idx]
+            return self._indices_method(f_A_, f_B_, f_AB_)
+
+        n = self._f_A.shape[1]
+
+        res = bootstrap(
+            [np.arange(n)], statistic=statistic, method="BCa",
+            n_resamples=n_resamples,
+            confidence_level=confidence_level,
+            bootstrap_result=self._bootstrap_result
+        )
+        self._bootstrap_result = res
+
+        first_order = BootstrapResult(
+            confidence_interval=ConfidenceInterval(
+                res.confidence_interval.low[0], res.confidence_interval.high[0]
+            ),
+            bootstrap_distribution=res.bootstrap_distribution[0],
+            standard_error=res.standard_error[0],
+        )
+        total_order = BootstrapResult(
+            confidence_interval=ConfidenceInterval(
+                res.confidence_interval.low[1], res.confidence_interval.high[1]
+            ),
+            bootstrap_distribution=res.bootstrap_distribution[1],
+            standard_error=res.standard_error[1],
+        )
+
+        return BootstrapSobolResult(
+            first_order=first_order, total_order=total_order
+        )
+
+@_transition_to_rng('random_state', replace_doc=False)
+def sobol_indices(
+    *,
+    func,
+    n,
+    dists=None,
+    method='saltelli_2010',
+    rng=None
+):
+    r"""Global sensitivity indices of Sobol'.
+
+    Parameters
+    ----------
+    func : callable or dict(str, array_like)
+        If `func` is a callable, function to compute the Sobol' indices from.
+        Its signature must be::
+
+            func(x: ArrayLike) -> ArrayLike
+
+        with ``x`` of shape ``(d, n)`` and output of shape ``(s, n)`` where:
+
+        - ``d`` is the input dimensionality of `func`
+          (number of input variables),
+        - ``s`` is the output dimensionality of `func`
+          (number of output variables), and
+        - ``n`` is the number of samples (see `n` below).
+
+        Function evaluation values must be finite.
+
+        If `func` is a dictionary, contains the function evaluations from three
+        different arrays. Keys must be: ``f_A``, ``f_B`` and ``f_AB``.
+        ``f_A`` and ``f_B`` should have a shape ``(s, n)`` and ``f_AB``
+        should have a shape ``(d, s, n)``.
+        This is an advanced feature and misuse can lead to wrong analysis.
+    n : int
+        Number of samples used to generate the matrices ``A`` and ``B``.
+        Must be a power of 2. The total number of points at which `func` is
+        evaluated will be ``n*(d+2)``.
+    dists : list(distributions), optional
+        List of each parameter's distribution. The distribution of parameters
+        depends on the application and should be carefully chosen.
+        Parameters are assumed to be independently distributed, meaning there
+        is no constraint nor relationship between their values.
+
+        Distributions must be an instance of a class with a ``ppf``
+        method.
+
+        Must be specified if `func` is a callable, and ignored otherwise.
+    method : Callable or str, default: 'saltelli_2010'
+        Method used to compute the first and total Sobol' indices.
+
+        If a callable, its signature must be::
+
+            func(f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray)
+            -> Tuple[np.ndarray, np.ndarray]
+
+        with ``f_A, f_B`` of shape ``(s, n)`` and ``f_AB`` of shape
+        ``(d, s, n)``.
+        These arrays contain the function evaluations from three different sets
+        of samples.
+        The output is a tuple of the first and total indices with
+        shape ``(s, d)``.
+        This is an advanced feature and misuse can lead to wrong analysis.
+    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`, this keyword was changed from `random_state` 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 `random_state` keyword will emit warnings. Following a
+            deprecation period, the `random_state` keyword will be removed.
+
+    Returns
+    -------
+    res : SobolResult
+        An object with attributes:
+
+        first_order : ndarray of shape (s, d)
+            First order Sobol' indices.
+        total_order : ndarray of shape (s, d)
+            Total order Sobol' indices.
+
+        And method:
+
+        bootstrap(confidence_level: float, n_resamples: int)
+        -> BootstrapSobolResult
+
+            A method providing confidence intervals on the indices.
+            See `scipy.stats.bootstrap` for more details.
+
+            The bootstrapping is done on both first and total order indices,
+            and they are available in `BootstrapSobolResult` as attributes
+            ``first_order`` and ``total_order``.
+
+    Notes
+    -----
+    The Sobol' method [1]_, [2]_ is a variance-based Sensitivity Analysis which
+    obtains the contribution of each parameter to the variance of the
+    quantities of interest (QoIs; i.e., the outputs of `func`).
+    Respective contributions can be used to rank the parameters and
+    also gauge the complexity of the model by computing the
+    model's effective (or mean) dimension.
+
+    .. note::
+
+        Parameters are assumed to be independently distributed. Each
+        parameter can still follow any distribution. In fact, the distribution
+        is very important and should match the real distribution of the
+        parameters.
+
+    It uses a functional decomposition of the variance of the function to
+    explore
+
+    .. math::
+
+        \mathbb{V}(Y) = \sum_{i}^{d} \mathbb{V}_i (Y) + \sum_{i= 2**12``. The more complex the model is,
+        the more samples will be needed.
+
+        Even for a purely additive model, the indices may not sum to 1 due
+        to numerical noise.
+
+    References
+    ----------
+    .. [1] Sobol, I. M.. "Sensitivity analysis for nonlinear mathematical
+       models." Mathematical Modeling and Computational Experiment, 1:407-414,
+       1993.
+    .. [2] Sobol, I. M. (2001). "Global sensitivity indices for nonlinear
+       mathematical models and their Monte Carlo estimates." Mathematics
+       and Computers in Simulation, 55(1-3):271-280,
+       :doi:`10.1016/S0378-4754(00)00270-6`, 2001.
+    .. [3] Saltelli, A. "Making best use of model evaluations to
+       compute sensitivity indices."  Computer Physics Communications,
+       145(2):280-297, :doi:`10.1016/S0010-4655(02)00280-1`, 2002.
+    .. [4] Saltelli, A., M. Ratto, T. Andres, F. Campolongo, J. Cariboni,
+       D. Gatelli, M. Saisana, and S. Tarantola. "Global Sensitivity Analysis.
+       The Primer." 2007.
+    .. [5] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    .. [6] Ishigami, T. and T. Homma. "An importance quantification technique
+       in uncertainty analysis for computer models." IEEE,
+       :doi:`10.1109/ISUMA.1990.151285`, 1990.
+
+    Examples
+    --------
+    The following is an example with the Ishigami function [6]_
+
+    .. math::
+
+        Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1,
+
+    with :math:`\mathbf{x} \in [-\pi, \pi]^3`. This function exhibits strong
+    non-linearity and non-monotonicity.
+
+    Remember, Sobol' indices assumes that samples are independently
+    distributed. In this case we use a uniform distribution on each marginals.
+
+    >>> import numpy as np
+    >>> from scipy.stats import sobol_indices, uniform
+    >>> rng = np.random.default_rng()
+    >>> def f_ishigami(x):
+    ...     f_eval = (
+    ...         np.sin(x[0])
+    ...         + 7 * np.sin(x[1])**2
+    ...         + 0.1 * (x[2]**4) * np.sin(x[0])
+    ...     )
+    ...     return f_eval
+    >>> indices = sobol_indices(
+    ...     func=f_ishigami, n=1024,
+    ...     dists=[
+    ...         uniform(loc=-np.pi, scale=2*np.pi),
+    ...         uniform(loc=-np.pi, scale=2*np.pi),
+    ...         uniform(loc=-np.pi, scale=2*np.pi)
+    ...     ],
+    ...     rng=rng
+    ... )
+    >>> indices.first_order
+    array([0.31637954, 0.43781162, 0.00318825])
+    >>> indices.total_order
+    array([0.56122127, 0.44287857, 0.24229595])
+
+    Confidence interval can be obtained using bootstrapping.
+
+    >>> boot = indices.bootstrap()
+
+    Then, this information can be easily visualized.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, axs = plt.subplots(1, 2, figsize=(9, 4))
+    >>> _ = axs[0].errorbar(
+    ...     [1, 2, 3], indices.first_order, fmt='o',
+    ...     yerr=[
+    ...         indices.first_order - boot.first_order.confidence_interval.low,
+    ...         boot.first_order.confidence_interval.high - indices.first_order
+    ...     ],
+    ... )
+    >>> axs[0].set_ylabel("First order Sobol' indices")
+    >>> axs[0].set_xlabel('Input parameters')
+    >>> axs[0].set_xticks([1, 2, 3])
+    >>> _ = axs[1].errorbar(
+    ...     [1, 2, 3], indices.total_order, fmt='o',
+    ...     yerr=[
+    ...         indices.total_order - boot.total_order.confidence_interval.low,
+    ...         boot.total_order.confidence_interval.high - indices.total_order
+    ...     ],
+    ... )
+    >>> axs[1].set_ylabel("Total order Sobol' indices")
+    >>> axs[1].set_xlabel('Input parameters')
+    >>> axs[1].set_xticks([1, 2, 3])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    .. note::
+
+        By default, `scipy.stats.uniform` has support ``[0, 1]``.
+        Using the parameters ``loc`` and ``scale``, one obtains the uniform
+        distribution on ``[loc, loc + scale]``.
+
+    This result is particularly interesting because the first order index
+    :math:`S_{x_3} = 0` whereas its total order is :math:`S_{T_{x_3}} = 0.244`.
+    This means that higher order interactions with :math:`x_3` are responsible
+    for the difference. Almost 25% of the observed variance
+    on the QoI is due to the correlations between :math:`x_3` and :math:`x_1`,
+    although :math:`x_3` by itself has no impact on the QoI.
+
+    The following gives a visual explanation of Sobol' indices on this
+    function. Let's generate 1024 samples in :math:`[-\pi, \pi]^3` and
+    calculate the value of the output.
+
+    >>> from scipy.stats import qmc
+    >>> n_dim = 3
+    >>> p_labels = ['$x_1$', '$x_2$', '$x_3$']
+    >>> sample = qmc.Sobol(d=n_dim, seed=rng).random(1024)
+    >>> sample = qmc.scale(
+    ...     sample=sample,
+    ...     l_bounds=[-np.pi, -np.pi, -np.pi],
+    ...     u_bounds=[np.pi, np.pi, np.pi]
+    ... )
+    >>> output = f_ishigami(sample.T)
+
+    Now we can do scatter plots of the output with respect to each parameter.
+    This gives a visual way to understand how each parameter impacts the
+    output of the function.
+
+    >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
+    >>> for i in range(n_dim):
+    ...     xi = sample[:, i]
+    ...     ax[i].scatter(xi, output, marker='+')
+    ...     ax[i].set_xlabel(p_labels[i])
+    >>> ax[0].set_ylabel('Y')
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    Now Sobol' goes a step further:
+    by conditioning the output value by given values of the parameter
+    (black lines), the conditional output mean is computed. It corresponds to
+    the term :math:`\mathbb{E}(Y|x_i)`. Taking the variance of this term gives
+    the numerator of the Sobol' indices.
+
+    >>> mini = np.min(output)
+    >>> maxi = np.max(output)
+    >>> n_bins = 10
+    >>> bins = np.linspace(-np.pi, np.pi, num=n_bins, endpoint=False)
+    >>> dx = bins[1] - bins[0]
+    >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
+    >>> for i in range(n_dim):
+    ...     xi = sample[:, i]
+    ...     ax[i].scatter(xi, output, marker='+')
+    ...     ax[i].set_xlabel(p_labels[i])
+    ...     for bin_ in bins:
+    ...         idx = np.where((bin_ <= xi) & (xi <= bin_ + dx))
+    ...         xi_ = xi[idx]
+    ...         y_ = output[idx]
+    ...         ave_y_ = np.mean(y_)
+    ...         ax[i].plot([bin_ + dx/2] * 2, [mini, maxi], c='k')
+    ...         ax[i].scatter(bin_ + dx/2, ave_y_, c='r')
+    >>> ax[0].set_ylabel('Y')
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    Looking at :math:`x_3`, the variance
+    of the mean is zero leading to :math:`S_{x_3} = 0`. But we can further
+    observe that the variance of the output is not constant along the parameter
+    values of :math:`x_3`. This heteroscedasticity is explained by higher order
+    interactions. Moreover, an heteroscedasticity is also noticeable on
+    :math:`x_1` leading to an interaction between :math:`x_3` and :math:`x_1`.
+    On :math:`x_2`, the variance seems to be constant and thus null interaction
+    with this parameter can be supposed.
+
+    This case is fairly simple to analyse visually---although it is only a
+    qualitative analysis. Nevertheless, when the number of input parameters
+    increases such analysis becomes unrealistic as it would be difficult to
+    conclude on high-order terms. Hence the benefit of using Sobol' indices.
+
+    """
+    rng = check_random_state(rng)
+
+    n_ = int(n)
+    if not (n_ & (n_ - 1) == 0) or n != n_:
+        raise ValueError(
+            "The balance properties of Sobol' points require 'n' "
+            "to be a power of 2."
+        )
+    n = n_
+
+    if not callable(method):
+        indices_methods = {
+            "saltelli_2010": saltelli_2010,
+        }
+        try:
+            method = method.lower()  # type: ignore[assignment]
+            indices_method_ = indices_methods[method]
+        except KeyError as exc:
+            message = (
+                f"{method!r} is not a valid 'method'. It must be one of"
+                f" {set(indices_methods)!r} or a callable."
+            )
+            raise ValueError(message) from exc
+    else:
+        indices_method_ = method
+        sig = inspect.signature(indices_method_)
+
+        if set(sig.parameters) != {'f_A', 'f_B', 'f_AB'}:
+            message = (
+                "If 'method' is a callable, it must have the following"
+                f" signature: {inspect.signature(saltelli_2010)}"
+            )
+            raise ValueError(message)
+
+    def indices_method(f_A, f_B, f_AB):
+        """Wrap indices method to ensure proper output dimension.
+
+        1D when single output, 2D otherwise.
+        """
+        return np.squeeze(indices_method_(f_A=f_A, f_B=f_B, f_AB=f_AB))
+
+    if callable(func):
+        if dists is None:
+            raise ValueError(
+                "'dists' must be defined when 'func' is a callable."
+            )
+
+        def wrapped_func(x):
+            return np.atleast_2d(func(x))
+
+        A, B = sample_A_B(n=n, dists=dists, rng=rng)
+        AB = sample_AB(A=A, B=B)
+
+        f_A = wrapped_func(A)
+
+        if f_A.shape[1] != n:
+            raise ValueError(
+                "'func' output should have a shape ``(s, -1)`` with ``s`` "
+                "the number of output."
+            )
+
+        def funcAB(AB):
+            d, d, n = AB.shape
+            AB = np.moveaxis(AB, 0, -1).reshape(d, n*d)
+            f_AB = wrapped_func(AB)
+            return np.moveaxis(f_AB.reshape((-1, n, d)), -1, 0)
+
+        f_B = wrapped_func(B)
+        f_AB = funcAB(AB)
+    else:
+        message = (
+            "When 'func' is a dictionary, it must contain the following "
+            "keys: 'f_A', 'f_B' and 'f_AB'."
+            "'f_A' and 'f_B' should have a shape ``(s, n)`` and 'f_AB' "
+            "should have a shape ``(d, s, n)``."
+        )
+        try:
+            f_A, f_B, f_AB = map(lambda arr: arr.copy(), np.atleast_2d(
+                func['f_A'], func['f_B'], func['f_AB']
+            ))
+        except KeyError as exc:
+            raise ValueError(message) from exc
+
+        if f_A.shape[1] != n or f_A.shape != f_B.shape or \
+                f_AB.shape == f_A.shape or f_AB.shape[-1] % n != 0:
+            raise ValueError(message)
+
+    # Normalization by mean
+    # Sobol', I. and Levitan, Y. L. (1999). On the use of variance reducing
+    # multipliers in monte carlo computations of a global sensitivity index.
+    # Computer Physics Communications, 117(1) :52-61.
+    mean = np.mean([f_A, f_B], axis=(0, -1)).reshape(-1, 1)
+    f_A -= mean
+    f_B -= mean
+    f_AB -= mean
+
+    # Compute indices
+    # Filter warnings for constant output as var = 0
+    with np.errstate(divide='ignore', invalid='ignore'):
+        first_order, total_order = indices_method(f_A=f_A, f_B=f_B, f_AB=f_AB)
+
+    # null variance means null indices
+    first_order[~np.isfinite(first_order)] = 0
+    total_order[~np.isfinite(total_order)] = 0
+
+    res = dict(
+        first_order=first_order,
+        total_order=total_order,
+        _indices_method=indices_method,
+        _f_A=f_A,
+        _f_B=f_B,
+        _f_AB=f_AB
+    )
+
+    if callable(func):
+        res.update(
+            dict(
+                _A=A,
+                _B=B,
+                _AB=AB,
+            )
+        )
+
+    return SobolResult(**res)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_sobol.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_sobol.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..475da064f62d6749b062ff3063b31df7f8b5e20b
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_sobol.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_sobol.pyi b/python_embeded/Lib/site-packages/scipy/stats/_sobol.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8f5d794d03976f504d2afe5f9a77a8fbf8dd159b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_sobol.pyi
@@ -0,0 +1,54 @@
+import numpy as np
+from scipy._lib._util import IntNumber
+from typing import Literal
+
+def _initialize_v(
+    v : np.ndarray, 
+    dim : IntNumber,
+    bits: IntNumber
+) -> None: ...
+
+def _cscramble (
+    dim : IntNumber,
+    bits: IntNumber,
+    ltm : np.ndarray,
+    sv: np.ndarray
+) -> None: ...
+
+def _fill_p_cumulative(
+    p: np.ndarray,
+    p_cumulative: np.ndarray
+) -> None: ...
+
+def _draw(
+    n : IntNumber,
+    num_gen: IntNumber,
+    dim: IntNumber,
+    scale: float,
+    sv: np.ndarray,
+    quasi: np.ndarray,
+    sample: np.ndarray
+    ) -> None: ...
+
+def _fast_forward(
+    n: IntNumber,
+    num_gen: IntNumber,
+    dim: IntNumber,
+    sv: np.ndarray,
+    quasi: np.ndarray
+    ) -> None: ...
+
+def _categorize(
+    draws: np.ndarray,
+    p_cumulative: np.ndarray,
+    result: np.ndarray
+    ) -> None: ...
+
+_MAXDIM: Literal[21201]
+_MAXDEG: Literal[18]
+
+def _test_find_index(
+    p_cumulative: np.ndarray, 
+    size: int, 
+    value: float
+    ) -> int: ...
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_stats.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_stats.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..b8ffcbed4a6a25095faf55aa2aa167d56101df76
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_stats.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_stats.pxd b/python_embeded/Lib/site-packages/scipy/stats/_stats.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..b6ce5f7ee186cef2ff339c1621c0d38f666e136d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_stats.pxd
@@ -0,0 +1,10 @@
+# destined to be used in a LowLevelCallable
+
+cdef double _geninvgauss_pdf(double x, void *user_data) noexcept nogil
+cdef double _studentized_range_cdf(int n, double[2] x, void *user_data) noexcept nogil
+cdef double _studentized_range_cdf_asymptotic(double z, void *user_data) noexcept nogil
+cdef double _studentized_range_pdf(int n, double[2] x, void *user_data) noexcept nogil
+cdef double _studentized_range_pdf_asymptotic(double z, void *user_data) noexcept nogil
+cdef double _studentized_range_moment(int n, double[3] x_arg, void *user_data) noexcept nogil
+cdef double _genhyperbolic_pdf(double x, void *user_data) noexcept nogil
+cdef double _genhyperbolic_logpdf(double x, void *user_data) noexcept nogil
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_stats_mstats_common.py b/python_embeded/Lib/site-packages/scipy/stats/_stats_mstats_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..920c34f062584b52a74a1976118b9b71c6ee6320
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_stats_mstats_common.py
@@ -0,0 +1,303 @@
+import warnings
+import numpy as np
+from . import distributions
+from .._lib._bunch import _make_tuple_bunch
+from ._stats_pythran import siegelslopes as siegelslopes_pythran
+
+__all__ = ['_find_repeats', 'theilslopes', 'siegelslopes']
+
+# This is not a namedtuple for backwards compatibility. See PR #12983
+TheilslopesResult = _make_tuple_bunch('TheilslopesResult',
+                                      ['slope', 'intercept',
+                                       'low_slope', 'high_slope'])
+SiegelslopesResult = _make_tuple_bunch('SiegelslopesResult',
+                                       ['slope', 'intercept'])
+
+
+def theilslopes(y, x=None, alpha=0.95, method='separate'):
+    r"""
+    Computes the Theil-Sen estimator for a set of points (x, y).
+
+    `theilslopes` implements a method for robust linear regression.  It
+    computes the slope as the median of all slopes between paired values.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    alpha : float, optional
+        Confidence degree between 0 and 1. Default is 95% confidence.
+        Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are
+        interpreted as "find the 90% confidence interval".
+    method : {'joint', 'separate'}, optional
+        Method to be used for computing estimate for intercept.
+        Following methods are supported,
+
+            * 'joint': Uses np.median(y - slope * x) as intercept.
+            * 'separate': Uses np.median(y) - slope * np.median(x)
+                          as intercept.
+
+        The default is 'separate'.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    result : ``TheilslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Theil slope.
+        intercept : float
+            Intercept of the Theil line.
+        low_slope : float
+            Lower bound of the confidence interval on `slope`.
+        high_slope : float
+            Upper bound of the confidence interval on `slope`.
+
+    See Also
+    --------
+    siegelslopes : a similar technique using repeated medians
+
+    Notes
+    -----
+    The implementation of `theilslopes` follows [1]_. The intercept is
+    not defined in [1]_, and here it is defined as ``median(y) -
+    slope*median(x)``, which is given in [3]_. Other definitions of
+    the intercept exist in the literature such as  ``median(y - slope*x)``
+    in [4]_. The approach to compute the intercept can be determined by the
+    parameter ``method``. A confidence interval for the intercept is not
+    given as this question is not addressed in [1]_.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 4, with fields ``slope``, ``intercept``,
+    ``low_slope``, and ``high_slope``, so one can continue to write::
+
+        slope, intercept, low_slope, high_slope = theilslopes(y, x)
+
+    References
+    ----------
+    .. [1] P.K. Sen, "Estimates of the regression coefficient based on
+           Kendall's tau", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968.
+    .. [2] H. Theil, "A rank-invariant method of linear and polynomial
+           regression analysis I, II and III",  Nederl. Akad. Wetensch., Proc.
+           53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950.
+    .. [3] W.L. Conover, "Practical nonparametric statistics", 2nd ed.,
+           John Wiley and Sons, New York, pp. 493.
+    .. [4] https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-5, 5, num=150)
+    >>> y = x + np.random.normal(size=x.size)
+    >>> y[11:15] += 10  # add outliers
+    >>> y[-5:] -= 7
+
+    Compute the slope, intercept and 90% confidence interval.  For comparison,
+    also compute the least-squares fit with `linregress`:
+
+    >>> res = stats.theilslopes(y, x, 0.90, method='separate')
+    >>> lsq_res = stats.linregress(x, y)
+
+    Plot the results. The Theil-Sen regression line is shown in red, with the
+    dashed red lines illustrating the confidence interval of the slope (note
+    that the dashed red lines are not the confidence interval of the regression
+    as the confidence interval of the intercept is not included). The green
+    line shows the least-squares fit for comparison.
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, y, 'b.')
+    >>> ax.plot(x, res[1] + res[0] * x, 'r-')
+    >>> ax.plot(x, res[1] + res[2] * x, 'r--')
+    >>> ax.plot(x, res[1] + res[3] * x, 'r--')
+    >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
+    >>> plt.show()
+
+    """
+    if method not in ['joint', 'separate']:
+        raise ValueError("method must be either 'joint' or 'separate'."
+                         f"'{method}' is invalid.")
+    # We copy both x and y so we can use _find_repeats.
+    y = np.array(y, dtype=float, copy=True).ravel()
+    if x is None:
+        x = np.arange(len(y), dtype=float)
+    else:
+        x = np.array(x, dtype=float, copy=True).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    # Compute sorted slopes only when deltax > 0
+    deltax = x[:, np.newaxis] - x
+    deltay = y[:, np.newaxis] - y
+    slopes = deltay[deltax > 0] / deltax[deltax > 0]
+    if not slopes.size:
+        msg = "All `x` coordinates are identical."
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+    slopes.sort()
+    medslope = np.median(slopes)
+    if method == 'joint':
+        medinter = np.median(y - medslope * x)
+    else:
+        medinter = np.median(y) - medslope * np.median(x)
+    # Now compute confidence intervals
+    if alpha > 0.5:
+        alpha = 1. - alpha
+
+    z = distributions.norm.ppf(alpha / 2.)
+    # This implements (2.6) from Sen (1968)
+    _, nxreps = _find_repeats(x)
+    _, nyreps = _find_repeats(y)
+    nt = len(slopes)       # N in Sen (1968)
+    ny = len(y)            # n in Sen (1968)
+    # Equation 2.6 in Sen (1968):
+    sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) -
+                     sum(k * (k-1) * (2*k + 5) for k in nxreps) -
+                     sum(k * (k-1) * (2*k + 5) for k in nyreps))
+    # Find the confidence interval indices in `slopes`
+    try:
+        sigma = np.sqrt(sigsq)
+        Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)
+        Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)
+        delta = slopes[[Rl, Ru]]
+    except (ValueError, IndexError):
+        delta = (np.nan, np.nan)
+
+    return TheilslopesResult(slope=medslope, intercept=medinter,
+                             low_slope=delta[0], high_slope=delta[1])
+
+
+def _find_repeats(arr):
+    # This function assumes it may clobber its input.
+    if len(arr) == 0:
+        return np.array(0, np.float64), np.array(0, np.intp)
+
+    # XXX This cast was previously needed for the Fortran implementation,
+    # should we ditch it?
+    arr = np.asarray(arr, np.float64).ravel()
+    arr.sort()
+
+    # Taken from NumPy 1.9's np.unique.
+    change = np.concatenate(([True], arr[1:] != arr[:-1]))
+    unique = arr[change]
+    change_idx = np.concatenate(np.nonzero(change) + ([arr.size],))
+    freq = np.diff(change_idx)
+    atleast2 = freq > 1
+    return unique[atleast2], freq[atleast2]
+
+
+def siegelslopes(y, x=None, method="hierarchical"):
+    r"""
+    Computes the Siegel estimator for a set of points (x, y).
+
+    `siegelslopes` implements a method for robust linear regression
+    using repeated medians (see [1]_) to fit a line to the points (x, y).
+    The method is robust to outliers with an asymptotic breakdown point
+    of 50%.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    method : {'hierarchical', 'separate'}
+        If 'hierarchical', estimate the intercept using the estimated
+        slope ``slope`` (default option).
+        If 'separate', estimate the intercept independent of the estimated
+        slope. See Notes for details.
+
+    Returns
+    -------
+    result : ``SiegelslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Estimate of the slope of the regression line.
+        intercept : float
+            Estimate of the intercept of the regression line.
+
+    See Also
+    --------
+    theilslopes : a similar technique without repeated medians
+
+    Notes
+    -----
+    With ``n = len(y)``, compute ``m_j`` as the median of
+    the slopes from the point ``(x[j], y[j])`` to all other `n-1` points.
+    ``slope`` is then the median of all slopes ``m_j``.
+    Two ways are given to estimate the intercept in [1]_ which can be chosen
+    via the parameter ``method``.
+    The hierarchical approach uses the estimated slope ``slope``
+    and computes ``intercept`` as the median of ``y - slope*x``.
+    The other approach estimates the intercept separately as follows: for
+    each point ``(x[j], y[j])``, compute the intercepts of all the `n-1`
+    lines through the remaining points and take the median ``i_j``.
+    ``intercept`` is the median of the ``i_j``.
+
+    The implementation computes `n` times the median of a vector of size `n`
+    which can be slow for large vectors. There are more efficient algorithms
+    (see [2]_) which are not implemented here.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 2, with fields ``slope`` and
+    ``intercept``, so one can continue to write::
+
+        slope, intercept = siegelslopes(y, x)
+
+    References
+    ----------
+    .. [1] A. Siegel, "Robust Regression Using Repeated Medians",
+           Biometrika, Vol. 69, pp. 242-244, 1982.
+
+    .. [2] A. Stein and M. Werman, "Finding the repeated median regression
+           line", Proceedings of the Third Annual ACM-SIAM Symposium on
+           Discrete Algorithms, pp. 409-413, 1992.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-5, 5, num=150)
+    >>> y = x + np.random.normal(size=x.size)
+    >>> y[11:15] += 10  # add outliers
+    >>> y[-5:] -= 7
+
+    Compute the slope and intercept.  For comparison, also compute the
+    least-squares fit with `linregress`:
+
+    >>> res = stats.siegelslopes(y, x)
+    >>> lsq_res = stats.linregress(x, y)
+
+    Plot the results. The Siegel regression line is shown in red. The green
+    line shows the least-squares fit for comparison.
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, y, 'b.')
+    >>> ax.plot(x, res[1] + res[0] * x, 'r-')
+    >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
+    >>> plt.show()
+
+    """
+    if method not in ['hierarchical', 'separate']:
+        raise ValueError("method can only be 'hierarchical' or 'separate'")
+    y = np.asarray(y).ravel()
+    if x is None:
+        x = np.arange(len(y), dtype=float)
+    else:
+        x = np.asarray(x, dtype=float).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+    dtype = np.result_type(x, y, np.float32)  # use at least float32
+    y, x = y.astype(dtype), x.astype(dtype)
+    medslope, medinter = siegelslopes_pythran(y, x, method)
+    return SiegelslopesResult(slope=medslope, intercept=medinter)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_stats_py.py b/python_embeded/Lib/site-packages/scipy/stats/_stats_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..02861b180560c44aea179fdf634ff454ad3379bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_stats_py.py
@@ -0,0 +1,11015 @@
+# Copyright 2002 Gary Strangman.  All rights reserved
+# Copyright 2002-2016 The SciPy Developers
+#
+# The original code from Gary Strangman was heavily adapted for
+# use in SciPy by Travis Oliphant.  The original code came with the
+# following disclaimer:
+#
+# This software is provided "as-is".  There are no expressed or implied
+# warranties of any kind, including, but not limited to, the warranties
+# of merchantability and fitness for a given application.  In no event
+# shall Gary Strangman be liable for any direct, indirect, incidental,
+# special, exemplary or consequential damages (including, but not limited
+# to, 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.
+
+"""
+A collection of basic statistical functions for Python.
+
+References
+----------
+.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+   Probability and Statistics Tables and Formulae. Chapman & Hall: New
+   York. 2000.
+
+"""
+import warnings
+import math
+from math import gcd
+from collections import namedtuple
+from collections.abc import Sequence
+
+import numpy as np
+from numpy import array, asarray, ma
+
+from scipy import sparse
+from scipy.spatial import distance_matrix
+
+from scipy.optimize import milp, LinearConstraint
+from scipy._lib._util import (check_random_state, _get_nan,
+                              _rename_parameter, _contains_nan,
+                              AxisError, _lazywhere)
+from scipy._lib.deprecation import _deprecate_positional_args
+
+
+import scipy.special as special
+# Import unused here but needs to stay until end of deprecation periode
+# See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522
+from scipy import linalg  # noqa: F401
+from . import distributions
+from . import _mstats_basic as mstats_basic
+
+from ._stats_mstats_common import _find_repeats, theilslopes, siegelslopes
+from ._stats import _kendall_dis, _toint64, _weightedrankedtau
+
+from dataclasses import dataclass, field
+from ._hypotests import _all_partitions
+from ._stats_pythran import _compute_outer_prob_inside_method
+from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod,
+                          monte_carlo_test, permutation_test, bootstrap,
+                          _batch_generator)
+from ._axis_nan_policy import (_axis_nan_policy_factory,
+                               _broadcast_concatenate, _broadcast_shapes,
+                               _broadcast_array_shapes_remove_axis, SmallSampleWarning,
+                               too_small_1d_not_omit, too_small_1d_omit,
+                               too_small_nd_not_omit, too_small_nd_omit)
+from ._binomtest import _binary_search_for_binom_tst as _binary_search
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy import stats
+from scipy.optimize import root_scalar
+from scipy._lib._util import normalize_axis_index
+from scipy._lib._array_api import (
+    _asarray,
+    array_namespace,
+    is_numpy,
+    xp_size,
+    xp_moveaxis_to_end,
+    xp_sign,
+    xp_vector_norm,
+    xp_broadcast_promote,
+)
+from scipy._lib import array_api_extra as xpx
+from scipy._lib.deprecation import _deprecated
+
+
+# Functions/classes in other files should be added in `__init__.py`, not here
+__all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
+           'tmin', 'tmax', 'tstd', 'tsem', 'moment',
+           'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
+           'normaltest', 'jarque_bera',
+           'scoreatpercentile', 'percentileofscore',
+           'cumfreq', 'relfreq', 'obrientransform',
+           'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
+           'median_abs_deviation',
+           'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
+           'f_oneway', 'pearsonr', 'fisher_exact',
+           'spearmanr', 'pointbiserialr',
+           'kendalltau', 'weightedtau',
+           'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
+           'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
+           'kstest', 'ks_1samp', 'ks_2samp',
+           'chisquare', 'power_divergence',
+           'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
+           'rankdata', 'combine_pvalues', 'quantile_test',
+           'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance',
+           'brunnermunzel', 'alexandergovern',
+           'expectile', 'lmoment']
+
+
+def _chk_asarray(a, axis, *, xp=None):
+    if xp is None:
+        xp = array_namespace(a)
+
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        outaxis = 0
+    else:
+        a = xp.asarray(a)
+        outaxis = axis
+
+    if a.ndim == 0:
+        a = xp.reshape(a, (-1,))
+
+    return a, outaxis
+
+
+def _chk2_asarray(a, b, axis):
+    if axis is None:
+        a = np.ravel(a)
+        b = np.ravel(b)
+        outaxis = 0
+    else:
+        a = np.asarray(a)
+        b = np.asarray(b)
+        outaxis = axis
+
+    if a.ndim == 0:
+        a = np.atleast_1d(a)
+    if b.ndim == 0:
+        b = np.atleast_1d(b)
+
+    return a, b, outaxis
+
+
+def _convert_common_float(*arrays, xp=None):
+    xp = array_namespace(*arrays) if xp is None else xp
+    arrays = [_asarray(array, subok=True) for array in arrays]
+    dtypes = [(xp.asarray(1.).dtype if xp.isdtype(array.dtype, 'integral')
+               else array.dtype) for array in arrays]
+    dtype = xp.result_type(*dtypes)
+    arrays = [xp.astype(array, dtype, copy=False) for array in arrays]
+    return arrays[0] if len(arrays)==1 else tuple(arrays)
+
+
+SignificanceResult = _make_tuple_bunch('SignificanceResult',
+                                       ['statistic', 'pvalue'], [])
+
+
+# note that `weights` are paired with `x`
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def gmean(a, axis=0, dtype=None, weights=None):
+    r"""Compute the weighted geometric mean along the specified axis.
+
+    The weighted geometric mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
+                   \right) \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \sqrt[n]{ \prod_{i=1}^n a_i } \, .
+
+    Parameters
+    ----------
+    a : array_like
+        Input array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the geometric mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type to which the input arrays are cast before the calculation is
+        performed.
+    weights : array_like, optional
+        The `weights` array must be broadcastable to the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+    Returns
+    -------
+    gmean : ndarray
+        See `dtype` parameter above.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.average : Weighted average
+    hmean : Harmonic mean
+
+    Notes
+    -----
+    The sample geometric mean is the exponential of the mean of the natural
+    logarithms of the observations.
+    Negative observations will produce NaNs in the output because the *natural*
+    logarithm (as opposed to the *complex* logarithm) is defined only for
+    non-negative reals.
+
+    References
+    ----------
+    .. [1] "Weighted Geometric Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Weighted_geometric_mean.
+    .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach",
+           Archimedes Foundation, 1983
+
+    Examples
+    --------
+    >>> from scipy.stats import gmean
+    >>> gmean([1, 4])
+    2.0
+    >>> gmean([1, 2, 3, 4, 5, 6, 7])
+    3.3800151591412964
+    >>> gmean([1, 4, 7], weights=[3, 1, 3])
+    2.80668351922014
+
+    """
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    with np.errstate(divide='ignore'):
+        log_a = xp.log(a)
+
+    return xp.exp(_xp_mean(log_a, axis=axis, weights=weights))
+
+
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def hmean(a, axis=0, dtype=None, *, weights=None):
+    r"""Calculate the weighted harmonic mean along the specified axis.
+
+    The weighted harmonic mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .
+
+    Parameters
+    ----------
+    a : array_like
+        Input array, masked array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the harmonic mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type of the returned array and of the accumulator in which the
+        elements are summed. If `dtype` is not specified, it defaults to the
+        dtype of `a`, unless `a` has an integer `dtype` with a precision less
+        than that of the default platform integer. In that case, the default
+        platform integer is used.
+    weights : array_like, optional
+        The weights array can either be 1-D (in which case its length must be
+        the size of `a` along the given `axis`) or of the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+        .. versionadded:: 1.9
+
+    Returns
+    -------
+    hmean : ndarray
+        See `dtype` parameter above.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.average : Weighted average
+    gmean : Geometric mean
+
+    Notes
+    -----
+    The sample harmonic mean is the reciprocal of the mean of the reciprocals
+    of the observations.
+
+    The harmonic mean is computed over a single dimension of the input
+    array, axis=0 by default, or all values in the array if axis=None.
+    float64 intermediate and return values are used for integer inputs.
+
+    The harmonic mean is only defined if all observations are non-negative;
+    otherwise, the result is NaN.
+
+    References
+    ----------
+    .. [1] "Weighted Harmonic Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
+    .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
+           the American Statistical Association, vol. 26, pp. 36-40, 1931
+
+    Examples
+    --------
+    >>> from scipy.stats import hmean
+    >>> hmean([1, 4])
+    1.6000000000000001
+    >>> hmean([1, 2, 3, 4, 5, 6, 7])
+    2.6997245179063363
+    >>> hmean([1, 4, 7], weights=[3, 1, 3])
+    1.9029126213592233
+
+    """
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    negative_mask = a < 0
+    if xp.any(negative_mask):
+        # `where` avoids having to be careful about dtypes and will work with
+        # JAX. This is the exceptional case, so it's OK to be a little slower.
+        # Won't work for array_api_strict for now, but see data-apis/array-api#807
+        a = xp.where(negative_mask, xp.nan, a)
+        message = ("The harmonic mean is only defined if all elements are "
+                   "non-negative; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    with np.errstate(divide='ignore'):
+        return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights)
+
+
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def pmean(a, p, *, axis=0, dtype=None, weights=None):
+    r"""Calculate the weighted power mean along the specified axis.
+
+    The weighted power mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
+              \right)^{ 1 / p } \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p }  \, .
+
+    When ``p=0``, it returns the geometric mean.
+
+    This mean is also called generalized mean or Hölder mean, and must not be
+    confused with the Kolmogorov generalized mean, also called
+    quasi-arithmetic mean or generalized f-mean [3]_.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array, masked array or object that can be converted to an array.
+    p : int or float
+        Exponent.
+    axis : int or None, optional
+        Axis along which the power mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type of the returned array and of the accumulator in which the
+        elements are summed. If `dtype` is not specified, it defaults to the
+        dtype of `a`, unless `a` has an integer `dtype` with a precision less
+        than that of the default platform integer. In that case, the default
+        platform integer is used.
+    weights : array_like, optional
+        The weights array can either be 1-D (in which case its length must be
+        the size of `a` along the given `axis`) or of the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+    Returns
+    -------
+    pmean : ndarray, see `dtype` parameter above.
+        Output array containing the power mean values.
+
+    See Also
+    --------
+    numpy.average : Weighted average
+    gmean : Geometric mean
+    hmean : Harmonic mean
+
+    Notes
+    -----
+    The power mean is computed over a single dimension of the input
+    array, ``axis=0`` by default, or all values in the array if ``axis=None``.
+    float64 intermediate and return values are used for integer inputs.
+
+    The power mean is only defined if all observations are non-negative;
+    otherwise, the result is NaN.
+
+    .. versionadded:: 1.9
+
+    References
+    ----------
+    .. [1] "Generalized Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Generalized_mean
+    .. [2] Norris, N., "Convexity properties of generalized mean value
+           functions", The Annals of Mathematical Statistics, vol. 8,
+           pp. 118-120, 1937
+    .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003
+
+    Examples
+    --------
+    >>> from scipy.stats import pmean, hmean, gmean
+    >>> pmean([1, 4], 1.3)
+    2.639372938300652
+    >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
+    4.157111214492084
+    >>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
+    1.4969684896631954
+
+    For p=-1, power mean is equal to harmonic mean:
+
+    >>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
+    1.9029126213592233
+    >>> hmean([1, 4, 7], weights=[3, 1, 3])
+    1.9029126213592233
+
+    For p=0, power mean is defined as the geometric mean:
+
+    >>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
+    2.80668351922014
+    >>> gmean([1, 4, 7], weights=[3, 1, 3])
+    2.80668351922014
+
+    """
+    if not isinstance(p, (int, float)):
+        raise ValueError("Power mean only defined for exponent of type int or "
+                         "float.")
+    if p == 0:
+        return gmean(a, axis=axis, dtype=dtype, weights=weights)
+
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    negative_mask = a < 0
+    if xp.any(negative_mask):
+        # `where` avoids having to be careful about dtypes and will work with
+        # JAX. This is the exceptional case, so it's OK to be a little slower.
+        # Won't work for array_api_strict for now, but see data-apis/array-api#807
+        a = xp.where(negative_mask, np.nan, a)
+        message = ("The power mean is only defined if all elements are "
+                   "non-negative; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p)
+
+
+ModeResult = namedtuple('ModeResult', ('mode', 'count'))
+
+
+def _mode_result(mode, count):
+    # When a slice is empty, `_axis_nan_policy` automatically produces
+    # NaN for `mode` and `count`. This is a reasonable convention for `mode`,
+    # but `count` should not be NaN; it should be zero.
+    i = np.isnan(count)
+    if i.shape == ():
+        count = np.asarray(0, dtype=count.dtype)[()] if i else count
+    else:
+        count[i] = 0
+    return ModeResult(mode, count)
+
+
+@_axis_nan_policy_factory(_mode_result, override={'vectorization': True,
+                                                  'nan_propagation': False})
+def mode(a, axis=0, nan_policy='propagate', keepdims=False):
+    r"""Return an array of the modal (most common) value in the passed array.
+
+    If there is more than one such value, only one is returned.
+    The bin-count for the modal bins is also returned.
+
+    Parameters
+    ----------
+    a : array_like
+        Numeric, n-dimensional array of which to find mode(s).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': treats nan as it would treat any other value
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    keepdims : bool, optional
+        If set to ``False``, the `axis` over which the statistic is taken
+        is consumed (eliminated from the output array). If set to ``True``,
+        the `axis` is retained with size one, and the result will broadcast
+        correctly against the input array.
+
+    Returns
+    -------
+    mode : ndarray
+        Array of modal values.
+    count : ndarray
+        Array of counts for each mode.
+
+    Notes
+    -----
+    The mode  is calculated using `numpy.unique`.
+    In NumPy versions 1.21 and after, all NaNs - even those with different
+    binary representations - are treated as equivalent and counted as separate
+    instances of the same value.
+
+    By convention, the mode of an empty array is NaN, and the associated count
+    is zero.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[3, 0, 3, 7],
+    ...               [3, 2, 6, 2],
+    ...               [1, 7, 2, 8],
+    ...               [3, 0, 6, 1],
+    ...               [3, 2, 5, 5]])
+    >>> from scipy import stats
+    >>> stats.mode(a, keepdims=True)
+    ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]]))
+
+    To get mode of whole array, specify ``axis=None``:
+
+    >>> stats.mode(a, axis=None, keepdims=True)
+    ModeResult(mode=[[3]], count=[[5]])
+    >>> stats.mode(a, axis=None, keepdims=False)
+    ModeResult(mode=3, count=5)
+
+    """
+    # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy`
+    if not np.issubdtype(a.dtype, np.number):
+        message = ("Argument `a` is not recognized as numeric. "
+                   "Support for input that cannot be coerced to a numeric "
+                   "array was deprecated in SciPy 1.9.0 and removed in SciPy "
+                   "1.11.0. Please consider `np.unique`.")
+        raise TypeError(message)
+
+    if a.size == 0:
+        NaN = _get_nan(a)
+        return ModeResult(*np.array([NaN, 0], dtype=NaN.dtype))
+
+    vals, cnts = np.unique(a, return_counts=True)
+    modes, counts = vals[cnts.argmax()], cnts.max()
+    return ModeResult(modes[()], counts[()])
+
+
+def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None):
+    """Replace elements outside limits with a value.
+
+    This is primarily a utility function.
+
+    Parameters
+    ----------
+    a : array
+    limits : (float or None, float or None)
+        A tuple consisting of the (lower limit, upper limit).  Elements in the
+        input array less than the lower limit or greater than the upper limit
+        will be replaced with `val`. None implies no limit.
+    inclusive : (bool, bool)
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to lower or upper are allowed.
+    val : float, default: NaN
+        The value with which extreme elements of the array are replaced.
+
+    """
+    xp = array_namespace(a) if xp is None else xp
+    mask = xp.zeros(a.shape, dtype=xp.bool)
+    if limits is None:
+        return a, mask
+    lower_limit, upper_limit = limits
+    lower_include, upper_include = inclusive
+    if lower_limit is not None:
+        mask |= (a < lower_limit) if lower_include else a <= lower_limit
+    if upper_limit is not None:
+        mask |= (a > upper_limit) if upper_include else a >= upper_limit
+    if xp.all(mask):
+        raise ValueError("No array values within given limits")
+    if xp.any(mask):
+        # hopefully this (and many other instances of this idiom) are temporary when
+        # data-apis/array-api#807 is resolved
+        dtype = xp.asarray(1.).dtype if xp.isdtype(a.dtype, 'integral') else a.dtype
+        a = xp.where(mask, xp.asarray(val, dtype=dtype), a)
+    return a, mask
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def tmean(a, limits=None, inclusive=(True, True), axis=None):
+    """Compute the trimmed mean.
+
+    This function finds the arithmetic mean of given values, ignoring values
+    outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored.  When limits is None (default), then all
+        values are used.  Either of the limit values in the tuple can also be
+        None representing a half-open interval.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to compute test. Default is None.
+
+    Returns
+    -------
+    tmean : ndarray
+        Trimmed mean.
+
+    See Also
+    --------
+    trim_mean : Returns mean after trimming a proportion from both tails.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmean(x)
+    9.5
+    >>> stats.tmean(x, (3,17))
+    10.0
+
+    """
+    xp = array_namespace(a)
+    a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp)
+    # explicit dtype specification required due to data-apis/array-api-compat#152
+    sum = xp.sum(a, axis=axis, dtype=a.dtype)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis, dtype=a.dtype)
+    mean = _lazywhere(n != 0, (sum, n), xp.divide, xp.nan)
+    return mean[()] if mean.ndim == 0 else mean
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed variance.
+
+    This function computes the sample variance of an array of values,
+    while ignoring values which are outside of given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tvar : float
+        Trimmed variance.
+
+    Notes
+    -----
+    `tvar` computes the unbiased sample variance, i.e. it uses a correction
+    factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tvar(x)
+    35.0
+    >>> stats.tvar(x, (3,17))
+    20.0
+
+    """
+    xp = array_namespace(a)
+    a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", SmallSampleWarning)
+        # Currently, this behaves like nan_policy='omit' for alternative array
+        # backends, but nan_policy='propagate' will be handled for other backends
+        # by the axis_nan_policy decorator shortly.
+        return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
+    """Compute the trimmed minimum.
+
+    This function finds the minimum value of an array `a` along the
+    specified axis, but only considering values greater than a specified
+    lower limit.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    lowerlimit : None or float, optional
+        Values in the input array less than the given limit will be ignored.
+        When lowerlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the lower limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmin : float, int or ndarray
+        Trimmed minimum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmin(x)
+    0
+
+    >>> stats.tmin(x, 13)
+    13
+
+    >>> stats.tmin(x, 13, inclusive=False)
+    14
+
+    """
+    xp = array_namespace(a)
+
+    # remember original dtype; _put_val_to_limits might need to change it
+    dtype = a.dtype
+    a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None),
+                                 val=xp.inf, xp=xp)
+
+    min = xp.min(a, axis=axis)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis)
+    res = xp.where(n != 0, min, xp.nan)
+
+    if not xp.any(xp.isnan(res)):
+        # needed if input is of integer dtype
+        res = xp.astype(res, dtype, copy=False)
+
+    return res[()] if res.ndim == 0 else res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
+    """Compute the trimmed maximum.
+
+    This function computes the maximum value of an array along a given axis,
+    while ignoring values larger than a specified upper limit.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    upperlimit : None or float, optional
+        Values in the input array greater than the given limit will be ignored.
+        When upperlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the upper limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmax : float, int or ndarray
+        Trimmed maximum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmax(x)
+    19
+
+    >>> stats.tmax(x, 13)
+    13
+
+    >>> stats.tmax(x, 13, inclusive=False)
+    12
+
+    """
+    xp = array_namespace(a)
+
+    # remember original dtype; _put_val_to_limits might need to change it
+    dtype = a.dtype
+    a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive),
+                                 val=-xp.inf, xp=xp)
+
+    max = xp.max(a, axis=axis)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis)
+    res = xp.where(n != 0, max, xp.nan)
+
+    if not xp.any(xp.isnan(res)):
+        # needed if input is of integer dtype
+        res = xp.astype(res, dtype, copy=False)
+
+    return res[()] if res.ndim == 0 else res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed sample standard deviation.
+
+    This function finds the sample standard deviation of given values,
+    ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tstd : float
+        Trimmed sample standard deviation.
+
+    Notes
+    -----
+    `tstd` computes the unbiased sample standard deviation, i.e. it uses a
+    correction factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tstd(x)
+    5.9160797830996161
+    >>> stats.tstd(x, (3,17))
+    4.4721359549995796
+
+    """
+    return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed standard error of the mean.
+
+    This function finds the standard error of the mean for given
+    values, ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tsem : float
+        Trimmed standard error of the mean.
+
+    Notes
+    -----
+    `tsem` uses unbiased sample standard deviation, i.e. it uses a
+    correction factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tsem(x)
+    1.3228756555322954
+    >>> stats.tsem(x, (3,17))
+    1.1547005383792515
+
+    """
+    xp = array_namespace(a)
+    a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", SmallSampleWarning)
+        # Currently, this behaves like nan_policy='omit' for alternative array
+        # backends, but nan_policy='propagate' will be handled for other backends
+        # by the axis_nan_policy decorator shortly.
+        sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5
+
+    n_obs = xp.sum(~xp.isnan(a), axis=axis, dtype=sd.dtype)
+    return sd / n_obs**0.5
+
+
+#####################################
+#              MOMENTS              #
+#####################################
+
+
+def _moment_outputs(kwds, default_order=1):
+    order = np.atleast_1d(kwds.get('order', default_order))
+    message = "`order` must be a scalar or a non-empty 1D array."
+    if order.size == 0 or order.ndim > 1:
+        raise ValueError(message)
+    return len(order)
+
+
+def _moment_result_object(*args):
+    if len(args) == 1:
+        return args[0]
+    return np.asarray(args)
+
+
+# When `order` is array-like with size > 1, moment produces an *array*
+# rather than a tuple, but the zeroth dimension is to be treated like
+# separate outputs. It is important to make the distinction between
+# separate outputs when adding the reduced axes back (`keepdims=True`).
+def _moment_tuple(x, n_out):
+    return tuple(x) if n_out > 1 else (x,)
+
+
+# `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual
+# because the number of outputs is variable. Specifically,
+# `result_to_tuple=lambda x: (x,)` may be surprising for a function that
+# can produce more than one output, but it is intended here.
+# When `moment is called to produce the output:
+# - `result_to_tuple` packs the returned array into a single-element tuple,
+# - `_moment_result_object` extracts and returns that single element.
+# However, when the input array is empty, `moment` is never called. Instead,
+# - `_check_empty_inputs` is used to produce an empty array with the
+#   appropriate dimensions.
+# - A list comprehension creates the appropriate number of copies of this
+#   array, depending on `n_outputs`.
+# - This list - which may have multiple elements - is passed into
+#   `_moment_result_object`.
+# - If there is a single output, `_moment_result_object` extracts and returns
+#   the single output from the list.
+# - If there are multiple outputs, and therefore multiple elements in the list,
+#   `_moment_result_object` converts the list of arrays to a single array and
+#   returns it.
+# Currently, this leads to a slight inconsistency: when the input array is
+# empty, there is no distinction between the `moment` function being called
+# with parameter `order=1` and `order=[1]`; the latter *should* produce
+# the same as the former but with a singleton zeroth dimension.
+@_rename_parameter('moment', 'order')
+@_axis_nan_policy_factory(  # noqa: E302
+    _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
+    n_outputs=_moment_outputs
+)
+def moment(a, order=1, axis=0, nan_policy='propagate', *, center=None):
+    r"""Calculate the nth moment about the mean for a sample.
+
+    A moment is a specific quantitative measure of the shape of a set of
+    points. It is often used to calculate coefficients of skewness and kurtosis
+    due to its close relationship with them.
+
+    Parameters
+    ----------
+    a : array_like
+       Input array.
+    order : int or 1-D array_like of ints, optional
+       Order of central moment that is returned. Default is 1.
+    axis : int or None, optional
+       Axis along which the central moment is computed. Default is 0.
+       If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    center : float or None, optional
+       The point about which moments are taken. This can be the sample mean,
+       the origin, or any other be point. If `None` (default) compute the
+       center as the sample mean.
+
+    Returns
+    -------
+    n-th moment about the `center` : ndarray or float
+       The appropriate moment along the given axis or over all values if axis
+       is None. The denominator for the moment calculation is the number of
+       observations, no degrees of freedom correction is done.
+
+    See Also
+    --------
+    kurtosis, skew, describe
+
+    Notes
+    -----
+    The k-th moment of a data sample is:
+
+    .. math::
+
+        m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k
+
+    Where `n` is the number of samples, and `c` is the center around which the
+    moment is calculated. This function uses exponentiation by squares [1]_ for
+    efficiency.
+
+    Note that, if `a` is an empty array (``a.size == 0``), array `moment` with
+    one element (`moment.size == 1`) is treated the same as scalar `moment`
+    (``np.isscalar(moment)``). This might produce arrays of unexpected shape.
+
+    References
+    ----------
+    .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
+
+    Examples
+    --------
+    >>> from scipy.stats import moment
+    >>> moment([1, 2, 3, 4, 5], order=1)
+    0.0
+    >>> moment([1, 2, 3, 4, 5], order=2)
+    2.0
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.asarray(a, dtype=xp.float64)
+    else:
+        a = xp.asarray(a)
+
+    order = xp.asarray(order, dtype=a.dtype)
+    if xp_size(order) == 0:
+        # This is tested by `_moment_outputs`, which is run by the `_axis_nan_policy`
+        # decorator. Currently, the `_axis_nan_policy` decorator is skipped when `a`
+        # is a non-NumPy array, so we need to check again. When the decorator is
+        # updated for array API compatibility, we can remove this second check.
+        raise ValueError("`order` must be a scalar or a non-empty 1D array.")
+    if xp.any(order != xp.round(order)):
+        raise ValueError("All elements of `order` must be integral.")
+    order = order[()] if order.ndim == 0 else order
+
+    # for array_like order input, return a value for each.
+    if order.ndim > 0:
+        # Calculated the mean once at most, and only if it will be used
+        calculate_mean = center is None and xp.any(order > 1)
+        mean = xp.mean(a, axis=axis, keepdims=True) if calculate_mean else None
+        mmnt = []
+        for i in range(order.shape[0]):
+            order_i = order[i]
+            if center is None and order_i > 1:
+                mmnt.append(_moment(a, order_i, axis, mean=mean)[np.newaxis, ...])
+            else:
+                mmnt.append(_moment(a, order_i, axis, mean=center)[np.newaxis, ...])
+        return xp.concat(mmnt, axis=0)
+    else:
+        return _moment(a, order, axis, mean=center)
+
+
+def _demean(a, mean, axis, *, xp, precision_warning=True):
+    # subtracts `mean` from `a` and returns the result,
+    # warning if there is catastrophic cancellation. `mean`
+    # must be the mean of `a` along axis with `keepdims=True`.
+    # Used in e.g. `_moment`, `_zscore`, `_xp_var`. See gh-15905.
+    a_zero_mean = a - mean
+
+    if xp_size(a_zero_mean) == 0:
+        return a_zero_mean
+
+    eps = xp.finfo(mean.dtype).eps * 10
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        rel_diff = xp.max(xp.abs(a_zero_mean), axis=axis,
+                          keepdims=True) / xp.abs(mean)
+    with np.errstate(invalid='ignore'):
+        precision_loss = xp.any(rel_diff < eps)
+    n = (xp_size(a) if axis is None
+         # compact way to deal with axis tuples or ints
+         else np.prod(np.asarray(a.shape)[np.asarray(axis)]))
+
+    if precision_loss and n > 1 and precision_warning:
+        message = ("Precision loss occurred in moment calculation due to "
+                   "catastrophic cancellation. This occurs when the data "
+                   "are nearly identical. Results may be unreliable.")
+        warnings.warn(message, RuntimeWarning, stacklevel=5)
+    return a_zero_mean
+
+
+def _moment(a, order, axis, *, mean=None, xp=None):
+    """Vectorized calculation of raw moment about specified center
+
+    When `mean` is None, the mean is computed and used as the center;
+    otherwise, the provided value is used as the center.
+
+    """
+    xp = array_namespace(a) if xp is None else xp
+
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.asarray(a, dtype=xp.float64)
+
+    dtype = a.dtype
+
+    # moment of empty array is the same regardless of order
+    if xp_size(a) == 0:
+        return xp.mean(a, axis=axis)
+
+    if order == 0 or (order == 1 and mean is None):
+        # By definition the zeroth moment is always 1, and the first *central*
+        # moment is 0.
+        shape = list(a.shape)
+        del shape[axis]
+
+        temp = (xp.ones(shape, dtype=dtype) if order == 0
+                else xp.zeros(shape, dtype=dtype))
+        return temp[()] if temp.ndim == 0 else temp
+
+    # Exponentiation by squares: form exponent sequence
+    n_list = [order]
+    current_n = order
+    while current_n > 2:
+        if current_n % 2:
+            current_n = (current_n - 1) / 2
+        else:
+            current_n /= 2
+        n_list.append(current_n)
+
+    # Starting point for exponentiation by squares
+    mean = (xp.mean(a, axis=axis, keepdims=True) if mean is None
+            else xp.asarray(mean, dtype=dtype))
+    mean = mean[()] if mean.ndim == 0 else mean
+    a_zero_mean = _demean(a, mean, axis, xp=xp)
+
+    if n_list[-1] == 1:
+        s = xp.asarray(a_zero_mean, copy=True)
+    else:
+        s = a_zero_mean**2
+
+    # Perform multiplications
+    for n in n_list[-2::-1]:
+        s = s**2
+        if n % 2:
+            s *= a_zero_mean
+    return xp.mean(s, axis=axis)
+
+
+def _var(x, axis=0, ddof=0, mean=None, xp=None):
+    # Calculate variance of sample, warning if precision is lost
+    xp = array_namespace(x) if xp is None else xp
+    var = _moment(x, 2, axis, mean=mean, xp=xp)
+    if ddof != 0:
+        n = x.shape[axis] if axis is not None else xp_size(x)
+        var *= np.divide(n, n-ddof)  # to avoid error on division by zero
+    return var
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
+)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def skew(a, axis=0, bias=True, nan_policy='propagate'):
+    r"""Compute the sample skewness of a data set.
+
+    For normally distributed data, the skewness should be about zero. For
+    unimodal continuous distributions, a skewness value greater than zero means
+    that there is more weight in the right tail of the distribution. The
+    function `skewtest` can be used to determine if the skewness value
+    is close enough to zero, statistically speaking.
+
+    Parameters
+    ----------
+    a : ndarray
+        Input array.
+    axis : int or None, optional
+        Axis along which skewness is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    skewness : ndarray
+        The skewness of values along an axis, returning NaN where all values
+        are equal.
+
+    Notes
+    -----
+    The sample skewness is computed as the Fisher-Pearson coefficient
+    of skewness, i.e.
+
+    .. math::
+
+        g_1=\frac{m_3}{m_2^{3/2}}
+
+    where
+
+    .. math::
+
+        m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
+
+    is the biased sample :math:`i\texttt{th}` central moment, and
+    :math:`\bar{x}` is
+    the sample mean.  If ``bias`` is False, the calculations are
+    corrected for bias and the value computed is the adjusted
+    Fisher-Pearson standardized moment coefficient, i.e.
+
+    .. math::
+
+        G_1=\frac{k_3}{k_2^{3/2}}=
+            \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+       Section 2.2.24.1
+
+    Examples
+    --------
+    >>> from scipy.stats import skew
+    >>> skew([1, 2, 3, 4, 5])
+    0.0
+    >>> skew([2, 8, 0, 4, 1, 9, 9, 0])
+    0.2650554122698573
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+    n = a.shape[axis]
+
+    mean = xp.mean(a, axis=axis, keepdims=True)
+    mean_reduced = xp.squeeze(mean, axis=axis)  # needed later
+    m2 = _moment(a, 2, axis, mean=mean, xp=xp)
+    m3 = _moment(a, 3, axis, mean=mean, xp=xp)
+    with np.errstate(all='ignore'):
+        eps = xp.finfo(m2.dtype).eps
+        zero = m2 <= (eps * mean_reduced)**2
+        vals = xp.where(zero, xp.asarray(xp.nan), m3 / m2**1.5)
+    if not bias:
+        can_correct = ~zero & (n > 2)
+        if xp.any(can_correct):
+            m2 = m2[can_correct]
+            m3 = m3[can_correct]
+            nval = ((n - 1.0) * n)**0.5 / (n - 2.0) * m3 / m2**1.5
+            vals[can_correct] = nval
+
+    return vals[()] if vals.ndim == 0 else vals
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
+)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
+    """Compute the kurtosis (Fisher or Pearson) of a dataset.
+
+    Kurtosis is the fourth central moment divided by the square of the
+    variance. If Fisher's definition is used, then 3.0 is subtracted from
+    the result to give 0.0 for a normal distribution.
+
+    If bias is False then the kurtosis is calculated using k statistics to
+    eliminate bias coming from biased moment estimators
+
+    Use `kurtosistest` to see if result is close enough to normal.
+
+    Parameters
+    ----------
+    a : array
+        Data for which the kurtosis is calculated.
+    axis : int or None, optional
+        Axis along which the kurtosis is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    fisher : bool, optional
+        If True, Fisher's definition is used (normal ==> 0.0). If False,
+        Pearson's definition is used (normal ==> 3.0).
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+
+    Returns
+    -------
+    kurtosis : array
+        The kurtosis of values along an axis, returning NaN where all values
+        are equal.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+
+    Examples
+    --------
+    In Fisher's definition, the kurtosis of the normal distribution is zero.
+    In the following example, the kurtosis is close to zero, because it was
+    calculated from the dataset, not from the continuous distribution.
+
+    >>> import numpy as np
+    >>> from scipy.stats import norm, kurtosis
+    >>> data = norm.rvs(size=1000, random_state=3)
+    >>> kurtosis(data)
+    -0.06928694200380558
+
+    The distribution with a higher kurtosis has a heavier tail.
+    The zero valued kurtosis of the normal distribution in Fisher's definition
+    can serve as a reference point.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import scipy.stats as stats
+    >>> from scipy.stats import kurtosis
+
+    >>> x = np.linspace(-5, 5, 100)
+    >>> ax = plt.subplot()
+    >>> distnames = ['laplace', 'norm', 'uniform']
+
+    >>> for distname in distnames:
+    ...     if distname == 'uniform':
+    ...         dist = getattr(stats, distname)(loc=-2, scale=4)
+    ...     else:
+    ...         dist = getattr(stats, distname)
+    ...     data = dist.rvs(size=1000)
+    ...     kur = kurtosis(data, fisher=True)
+    ...     y = dist.pdf(x)
+    ...     ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
+    ...     ax.legend()
+
+    The Laplace distribution has a heavier tail than the normal distribution.
+    The uniform distribution (which has negative kurtosis) has the thinnest
+    tail.
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+    mean = xp.mean(a, axis=axis, keepdims=True)
+    mean_reduced = xp.squeeze(mean, axis=axis)  # needed later
+    m2 = _moment(a, 2, axis, mean=mean, xp=xp)
+    m4 = _moment(a, 4, axis, mean=mean, xp=xp)
+    with np.errstate(all='ignore'):
+        zero = m2 <= (xp.finfo(m2.dtype).eps * mean_reduced)**2
+        NaN = _get_nan(m4, xp=xp)
+        vals = xp.where(zero, NaN, m4 / m2**2.0)
+
+    if not bias:
+        can_correct = ~zero & (n > 3)
+        if xp.any(can_correct):
+            m2 = m2[can_correct]
+            m4 = m4[can_correct]
+            nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
+            vals[can_correct] = nval + 3.0
+
+    vals = vals - 3 if fisher else vals
+    return vals[()] if vals.ndim == 0 else vals
+
+
+DescribeResult = namedtuple('DescribeResult',
+                            ('nobs', 'minmax', 'mean', 'variance', 'skewness',
+                             'kurtosis'))
+
+
+def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
+    """Compute several descriptive statistics of the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        Input data.
+    axis : int or None, optional
+        Axis along which statistics are calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom (only for variance).  Default is 1.
+    bias : bool, optional
+        If False, then the skewness and kurtosis calculations are corrected
+        for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    nobs : int or ndarray of ints
+        Number of observations (length of data along `axis`).
+        When 'omit' is chosen as nan_policy, the length along each axis
+        slice is counted separately.
+    minmax: tuple of ndarrays or floats
+        Minimum and maximum value of `a` along the given axis.
+    mean : ndarray or float
+        Arithmetic mean of `a` along the given axis.
+    variance : ndarray or float
+        Unbiased variance of `a` along the given axis; denominator is number
+        of observations minus one.
+    skewness : ndarray or float
+        Skewness of `a` along the given axis, based on moment calculations
+        with denominator equal to the number of observations, i.e. no degrees
+        of freedom correction.
+    kurtosis : ndarray or float
+        Kurtosis (Fisher) of `a` along the given axis.  The kurtosis is
+        normalized so that it is zero for the normal distribution.  No
+        degrees of freedom are used.
+
+    Raises
+    ------
+    ValueError
+        If size of `a` is 0.
+
+    See Also
+    --------
+    skew, kurtosis
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(10)
+    >>> stats.describe(a)
+    DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
+                   variance=9.166666666666666, skewness=0.0,
+                   kurtosis=-1.2242424242424244)
+    >>> b = [[1, 2], [3, 4]]
+    >>> stats.describe(b)
+    DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
+                   mean=array([2., 3.]), variance=array([2., 2.]),
+                   skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    contains_nan, nan_policy = _contains_nan(a, nan_policy)
+
+    if contains_nan and nan_policy == 'omit':
+        # only NumPy gets here; `_contains_nan` raises error for the rest
+        a = ma.masked_invalid(a)
+        return mstats_basic.describe(a, axis, ddof, bias)
+
+    if xp_size(a) == 0:
+        raise ValueError("The input must not be empty.")
+
+    n = a.shape[axis]
+    mm = (xp.min(a, axis=axis), xp.max(a, axis=axis))
+    m = xp.mean(a, axis=axis)
+    v = _var(a, axis=axis, ddof=ddof, xp=xp)
+    sk = skew(a, axis, bias=bias)
+    kurt = kurtosis(a, axis, bias=bias)
+
+    return DescribeResult(n, mm, m, v, sk, kurt)
+
+#####################################
+#         NORMALITY TESTS           #
+#####################################
+
+
+def _get_pvalue(statistic, distribution, alternative, symmetric=True, xp=None):
+    """Get p-value given the statistic, (continuous) distribution, and alternative"""
+    xp = array_namespace(statistic) if xp is None else xp
+
+    if alternative == 'less':
+        pvalue = distribution.cdf(statistic)
+    elif alternative == 'greater':
+        pvalue = distribution.sf(statistic)
+    elif alternative == 'two-sided':
+        pvalue = 2 * (distribution.sf(xp.abs(statistic)) if symmetric
+                      else xp.minimum(distribution.cdf(statistic),
+                                      distribution.sf(statistic)))
+    else:
+        message = "`alternative` must be 'less', 'greater', or 'two-sided'."
+        raise ValueError(message)
+
+    return pvalue
+
+
+SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(SkewtestResult, n_samples=1, too_small=7)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
+    r"""Test whether the skew is different from the normal distribution.
+
+    This function tests the null hypothesis that the skewness of
+    the population that the sample was drawn from is the same
+    as that of a corresponding normal distribution.
+
+    Parameters
+    ----------
+    a : array
+        The data to be tested. Must contain at least eight observations.
+    axis : int or None, optional
+       Axis along which statistics are calculated. Default is 0.
+       If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the skewness of the distribution underlying the sample
+          is different from that of the normal distribution (i.e. 0)
+        * 'less': the skewness of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the skewness of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The computed z-score for this test.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_skewtest` : Extended example
+
+    Notes
+    -----
+    The sample size must be at least 8.
+
+    References
+    ----------
+    .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
+            "A suggestion for using powerful and informative tests of
+            normality", American Statistician 44, pp. 316-321, 1990.
+
+    Examples
+    --------
+
+    >>> from scipy.stats import skewtest
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
+    >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
+    SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
+    SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
+    >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
+    SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less')
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater')
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484)
+
+    For a more detailed example, see :ref:`hypothesis_skewtest`.
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    b2 = skew(a, axis, _no_deco=True)
+    n = a.shape[axis]
+    if n < 8:
+        message = ("`skewtest` requires at least 8 observations; "
+                   f"only {n=} observations were given.")
+        raise ValueError(message)
+
+    y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
+    beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
+             ((n-2.0) * (n+5) * (n+7) * (n+9)))
+    W2 = -1 + math.sqrt(2 * (beta2 - 1))
+    delta = 1 / math.sqrt(0.5 * math.log(W2))
+    alpha = math.sqrt(2.0 / (W2 - 1))
+    y = xp.where(y == 0, xp.asarray(1, dtype=y.dtype), y)
+    Z = delta * xp.log(y / alpha + xp.sqrt((y / alpha)**2 + 1))
+
+    pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
+
+    Z = Z[()] if Z.ndim == 0 else Z
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return SkewtestResult(Z, pvalue)
+
+
+KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(KurtosistestResult, n_samples=1, too_small=4)
+def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
+    r"""Test whether a dataset has normal kurtosis.
+
+    This function tests the null hypothesis that the kurtosis
+    of the population from which the sample was drawn is that
+    of the normal distribution.
+
+    Parameters
+    ----------
+    a : array
+        Array of the sample data. Must contain at least five observations.
+    axis : int or None, optional
+       Axis along which to compute test. Default is 0. If None,
+       compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the kurtosis of the distribution underlying the sample
+          is different from that of the normal distribution
+        * 'less': the kurtosis of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the kurtosis of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The computed z-score for this test.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_kurtosistest` : Extended example
+
+    Notes
+    -----
+    Valid only for n>20. This function uses the method described in [1]_.
+
+    References
+    ----------
+    .. [1] F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
+       statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.stats import kurtosistest
+    >>> kurtosistest(list(range(20)))
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
+    >>> kurtosistest(list(range(20)), alternative='less')
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174)
+    >>> kurtosistest(list(range(20)), alternative='greater')
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583)
+    >>> rng = np.random.default_rng()
+    >>> s = rng.normal(0, 1, 1000)
+    >>> kurtosistest(s)
+    KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987)
+
+    For a more detailed example, see :ref:`hypothesis_kurtosistest`.
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+
+    if n < 5:
+        message = ("`kurtosistest` requires at least 5 observations; "
+                   f"only {n=} observations were given.")
+        raise ValueError(message)
+    if n < 20:
+        message = ("`kurtosistest` p-value may be inaccurate with fewer than 20 "
+                   f"observations; only {n=} observations were given.")
+        warnings.warn(message, stacklevel=2)
+    b2 = kurtosis(a, axis, fisher=False, _no_deco=True)
+
+    E = 3.0*(n-1) / (n+1)
+    varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5))  # [1]_ Eq. 1
+    x = (b2-E) / varb2**0.5  # [1]_ Eq. 4
+    # [1]_ Eq. 2:
+    sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * ((6.0*(n+3)*(n+5))
+                                                 / (n*(n-2)*(n-3)))**0.5
+    # [1]_ Eq. 3:
+    A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + (1+4.0/(sqrtbeta1**2))**0.5)
+    term1 = 1 - 2/(9.0*A)
+    denom = 1 + x * (2/(A-4.0))**0.5
+    NaN = _get_nan(x, xp=xp)
+    term2 = xp_sign(denom) * xp.where(denom == 0.0, NaN,
+                                      ((1-2.0/A)/xp.abs(denom))**(1/3))
+    if xp.any(denom == 0):
+        msg = ("Test statistic not defined in some cases due to division by "
+               "zero. Return nan in that case...")
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+
+    Z = (term1 - term2) / (2/(9.0*A))**0.5  # [1]_ Eq. 5
+
+    pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
+
+    Z = Z[()] if Z.ndim == 0 else Z
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return KurtosistestResult(Z, pvalue)
+
+
+NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(NormaltestResult, n_samples=1, too_small=7)
+def normaltest(a, axis=0, nan_policy='propagate'):
+    r"""Test whether a sample differs from a normal distribution.
+
+    This function tests the null hypothesis that a sample comes
+    from a normal distribution.  It is based on D'Agostino and
+    Pearson's [1]_, [2]_ test that combines skew and kurtosis to
+    produce an omnibus test of normality.
+
+    Parameters
+    ----------
+    a : array_like
+        The array containing the sample to be tested. Must contain
+        at least eight observations.
+    axis : int or None, optional
+        Axis along which to compute test. Default is 0. If None,
+        compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+            * 'propagate': returns nan
+            * 'raise': throws an error
+            * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float or array
+        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
+        ``k`` is the z-score returned by `kurtosistest`.
+    pvalue : float or array
+        A 2-sided chi squared probability for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_normaltest` : Extended example
+
+    References
+    ----------
+    .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
+            moderate and large sample size", Biometrika, 58, 341-348
+    .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
+            normality", Biometrika, 60, 613-622
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> pts = 1000
+    >>> a = rng.normal(0, 1, size=pts)
+    >>> b = rng.normal(2, 1, size=pts)
+    >>> x = np.concatenate((a, b))
+    >>> res = stats.normaltest(x)
+    >>> res.statistic
+    53.619...  # random
+    >>> res.pvalue
+    2.273917413209226e-12  # random
+
+    For a more detailed example, see :ref:`hypothesis_normaltest`.
+    """
+    xp = array_namespace(a)
+
+    s, _ = skewtest(a, axis, _no_deco=True)
+    k, _ = kurtosistest(a, axis, _no_deco=True)
+    statistic = s*s + k*k
+
+    chi2 = _SimpleChi2(xp.asarray(2.))
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    statistic = statistic[()] if statistic.ndim == 0 else statistic
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return NormaltestResult(statistic, pvalue)
+
+
+@_axis_nan_policy_factory(SignificanceResult, default_axis=None)
+def jarque_bera(x, *, axis=None):
+    r"""Perform the Jarque-Bera goodness of fit test on sample data.
+
+    The Jarque-Bera test tests whether the sample data has the skewness and
+    kurtosis matching a normal distribution.
+
+    Note that this test only works for a large enough number of data samples
+    (>2000) as the test statistic asymptotically has a Chi-squared distribution
+    with 2 degrees of freedom.
+
+    Parameters
+    ----------
+    x : array_like
+        Observations of a random variable.
+    axis : int or None, default: 0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear in
+        a corresponding element of the output.
+        If ``None``, the input will be raveled before computing the statistic.
+
+    Returns
+    -------
+    result : SignificanceResult
+        An object with the following attributes:
+
+        statistic : float
+            The test statistic.
+        pvalue : float
+            The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_jarque_bera` : Extended example
+
+    References
+    ----------
+    .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
+           homoscedasticity and serial independence of regression residuals",
+           6 Econometric Letters 255-259.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = rng.normal(0, 1, 100000)
+    >>> jarque_bera_test = stats.jarque_bera(x)
+    >>> jarque_bera_test
+    Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775)
+    >>> jarque_bera_test.statistic
+    3.3415184718131554
+    >>> jarque_bera_test.pvalue
+    0.18810419594996775
+
+    For a more detailed example, see :ref:`hypothesis_jarque_bera`.
+    """
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    if axis is None:
+        x = xp.reshape(x, (-1,))
+        axis = 0
+
+    n = x.shape[axis]
+    if n == 0:
+        raise ValueError('At least one observation is required.')
+
+    mu = xp.mean(x, axis=axis, keepdims=True)
+    diffx = x - mu
+    s = skew(diffx, axis=axis, _no_deco=True)
+    k = kurtosis(diffx, axis=axis, _no_deco=True)
+    statistic = n / 6 * (s**2 + k**2 / 4)
+
+    chi2 = _SimpleChi2(xp.asarray(2.))
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    statistic = statistic[()] if statistic.ndim == 0 else statistic
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return SignificanceResult(statistic, pvalue)
+
+
+#####################################
+#        FREQUENCY FUNCTIONS        #
+#####################################
+
+
+def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
+                      axis=None):
+    """Calculate the score at a given percentile of the input sequence.
+
+    For example, the score at ``per=50`` is the median. If the desired quantile
+    lies between two data points, we interpolate between them, according to
+    the value of `interpolation`. If the parameter `limit` is provided, it
+    should be a tuple (lower, upper) of two values.
+
+    Parameters
+    ----------
+    a : array_like
+        A 1-D array of values from which to extract score.
+    per : array_like
+        Percentile(s) at which to extract score.  Values should be in range
+        [0,100].
+    limit : tuple, optional
+        Tuple of two scalars, the lower and upper limits within which to
+        compute the percentile. Values of `a` outside
+        this (closed) interval will be ignored.
+    interpolation_method : {'fraction', 'lower', 'higher'}, optional
+        Specifies the interpolation method to use,
+        when the desired quantile lies between two data points `i` and `j`
+        The following options are available (default is 'fraction'):
+
+          * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
+            fractional part of the index surrounded by ``i`` and ``j``
+          * 'lower': ``i``
+          * 'higher': ``j``
+
+    axis : int, optional
+        Axis along which the percentiles are computed. Default is None. If
+        None, compute over the whole array `a`.
+
+    Returns
+    -------
+    score : float or ndarray
+        Score at percentile(s).
+
+    See Also
+    --------
+    percentileofscore, numpy.percentile
+
+    Notes
+    -----
+    This function will become obsolete in the future.
+    For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
+    that `scoreatpercentile` provides.  And it's significantly faster.
+    Therefore it's recommended to use `numpy.percentile` for users that have
+    numpy >= 1.9.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(100)
+    >>> stats.scoreatpercentile(a, 50)
+    49.5
+
+    """
+    # adapted from NumPy's percentile function.  When we require numpy >= 1.8,
+    # the implementation of this function can be replaced by np.percentile.
+    a = np.asarray(a)
+    if a.size == 0:
+        # empty array, return nan(s) with shape matching `per`
+        if np.isscalar(per):
+            return np.nan
+        else:
+            return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
+
+    if limit:
+        a = a[(limit[0] <= a) & (a <= limit[1])]
+
+    sorted_ = np.sort(a, axis=axis)
+    if axis is None:
+        axis = 0
+
+    return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
+
+
+# handle sequence of per's without calling sort multiple times
+def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
+    if not np.isscalar(per):
+        score = [_compute_qth_percentile(sorted_, i,
+                                         interpolation_method, axis)
+                 for i in per]
+        return np.array(score)
+
+    if not (0 <= per <= 100):
+        raise ValueError("percentile must be in the range [0, 100]")
+
+    indexer = [slice(None)] * sorted_.ndim
+    idx = per / 100. * (sorted_.shape[axis] - 1)
+
+    if int(idx) != idx:
+        # round fractional indices according to interpolation method
+        if interpolation_method == 'lower':
+            idx = int(np.floor(idx))
+        elif interpolation_method == 'higher':
+            idx = int(np.ceil(idx))
+        elif interpolation_method == 'fraction':
+            pass  # keep idx as fraction and interpolate
+        else:
+            raise ValueError("interpolation_method can only be 'fraction', "
+                             "'lower' or 'higher'")
+
+    i = int(idx)
+    if i == idx:
+        indexer[axis] = slice(i, i + 1)
+        weights = array(1)
+        sumval = 1.0
+    else:
+        indexer[axis] = slice(i, i + 2)
+        j = i + 1
+        weights = array([(j - idx), (idx - i)], float)
+        wshape = [1] * sorted_.ndim
+        wshape[axis] = 2
+        weights.shape = wshape
+        sumval = weights.sum()
+
+    # Use np.add.reduce (== np.sum but a little faster) to coerce data type
+    return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
+
+
+def percentileofscore(a, score, kind='rank', nan_policy='propagate'):
+    """Compute the percentile rank of a score relative to a list of scores.
+
+    A `percentileofscore` of, for example, 80% means that 80% of the
+    scores in `a` are below the given score. In the case of gaps or
+    ties, the exact definition depends on the optional keyword, `kind`.
+
+    Parameters
+    ----------
+    a : array_like
+        A 1-D array to which `score` is compared.
+    score : array_like
+        Scores to compute percentiles for.
+    kind : {'rank', 'weak', 'strict', 'mean'}, optional
+        Specifies the interpretation of the resulting score.
+        The following options are available (default is 'rank'):
+
+          * 'rank': Average percentage ranking of score.  In case of multiple
+            matches, average the percentage rankings of all matching scores.
+          * 'weak': This kind corresponds to the definition of a cumulative
+            distribution function.  A percentileofscore of 80% means that 80%
+            of values are less than or equal to the provided score.
+          * 'strict': Similar to "weak", except that only values that are
+            strictly less than the given score are counted.
+          * 'mean': The average of the "weak" and "strict" scores, often used
+            in testing.  See https://en.wikipedia.org/wiki/Percentile_rank
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Specifies how to treat `nan` values in `a`.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan (for each value in `score`).
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    pcos : float
+        Percentile-position of score (0-100) relative to `a`.
+
+    See Also
+    --------
+    numpy.percentile
+    scipy.stats.scoreatpercentile, scipy.stats.rankdata
+
+    Examples
+    --------
+    Three-quarters of the given values lie below a given score:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> stats.percentileofscore([1, 2, 3, 4], 3)
+    75.0
+
+    With multiple matches, note how the scores of the two matches, 0.6
+    and 0.8 respectively, are averaged:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
+    70.0
+
+    Only 2/5 values are strictly less than 3:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
+    40.0
+
+    But 4/5 values are less than or equal to 3:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
+    80.0
+
+    The average between the weak and the strict scores is:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
+    60.0
+
+    Score arrays (of any dimensionality) are supported:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3])
+    array([40., 70.])
+
+    The inputs can be infinite:
+
+    >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf])
+    array([75., 75., 100.])
+
+    If `a` is empty, then the resulting percentiles are all `nan`:
+
+    >>> stats.percentileofscore([], [1, 2])
+    array([nan, nan])
+    """
+
+    a = np.asarray(a)
+    n = len(a)
+    score = np.asarray(score)
+
+    # Nan treatment
+    cna, npa = _contains_nan(a, nan_policy)
+    cns, nps = _contains_nan(score, nan_policy)
+
+    if (cna or cns) and nan_policy == 'raise':
+        raise ValueError("The input contains nan values")
+
+    if cns:
+        # If a score is nan, then the output should be nan
+        # (also if nan_policy is "omit", because it only applies to `a`)
+        score = ma.masked_where(np.isnan(score), score)
+
+    if cna:
+        if nan_policy == "omit":
+            # Don't count nans
+            a = ma.masked_where(np.isnan(a), a)
+            n = a.count()
+
+        if nan_policy == "propagate":
+            # All outputs should be nans
+            n = 0
+
+    # Cannot compare to empty list ==> nan
+    if n == 0:
+        perct = np.full_like(score, np.nan, dtype=np.float64)
+
+    else:
+        # Prepare broadcasting
+        score = score[..., None]
+
+        def count(x):
+            return np.count_nonzero(x, -1)
+
+        # Main computations/logic
+        if kind == 'rank':
+            left = count(a < score)
+            right = count(a <= score)
+            plus1 = left < right
+            perct = (left + right + plus1) * (50.0 / n)
+        elif kind == 'strict':
+            perct = count(a < score) * (100.0 / n)
+        elif kind == 'weak':
+            perct = count(a <= score) * (100.0 / n)
+        elif kind == 'mean':
+            left = count(a < score)
+            right = count(a <= score)
+            perct = (left + right) * (50.0 / n)
+        else:
+            raise ValueError(
+                "kind can only be 'rank', 'strict', 'weak' or 'mean'")
+
+    # Re-insert nan values
+    perct = ma.filled(perct, np.nan)
+
+    if perct.ndim == 0:
+        return perct[()]
+    return perct
+
+
+HistogramResult = namedtuple('HistogramResult',
+                             ('count', 'lowerlimit', 'binsize', 'extrapoints'))
+
+
+def _histogram(a, numbins=10, defaultlimits=None, weights=None,
+               printextras=False):
+    """Create a histogram.
+
+    Separate the range into several bins and return the number of instances
+    in each bin.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of scores which will be put into bins.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultlimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+    printextras : bool, optional
+        If True, if there are extra points (i.e. the points that fall outside
+        the bin limits) a warning is raised saying how many of those points
+        there are.  Default is False.
+
+    Returns
+    -------
+    count : ndarray
+        Number of points (or sum of weights) in each bin.
+    lowerlimit : float
+        Lowest value of histogram, the lower limit of the first bin.
+    binsize : float
+        The size of the bins (all bins have the same size).
+    extrapoints : int
+        The number of points outside the range of the histogram.
+
+    See Also
+    --------
+    numpy.histogram
+
+    Notes
+    -----
+    This histogram is based on numpy's histogram but has a larger range by
+    default if default limits is not set.
+
+    """
+    a = np.ravel(a)
+    if defaultlimits is None:
+        if a.size == 0:
+            # handle empty arrays. Undetermined range, so use 0-1.
+            defaultlimits = (0, 1)
+        else:
+            # no range given, so use values in `a`
+            data_min = a.min()
+            data_max = a.max()
+            # Have bins extend past min and max values slightly
+            s = (data_max - data_min) / (2. * (numbins - 1.))
+            defaultlimits = (data_min - s, data_max + s)
+
+    # use numpy's histogram method to compute bins
+    hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
+                                   weights=weights)
+    # hist are not always floats, convert to keep with old output
+    hist = np.array(hist, dtype=float)
+    # fixed width for bins is assumed, as numpy's histogram gives
+    # fixed width bins for int values for 'bins'
+    binsize = bin_edges[1] - bin_edges[0]
+    # calculate number of extra points
+    extrapoints = len([v for v in a
+                       if defaultlimits[0] > v or v > defaultlimits[1]])
+    if extrapoints > 0 and printextras:
+        warnings.warn(f"Points outside given histogram range = {extrapoints}",
+                      stacklevel=3,)
+
+    return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
+
+
+CumfreqResult = namedtuple('CumfreqResult',
+                           ('cumcount', 'lowerlimit', 'binsize',
+                            'extrapoints'))
+
+
+def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
+    """Return a cumulative frequency histogram, using the histogram function.
+
+    A cumulative histogram is a mapping that counts the cumulative number of
+    observations in all of the bins up to the specified bin.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultreallimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+
+    Returns
+    -------
+    cumcount : ndarray
+        Binned values of cumulative frequency.
+    lowerlimit : float
+        Lower real limit
+    binsize : float
+        Width of each bin.
+    extrapoints : int
+        Extra points.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = [1, 4, 2, 1, 3, 1]
+    >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
+    >>> res.cumcount
+    array([ 1.,  2.,  3.,  3.])
+    >>> res.extrapoints
+    3
+
+    Create a normal distribution with 1000 random values
+
+    >>> samples = stats.norm.rvs(size=1000, random_state=rng)
+
+    Calculate cumulative frequencies
+
+    >>> res = stats.cumfreq(samples, numbins=25)
+
+    Calculate space of values for x
+
+    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
+    ...                                  res.cumcount.size)
+
+    Plot histogram and cumulative histogram
+
+    >>> fig = plt.figure(figsize=(10, 4))
+    >>> ax1 = fig.add_subplot(1, 2, 1)
+    >>> ax2 = fig.add_subplot(1, 2, 2)
+    >>> ax1.hist(samples, bins=25)
+    >>> ax1.set_title('Histogram')
+    >>> ax2.bar(x, res.cumcount, width=res.binsize)
+    >>> ax2.set_title('Cumulative histogram')
+    >>> ax2.set_xlim([x.min(), x.max()])
+
+    >>> plt.show()
+
+    """
+    h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
+    cumhist = np.cumsum(h * 1, axis=0)
+    return CumfreqResult(cumhist, l, b, e)
+
+
+RelfreqResult = namedtuple('RelfreqResult',
+                           ('frequency', 'lowerlimit', 'binsize',
+                            'extrapoints'))
+
+
+def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
+    """Return a relative frequency histogram, using the histogram function.
+
+    A relative frequency  histogram is a mapping of the number of
+    observations in each of the bins relative to the total of observations.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultreallimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+
+    Returns
+    -------
+    frequency : ndarray
+        Binned values of relative frequency.
+    lowerlimit : float
+        Lower real limit.
+    binsize : float
+        Width of each bin.
+    extrapoints : int
+        Extra points.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> a = np.array([2, 4, 1, 2, 3, 2])
+    >>> res = stats.relfreq(a, numbins=4)
+    >>> res.frequency
+    array([ 0.16666667, 0.5       , 0.16666667,  0.16666667])
+    >>> np.sum(res.frequency)  # relative frequencies should add up to 1
+    1.0
+
+    Create a normal distribution with 1000 random values
+
+    >>> samples = stats.norm.rvs(size=1000, random_state=rng)
+
+    Calculate relative frequencies
+
+    >>> res = stats.relfreq(samples, numbins=25)
+
+    Calculate space of values for x
+
+    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
+    ...                                  res.frequency.size)
+
+    Plot relative frequency histogram
+
+    >>> fig = plt.figure(figsize=(5, 4))
+    >>> ax = fig.add_subplot(1, 1, 1)
+    >>> ax.bar(x, res.frequency, width=res.binsize)
+    >>> ax.set_title('Relative frequency histogram')
+    >>> ax.set_xlim([x.min(), x.max()])
+
+    >>> plt.show()
+
+    """
+    a = np.asanyarray(a)
+    h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
+    h = h / a.shape[0]
+
+    return RelfreqResult(h, l, b, e)
+
+
+#####################################
+#        VARIABILITY FUNCTIONS      #
+#####################################
+
+def obrientransform(*samples):
+    """Compute the O'Brien transform on input data (any number of arrays).
+
+    Used to test for homogeneity of variance prior to running one-way stats.
+    Each array in ``*samples`` is one level of a factor.
+    If `f_oneway` is run on the transformed data and found significant,
+    the variances are unequal.  From Maxwell and Delaney [1]_, p.112.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        Any number of arrays.
+
+    Returns
+    -------
+    obrientransform : ndarray
+        Transformed data for use in an ANOVA.  The first dimension
+        of the result corresponds to the sequence of transformed
+        arrays.  If the arrays given are all 1-D of the same length,
+        the return value is a 2-D array; otherwise it is a 1-D array
+        of type object, with each element being an ndarray.
+
+    Raises
+    ------
+    ValueError
+        If the mean of the transformed data is not equal to the original
+        variance, indicating a lack of convergence in the O'Brien transform.
+
+    References
+    ----------
+    .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
+           Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
+
+    Examples
+    --------
+    We'll test the following data sets for differences in their variance.
+
+    >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
+    >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
+
+    Apply the O'Brien transform to the data.
+
+    >>> from scipy.stats import obrientransform
+    >>> tx, ty = obrientransform(x, y)
+
+    Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
+    transformed data.
+
+    >>> from scipy.stats import f_oneway
+    >>> F, p = f_oneway(tx, ty)
+    >>> p
+    0.1314139477040335
+
+    If we require that ``p < 0.05`` for significance, we cannot conclude
+    that the variances are different.
+
+    """
+    TINY = np.sqrt(np.finfo(float).eps)
+
+    # `arrays` will hold the transformed arguments.
+    arrays = []
+    sLast = None
+
+    for sample in samples:
+        a = np.asarray(sample)
+        n = len(a)
+        mu = np.mean(a)
+        sq = (a - mu)**2
+        sumsq = sq.sum()
+
+        # The O'Brien transform.
+        t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
+
+        # Check that the mean of the transformed data is equal to the
+        # original variance.
+        var = sumsq / (n - 1)
+        if abs(var - np.mean(t)) > TINY:
+            raise ValueError('Lack of convergence in obrientransform.')
+
+        arrays.append(t)
+        sLast = a.shape
+
+    if sLast:
+        for arr in arrays[:-1]:
+            if sLast != arr.shape:
+                return np.array(arrays, dtype=object)
+    return np.array(arrays)
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, too_small=1
+)
+def sem(a, axis=0, ddof=1, nan_policy='propagate'):
+    """Compute standard error of the mean.
+
+    Calculate the standard error of the mean (or standard error of
+    measurement) of the values in the input array.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing the values for which the standard error is
+        returned. Must contain at least two observations.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Delta degrees-of-freedom. How many degrees of freedom to adjust
+        for bias in limited samples relative to the population estimate
+        of variance. Defaults to 1.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    s : ndarray or float
+        The standard error of the mean in the sample(s), along the input axis.
+
+    Notes
+    -----
+    The default value for `ddof` is different to the default (0) used by other
+    ddof containing routines, such as np.std and np.nanstd.
+
+    Examples
+    --------
+    Find standard error along the first axis:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(20).reshape(5,4)
+    >>> stats.sem(a)
+    array([ 2.8284,  2.8284,  2.8284,  2.8284])
+
+    Find standard error across the whole array, using n degrees of freedom:
+
+    >>> stats.sem(a, axis=None, ddof=0)
+    1.2893796958227628
+
+    """
+    xp = array_namespace(a)
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        axis = 0
+    a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+    n = a.shape[axis]
+    s = xp.std(a, axis=axis, correction=ddof) / n**0.5
+    return s
+
+
+def _isconst(x):
+    """
+    Check if all values in x are the same.  nans are ignored.
+
+    x must be a 1d array.
+
+    The return value is a 1d array with length 1, so it can be used
+    in np.apply_along_axis.
+    """
+    y = x[~np.isnan(x)]
+    if y.size == 0:
+        return np.array([True])
+    else:
+        return (y[0] == y).all(keepdims=True)
+
+
+def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Compute the z score.
+
+    Compute the z score of each value in the sample, relative to the
+    sample mean and standard deviation.
+
+    Parameters
+    ----------
+    a : array_like
+        An array like object containing the sample data.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.  Note that when the value is 'omit',
+        nans in the input also propagate to the output, but they do not affect
+        the z-scores computed for the non-nan values.
+
+    Returns
+    -------
+    zscore : array_like
+        The z-scores, standardized by mean and standard deviation of
+        input array `a`.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.std : Arithmetic standard deviation
+    scipy.stats.gzscore : Geometric standard score
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses `asanyarray` instead of
+    `asarray` for parameters).
+
+    References
+    ----------
+    .. [1] "Standard score", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Standard_score.
+    .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions
+           about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([ 0.7972,  0.0767,  0.4383,  0.7866,  0.8091,
+    ...                0.1954,  0.6307,  0.6599,  0.1065,  0.0508])
+    >>> from scipy import stats
+    >>> stats.zscore(a)
+    array([ 1.1273, -1.247 , -0.0552,  1.0923,  1.1664, -0.8559,  0.5786,
+            0.6748, -1.1488, -1.3324])
+
+    Computing along a specified axis, using n-1 degrees of freedom
+    (``ddof=1``) to calculate the standard deviation:
+
+    >>> b = np.array([[ 0.3148,  0.0478,  0.6243,  0.4608],
+    ...               [ 0.7149,  0.0775,  0.6072,  0.9656],
+    ...               [ 0.6341,  0.1403,  0.9759,  0.4064],
+    ...               [ 0.5918,  0.6948,  0.904 ,  0.3721],
+    ...               [ 0.0921,  0.2481,  0.1188,  0.1366]])
+    >>> stats.zscore(b, axis=1, ddof=1)
+    array([[-0.19264823, -1.28415119,  1.07259584,  0.40420358],
+           [ 0.33048416, -1.37380874,  0.04251374,  1.00081084],
+           [ 0.26796377, -1.12598418,  1.23283094, -0.37481053],
+           [-0.22095197,  0.24468594,  1.19042819, -1.21416216],
+           [-0.82780366,  1.4457416 , -0.43867764, -0.1792603 ]])
+
+    An example with ``nan_policy='omit'``:
+
+    >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
+    ...               [14.95, 16.06, 121.25, 94.35, 29.81]])
+    >>> stats.zscore(x, axis=1, nan_policy='omit')
+    array([[-1.13490897, -0.37830299,         nan, -0.08718406,  1.60039602],
+           [-0.91611681, -0.89090508,  1.4983032 ,  0.88731639, -0.5785977 ]])
+    """
+    return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
+
+
+def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Compute the geometric standard score.
+
+    Compute the geometric z score of each strictly positive value in the
+    sample, relative to the geometric mean and standard deviation.
+    Mathematically the geometric z score can be evaluated as::
+
+        gzscore = log(a/gmu) / log(gsigma)
+
+    where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard
+    deviation).
+
+    Parameters
+    ----------
+    a : array_like
+        Sample data.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.  Note that when the value is 'omit',
+        nans in the input also propagate to the output, but they do not affect
+        the geometric z scores computed for the non-nan values.
+
+    Returns
+    -------
+    gzscore : array_like
+        The geometric z scores, standardized by geometric mean and geometric
+        standard deviation of input array `a`.
+
+    See Also
+    --------
+    gmean : Geometric mean
+    gstd : Geometric standard deviation
+    zscore : Standard score
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses ``asanyarray`` instead of
+    ``asarray`` for parameters).
+
+    .. versionadded:: 1.8
+
+    References
+    ----------
+    .. [1] "Geometric standard score", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score.
+
+    Examples
+    --------
+    Draw samples from a log-normal distribution:
+
+    >>> import numpy as np
+    >>> from scipy.stats import zscore, gzscore
+    >>> import matplotlib.pyplot as plt
+
+    >>> rng = np.random.default_rng()
+    >>> mu, sigma = 3., 1.  # mean and standard deviation
+    >>> x = rng.lognormal(mu, sigma, size=500)
+
+    Display the histogram of the samples:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(x, 50)
+    >>> plt.show()
+
+    Display the histogram of the samples standardized by the classical zscore.
+    Distribution is rescaled but its shape is unchanged.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(zscore(x), 50)
+    >>> plt.show()
+
+    Demonstrate that the distribution of geometric zscores is rescaled and
+    quasinormal:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(gzscore(x), 50)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(a)
+    a = _convert_common_float(a, xp=xp)
+    log = ma.log if isinstance(a, ma.MaskedArray) else xp.log
+    return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy)
+
+
+def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Calculate the relative z-scores.
+
+    Return an array of z-scores, i.e., scores that are standardized to
+    zero mean and unit variance, where mean and variance are calculated
+    from the comparison array.
+
+    Parameters
+    ----------
+    scores : array_like
+        The input for which z-scores are calculated.
+    compare : array_like
+        The input from which the mean and standard deviation of the
+        normalization are taken; assumed to have the same dimension as
+        `scores`.
+    axis : int or None, optional
+        Axis over which mean and variance of `compare` are calculated.
+        Default is 0. If None, compute over the whole array `scores`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle the occurrence of nans in `compare`.
+        'propagate' returns nan, 'raise' raises an exception, 'omit'
+        performs the calculations ignoring nan values. Default is
+        'propagate'. Note that when the value is 'omit', nans in `scores`
+        also propagate to the output, but they do not affect the z-scores
+        computed for the non-nan values.
+
+    Returns
+    -------
+    zscore : array_like
+        Z-scores, in the same shape as `scores`.
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses `asanyarray` instead of
+    `asarray` for parameters).
+
+    Examples
+    --------
+    >>> from scipy.stats import zmap
+    >>> a = [0.5, 2.0, 2.5, 3]
+    >>> b = [0, 1, 2, 3, 4]
+    >>> zmap(a, b)
+    array([-1.06066017,  0.        ,  0.35355339,  0.70710678])
+
+    """
+    # The docstring explicitly states that it preserves subclasses.
+    # Let's table deprecating that and just get the array API version
+    # working.
+
+    like_zscore = (scores is compare)
+    xp = array_namespace(scores, compare)
+    scores, compare = _convert_common_float(scores, compare, xp=xp)
+
+    with warnings.catch_warnings():
+        if like_zscore:  # zscore should not emit SmallSampleWarning
+            warnings.simplefilter('ignore', SmallSampleWarning)
+
+        mn = _xp_mean(compare, axis=axis, keepdims=True, nan_policy=nan_policy)
+        std = _xp_var(compare, axis=axis, correction=ddof,
+                      keepdims=True, nan_policy=nan_policy)**0.5
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        z = _demean(scores, mn, axis, xp=xp, precision_warning=False) / std
+
+    # If we know that scores and compare are identical, we can infer that
+    # some slices should have NaNs.
+    if like_zscore:
+        eps = xp.finfo(z.dtype).eps
+        zero = std <= xp.abs(eps * mn)
+        zero = xp.broadcast_to(zero, z.shape)
+        z[zero] = xp.nan
+
+    return z
+
+
+def gstd(a, axis=0, ddof=1):
+    r"""
+    Calculate the geometric standard deviation of an array.
+
+    The geometric standard deviation describes the spread of a set of numbers
+    where the geometric mean is preferred. It is a multiplicative factor, and
+    so a dimensionless quantity.
+
+    It is defined as the exponential of the standard deviation of the
+    natural logarithms of the observations.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing finite, strictly positive, real numbers.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    axis : int, tuple or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degree of freedom correction in the calculation of the
+        geometric standard deviation. Default is 1.
+
+    Returns
+    -------
+    gstd : ndarray or float
+        An array of the geometric standard deviation. If `axis` is None or `a`
+        is a 1d array a float is returned.
+
+    See Also
+    --------
+    gmean : Geometric mean
+    numpy.std : Standard deviation
+    gzscore : Geometric standard score
+
+    Notes
+    -----
+    Mathematically, the sample geometric standard deviation :math:`s_G` can be
+    defined in terms of the natural logarithms of the observations
+    :math:`y_i = \log(x_i)`:
+
+    .. math::
+
+        s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2}
+
+    where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof`
+    to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural
+    logarithms of the observations. Note that the default ``ddof=1`` is different from
+    the default value used by similar functions, such as `numpy.std` and `numpy.var`.
+
+    When an observation is infinite, the geometric standard deviation is
+    NaN (undefined). Non-positive observations will also produce NaNs in the
+    output because the *natural* logarithm (as opposed to the *complex*
+    logarithm) is defined and finite only for positive reals.
+    The geometric standard deviation is sometimes confused with the exponential
+    of the standard deviation, ``exp(std(a))``. Instead, the geometric standard
+    deviation is ``exp(std(log(a)))``.
+
+    References
+    ----------
+    .. [1] "Geometric standard deviation", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Geometric_standard_deviation.
+    .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion",
+           Biometrics, vol. 35, pp. 908-909, 1979
+
+    Examples
+    --------
+    Find the geometric standard deviation of a log-normally distributed sample.
+    Note that the standard deviation of the distribution is one; on a
+    log scale this evaluates to approximately ``exp(1)``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import gstd
+    >>> rng = np.random.default_rng()
+    >>> sample = rng.lognormal(mean=0, sigma=1, size=1000)
+    >>> gstd(sample)
+    2.810010162475324
+
+    Compute the geometric standard deviation of a multidimensional array and
+    of a given axis.
+
+    >>> a = np.arange(1, 25).reshape(2, 3, 4)
+    >>> gstd(a, axis=None)
+    2.2944076136018947
+    >>> gstd(a, axis=2)
+    array([[1.82424757, 1.22436866, 1.13183117],
+           [1.09348306, 1.07244798, 1.05914985]])
+    >>> gstd(a, axis=(1,2))
+    array([2.12939215, 1.22120169])
+
+    """
+    a = np.asanyarray(a)
+    if isinstance(a, ma.MaskedArray):
+        message = ("`gstd` support for masked array input was deprecated in "
+                   "SciPy 1.14.0 and will be removed in version 1.16.0.")
+        warnings.warn(message, DeprecationWarning, stacklevel=2)
+        log = ma.log
+    else:
+        log = np.log
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        res = np.exp(np.std(log(a), axis=axis, ddof=ddof))
+
+    if (a <= 0).any():
+        message = ("The geometric standard deviation is only defined if all elements "
+                   "are greater than or equal to zero; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    return res
+
+# Private dictionary initialized only once at module level
+# See https://en.wikipedia.org/wiki/Robust_measures_of_scale
+_scale_conversions = {'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)}
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1,
+    default_axis=None, override={'nan_propagation': False}
+)
+def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
+        interpolation='linear', keepdims=False):
+    r"""
+    Compute the interquartile range of the data along the specified axis.
+
+    The interquartile range (IQR) is the difference between the 75th and
+    25th percentile of the data. It is a measure of the dispersion
+    similar to standard deviation or variance, but is much more robust
+    against outliers [2]_.
+
+    The ``rng`` parameter allows this function to compute other
+    percentile ranges than the actual IQR. For example, setting
+    ``rng=(0, 100)`` is equivalent to `numpy.ptp`.
+
+    The IQR of an empty array is `np.nan`.
+
+    .. versionadded:: 0.18.0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array or object that can be converted to an array.
+    axis : int or sequence of int, optional
+        Axis along which the range is computed. The default is to
+        compute the IQR for the entire array.
+    rng : Two-element sequence containing floats in range of [0,100] optional
+        Percentiles over which to compute the range. Each must be
+        between 0 and 100, inclusive. The default is the true IQR:
+        ``(25, 75)``. The order of the elements is not important.
+    scale : scalar or str or array_like of reals, optional
+        The numerical value of scale will be divided out of the final
+        result. The following string value is also recognized:
+
+          * 'normal' : Scale by
+            :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
+
+        The default is 1.0.
+        Array-like `scale` of real dtype is also allowed, as long
+        as it broadcasts correctly to the output such that
+        ``out / scale`` is a valid operation. The output dimensions
+        depend on the input array, `x`, the `axis` argument, and the
+        `keepdims` flag.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    interpolation : str, optional
+
+        Specifies the interpolation method to use when the percentile
+        boundaries lie between two data points ``i`` and ``j``.
+        The following options are available (default is 'linear'):
+
+          * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the
+            fractional part of the index surrounded by ``i`` and ``j``.
+          * 'lower': ``i``.
+          * 'higher': ``j``.
+          * 'nearest': ``i`` or ``j`` whichever is nearest.
+          * 'midpoint': ``(i + j)/2``.
+
+        For NumPy >= 1.22.0, the additional options provided by the ``method``
+        keyword of `numpy.percentile` are also valid.
+
+    keepdims : bool, optional
+        If this is set to True, the reduced axes are left in the
+        result as dimensions with size one. With this option, the result
+        will broadcast correctly against the original array `x`.
+
+    Returns
+    -------
+    iqr : scalar or ndarray
+        If ``axis=None``, a scalar is returned. If the input contains
+        integers or floats of smaller precision than ``np.float64``, then the
+        output data-type is ``np.float64``. Otherwise, the output data-type is
+        the same as that of the input.
+
+    See Also
+    --------
+    numpy.std, numpy.var
+
+    References
+    ----------
+    .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
+    .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
+    .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import iqr
+    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
+    >>> x
+    array([[10,  7,  4],
+           [ 3,  2,  1]])
+    >>> iqr(x)
+    4.0
+    >>> iqr(x, axis=0)
+    array([ 3.5,  2.5,  1.5])
+    >>> iqr(x, axis=1)
+    array([ 3.,  1.])
+    >>> iqr(x, axis=1, keepdims=True)
+    array([[ 3.],
+           [ 1.]])
+
+    """
+    x = asarray(x)
+
+    # This check prevents percentile from raising an error later. Also, it is
+    # consistent with `np.var` and `np.std`.
+    if not x.size:
+        return _get_nan(x)
+
+    # An error may be raised here, so fail-fast, before doing lengthy
+    # computations, even though `scale` is not used until later
+    if isinstance(scale, str):
+        scale_key = scale.lower()
+        if scale_key not in _scale_conversions:
+            raise ValueError(f"{scale} not a valid scale for `iqr`")
+        scale = _scale_conversions[scale_key]
+
+    # Select the percentile function to use based on nans and policy
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    if contains_nan and nan_policy == 'omit':
+        percentile_func = np.nanpercentile
+    else:
+        percentile_func = np.percentile
+
+    if len(rng) != 2:
+        raise TypeError("quantile range must be two element sequence")
+
+    if np.isnan(rng).any():
+        raise ValueError("range must not contain NaNs")
+
+    rng = sorted(rng)
+    pct = percentile_func(x, rng, axis=axis, method=interpolation,
+                          keepdims=keepdims)
+    out = np.subtract(pct[1], pct[0])
+
+    if scale != 1.0:
+        out /= scale
+
+    return out
+
+
+def _mad_1d(x, center, nan_policy):
+    # Median absolute deviation for 1-d array x.
+    # This is a helper function for `median_abs_deviation`; it assumes its
+    # arguments have been validated already.  In particular,  x must be a
+    # 1-d numpy array, center must be callable, and if nan_policy is not
+    # 'propagate', it is assumed to be 'omit', because 'raise' is handled
+    # in `median_abs_deviation`.
+    # No warning is generated if x is empty or all nan.
+    isnan = np.isnan(x)
+    if isnan.any():
+        if nan_policy == 'propagate':
+            return np.nan
+        x = x[~isnan]
+    if x.size == 0:
+        # MAD of an empty array is nan.
+        return np.nan
+    # Edge cases have been handled, so do the basic MAD calculation.
+    med = center(x)
+    mad = np.median(np.abs(x - med))
+    return mad
+
+
+def median_abs_deviation(x, axis=0, center=np.median, scale=1.0,
+                         nan_policy='propagate'):
+    r"""
+    Compute the median absolute deviation of the data along the given axis.
+
+    The median absolute deviation (MAD, [1]_) computes the median over the
+    absolute deviations from the median. It is a measure of dispersion
+    similar to the standard deviation but more robust to outliers [2]_.
+
+    The MAD of an empty array is ``np.nan``.
+
+    .. versionadded:: 1.5.0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the range is computed. Default is 0. If None, compute
+        the MAD over the entire array.
+    center : callable, optional
+        A function that will return the central value. The default is to use
+        np.median. Any user defined function used will need to have the
+        function signature ``func(arr, axis)``.
+    scale : scalar or str, optional
+        The numerical value of scale will be divided out of the final
+        result. The default is 1.0. The string "normal" is also accepted,
+        and results in `scale` being the inverse of the standard normal
+        quantile function at 0.75, which is approximately 0.67449.
+        Array-like scale is also allowed, as long as it broadcasts correctly
+        to the output such that ``out / scale`` is a valid operation. The
+        output dimensions depend on the input array, `x`, and the `axis`
+        argument.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    mad : scalar or ndarray
+        If ``axis=None``, a scalar is returned. If the input contains
+        integers or floats of smaller precision than ``np.float64``, then the
+        output data-type is ``np.float64``. Otherwise, the output data-type is
+        the same as that of the input.
+
+    See Also
+    --------
+    numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
+    scipy.stats.tstd, scipy.stats.tvar
+
+    Notes
+    -----
+    The `center` argument only affects the calculation of the central value
+    around which the MAD is calculated. That is, passing in ``center=np.mean``
+    will calculate the MAD around the mean - it will not calculate the *mean*
+    absolute deviation.
+
+    The input array may contain `inf`, but if `center` returns `inf`, the
+    corresponding MAD for that data will be `nan`.
+
+    References
+    ----------
+    .. [1] "Median absolute deviation",
+           https://en.wikipedia.org/wiki/Median_absolute_deviation
+    .. [2] "Robust measures of scale",
+           https://en.wikipedia.org/wiki/Robust_measures_of_scale
+
+    Examples
+    --------
+    When comparing the behavior of `median_abs_deviation` with ``np.std``,
+    the latter is affected when we change a single value of an array to have an
+    outlier value while the MAD hardly changes:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
+    >>> x.std()
+    0.9973906394005013
+    >>> stats.median_abs_deviation(x)
+    0.82832610097857
+    >>> x[0] = 345.6
+    >>> x.std()
+    34.42304872314415
+    >>> stats.median_abs_deviation(x)
+    0.8323442311590675
+
+    Axis handling example:
+
+    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
+    >>> x
+    array([[10,  7,  4],
+           [ 3,  2,  1]])
+    >>> stats.median_abs_deviation(x)
+    array([3.5, 2.5, 1.5])
+    >>> stats.median_abs_deviation(x, axis=None)
+    2.0
+
+    Scale normal example:
+
+    >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
+    >>> stats.median_abs_deviation(x)
+    1.3487398527041636
+    >>> stats.median_abs_deviation(x, scale='normal')
+    1.9996446978061115
+
+    """
+    if not callable(center):
+        raise TypeError("The argument 'center' must be callable. The given "
+                        f"value {repr(center)} is not callable.")
+
+    # An error may be raised here, so fail-fast, before doing lengthy
+    # computations, even though `scale` is not used until later
+    if isinstance(scale, str):
+        if scale.lower() == 'normal':
+            scale = 0.6744897501960817  # special.ndtri(0.75)
+        else:
+            raise ValueError(f"{scale} is not a valid scale value.")
+
+    x = asarray(x)
+
+    # Consistent with `np.var` and `np.std`.
+    if not x.size:
+        if axis is None:
+            return np.nan
+        nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis)
+        if nan_shape == ():
+            # Return nan, not array(nan)
+            return np.nan
+        return np.full(nan_shape, np.nan)
+
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    if contains_nan:
+        if axis is None:
+            mad = _mad_1d(x.ravel(), center, nan_policy)
+        else:
+            mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy)
+    else:
+        if axis is None:
+            med = center(x, axis=None)
+            mad = np.median(np.abs(x - med))
+        else:
+            # Wrap the call to center() in expand_dims() so it acts like
+            # keepdims=True was used.
+            med = np.expand_dims(center(x, axis=axis), axis)
+            mad = np.median(np.abs(x - med), axis=axis)
+
+    return mad / scale
+
+
+#####################################
+#         TRIMMING FUNCTIONS        #
+#####################################
+
+
+SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
+
+
+def sigmaclip(a, low=4., high=4.):
+    """Perform iterative sigma-clipping of array elements.
+
+    Starting from the full sample, all elements outside the critical range are
+    removed, i.e. all elements of the input array `c` that satisfy either of
+    the following conditions::
+
+        c < mean(c) - std(c)*low
+        c > mean(c) + std(c)*high
+
+    The iteration continues with the updated sample until no
+    elements are outside the (updated) range.
+
+    Parameters
+    ----------
+    a : array_like
+        Data array, will be raveled if not 1-D.
+    low : float, optional
+        Lower bound factor of sigma clipping. Default is 4.
+    high : float, optional
+        Upper bound factor of sigma clipping. Default is 4.
+
+    Returns
+    -------
+    clipped : ndarray
+        Input array with clipped elements removed.
+    lower : float
+        Lower threshold value use for clipping.
+    upper : float
+        Upper threshold value use for clipping.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import sigmaclip
+    >>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
+    ...                     np.linspace(0, 20, 5)))
+    >>> fact = 1.5
+    >>> c, low, upp = sigmaclip(a, fact, fact)
+    >>> c
+    array([  9.96666667,  10.        ,  10.03333333,  10.        ])
+    >>> c.var(), c.std()
+    (0.00055555555555555165, 0.023570226039551501)
+    >>> low, c.mean() - fact*c.std(), c.min()
+    (9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
+    >>> upp, c.mean() + fact*c.std(), c.max()
+    (10.035355339059327, 10.035355339059327, 10.033333333333333)
+
+    >>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
+    ...                     np.linspace(-100, -50, 3)))
+    >>> c, low, upp = sigmaclip(a, 1.8, 1.8)
+    >>> (c == np.linspace(9.5, 10.5, 11)).all()
+    True
+
+    """
+    c = np.asarray(a).ravel()
+    delta = 1
+    while delta:
+        c_std = c.std()
+        c_mean = c.mean()
+        size = c.size
+        critlower = c_mean - c_std * low
+        critupper = c_mean + c_std * high
+        c = c[(c >= critlower) & (c <= critupper)]
+        delta = size - c.size
+
+    return SigmaclipResult(c, critlower, critupper)
+
+
+def trimboth(a, proportiontocut, axis=0):
+    """Slice off a proportion of items from both ends of an array.
+
+    Slice off the passed proportion of items from both ends of the passed
+    array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
+    rightmost 10% of scores). The trimmed values are the lowest and
+    highest ones.
+    Slice off less if proportion results in a non-integer slice index (i.e.
+    conservatively slices off `proportiontocut`).
+
+    Parameters
+    ----------
+    a : array_like
+        Data to trim.
+    proportiontocut : float
+        Proportion (in range 0-1) of total data set to trim of each end.
+    axis : int or None, optional
+        Axis along which to trim data. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    out : ndarray
+        Trimmed version of array `a`. The order of the trimmed content
+        is undefined.
+
+    See Also
+    --------
+    trim_mean
+
+    Examples
+    --------
+    Create an array of 10 values and trim 10% of those values from each end:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+    >>> stats.trimboth(a, 0.1)
+    array([1, 3, 2, 4, 5, 6, 7, 8])
+
+    Note that the elements of the input array are trimmed by value, but the
+    output array is not necessarily sorted.
+
+    The proportion to trim is rounded down to the nearest integer. For
+    instance, trimming 25% of the values from each end of an array of 10
+    values will return an array of 6 values:
+
+    >>> b = np.arange(10)
+    >>> stats.trimboth(b, 1/4).shape
+    (6,)
+
+    Multidimensional arrays can be trimmed along any axis or across the entire
+    array:
+
+    >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
+    >>> d = np.array([a, b, c])
+    >>> stats.trimboth(d, 0.4, axis=0).shape
+    (1, 10)
+    >>> stats.trimboth(d, 0.4, axis=1).shape
+    (3, 2)
+    >>> stats.trimboth(d, 0.4, axis=None).shape
+    (6,)
+
+    """
+    a = np.asarray(a)
+
+    if a.size == 0:
+        return a
+
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+    lowercut = int(proportiontocut * nobs)
+    uppercut = nobs - lowercut
+    if (lowercut >= uppercut):
+        raise ValueError("Proportion too big.")
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return atmp[tuple(sl)]
+
+
+def trim1(a, proportiontocut, tail='right', axis=0):
+    """Slice off a proportion from ONE end of the passed array distribution.
+
+    If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
+    10% of scores. The lowest or highest values are trimmed (depending on
+    the tail).
+    Slice off less if proportion results in a non-integer slice index
+    (i.e. conservatively slices off `proportiontocut` ).
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    proportiontocut : float
+        Fraction to cut off of 'left' or 'right' of distribution.
+    tail : {'left', 'right'}, optional
+        Defaults to 'right'.
+    axis : int or None, optional
+        Axis along which to trim data. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    trim1 : ndarray
+        Trimmed version of array `a`. The order of the trimmed content is
+        undefined.
+
+    Examples
+    --------
+    Create an array of 10 values and trim 20% of its lowest values:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+    >>> stats.trim1(a, 0.2, 'left')
+    array([2, 4, 3, 5, 6, 7, 8, 9])
+
+    Note that the elements of the input array are trimmed by value, but the
+    output array is not necessarily sorted.
+
+    The proportion to trim is rounded down to the nearest integer. For
+    instance, trimming 25% of the values from an array of 10 values will
+    return an array of 8 values:
+
+    >>> b = np.arange(10)
+    >>> stats.trim1(b, 1/4).shape
+    (8,)
+
+    Multidimensional arrays can be trimmed along any axis or across the entire
+    array:
+
+    >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
+    >>> d = np.array([a, b, c])
+    >>> stats.trim1(d, 0.8, axis=0).shape
+    (1, 10)
+    >>> stats.trim1(d, 0.8, axis=1).shape
+    (3, 2)
+    >>> stats.trim1(d, 0.8, axis=None).shape
+    (6,)
+
+    """
+    a = np.asarray(a)
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+
+    # avoid possible corner case
+    if proportiontocut >= 1:
+        return []
+
+    if tail.lower() == 'right':
+        lowercut = 0
+        uppercut = nobs - int(proportiontocut * nobs)
+
+    elif tail.lower() == 'left':
+        lowercut = int(proportiontocut * nobs)
+        uppercut = nobs
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return atmp[tuple(sl)]
+
+
+def trim_mean(a, proportiontocut, axis=0):
+    """Return mean of array after trimming a specified fraction of extreme values
+
+    Removes the specified proportion of elements from *each* end of the
+    sorted array, then computes the mean of the remaining elements.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    proportiontocut : float
+        Fraction of the most positive and most negative elements to remove.
+        When the specified proportion does not result in an integer number of
+        elements, the number of elements to trim is rounded down.
+    axis : int or None, default: 0
+        Axis along which the trimmed means are computed.
+        If None, compute over the raveled array.
+
+    Returns
+    -------
+    trim_mean : ndarray
+        Mean of trimmed array.
+
+    See Also
+    --------
+    trimboth : Remove a proportion of elements from each end of an array.
+    tmean : Compute the mean after trimming values outside specified limits.
+
+    Notes
+    -----
+    For 1-D array `a`, `trim_mean` is approximately equivalent to the following
+    calculation::
+
+        import numpy as np
+        a = np.sort(a)
+        m = int(proportiontocut * len(a))
+        np.mean(a[m: len(a) - m])
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = [1, 2, 3, 5]
+    >>> stats.trim_mean(x, 0.25)
+    2.5
+
+    When the specified proportion does not result in an integer number of
+    elements, the number of elements to trim is rounded down.
+
+    >>> stats.trim_mean(x, 0.24999) == np.mean(x)
+    True
+
+    Use `axis` to specify the axis along which the calculation is performed.
+
+    >>> x2 = [[1, 2, 3, 5],
+    ...       [10, 20, 30, 50]]
+    >>> stats.trim_mean(x2, 0.25)
+    array([ 5.5, 11. , 16.5, 27.5])
+    >>> stats.trim_mean(x2, 0.25, axis=1)
+    array([ 2.5, 25. ])
+
+    """
+    a = np.asarray(a)
+
+    if a.size == 0:
+        return np.nan
+
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+    lowercut = int(proportiontocut * nobs)
+    uppercut = nobs - lowercut
+    if (lowercut > uppercut):
+        raise ValueError("Proportion too big.")
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return np.mean(atmp[tuple(sl)], axis=axis)
+
+
+F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
+
+
+def _create_f_oneway_nan_result(shape, axis, samples):
+    """
+    This is a helper function for f_oneway for creating the return values
+    in certain degenerate conditions.  It creates return values that are
+    all nan with the appropriate shape for the given `shape` and `axis`.
+    """
+    axis = normalize_axis_index(axis, len(shape))
+    shp = shape[:axis] + shape[axis+1:]
+    f = np.full(shp, fill_value=_get_nan(*samples))
+    prob = f.copy()
+    return F_onewayResult(f[()], prob[()])
+
+
+def _first(arr, axis):
+    """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position."""
+    return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis)
+
+
+def _f_oneway_is_too_small(samples, kwargs=None, axis=-1):
+    message = f"At least two samples are required; got {len(samples)}."
+    if len(samples) < 2:
+        raise TypeError(message)
+
+    # Check this after forming alldata, so shape errors are detected
+    # and reported before checking for 0 length inputs.
+    if any(sample.shape[axis] == 0 for sample in samples):
+        return True
+
+    # Must have at least one group with length greater than 1.
+    if all(sample.shape[axis] == 1 for sample in samples):
+        msg = ('all input arrays have length 1.  f_oneway requires that at '
+               'least one input has length greater than 1.')
+        warnings.warn(SmallSampleWarning(msg), stacklevel=2)
+        return True
+
+    return False
+
+
+@_axis_nan_policy_factory(
+    F_onewayResult, n_samples=None, too_small=_f_oneway_is_too_small)
+def f_oneway(*samples, axis=0):
+    """Perform one-way ANOVA.
+
+    The one-way ANOVA tests the null hypothesis that two or more groups have
+    the same population mean.  The test is applied to samples from two or
+    more groups, possibly with differing sizes.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group.  There must be at least
+        two arguments.  If the arrays are multidimensional, then all the
+        dimensions of the array must be the same except for `axis`.
+    axis : int, optional
+        Axis of the input arrays along which the test is applied.
+        Default is 0.
+
+    Returns
+    -------
+    statistic : float
+        The computed F statistic of the test.
+    pvalue : float
+        The associated p-value from the F distribution.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Emitted if all values within each of the input arrays are identical.
+        In this case the F statistic is either infinite or isn't defined,
+        so ``np.inf`` or ``np.nan`` is returned.
+
+    RuntimeWarning
+        Emitted if the length of any input array is 0, or if all the input
+        arrays have length 1.  ``np.nan`` is returned for the F statistic
+        and the p-value in these cases.
+
+    Notes
+    -----
+    The ANOVA test has important assumptions that must be satisfied in order
+    for the associated p-value to be valid.
+
+    1. The samples are independent.
+    2. Each sample is from a normally distributed population.
+    3. The population standard deviations of the groups are all equal.  This
+       property is known as homoscedasticity.
+
+    If these assumptions are not true for a given set of data, it may still
+    be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or
+    the Alexander-Govern test (`scipy.stats.alexandergovern`) although with
+    some loss of power.
+
+    The length of each group must be at least one, and there must be at
+    least one group with length greater than one.  If these conditions
+    are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
+    is returned.
+
+    If all values in each group are identical, and there exist at least two
+    groups with different values, the function generates a warning and
+    returns (``np.inf``, 0).
+
+    If all values in all groups are the same, function generates a warning
+    and returns (``np.nan``, ``np.nan``).
+
+    The algorithm is from Heiman [2]_, pp.394-7.
+
+    References
+    ----------
+    .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
+           Chapter 14, 2014, http://vassarstats.net/textbook/
+
+    .. [2] G.W. Heiman, "Understanding research methods and statistics: An
+           integrated introduction for psychology", Houghton, Mifflin and
+           Company, 2001.
+
+    .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
+           http://www.biostathandbook.com/onewayanova.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import f_oneway
+
+    Here are some data [3]_ on a shell measurement (the length of the anterior
+    adductor muscle scar, standardized by dividing by length) in the mussel
+    Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
+    Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
+    much larger data set used in McDonald et al. (1991).
+
+    >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
+    ...              0.0659, 0.0923, 0.0836]
+    >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
+    ...            0.0725]
+    >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
+    >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
+    ...            0.0689]
+    >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
+    >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
+    F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
+
+    `f_oneway` accepts multidimensional input arrays.  When the inputs
+    are multidimensional and `axis` is not given, the test is performed
+    along the first axis of the input arrays.  For the following data, the
+    test is performed three times, once for each column.
+
+    >>> a = np.array([[9.87, 9.03, 6.81],
+    ...               [7.18, 8.35, 7.00],
+    ...               [8.39, 7.58, 7.68],
+    ...               [7.45, 6.33, 9.35],
+    ...               [6.41, 7.10, 9.33],
+    ...               [8.00, 8.24, 8.44]])
+    >>> b = np.array([[6.35, 7.30, 7.16],
+    ...               [6.65, 6.68, 7.63],
+    ...               [5.72, 7.73, 6.72],
+    ...               [7.01, 9.19, 7.41],
+    ...               [7.75, 7.87, 8.30],
+    ...               [6.90, 7.97, 6.97]])
+    >>> c = np.array([[3.31, 8.77, 1.01],
+    ...               [8.25, 3.24, 3.62],
+    ...               [6.32, 8.81, 5.19],
+    ...               [7.48, 8.83, 8.91],
+    ...               [8.59, 6.01, 6.07],
+    ...               [3.07, 9.72, 7.48]])
+    >>> F = f_oneway(a, b, c)
+    >>> F.statistic
+    array([1.75676344, 0.03701228, 3.76439349])
+    >>> F.pvalue
+    array([0.20630784, 0.96375203, 0.04733157])
+
+    """
+    if len(samples) < 2:
+        raise TypeError('at least two inputs are required;'
+                        f' got {len(samples)}.')
+
+    # ANOVA on N groups, each in its own array
+    num_groups = len(samples)
+
+    # We haven't explicitly validated axis, but if it is bad, this call of
+    # np.concatenate will raise np.exceptions.AxisError. The call will raise
+    # ValueError if the dimensions of all the arrays, except the axis
+    # dimension, are not the same.
+    alldata = np.concatenate(samples, axis=axis)
+    bign = alldata.shape[axis]
+
+    # Check if the inputs are too small
+    if _f_oneway_is_too_small(samples):
+        return _create_f_oneway_nan_result(alldata.shape, axis, samples)
+
+    # Check if all values within each group are identical, and if the common
+    # value in at least one group is different from that in another group.
+    # Based on https://github.com/scipy/scipy/issues/11669
+
+    # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
+    # then is_const is a boolean array with shape (num_groups, ...).
+    # It is True if the values within the groups along the axis slice are
+    # identical. In the typical case where each input array is 1-d, is_const is
+    # a 1-d array with length num_groups.
+    is_const = np.concatenate(
+        [(_first(sample, axis) == sample).all(axis=axis,
+                                              keepdims=True)
+         for sample in samples],
+        axis=axis
+    )
+
+    # all_const is a boolean array with shape (...) (see previous comment).
+    # It is True if the values within each group along the axis slice are
+    # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
+    all_const = is_const.all(axis=axis)
+    if all_const.any():
+        msg = ("Each of the input arrays is constant; "
+               "the F statistic is not defined or infinite")
+        warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2)
+
+    # all_same_const is True if all the values in the groups along the axis=0
+    # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
+    all_same_const = (_first(alldata, axis) == alldata).all(axis=axis)
+
+    # Determine the mean of the data, and subtract that from all inputs to a
+    # variance (via sum_of_sq / sq_of_sum) calculation.  Variance is invariant
+    # to a shift in location, and centering all data around zero vastly
+    # improves numerical stability.
+    offset = alldata.mean(axis=axis, keepdims=True)
+    alldata = alldata - offset
+
+    normalized_ss = _square_of_sums(alldata, axis=axis) / bign
+
+    sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss
+
+    ssbn = 0
+    for sample in samples:
+        smo_ss = _square_of_sums(sample - offset, axis=axis)
+        ssbn = ssbn + smo_ss / sample.shape[axis]
+
+    # Naming: variables ending in bn/b are for "between treatments", wn/w are
+    # for "within treatments"
+    ssbn = ssbn - normalized_ss
+    sswn = sstot - ssbn
+    dfbn = num_groups - 1
+    dfwn = bign - num_groups
+    msb = ssbn / dfbn
+    msw = sswn / dfwn
+    with np.errstate(divide='ignore', invalid='ignore'):
+        f = msb / msw
+
+    prob = special.fdtrc(dfbn, dfwn, f)   # equivalent to stats.f.sf
+
+    # Fix any f values that should be inf or nan because the corresponding
+    # inputs were constant.
+    if np.isscalar(f):
+        if all_same_const:
+            f = np.nan
+            prob = np.nan
+        elif all_const:
+            f = np.inf
+            prob = 0.0
+    else:
+        f[all_const] = np.inf
+        prob[all_const] = 0.0
+        f[all_same_const] = np.nan
+        prob[all_same_const] = np.nan
+
+    return F_onewayResult(f, prob)
+
+
+@dataclass
+class AlexanderGovernResult:
+    statistic: float
+    pvalue: float
+
+
+@_axis_nan_policy_factory(
+    AlexanderGovernResult, n_samples=None,
+    result_to_tuple=lambda x: (x.statistic, x.pvalue),
+    too_small=1
+)
+def alexandergovern(*samples, nan_policy='propagate', axis=0):
+    """Performs the Alexander Govern test.
+
+    The Alexander-Govern approximation tests the equality of k independent
+    means in the face of heterogeneity of variance. The test is applied to
+    samples from two or more groups, possibly with differing sizes.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group.  There must be at least
+        two samples, and each sample must contain at least two observations.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    res : AlexanderGovernResult
+        An object with attributes:
+
+        statistic : float
+            The computed A statistic of the test.
+        pvalue : float
+            The associated p-value from the chi-squared distribution.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The statistic is not defined
+        in this case, so ``np.nan`` is returned.
+
+    See Also
+    --------
+    f_oneway : one-way ANOVA
+
+    Notes
+    -----
+    The use of this test relies on several assumptions.
+
+    1. The samples are independent.
+    2. Each sample is from a normally distributed population.
+    3. Unlike `f_oneway`, this test does not assume on homoscedasticity,
+       instead relaxing the assumption of equal variances.
+
+    Input samples must be finite, one dimensional, and with size greater than
+    one.
+
+    References
+    ----------
+    .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler
+           Approximation for ANOVA under Variance Heterogeneity." Journal
+           of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101.
+           JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020.
+
+    Examples
+    --------
+    >>> from scipy.stats import alexandergovern
+
+    Here are some data on annual percentage rate of interest charged on
+    new car loans at nine of the largest banks in four American cities
+    taken from the National Institute of Standards and Technology's
+    ANOVA dataset.
+
+    We use `alexandergovern` to test the null hypothesis that all cities
+    have the same mean APR against the alternative that the cities do not
+    all have the same mean APR. We decide that a significance level of 5%
+    is required to reject the null hypothesis in favor of the alternative.
+
+    >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5]
+    >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9]
+    >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5]
+    >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25,
+    ...           11.89]
+    >>> alexandergovern(atlanta, chicago, houston, memphis)
+    AlexanderGovernResult(statistic=4.65087071883494,
+                          pvalue=0.19922132490385214)
+
+    The p-value is 0.1992, indicating a nearly 20% chance of observing
+    such an extreme value of the test statistic under the null hypothesis.
+    This exceeds 5%, so we do not reject the null hypothesis in favor of
+    the alternative.
+
+    """
+    samples = _alexandergovern_input_validation(samples, nan_policy, axis)
+
+    # The following formula numbers reference the equation described on
+    # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other
+    # tests that serve as the basis for equation (8) but are not needed
+    # to perform the test.
+
+    # precalculate mean and length of each sample
+    lengths = [sample.shape[-1] for sample in samples]
+    means = np.asarray([_xp_mean(sample, axis=-1) for sample in samples])
+
+    # (1) determine standard error of the mean for each sample
+    se2 = [(_xp_var(sample, correction=1, axis=-1) / length)
+           for sample, length in zip(samples, lengths)]
+    standard_errors_squared = np.asarray(se2)
+    standard_errors = standard_errors_squared**0.5
+
+    # Special case: statistic is NaN when variance is zero
+    eps = np.finfo(standard_errors.dtype).eps
+    zero = standard_errors <= np.abs(eps * means)
+    NaN = np.asarray(np.nan, dtype=standard_errors.dtype)
+    standard_errors = np.where(zero, NaN, standard_errors)
+
+    # (2) define a weight for each sample
+    inv_sq_se = 1 / standard_errors_squared
+    weights = inv_sq_se / np.sum(inv_sq_se, axis=0, keepdims=True)
+
+    # (3) determine variance-weighted estimate of the common mean
+    var_w = np.sum(weights * means, axis=0, keepdims=True)
+
+    # (4) determine one-sample t statistic for each group
+    t_stats = _demean(means, var_w, axis=0, xp=np) / standard_errors
+
+    # calculate parameters to be used in transformation
+    v = np.asarray(lengths) - 1
+    # align along 0th axis, which corresponds with separate samples
+    v = np.reshape(v, (-1,) + (1,)*(t_stats.ndim-1))
+    a = v - .5
+    b = 48 * a**2
+    c = (a * np.log(1 + (t_stats ** 2)/v))**.5
+
+    # (8) perform a normalizing transformation on t statistic
+    z = (c + ((c**3 + 3*c)/b) -
+         ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) /
+          (b**2*10 + 8*b*c**4 + 1000*b)))
+
+    # (9) calculate statistic
+    A = np.sum(z**2, axis=0)
+
+    # "[the p value is determined from] central chi-square random deviates
+    # with k - 1 degrees of freedom". Alexander, Govern (94)
+    df = len(samples) - 1
+    chi2 = _SimpleChi2(df)
+    p = _get_pvalue(A, chi2, alternative='greater', symmetric=False, xp=np)
+    return AlexanderGovernResult(A, p)
+
+
+def _alexandergovern_input_validation(samples, nan_policy, axis):
+    if len(samples) < 2:
+        raise TypeError(f"2 or more inputs required, got {len(samples)}")
+
+    for sample in samples:
+        if sample.shape[axis] <= 1:
+            raise ValueError("Input sample size must be greater than one.")
+
+    samples = [np.moveaxis(sample, axis, -1) for sample in samples]
+
+    return samples
+
+
+def _pearsonr_fisher_ci(r, n, confidence_level, alternative):
+    """
+    Compute the confidence interval for Pearson's R.
+
+    Fisher's transformation is used to compute the confidence interval
+    (https://en.wikipedia.org/wiki/Fisher_transformation).
+    """
+    xp = array_namespace(r)
+
+    with np.errstate(divide='ignore'):
+        zr = xp.atanh(r)
+
+    ones = xp.ones_like(r)
+    n = xp.asarray(n, dtype=r.dtype)
+    confidence_level = xp.asarray(confidence_level, dtype=r.dtype)
+    if n > 3:
+        se = xp.sqrt(1 / (n - 3))
+        if alternative == "two-sided":
+            h = special.ndtri(0.5 + confidence_level/2)
+            zlo = zr - h*se
+            zhi = zr + h*se
+            rlo = xp.tanh(zlo)
+            rhi = xp.tanh(zhi)
+        elif alternative == "less":
+            h = special.ndtri(confidence_level)
+            zhi = zr + h*se
+            rhi = xp.tanh(zhi)
+            rlo = -ones
+        else:
+            # alternative == "greater":
+            h = special.ndtri(confidence_level)
+            zlo = zr - h*se
+            rlo = xp.tanh(zlo)
+            rhi = ones
+    else:
+        rlo, rhi = -ones, ones
+
+    rlo = rlo[()] if rlo.ndim == 0 else rlo
+    rhi = rhi[()] if rhi.ndim == 0 else rhi
+    return ConfidenceInterval(low=rlo, high=rhi)
+
+
+def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative, axis):
+    """
+    Compute the confidence interval for Pearson's R using the bootstrap.
+    """
+    def statistic(x, y, axis):
+        statistic, _ = pearsonr(x, y, axis=axis)
+        return statistic
+
+    res = bootstrap((x, y), statistic, confidence_level=confidence_level, axis=axis,
+                    paired=True, alternative=alternative, **method._asdict())
+    # for one-sided confidence intervals, bootstrap gives +/- inf on one side
+    res.confidence_interval = np.clip(res.confidence_interval, -1, 1)
+
+    return ConfidenceInterval(*res.confidence_interval)
+
+
+ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high'])
+
+PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase',
+                                       ['statistic', 'pvalue'], [])
+
+
+class PearsonRResult(PearsonRResultBase):
+    """
+    Result of `scipy.stats.pearsonr`
+
+    Attributes
+    ----------
+    statistic : float
+        Pearson product-moment correlation coefficient.
+    pvalue : float
+        The p-value associated with the chosen alternative.
+
+    Methods
+    -------
+    confidence_interval
+        Computes the confidence interval of the correlation
+        coefficient `statistic` for the given confidence level.
+
+    """
+    def __init__(self, statistic, pvalue, alternative, n, x, y, axis):
+        super().__init__(statistic, pvalue)
+        self._alternative = alternative
+        self._n = n
+        self._x = x
+        self._y = y
+        self._axis = axis
+
+        # add alias for consistency with other correlation functions
+        self.correlation = statistic
+
+    def confidence_interval(self, confidence_level=0.95, method=None):
+        """
+        The confidence interval for the correlation coefficient.
+
+        Compute the confidence interval for the correlation coefficient
+        ``statistic`` with the given confidence level.
+
+        If `method` is not provided,
+        The confidence interval is computed using the Fisher transformation
+        F(r) = arctanh(r) [1]_.  When the sample pairs are drawn from a
+        bivariate normal distribution, F(r) approximately follows a normal
+        distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the
+        length of the original samples along the calculation axis. When
+        ``n <= 3``, this approximation does not yield a finite, real standard
+        error, so we define the confidence interval to be -1 to 1.
+
+        If `method` is an instance of `BootstrapMethod`, the confidence
+        interval is computed using `scipy.stats.bootstrap` with the provided
+        configuration options and other appropriate settings. In some cases,
+        confidence limits may be NaN due to a degenerate resample, and this is
+        typical for very small samples (~6 observations).
+
+        Parameters
+        ----------
+        confidence_level : float
+            The confidence level for the calculation of the correlation
+            coefficient confidence interval. Default is 0.95.
+
+        method : BootstrapMethod, optional
+            Defines the method used to compute the confidence interval. See
+            method description for details.
+
+            .. versionadded:: 1.11.0
+
+        Returns
+        -------
+        ci : namedtuple
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+        References
+        ----------
+        .. [1] "Pearson correlation coefficient", Wikipedia,
+               https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+        """
+        if isinstance(method, BootstrapMethod):
+            xp = array_namespace(self._x)
+            message = ('`method` must be `None` if `pearsonr` '
+                       'arguments were not NumPy arrays.')
+            if not is_numpy(xp):
+                raise ValueError(message)
+
+            ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y,
+                                        self._alternative, self._axis)
+        elif method is None:
+            ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level,
+                                     self._alternative)
+        else:
+            message = ('`method` must be an instance of `BootstrapMethod` '
+                       'or None.')
+            raise ValueError(message)
+        return ci
+
+
+def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0):
+    r"""
+    Pearson correlation coefficient and p-value for testing non-correlation.
+
+    The Pearson correlation coefficient [1]_ measures the linear relationship
+    between two datasets. Like other correlation
+    coefficients, this one varies between -1 and +1 with 0 implying no
+    correlation. Correlations of -1 or +1 imply an exact linear relationship.
+    Positive correlations imply that as x increases, so does y. Negative
+    correlations imply that as x increases, y decreases.
+
+    This function also performs a test of the null hypothesis that the
+    distributions underlying the samples are uncorrelated and normally
+    distributed. (See Kowalski [3]_
+    for a discussion of the effects of non-normality of the input on the
+    distribution of the correlation coefficient.)
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Pearson correlation at least as extreme
+    as the one computed from these datasets.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    y : array_like
+        Input array.
+    axis : int or None, default
+        Axis along which to perform the calculation. Default is 0.
+        If None, ravel both arrays before performing the calculation.
+
+        .. versionadded:: 1.13.0
+    alternative : {'two-sided', 'greater', 'less'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.9.0
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
+        computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed as documented in the notes.
+
+        .. versionadded:: 1.11.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.PearsonRResult`
+        An object with the following attributes:
+
+        statistic : float
+            Pearson product-moment correlation coefficient.
+        pvalue : float
+            The p-value associated with the chosen alternative.
+
+        The object has the following method:
+
+        confidence_interval(confidence_level, method)
+            This computes the confidence interval of the correlation
+            coefficient `statistic` for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`. If `method` is not provided, the
+            confidence interval is computed using the Fisher transformation
+            [1]_. If `method` is an instance of `BootstrapMethod`, the
+            confidence interval is computed using `scipy.stats.bootstrap` with
+            the provided configuration options and other appropriate settings.
+            In some cases, confidence limits may be NaN due to a degenerate
+            resample, and this is typical for very small samples (~6
+            observations).
+
+    Raises
+    ------
+    ValueError
+        If `x` and `y` do not have length at least 2.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    `~scipy.stats.NearConstantInputWarning`
+        Raised if an input is "nearly" constant.  The array ``x`` is considered
+        nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
+        Numerical errors in the calculation ``x - mean(x)`` in this case might
+        result in an inaccurate calculation of r.
+
+    See Also
+    --------
+    spearmanr : Spearman rank-order correlation coefficient.
+    kendalltau : Kendall's tau, a correlation measure for ordinal data.
+
+    Notes
+    -----
+    The correlation coefficient is calculated as follows:
+
+    .. math::
+
+        r = \frac{\sum (x - m_x) (y - m_y)}
+                 {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
+
+    where :math:`m_x` is the mean of the vector x and :math:`m_y` is
+    the mean of the vector y.
+
+    Under the assumption that x and y are drawn from
+    independent normal distributions (so the population correlation coefficient
+    is 0), the probability density function of the sample correlation
+    coefficient r is ([1]_, [2]_):
+
+    .. math::
+        f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
+
+    where n is the number of samples, and B is the beta function.  This
+    is sometimes referred to as the exact distribution of r.  This is
+    the distribution that is used in `pearsonr` to compute the p-value when
+    the `method` parameter is left at its default value (None).
+    The distribution is a beta distribution on the interval [-1, 1],
+    with equal shape parameters a = b = n/2 - 1.  In terms of SciPy's
+    implementation of the beta distribution, the distribution of r is::
+
+        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
+
+    The default p-value returned by `pearsonr` is a two-sided p-value. For a
+    given sample with correlation coefficient r, the p-value is
+    the probability that abs(r') of a random sample x' and y' drawn from
+    the population with zero correlation would be greater than or equal
+    to abs(r). In terms of the object ``dist`` shown above, the p-value
+    for a given r and length n can be computed as::
+
+        p = 2*dist.cdf(-abs(r))
+
+    When n is 2, the above continuous distribution is not well-defined.
+    One can interpret the limit of the beta distribution as the shape
+    parameters a and b approach a = b = 0 as a discrete distribution with
+    equal probability masses at r = 1 and r = -1.  More directly, one
+    can observe that, given the data x = [x1, x2] and y = [y1, y2], and
+    assuming x1 != x2 and y1 != y2, the only possible values for r are 1
+    and -1.  Because abs(r') for any sample x' and y' with length 2 will
+    be 1, the two-sided p-value for a sample of length 2 is always 1.
+
+    For backwards compatibility, the object that is returned also behaves
+    like a tuple of length two that holds the statistic and the p-value.
+
+    References
+    ----------
+    .. [1] "Pearson correlation coefficient", Wikipedia,
+           https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+    .. [2] Student, "Probable error of a correlation coefficient",
+           Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
+    .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
+           of the Sample Product-Moment Correlation Coefficient"
+           Journal of the Royal Statistical Society. Series C (Applied
+           Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2]
+    >>> res = stats.pearsonr(x, y)
+    >>> res
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286)
+
+    To perform an exact permutation version of the test:
+
+    >>> rng = np.random.default_rng(7796654889291491997)
+    >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng)
+    >>> stats.pearsonr(x, y, method=method)
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175)
+
+    To perform the test under the null hypothesis that the data were drawn from
+    *uniform* distributions:
+
+    >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform))
+    >>> stats.pearsonr(x, y, method=method)
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188)
+
+    To produce an asymptotic 90% confidence interval:
+
+    >>> res.confidence_interval(confidence_level=0.9)
+    ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273)
+
+    And for a bootstrap confidence interval:
+
+    >>> method = stats.BootstrapMethod(method='BCa', rng=rng)
+    >>> res.confidence_interval(confidence_level=0.9, method=method)
+    ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443)  # may vary
+
+    If N-dimensional arrays are provided, multiple tests are performed in a
+    single call according to the same conventions as most `scipy.stats` functions:
+
+    >>> rng = np.random.default_rng(2348246935601934321)
+    >>> x = rng.standard_normal((8, 15))
+    >>> y = rng.standard_normal((8, 15))
+    >>> stats.pearsonr(x, y, axis=0).statistic.shape  # between corresponding columns
+    (15,)
+    >>> stats.pearsonr(x, y, axis=1).statistic.shape  # between corresponding rows
+    (8,)
+
+    To perform all pairwise comparisons between slices of the arrays,
+    use standard NumPy broadcasting techniques. For instance, to compute the
+    correlation between all pairs of rows:
+
+    >>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape
+    (8, 8)
+
+    There is a linear dependence between x and y if y = a + b*x + e, where
+    a,b are constants and e is a random error term, assumed to be independent
+    of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
+    e follow a normal distribution with mean zero and standard deviation s>0.
+
+    >>> rng = np.random.default_rng()
+    >>> s = 0.5
+    >>> x = stats.norm.rvs(size=500, random_state=rng)
+    >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng)
+    >>> y = x + e
+    >>> stats.pearsonr(x, y).statistic
+    0.9001942438244763
+
+    This should be close to the exact value given by
+
+    >>> 1/np.sqrt(1 + s**2)
+    0.8944271909999159
+
+    For s=0.5, we observe a high level of correlation. In general, a large
+    variance of the noise reduces the correlation, while the correlation
+    approaches one as the variance of the error goes to zero.
+
+    It is important to keep in mind that no correlation does not imply
+    independence unless (x, y) is jointly normal. Correlation can even be zero
+    when there is a very simple dependence structure: if X follows a
+    standard normal distribution, let y = abs(x). Note that the correlation
+    between x and y is zero. Indeed, since the expectation of x is zero,
+    cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
+    by symmetry. The following lines of code illustrate this observation:
+
+    >>> y = np.abs(x)
+    >>> stats.pearsonr(x, y)
+    PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743)
+
+    A non-zero correlation coefficient can be misleading. For example, if X has
+    a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
+    A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
+    implying a high level of correlation:
+
+    >>> y = np.where(x < 0, x, 0)
+    >>> stats.pearsonr(x, y)
+    PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149)
+
+    This is unintuitive since there is no dependence of x and y if x is larger
+    than zero which happens in about half of the cases if we sample x and y.
+
+    """
+    xp = array_namespace(x, y)
+    x = xp.asarray(x)
+    y = xp.asarray(y)
+
+    if not is_numpy(xp) and method is not None:
+        method = 'invalid'
+
+    if axis is None:
+        x = xp.reshape(x, (-1,))
+        y = xp.reshape(y, (-1,))
+        axis = -1
+
+    axis_int = int(axis)
+    if axis_int != axis:
+        raise ValueError('`axis` must be an integer.')
+    axis = axis_int
+
+    n = x.shape[axis]
+    if n != y.shape[axis]:
+        raise ValueError('`x` and `y` must have the same length along `axis`.')
+
+    if n < 2:
+        raise ValueError('`x` and `y` must have length at least 2.')
+
+    try:
+        x, y = xp.broadcast_arrays(x, y)
+    except (ValueError, RuntimeError) as e:
+        message = '`x` and `y` must be broadcastable.'
+        raise ValueError(message) from e
+
+    # `moveaxis` only recently added to array API, so it's not yey available in
+    # array_api_strict. Replace with e.g. `xp.moveaxis(x, axis, -1)` when available.
+    x = xp_moveaxis_to_end(x, axis, xp=xp)
+    y = xp_moveaxis_to_end(y, axis, xp=xp)
+    axis = -1
+
+    dtype = xp.result_type(x.dtype, y.dtype)
+    if xp.isdtype(dtype, "integral"):
+        dtype = xp.asarray(1.).dtype
+
+    if xp.isdtype(dtype, "complex floating"):
+        raise ValueError('This function does not support complex data')
+
+    x = xp.astype(x, dtype, copy=False)
+    y = xp.astype(y, dtype, copy=False)
+    threshold = xp.finfo(dtype).eps ** 0.75
+
+    # If an input is constant, the correlation coefficient is not defined.
+    const_x = xp.all(x == x[..., 0:1], axis=-1)
+    const_y = xp.all(y == y[..., 0:1], axis=-1)
+    const_xy = const_x | const_y
+    if xp.any(const_xy):
+        msg = ("An input array is constant; the correlation coefficient "
+               "is not defined.")
+        warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2)
+
+    if isinstance(method, PermutationMethod):
+        def statistic(y, axis):
+            statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
+            return statistic
+
+        res = permutation_test((y,), statistic, permutation_type='pairings',
+                               axis=axis, alternative=alternative, **method._asdict())
+
+        return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
+                              alternative=alternative, x=x, y=y, axis=axis)
+    elif isinstance(method, MonteCarloMethod):
+        def statistic(x, y, axis):
+            statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
+            return statistic
+
+        # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
+        # If the user specified an `rng`, replace it with the appropriate callables
+        method = method._asdict()
+        if (rng := method.pop('rng', None)) is not None:  # goo-goo g'joob
+            rng = np.random.default_rng(rng)
+            method['rvs'] = rng.normal, rng.normal
+
+        res = monte_carlo_test((x, y,), statistic=statistic, axis=axis,
+                               alternative=alternative, **method)
+
+        return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
+                              alternative=alternative, x=x, y=y, axis=axis)
+    elif method == 'invalid':
+        message = '`method` must be `None` if arguments are not NumPy arrays.'
+        raise ValueError(message)
+    elif method is not None:
+        message = ('`method` must be an instance of `PermutationMethod`,'
+                   '`MonteCarloMethod`, or None.')
+        raise ValueError(message)
+
+    xmean = xp.mean(x, axis=axis, keepdims=True)
+    ymean = xp.mean(y, axis=axis, keepdims=True)
+    xm = x - xmean
+    ym = y - ymean
+
+    # scipy.linalg.norm(xm) avoids premature overflow when xm is e.g.
+    # [-5e210, 5e210, 3e200, -3e200]
+    # but not when `axis` is provided, so scale manually. scipy.linalg.norm
+    # also raises an error with NaN input rather than returning NaN, so
+    # use np.linalg.norm.
+    xmax = xp.max(xp.abs(xm), axis=axis, keepdims=True)
+    ymax = xp.max(xp.abs(ym), axis=axis, keepdims=True)
+    with np.errstate(invalid='ignore', divide='ignore'):
+        normxm = xmax * xp_vector_norm(xm/xmax, axis=axis, keepdims=True)
+        normym = ymax * xp_vector_norm(ym/ymax, axis=axis, keepdims=True)
+
+    nconst_x = xp.any(normxm < threshold*xp.abs(xmean), axis=axis)
+    nconst_y = xp.any(normym < threshold*xp.abs(ymean), axis=axis)
+    nconst_xy = nconst_x | nconst_y
+    if xp.any(nconst_xy & (~const_xy)):
+        # If all the values in x (likewise y) are very close to the mean,
+        # the loss of precision that occurs in the subtraction xm = x - xmean
+        # might result in large errors in r.
+        msg = ("An input array is nearly constant; the computed "
+               "correlation coefficient may be inaccurate.")
+        warnings.warn(stats.NearConstantInputWarning(msg), stacklevel=2)
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        r = xp.sum(xm/normxm * ym/normym, axis=axis)
+
+    # Presumably, if abs(r) > 1, then it is only some small artifact of
+    # floating point arithmetic.
+    one = xp.asarray(1, dtype=dtype)
+    r = xp.asarray(xp.clip(r, -one, one))
+    r[const_xy] = xp.nan
+
+    # Make sure we return exact 1.0 or -1.0 values for n == 2 case as promised
+    # in the docs.
+    if n == 2:
+        r = xp.round(r)
+        one = xp.asarray(1, dtype=dtype)
+        pvalue = xp.where(xp.asarray(xp.isnan(r)), xp.nan*one, one)
+    else:
+        # As explained in the docstring, the distribution of `r` under the null
+        # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1.
+        ab = xp.asarray(n/2 - 1)
+        dist = _SimpleBeta(ab, ab, loc=-1, scale=2)
+        pvalue = _get_pvalue(r, dist, alternative, xp=xp)
+
+    r = r[()] if r.ndim == 0 else r
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return PearsonRResult(statistic=r, pvalue=pvalue, n=n,
+                          alternative=alternative, x=x, y=y, axis=axis)
+
+
+def fisher_exact(table, alternative=None, *, method=None):
+    """Perform a Fisher exact test on a contingency table.
+
+    For a 2x2 table,
+    the null hypothesis is that the true odds ratio of the populations
+    underlying the observations is one, and the observations were sampled
+    from these populations under a condition: the marginals of the
+    resulting table must equal those of the observed table.
+    The statistic is the unconditional maximum likelihood estimate of the odds
+    ratio, and the p-value is the probability under the null hypothesis of
+    obtaining a table at least as extreme as the one that was actually
+    observed.
+
+    For other table sizes, or if `method` is provided, the null hypothesis
+    is that the rows and columns of the tables have fixed sums and are
+    independent; i.e., the table was sampled from a `scipy.stats.random_table`
+    distribution with the observed marginals. The statistic is the
+    probability mass of this distribution evaluated at `table`, and the
+    p-value is the percentage of the population of tables with statistic at
+    least as extreme (small) as that of `table`. There is only one alternative
+    hypothesis available: the rows and columns are not independent.
+
+    There are other possible choices of statistic and two-sided
+    p-value definition associated with Fisher's exact test; please see the
+    Notes for more information.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A contingency table.  Elements must be non-negative integers.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis for 2x2 tables; unused for other
+        table sizes.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the odds ratio of the underlying population is not one
+        * 'less': the odds ratio of the underlying population is less than one
+        * 'greater': the odds ratio of the underlying population is greater
+          than one
+
+        See the Notes for more details.
+
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value.
+        If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
+        the p-value is computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
+        attribute must be left unspecified; Monte Carlo samples are always drawn
+        using the ``rvs`` method of `scipy.stats.random_table`.
+        Otherwise, the p-value is computed as documented in the notes.
+
+        .. versionadded:: 1.15.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            For a 2x2 table with default `method`, this is the odds ratio - the
+            prior odds ratio not a posterior estimate. In all other cases, this
+            is the probability density of obtaining the observed table under the
+            null hypothesis of independence with marginals fixed.
+        pvalue : float
+            The probability under the null hypothesis of obtaining a
+            table at least as extreme as the one that was actually observed.
+
+    Raises
+    ------
+    ValueError
+        If `table` is not two-dimensional or has negative entries.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.  This can be used as an alternative to
+        `fisher_exact` when the numbers in the table are large.
+    contingency.odds_ratio : Compute the odds ratio (sample or conditional
+        MLE) for a 2x2 contingency table.
+    barnard_exact : Barnard's exact test, which is a more powerful alternative
+        than Fisher's exact test for 2x2 contingency tables.
+    boschloo_exact : Boschloo's exact test, which is a more powerful
+        alternative than Fisher's exact test for 2x2 contingency tables.
+    :ref:`hypothesis_fisher_exact` : Extended example
+
+    Notes
+    -----
+    *Null hypothesis and p-values*
+
+    The null hypothesis is that the true odds ratio of the populations
+    underlying the observations is one, and the observations were sampled at
+    random from these populations under a condition: the marginals of the
+    resulting table must equal those of the observed table. Equivalently,
+    the null hypothesis is that the input table is from the hypergeometric
+    distribution with parameters (as used in `hypergeom`)
+    ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the
+    input table is ``[[a, b], [c, d]]``.  This distribution has support
+    ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values
+    in the input table, ``min(0, a - d) <= x <= a + min(b, c)``.  ``x``
+    can be interpreted as the upper-left element of a 2x2 table, so the
+    tables in the distribution have form::
+
+        [  x           n - x     ]
+        [N - x    M - (n + N) + x]
+
+    For example, if::
+
+        table = [6  2]
+                [1  4]
+
+    then the support is ``2 <= x <= 7``, and the tables in the distribution
+    are::
+
+        [2 6]   [3 5]   [4 4]   [5 3]   [6 2]  [7 1]
+        [5 0]   [4 1]   [3 2]   [2 3]   [1 4]  [0 5]
+
+    The probability of each table is given by the hypergeometric distribution
+    ``hypergeom.pmf(x, M, n, N)``.  For this example, these are (rounded to
+    three significant digits)::
+
+        x       2      3      4      5       6        7
+        p  0.0163  0.163  0.408  0.326  0.0816  0.00466
+
+    These can be computed with::
+
+        >>> import numpy as np
+        >>> from scipy.stats import hypergeom
+        >>> table = np.array([[6, 2], [1, 4]])
+        >>> M = table.sum()
+        >>> n = table[0].sum()
+        >>> N = table[:, 0].sum()
+        >>> start, end = hypergeom.support(M, n, N)
+        >>> hypergeom.pmf(np.arange(start, end+1), M, n, N)
+        array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508,
+               0.004662  ])
+
+    The two-sided p-value is the probability that, under the null hypothesis,
+    a random table would have a probability equal to or less than the
+    probability of the input table.  For our example, the probability of
+    the input table (where ``x = 6``) is 0.0816.  The x values where the
+    probability does not exceed this are 2, 6 and 7, so the two-sided p-value
+    is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``::
+
+        >>> from scipy.stats import fisher_exact
+        >>> res = fisher_exact(table, alternative='two-sided')
+        >>> res.pvalue
+        0.10256410256410257
+
+    The one-sided p-value for ``alternative='greater'`` is the probability
+    that a random table has ``x >= a``, which in our example is ``x >= 6``,
+    or ``0.0816 + 0.00466 ~= 0.08626``::
+
+        >>> res = fisher_exact(table, alternative='greater')
+        >>> res.pvalue
+        0.08624708624708627
+
+    This is equivalent to computing the survival function of the
+    distribution at ``x = 5`` (one less than ``x`` from the input table,
+    because we want to include the probability of ``x = 6`` in the sum)::
+
+        >>> hypergeom.sf(5, M, n, N)
+        0.08624708624708627
+
+    For ``alternative='less'``, the one-sided p-value is the probability
+    that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example),
+    or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``::
+
+        >>> res = fisher_exact(table, alternative='less')
+        >>> res.pvalue
+        0.9953379953379957
+
+    This is equivalent to computing the cumulative distribution function
+    of the distribution at ``x = 6``:
+
+        >>> hypergeom.cdf(6, M, n, N)
+        0.9953379953379957
+
+    *Odds ratio*
+
+    The calculated odds ratio is different from the value computed by the
+    R function ``fisher.test``.  This implementation returns the "sample"
+    or "unconditional" maximum likelihood estimate, while ``fisher.test``
+    in R uses the conditional maximum likelihood estimate.  To compute the
+    conditional maximum likelihood estimate of the odds ratio, use
+    `scipy.stats.contingency.odds_ratio`.
+
+    References
+    ----------
+    .. [1] Fisher, Sir Ronald A, "The Design of Experiments:
+           Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935.
+    .. [2] "Fisher's exact test",
+           https://en.wikipedia.org/wiki/Fisher's_exact_test
+
+    Examples
+    --------
+
+    >>> from scipy.stats import fisher_exact
+    >>> res = fisher_exact([[8, 2], [1, 5]])
+    >>> res.statistic
+    20.0
+    >>> res.pvalue
+    0.034965034965034975
+
+    For tables with shape other than ``(2, 2)``, provide an instance of
+    `scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the
+    `method` parameter:
+
+    >>> import numpy as np
+    >>> from scipy.stats import MonteCarloMethod
+    >>> rng = np.random.default_rng(4507195762371367)
+    >>> method = MonteCarloMethod(rng=rng)
+    >>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method)
+    SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603))
+
+    For a more detailed example, see :ref:`hypothesis_fisher_exact`.
+    """
+    hypergeom = distributions.hypergeom
+    # int32 is not enough for the algorithm
+    c = np.asarray(table, dtype=np.int64)
+    if not c.ndim == 2:
+        raise ValueError("The input `table` must have two dimensions.")
+
+    if np.any(c < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if not c.shape == (2, 2) or method is not None:
+        return _fisher_exact_rxc(c, alternative, method)
+    alternative = 'two-sided' if alternative is None else alternative
+
+    if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
+        # If both values in a row or column are zero, the p-value is 1 and
+        # the odds ratio is NaN.
+        return SignificanceResult(np.nan, 1.0)
+
+    if c[1, 0] > 0 and c[0, 1] > 0:
+        oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
+    else:
+        oddsratio = np.inf
+
+    n1 = c[0, 0] + c[0, 1]
+    n2 = c[1, 0] + c[1, 1]
+    n = c[0, 0] + c[1, 0]
+
+    def pmf(x):
+        return hypergeom.pmf(x, n1 + n2, n1, n)
+
+    if alternative == 'less':
+        pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
+    elif alternative == 'greater':
+        # Same formula as the 'less' case, but with the second column.
+        pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
+    elif alternative == 'two-sided':
+        mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
+        pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
+        pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
+
+        epsilon = 1e-14
+        gamma = 1 + epsilon
+
+        if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon:
+            return SignificanceResult(oddsratio, 1.)
+
+        elif c[0, 0] < mode:
+            plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
+            if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma:
+                return SignificanceResult(oddsratio, plower)
+
+            guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n)
+            pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n)
+        else:
+            pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
+            if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma:
+                return SignificanceResult(oddsratio, pupper)
+
+            guess = _binary_search(pmf, pexact * gamma, 0, mode)
+            pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
+    else:
+        msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
+        raise ValueError(msg)
+
+    pvalue = min(pvalue, 1.0)
+
+    return SignificanceResult(oddsratio, pvalue)
+
+
+def _fisher_exact_rxc(table, alternative, method):
+    if alternative is not None:
+        message = ('`alternative` must be the default (None) unless '
+                  '`table` has shape `(2, 2)` and `method is None`.')
+        raise ValueError(message)
+
+    if table.size == 0:
+        raise ValueError("`table` must have at least one row and one column.")
+
+    if table.shape[0] == 1 or table.shape[1] == 1 or np.all(table == 0):
+        # Only one such table with those marginals
+        return SignificanceResult(1.0, 1.0)
+
+    if method is None:
+        method = stats.MonteCarloMethod()
+
+    if isinstance(method, stats.PermutationMethod):
+        res = _fisher_exact_permutation_method(table, method)
+    elif isinstance(method, stats.MonteCarloMethod):
+        res = _fisher_exact_monte_carlo_method(table, method)
+    else:
+        message = (f'`{method=}` not recognized; if provided, `method` must be an '
+                   'instance of `PermutationMethod` or `MonteCarloMethod`.')
+        raise ValueError(message)
+
+    return SignificanceResult(np.clip(res.statistic, None, 1.0), res.pvalue)
+
+
+def _fisher_exact_permutation_method(table, method):
+    x, y = _untabulate(table)
+    colsums = np.sum(table, axis=0)
+    rowsums = np.sum(table, axis=1)
+    X = stats.random_table(rowsums, colsums)
+
+    # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
+    # which pairs observations in `x` with different observations in `y`.
+    def statistic(x):
+        # crosstab the resample and compute the statistic
+        table = stats.contingency.crosstab(x, y)[1]
+        return X.pmf(table)
+
+    # tables with *smaller* probability mass are considered to be more extreme
+    return stats.permutation_test((x,), statistic, permutation_type='pairings',
+                                  alternative='less', **method._asdict())
+
+
+def _fisher_exact_monte_carlo_method(table, method):
+    method = method._asdict()
+
+    if method.pop('rvs', None) is not None:
+        message = ('If the `method` argument of `fisher_exact` is an '
+                   'instance of `MonteCarloMethod`, its `rvs` attribute '
+                   'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
+                   'to control the random state.')
+        raise ValueError(message)
+    rng = np.random.default_rng(method.pop('rng', None))
+
+    # `random_table.rvs` produces random contingency tables with the given marginals
+    # under the null hypothesis of independence
+    shape = table.shape
+    colsums = np.sum(table, axis=0)
+    rowsums = np.sum(table, axis=1)
+    totsum = np.sum(table)
+    X = stats.random_table(rowsums, colsums, seed=rng)
+
+    def rvs(size):
+        n_resamples = size[0]
+        return X.rvs(size=n_resamples).reshape(size)
+
+    # axis signals to `monte_carlo_test` that statistic is vectorized, but we know
+    # how it will pass the table(s), so we don't need to use `axis` explicitly.
+    def statistic(table, axis):
+        shape_ = (-1,) + shape if table.size > totsum else shape
+        return X.pmf(table.reshape(shape_))
+
+    # tables with *smaller* probability mass are considered to be more extreme
+    return stats.monte_carlo_test(table.ravel(), rvs, statistic,
+                                  alternative='less', **method)
+
+
+def _untabulate(table):
+    # converts a contingency table to paired samples indicating the
+    # correspondence between row and column indices
+    r, c = table.shape
+    x, y = [], []
+    for i in range(r):
+        for j in range(c):
+            x.append([i] * table[i, j])
+            y.append([j] * table[i, j])
+    return np.concatenate(x), np.concatenate(y)
+
+
+def spearmanr(a, b=None, axis=0, nan_policy='propagate',
+              alternative='two-sided'):
+    r"""Calculate a Spearman correlation coefficient with associated p-value.
+
+    The Spearman rank-order correlation coefficient is a nonparametric measure
+    of the monotonicity of the relationship between two datasets.
+    Like other correlation coefficients,
+    this one varies between -1 and +1 with 0 implying no correlation.
+    Correlations of -1 or +1 imply an exact monotonic relationship. Positive
+    correlations imply that as x increases, so does y. Negative correlations
+    imply that as x increases, y decreases.
+
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Spearman correlation at least as extreme
+    as the one computed from these datasets. Although calculation of the
+    p-value does not make strong assumptions about the distributions underlying
+    the samples, it is only accurate for very large samples (>500
+    observations). For smaller sample sizes, consider a permutation test (see
+    Examples section below).
+
+    Parameters
+    ----------
+    a, b : 1D or 2D array_like, b is optional
+        One or two 1-D or 2-D arrays containing multiple variables and
+        observations. When these are 1-D, each represents a vector of
+        observations of a single variable. For the behavior in the 2-D case,
+        see under ``axis``, below.
+        Both arrays need to have the same length in the ``axis`` dimension.
+    axis : int or None, optional
+        If axis=0 (default), then each column represents a variable, with
+        observations in the rows. If axis=1, the relationship is transposed:
+        each row represents a variable, while the columns contain observations.
+        If axis=None, then both arrays will be raveled.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float or ndarray (2-D square)
+            Spearman correlation matrix or correlation coefficient (if only 2
+            variables are given as parameters). Correlation matrix is square
+            with length equal to total number of variables (columns or rows) in
+            ``a`` and ``b`` combined.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis
+            is that two samples have no ordinal correlation. See
+            `alternative` above for alternative hypotheses. `pvalue` has the
+            same shape as `statistic`.
+
+    Raises
+    ------
+    ValueError
+        If `axis` is not 0, 1 or None, or if the number of dimensions of `a`
+        is greater than 2, or if `b` is None and the number of dimensions of
+        `a` is less than 2.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    See Also
+    --------
+    :ref:`hypothesis_spearmanr` : Extended example
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+       Section  14.7
+    .. [2] Kendall, M. G. and Stuart, A. (1973).
+       The Advanced Theory of Statistics, Volume 2: Inference and Relationship.
+       Griffin. 1973.
+       Section 31.18
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7])
+    >>> res.statistic
+    0.8207826816681233
+    >>> res.pvalue
+    0.08858700531354381
+
+    >>> rng = np.random.default_rng()
+    >>> x2n = rng.standard_normal((100, 2))
+    >>> y2n = rng.standard_normal((100, 2))
+    >>> res = stats.spearmanr(x2n)
+    >>> res.statistic, res.pvalue
+    (-0.07960396039603959, 0.4311168705769747)
+
+    >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1])
+    >>> res.statistic, res.pvalue
+    (-0.07960396039603959, 0.4311168705769747)
+
+    >>> res = stats.spearmanr(x2n, y2n)
+    >>> res.statistic
+    array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
+           [-0.07960396, 1. , -0.14448245, 0.16738074],
+           [-0.08314431, -0.14448245, 1. , 0.03234323],
+           [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
+    >>> res.pvalue
+    array([[0. , 0.43111687, 0.41084066, 0.33891628],
+           [0.43111687, 0. , 0.15151618, 0.09600687],
+           [0.41084066, 0.15151618, 0. , 0.74938561],
+           [0.33891628, 0.09600687, 0.74938561, 0. ]])
+
+    >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1)
+    >>> res.statistic
+    array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
+           [-0.07960396, 1. , -0.14448245, 0.16738074],
+           [-0.08314431, -0.14448245, 1. , 0.03234323],
+           [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
+
+    >>> res = stats.spearmanr(x2n, y2n, axis=None)
+    >>> res.statistic, res.pvalue
+    (0.044981624540613524, 0.5270803651336189)
+
+    >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel())
+    >>> res.statistic, res.pvalue
+    (0.044981624540613524, 0.5270803651336189)
+
+    >>> rng = np.random.default_rng()
+    >>> xint = rng.integers(10, size=(100, 2))
+    >>> res = stats.spearmanr(xint)
+    >>> res.statistic, res.pvalue
+    (0.09800224850707953, 0.3320271757932076)
+
+    For small samples, consider performing a permutation test instead of
+    relying on the asymptotic p-value. Note that to calculate the null
+    distribution of the statistic (for all possibly pairings between
+    observations in sample ``x`` and ``y``), only one of the two inputs needs
+    to be permuted.
+
+    >>> x = [1.76405235, 0.40015721, 0.97873798,
+    ... 2.2408932, 1.86755799, -0.97727788]
+    >>> y = [2.71414076, 0.2488, 0.87551913,
+    ... 2.6514917, 2.01160156, 0.47699563]
+
+    >>> def statistic(x): # permute only `x`
+    ...     return stats.spearmanr(x, y).statistic
+    >>> res_exact = stats.permutation_test((x,), statistic,
+    ...     permutation_type='pairings')
+    >>> res_asymptotic = stats.spearmanr(x, y)
+    >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low
+    (0.10277777777777777, 0.07239650145772594)
+
+    For a more detailed example, see :ref:`hypothesis_spearmanr`.
+    """
+    if axis is not None and axis > 1:
+        raise ValueError("spearmanr only handles 1-D or 2-D arrays, "
+                         f"supplied axis argument {axis}, please use only "
+                         "values 0, 1 or None for axis")
+
+    a, axisout = _chk_asarray(a, axis)
+    if a.ndim > 2:
+        raise ValueError("spearmanr only handles 1-D or 2-D arrays")
+
+    if b is None:
+        if a.ndim < 2:
+            raise ValueError("`spearmanr` needs at least 2 "
+                             "variables to compare")
+    else:
+        # Concatenate a and b, so that we now only have to handle the case
+        # of a 2-D `a`.
+        b, _ = _chk_asarray(b, axis)
+        if axisout == 0:
+            a = np.column_stack((a, b))
+        else:
+            a = np.vstack((a, b))
+
+    n_vars = a.shape[1 - axisout]
+    n_obs = a.shape[axisout]
+    if n_obs <= 1:
+        # Handle empty arrays or single observations.
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    warn_msg = ("An input array is constant; the correlation coefficient "
+                "is not defined.")
+    if axisout == 0:
+        if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
+            # If an input is constant, the correlation coefficient
+            # is not defined.
+            warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
+            res = SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+    else:  # case when axisout == 1 b/c a is 2 dim only
+        if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
+            # If an input is constant, the correlation coefficient
+            # is not defined.
+            warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
+            res = SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+
+    a_contains_nan, nan_policy = _contains_nan(a, nan_policy)
+    variable_has_nan = np.zeros(n_vars, dtype=bool)
+    if a_contains_nan:
+        if nan_policy == 'omit':
+            return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy,
+                                          alternative=alternative)
+        elif nan_policy == 'propagate':
+            if a.ndim == 1 or n_vars <= 2:
+                res = SignificanceResult(np.nan, np.nan)
+                res.correlation = np.nan
+                return res
+            else:
+                # Keep track of variables with NaNs, set the outputs to NaN
+                # only for those variables
+                variable_has_nan = np.isnan(a).any(axis=axisout)
+
+    a_ranked = np.apply_along_axis(rankdata, axisout, a)
+    rs = np.corrcoef(a_ranked, rowvar=axisout)
+    dof = n_obs - 2  # degrees of freedom
+
+    # rs can have elements equal to 1, so avoid zero division warnings
+    with np.errstate(divide='ignore'):
+        # clip the small negative values possibly caused by rounding
+        # errors before taking the square root
+        t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
+
+    dist = _SimpleStudentT(dof)
+    prob = _get_pvalue(t, dist, alternative, xp=np)
+
+    # For backwards compatibility, return scalars when comparing 2 columns
+    if rs.shape == (2, 2):
+        res = SignificanceResult(rs[1, 0], prob[1, 0])
+        res.correlation = rs[1, 0]
+        return res
+    else:
+        rs[variable_has_nan, :] = np.nan
+        rs[:, variable_has_nan] = np.nan
+        res = SignificanceResult(rs[()], prob[()])
+        res.correlation = rs
+        return res
+
+
+def pointbiserialr(x, y):
+    r"""Calculate a point biserial correlation coefficient and its p-value.
+
+    The point biserial correlation is used to measure the relationship
+    between a binary variable, x, and a continuous variable, y. Like other
+    correlation coefficients, this one varies between -1 and +1 with 0
+    implying no correlation. Correlations of -1 or +1 imply a determinative
+    relationship.
+
+    This function may be computed using a shortcut formula but produces the
+    same result as `pearsonr`.
+
+    Parameters
+    ----------
+    x : array_like of bools
+        Input array.
+    y : array_like
+        Input array.
+
+    Returns
+    -------
+    res: SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The R value.
+        pvalue : float
+            The two-sided p-value.
+
+    Notes
+    -----
+    `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
+    It is equivalent to `pearsonr`.
+
+    The value of the point-biserial correlation can be calculated from:
+
+    .. math::
+
+        r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}}
+                      {s_y}
+                 \sqrt{\frac{N_0 N_1}
+                            {N (N - 1)}}
+
+    Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means
+    of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and
+    :math:`N_{1}` are number of observations coded 0 and 1 respectively;
+    :math:`N` is the total number of observations and :math:`s_{y}` is the
+    standard deviation of all the metric observations.
+
+    A value of :math:`r_{pb}` that is significantly different from zero is
+    completely equivalent to a significant difference in means between the two
+    groups. Thus, an independent groups t Test with :math:`N-2` degrees of
+    freedom may be used to test whether :math:`r_{pb}` is nonzero. The
+    relation between the t-statistic for comparing two independent groups and
+    :math:`r_{pb}` is given by:
+
+    .. math::
+
+        t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
+
+    References
+    ----------
+    .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
+           Statist., Vol. 20, no.1, pp. 125-126, 1949.
+
+    .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
+           Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
+           np. 3, pp. 603-607, 1954.
+
+    .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
+           Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
+           :doi:`10.1002/9781118445112.stat06227`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
+    >>> b = np.arange(7)
+    >>> stats.pointbiserialr(a, b)
+    (0.8660254037844386, 0.011724811003954652)
+    >>> stats.pearsonr(a, b)
+    (0.86602540378443871, 0.011724811003954626)
+    >>> np.corrcoef(a, b)
+    array([[ 1.       ,  0.8660254],
+           [ 0.8660254,  1.       ]])
+
+    """
+    rpb, prob = pearsonr(x, y)
+    # create result object with alias for backward compatibility
+    res = SignificanceResult(rpb, prob)
+    res.correlation = rpb
+    return res
+
+
+def kendalltau(x, y, *, nan_policy='propagate',
+               method='auto', variant='b', alternative='two-sided'):
+    r"""Calculate Kendall's tau, a correlation measure for ordinal data.
+
+    Kendall's tau is a measure of the correspondence between two rankings.
+    Values close to 1 indicate strong agreement, and values close to -1
+    indicate strong disagreement. This implements two variants of Kendall's
+    tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
+    differ only in how they are normalized to lie within the range -1 to 1;
+    the hypothesis tests (their p-values) are identical. Kendall's original
+    tau-a is not implemented separately because both tau-b and tau-c reduce
+    to tau-a in the absence of ties.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of rankings, of the same shape. If arrays are not 1-D, they
+        will be flattened to 1-D.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Defines which method is used to calculate the p-value [5]_.
+        The following options are available (default is 'auto'):
+
+        * 'auto': selects the appropriate method based on a trade-off
+          between speed and accuracy
+        * 'asymptotic': uses a normal approximation valid for large samples
+        * 'exact': computes the exact p-value, but can only be used if no ties
+          are present. As the sample size increases, the 'exact' computation
+          time may grow and the result may lose some precision.
+
+    variant : {'b', 'c'}, optional
+        Defines which variant of Kendall's tau is returned. Default is 'b'.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater': the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The tau statistic.
+        pvalue : float
+           The p-value for a hypothesis test whose null hypothesis is
+           an absence of association, tau = 0.
+
+    Raises
+    ------
+    ValueError
+        If `nan_policy` is 'omit' and `variant` is not 'b' or
+        if `method` is 'exact' and there are ties between `x` and `y`.
+
+    See Also
+    --------
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
+    weightedtau : Computes a weighted version of Kendall's tau.
+    :ref:`hypothesis_kendalltau` : Extended example
+
+    Notes
+    -----
+    The definition of Kendall's tau that is used is [2]_::
+
+      tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
+
+      tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
+
+    where P is the number of concordant pairs, Q the number of discordant
+    pairs, T the number of ties only in `x`, and U the number of ties only in
+    `y`.  If a tie occurs for the same pair in both `x` and `y`, it is not
+    added to either T or U. n is the total number of samples, and m is the
+    number of unique values in either `x` or `y`, whichever is smaller.
+
+    References
+    ----------
+    .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
+           Vol. 30, No. 1/2, pp. 81-93, 1938.
+    .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
+           Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
+    .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
+           Wiley & Sons, 1967.
+    .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
+           tables", Software: Practice and Experience, Vol. 24, No. 3,
+           pp. 327-336, 1994.
+    .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
+           Charles Griffin & Co., 1970.
+
+    Examples
+    --------
+
+    >>> from scipy import stats
+    >>> x1 = [12, 2, 1, 12, 2]
+    >>> x2 = [1, 4, 7, 1, 0]
+    >>> res = stats.kendalltau(x1, x2)
+    >>> res.statistic
+    -0.47140452079103173
+    >>> res.pvalue
+    0.2827454599327748
+
+    For a more detailed example, see :ref:`hypothesis_kendalltau`.
+    """
+    x = np.asarray(x).ravel()
+    y = np.asarray(y).ravel()
+
+    if x.size != y.size:
+        raise ValueError("All inputs to `kendalltau` must be of the same "
+                         f"size, found x-size {x.size} and y-size {y.size}")
+    elif not x.size or not y.size:
+        # Return NaN if arrays are empty
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # check both x and y
+    cnx, npx = _contains_nan(x, nan_policy)
+    cny, npy = _contains_nan(y, nan_policy)
+    contains_nan = cnx or cny
+    if npx == 'omit' or npy == 'omit':
+        nan_policy = 'omit'
+
+    if contains_nan and nan_policy == 'propagate':
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    elif contains_nan and nan_policy == 'omit':
+        x = ma.masked_invalid(x)
+        y = ma.masked_invalid(y)
+        if variant == 'b':
+            return mstats_basic.kendalltau(x, y, method=method, use_ties=True,
+                                           alternative=alternative)
+        else:
+            message = ("nan_policy='omit' is currently compatible only with "
+                       "variant='b'.")
+            raise ValueError(message)
+
+    def count_rank_tie(ranks):
+        cnt = np.bincount(ranks).astype('int64', copy=False)
+        cnt = cnt[cnt > 1]
+        # Python ints to avoid overflow down the line
+        return (int((cnt * (cnt - 1) // 2).sum()),
+                int((cnt * (cnt - 1.) * (cnt - 2)).sum()),
+                int((cnt * (cnt - 1.) * (2*cnt + 5)).sum()))
+
+    size = x.size
+    perm = np.argsort(y)  # sort on y and convert y to dense ranks
+    x, y = x[perm], y[perm]
+    y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
+
+    # stable sort on x and convert x to dense ranks
+    perm = np.argsort(x, kind='mergesort')
+    x, y = x[perm], y[perm]
+    x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
+
+    dis = _kendall_dis(x, y)  # discordant pairs
+
+    obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
+    cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
+
+    ntie = int((cnt * (cnt - 1) // 2).sum())  # joint ties
+    xtie, x0, x1 = count_rank_tie(x)     # ties in x, stats
+    ytie, y0, y1 = count_rank_tie(y)     # ties in y, stats
+
+    tot = (size * (size - 1)) // 2
+
+    if xtie == tot or ytie == tot:
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
+    #               = con + dis + xtie + ytie - ntie
+    con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
+    if variant == 'b':
+        tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
+    elif variant == 'c':
+        minclasses = min(len(set(x)), len(set(y)))
+        tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
+    else:
+        raise ValueError(f"Unknown variant of the method chosen: {variant}. "
+                         "variant must be 'b' or 'c'.")
+
+    # Limit range to fix computational errors
+    tau = np.minimum(1., max(-1., tau))
+
+    # The p-value calculation is the same for all variants since the p-value
+    # depends only on con_minus_dis.
+    if method == 'exact' and (xtie != 0 or ytie != 0):
+        raise ValueError("Ties found, exact method cannot be used.")
+
+    if method == 'auto':
+        if (xtie == 0 and ytie == 0) and (size <= 33 or
+                                          min(dis, tot-dis) <= 1):
+            method = 'exact'
+        else:
+            method = 'asymptotic'
+
+    if xtie == 0 and ytie == 0 and method == 'exact':
+        pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative)
+    elif method == 'asymptotic':
+        # con_minus_dis is approx normally distributed with this variance [3]_
+        m = size * (size - 1.)
+        var = ((m * (2*size + 5) - x1 - y1) / 18 +
+               (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
+        z = con_minus_dis / np.sqrt(var)
+        pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    else:
+        raise ValueError(f"Unknown method {method} specified.  Use 'auto', "
+                         "'exact' or 'asymptotic'.")
+
+    # create result object with alias for backward compatibility
+    res = SignificanceResult(tau[()], pvalue[()])
+    res.correlation = tau[()]
+    return res
+
+
+def weightedtau(x, y, rank=True, weigher=None, additive=True):
+    r"""Compute a weighted version of Kendall's :math:`\tau`.
+
+    The weighted :math:`\tau` is a weighted version of Kendall's
+    :math:`\tau` in which exchanges of high weight are more influential than
+    exchanges of low weight. The default parameters compute the additive
+    hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
+    been shown to provide the best balance between important and
+    unimportant elements [1]_.
+
+    The weighting is defined by means of a rank array, which assigns a
+    nonnegative rank to each element (higher importance ranks being
+    associated with smaller values, e.g., 0 is the highest possible rank),
+    and a weigher function, which assigns a weight based on the rank to
+    each element. The weight of an exchange is then the sum or the product
+    of the weights of the ranks of the exchanged elements. The default
+    parameters compute :math:`\tau_\mathrm h`: an exchange between
+    elements with rank :math:`r` and :math:`s` (starting from zero) has
+    weight :math:`1/(r+1) + 1/(s+1)`.
+
+    Specifying a rank array is meaningful only if you have in mind an
+    external criterion of importance. If, as it usually happens, you do
+    not have in mind a specific rank, the weighted :math:`\tau` is
+    defined by averaging the values obtained using the decreasing
+    lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
+    behavior with default parameters. Note that the convention used
+    here for ranking (lower values imply higher importance) is opposite
+    to that used by other SciPy statistical functions.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of scores, of the same shape. If arrays are not 1-D, they will
+        be flattened to 1-D.
+    rank : array_like of ints or bool, optional
+        A nonnegative rank assigned to each element. If it is None, the
+        decreasing lexicographical rank by (`x`, `y`) will be used: elements of
+        higher rank will be those with larger `x`-values, using `y`-values to
+        break ties (in particular, swapping `x` and `y` will give a different
+        result). If it is False, the element indices will be used
+        directly as ranks. The default is True, in which case this
+        function returns the average of the values obtained using the
+        decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
+    weigher : callable, optional
+        The weigher function. Must map nonnegative integers (zero
+        representing the most important element) to a nonnegative weight.
+        The default, None, provides hyperbolic weighing, that is,
+        rank :math:`r` is mapped to weight :math:`1/(r+1)`.
+    additive : bool, optional
+        If True, the weight of an exchange is computed by adding the
+        weights of the ranks of the exchanged elements; otherwise, the weights
+        are multiplied. The default is True.
+
+    Returns
+    -------
+    res: SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The weighted :math:`\tau` correlation index.
+        pvalue : float
+           Presently ``np.nan``, as the null distribution of the statistic is
+           unknown (even in the additive hyperbolic case).
+
+    See Also
+    --------
+    kendalltau : Calculates Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
+
+    Notes
+    -----
+    This function uses an :math:`O(n \log n)`, mergesort-based algorithm
+    [1]_ that is a weighted extension of Knight's algorithm for Kendall's
+    :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
+    between rankings without ties (i.e., permutations) by setting
+    `additive` and `rank` to False, as the definition given in [1]_ is a
+    generalization of Shieh's.
+
+    NaNs are considered the smallest possible score.
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
+           ties", Proceedings of the 24th international conference on World
+           Wide Web, pp. 1166-1176, ACM, 2015.
+    .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
+           Ungrouped Data", Journal of the American Statistical Association,
+           Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
+    .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
+           Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> res = stats.weightedtau(x, y)
+    >>> res.statistic
+    -0.56694968153682723
+    >>> res.pvalue
+    nan
+    >>> res = stats.weightedtau(x, y, additive=False)
+    >>> res.statistic
+    -0.62205716951801038
+
+    NaNs are considered the smallest possible score:
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, np.nan]
+    >>> res = stats.weightedtau(x, y)
+    >>> res.statistic
+    -0.56694968153682723
+
+    This is exactly Kendall's tau:
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> res = stats.weightedtau(x, y, weigher=lambda x: 1)
+    >>> res.statistic
+    -0.47140452079103173
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> stats.weightedtau(x, y, rank=None)
+    SignificanceResult(statistic=-0.4157652301037516, pvalue=nan)
+    >>> stats.weightedtau(y, x, rank=None)
+    SignificanceResult(statistic=-0.7181341329699028, pvalue=nan)
+
+    """
+    x = np.asarray(x).ravel()
+    y = np.asarray(y).ravel()
+
+    if x.size != y.size:
+        raise ValueError("All inputs to `weightedtau` must be "
+                         "of the same size, "
+                         f"found x-size {x.size} and y-size {y.size}")
+    if not x.size:
+        # Return NaN if arrays are empty
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # If there are NaNs we apply _toint64()
+    if np.isnan(np.sum(x)):
+        x = _toint64(x)
+    if np.isnan(np.sum(y)):
+        y = _toint64(y)
+
+    # Reduce to ranks unsupported types
+    if x.dtype != y.dtype:
+        if x.dtype != np.int64:
+            x = _toint64(x)
+        if y.dtype != np.int64:
+            y = _toint64(y)
+    else:
+        if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
+            x = _toint64(x)
+            y = _toint64(y)
+
+    if rank is True:
+        tau = (
+            _weightedrankedtau(x, y, None, weigher, additive) +
+            _weightedrankedtau(y, x, None, weigher, additive)
+        ) / 2
+        res = SignificanceResult(tau, np.nan)
+        res.correlation = tau
+        return res
+
+    if rank is False:
+        rank = np.arange(x.size, dtype=np.intp)
+    elif rank is not None:
+        rank = np.asarray(rank).ravel()
+        if rank.size != x.size:
+            raise ValueError(
+                "All inputs to `weightedtau` must be of the same size, "
+                f"found x-size {x.size} and rank-size {rank.size}"
+            )
+
+    tau = _weightedrankedtau(x, y, rank, weigher, additive)
+    res = SignificanceResult(tau, np.nan)
+    res.correlation = tau
+    return res
+
+
+#####################################
+#       INFERENTIAL STATISTICS      #
+#####################################
+
+TtestResultBase = _make_tuple_bunch('TtestResultBase',
+                                    ['statistic', 'pvalue'], ['df'])
+
+
+class TtestResult(TtestResultBase):
+    """
+    Result of a t-test.
+
+    See the documentation of the particular t-test function for more
+    information about the definition of the statistic and meaning of
+    the confidence interval.
+
+    Attributes
+    ----------
+    statistic : float or array
+        The t-statistic of the sample.
+    pvalue : float or array
+        The p-value associated with the given alternative.
+    df : float or array
+        The number of degrees of freedom used in calculation of the
+        t-statistic; this is one less than the size of the sample
+        (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs).
+
+    Methods
+    -------
+    confidence_interval
+        Computes a confidence interval around the population statistic
+        for the given confidence level.
+        The confidence interval is returned in a ``namedtuple`` with
+        fields `low` and `high`.
+
+    """
+
+    def __init__(self, statistic, pvalue, df,  # public
+                 alternative, standard_error, estimate,  # private
+                 statistic_np=None, xp=None):  # private
+        super().__init__(statistic, pvalue, df=df)
+        self._alternative = alternative
+        self._standard_error = standard_error  # denominator of t-statistic
+        self._estimate = estimate  # point estimate of sample mean
+        self._statistic_np = statistic if statistic_np is None else statistic_np
+        self._dtype = statistic.dtype
+        self._xp = array_namespace(statistic, pvalue) if xp is None else xp
+
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Parameters
+        ----------
+        confidence_level : float
+            The confidence level for the calculation of the population mean
+            confidence interval. Default is 0.95.
+
+        Returns
+        -------
+        ci : namedtuple
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+        """
+        low, high = _t_confidence_interval(self.df, self._statistic_np,
+                                           confidence_level, self._alternative,
+                                           self._dtype, self._xp)
+        low = low * self._standard_error + self._estimate
+        high = high * self._standard_error + self._estimate
+        return ConfidenceInterval(low=low, high=high)
+
+
+def pack_TtestResult(statistic, pvalue, df, alternative, standard_error,
+                     estimate):
+    # this could be any number of dimensions (including 0d), but there is
+    # at most one unique non-NaN value
+    alternative = np.atleast_1d(alternative)  # can't index 0D object
+    alternative = alternative[np.isfinite(alternative)]
+    alternative = alternative[0] if alternative.size else np.nan
+    return TtestResult(statistic, pvalue, df=df, alternative=alternative,
+                       standard_error=standard_error, estimate=estimate)
+
+
+def unpack_TtestResult(res):
+    return (res.statistic, res.pvalue, res.df, res._alternative,
+            res._standard_error, res._estimate)
+
+
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def ttest_1samp(a, popmean, axis=0, nan_policy="propagate", alternative="two-sided"):
+    """Calculate the T-test for the mean of ONE group of scores.
+
+    This is a test for the null hypothesis that the expected value
+    (mean) of a sample of independent observations `a` is equal to the given
+    population mean, `popmean`.
+
+    Parameters
+    ----------
+    a : array_like
+        Sample observations.
+    popmean : float or array_like
+        Expected value in null hypothesis. If array_like, then its length along
+        `axis` must equal 1, and it must otherwise be broadcastable with `a`.
+    axis : int or None, optional
+        Axis along which to compute test; default is 0. If None, compute over
+        the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the mean of the underlying distribution of the sample
+          is different than the given population mean (`popmean`)
+        * 'less': the mean of the underlying distribution of the sample is
+          less than the given population mean (`popmean`)
+        * 'greater': the mean of the underlying distribution of the sample is
+          greater than the given population mean (`popmean`)
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or array
+            The t-statistic.
+        pvalue : float or array
+            The p-value associated with the given alternative.
+        df : float or array
+            The number of degrees of freedom used in calculation of the
+            t-statistic; this is one less than the size of the sample
+            (``a.shape[axis]``).
+
+            .. versionadded:: 1.10.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the population
+            mean for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+            .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    The statistic is calculated as ``(np.mean(a) - popmean)/se``, where
+    ``se`` is the standard error. Therefore, the statistic will be positive
+    when the sample mean is greater than the population mean and negative when
+    the sample mean is less than the population mean.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that the mean of a population
+    is equal to 0.5. We choose a confidence level of 99%; that is, we will
+    reject the null hypothesis in favor of the alternative if the p-value is
+    less than 0.01.
+
+    When testing random variates from the standard uniform distribution, which
+    has a mean of 0.5, we expect the data to be consistent with the null
+    hypothesis most of the time.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> rvs = stats.uniform.rvs(size=50, random_state=rng)
+    >>> stats.ttest_1samp(rvs, popmean=0.5)
+    TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49)
+
+    As expected, the p-value of 0.017 is not below our threshold of 0.01, so
+    we cannot reject the null hypothesis.
+
+    When testing data from the standard *normal* distribution, which has a mean
+    of 0, we would expect the null hypothesis to be rejected.
+
+    >>> rvs = stats.norm.rvs(size=50, random_state=rng)
+    >>> stats.ttest_1samp(rvs, popmean=0.5)
+    TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49)
+
+    Indeed, the p-value is lower than our threshold of 0.01, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the mean
+    of the population is *not* equal to 0.5.
+
+    However, suppose we were to test the null hypothesis against the
+    one-sided alternative that the mean of the population is *greater* than
+    0.5. Since the mean of the standard normal is less than 0.5, we would not
+    expect the null hypothesis to be rejected.
+
+    >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater')
+    TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49)
+
+    Unsurprisingly, with a p-value greater than our threshold, we would not
+    reject the null hypothesis.
+
+    Note that when working with a confidence level of 99%, a true null
+    hypothesis will be rejected approximately 1% of the time.
+
+    >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1)
+    >>> np.sum(res.pvalue < 0.01)
+    1
+
+    Indeed, even though all 100 samples above were drawn from the standard
+    uniform distribution, which *does* have a population mean of 0.5, we would
+    mistakenly reject the null hypothesis for one of them.
+
+    `ttest_1samp` can also compute a confidence interval around the population
+    mean.
+
+    >>> rvs = stats.norm.rvs(size=50, random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0)
+    >>> ci = res.confidence_interval(confidence_level=0.95)
+    >>> ci
+    ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972)
+
+    The bounds of the 95% confidence interval are the
+    minimum and maximum values of the parameter `popmean` for which the
+    p-value of the test would be 0.05.
+
+    >>> res = stats.ttest_1samp(rvs, popmean=ci.low)
+    >>> np.testing.assert_allclose(res.pvalue, 0.05)
+    >>> res = stats.ttest_1samp(rvs, popmean=ci.high)
+    >>> np.testing.assert_allclose(res.pvalue, 0.05)
+
+    Under certain assumptions about the population from which a sample
+    is drawn, the confidence interval with confidence level 95% is expected
+    to contain the true population mean in 95% of sample replications.
+
+    >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0)
+    >>> ci = res.confidence_interval()
+    >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1)
+    >>> contains_pop_mean.sum()
+    953
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+    df = n - 1
+
+    if n == 0:
+        # This is really only needed for *testing* _axis_nan_policy decorator
+        # It won't happen when the decorator is used.
+        NaN = _get_nan(a)
+        return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
+                           standard_error=NaN, estimate=NaN)
+
+    mean = xp.mean(a, axis=axis)
+    try:
+        popmean = xp.asarray(popmean)
+        popmean = xp.squeeze(popmean, axis=axis) if popmean.ndim > 0 else popmean
+    except ValueError as e:
+        raise ValueError("`popmean.shape[axis]` must equal 1.") from e
+    d = mean - popmean
+    v = _var(a, axis=axis, ddof=1)
+    denom = xp.sqrt(v / n)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = xp.divide(d, denom)
+        t = t[()] if t.ndim == 0 else t
+
+    dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype))
+    prob = _get_pvalue(t, dist, alternative, xp=xp)
+    prob = prob[()] if prob.ndim == 0 else prob
+
+    # when nan_policy='omit', `df` can be different for different axis-slices
+    df = xp.broadcast_to(xp.asarray(df), t.shape)
+    df = df[()] if df.ndim == 0 else df
+    # _axis_nan_policy decorator doesn't play well with strings
+    alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative]
+    return TtestResult(t, prob, df=df, alternative=alternative_num,
+                       standard_error=denom, estimate=mean,
+                       statistic_np=xp.asarray(t), xp=xp)
+
+
+def _t_confidence_interval(df, t, confidence_level, alternative, dtype=None, xp=None):
+    # Input validation on `alternative` is already done
+    # We just need IV on confidence_level
+    dtype = t.dtype if dtype is None else dtype
+    xp = array_namespace(t) if xp is None else xp
+
+    # stdtrit not dispatched yet; use NumPy
+    df, t = np.asarray(df), np.asarray(t)
+
+    if confidence_level < 0 or confidence_level > 1:
+        message = "`confidence_level` must be a number between 0 and 1."
+        raise ValueError(message)
+
+    if alternative < 0:  # 'less'
+        p = confidence_level
+        low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p))
+    elif alternative > 0:  # 'greater'
+        p = 1 - confidence_level
+        low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf)
+    elif alternative == 0:  # 'two-sided'
+        tail_probability = (1 - confidence_level)/2
+        p = tail_probability, 1-tail_probability
+        # axis of p must be the zeroth and orthogonal to all the rest
+        p = np.reshape(p, [2] + [1]*np.asarray(df).ndim)
+        low, high = special.stdtrit(df, p)
+    else:  # alternative is NaN when input is empty (see _axis_nan_policy)
+        p, nans = np.broadcast_arrays(t, np.nan)
+        low, high = nans, nans
+
+    low = xp.asarray(low, dtype=dtype)
+    low = low[()] if low.ndim == 0 else low
+    high = xp.asarray(high, dtype=dtype)
+    high = high[()] if high.ndim == 0 else high
+    return low, high
+
+
+def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative, xp=None):
+    xp = array_namespace(mean1, mean2, denom) if xp is None else xp
+
+    d = mean1 - mean2
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = xp.divide(d, denom)
+
+    t_np = np.asarray(t)
+    df_np = np.asarray(df)
+    prob = _get_pvalue(t_np, distributions.t(df_np), alternative, xp=np)
+    prob = xp.asarray(prob, dtype=t.dtype)
+
+    t = t[()] if t.ndim == 0 else t
+    prob = prob[()] if prob.ndim == 0 else prob
+    return t, prob
+
+
+def _unequal_var_ttest_denom(v1, n1, v2, n2, xp=None):
+    xp = array_namespace(v1, v2) if xp is None else xp
+    vn1 = v1 / n1
+    vn2 = v2 / n2
+    with np.errstate(divide='ignore', invalid='ignore'):
+        df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
+
+    # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
+    # Hence it doesn't matter what df is as long as it's not NaN.
+    df = xp.where(xp.isnan(df), xp.asarray(1.), df)
+    denom = xp.sqrt(vn1 + vn2)
+    return df, denom
+
+
+def _equal_var_ttest_denom(v1, n1, v2, n2, xp=None):
+    xp = array_namespace(v1, v2) if xp is None else xp
+
+    # If there is a single observation in one sample, this formula for pooled
+    # variance breaks down because the variance of that sample is undefined.
+    # The pooled variance is still defined, though, because the (n-1) in the
+    # numerator should cancel with the (n-1) in the denominator, leaving only
+    # the sum of squared differences from the mean: zero.
+    zero = xp.asarray(0.)
+    v1 = xp.where(xp.asarray(n1 == 1), zero, v1)
+    v2 = xp.where(xp.asarray(n2 == 1), zero, v2)
+
+    df = n1 + n2 - 2.0
+    svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
+    denom = xp.sqrt(svar * (1.0 / n1 + 1.0 / n2))
+    return df, denom
+
+
+Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
+
+
+def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
+                         equal_var=True, alternative="two-sided"):
+    r"""
+    T-test for means of two independent samples from descriptive statistics.
+
+    This is a test for the null hypothesis that two independent
+    samples have identical average (expected) values.
+
+    Parameters
+    ----------
+    mean1 : array_like
+        The mean(s) of sample 1.
+    std1 : array_like
+        The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``).
+    nobs1 : array_like
+        The number(s) of observations of sample 1.
+    mean2 : array_like
+        The mean(s) of sample 2.
+    std2 : array_like
+        The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``).
+    nobs2 : array_like
+        The number(s) of observations of sample 2.
+    equal_var : bool, optional
+        If True (default), perform a standard independent 2 sample test
+        that assumes equal population variances [1]_.
+        If False, perform Welch's t-test, which does not assume equal
+        population variance [2]_.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions are unequal.
+        * 'less': the mean of the first distribution is less than the
+          mean of the second distribution.
+        * 'greater': the mean of the first distribution is greater than the
+          mean of the second distribution.
+
+        .. versionadded:: 1.6.0
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistics.
+    pvalue : float or array
+        The two-tailed p-value.
+
+    See Also
+    --------
+    scipy.stats.ttest_ind
+
+    Notes
+    -----
+    The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the
+    standard error. Therefore, the statistic will be positive when `mean1` is
+    greater than `mean2` and negative when `mean1` is less than `mean2`.
+
+    This method does not check whether any of the elements of `std1` or `std2`
+    are negative. If any elements of the `std1` or `std2` parameters are
+    negative in a call to this method, this method will return the same result
+    as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``,
+    respectively, instead; no exceptions or warnings will be emitted.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
+
+    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
+
+    Examples
+    --------
+    Suppose we have the summary data for two samples, as follows (with the
+    Sample Variance being the corrected sample variance)::
+
+                         Sample   Sample
+                   Size   Mean   Variance
+        Sample 1    13    15.0     87.5
+        Sample 2    11    12.0     39.0
+
+    Apply the t-test to this data (with the assumption that the population
+    variances are equal):
+
+    >>> import numpy as np
+    >>> from scipy.stats import ttest_ind_from_stats
+    >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
+    ...                      mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
+    Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
+
+    For comparison, here is the data from which those summary statistics
+    were taken.  With this data, we can compute the same result using
+    `scipy.stats.ttest_ind`:
+
+    >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
+    >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
+    >>> from scipy.stats import ttest_ind
+    >>> ttest_ind(a, b)
+    TtestResult(statistic=0.905135809331027,
+                pvalue=0.3751996797581486,
+                df=22.0)
+
+    Suppose we instead have binary data and would like to apply a t-test to
+    compare the proportion of 1s in two independent groups::
+
+                          Number of    Sample     Sample
+                    Size    ones        Mean     Variance
+        Sample 1    150      30         0.2        0.161073
+        Sample 2    200      45         0.225      0.175251
+
+    The sample mean :math:`\hat{p}` is the proportion of ones in the sample
+    and the variance for a binary observation is estimated by
+    :math:`\hat{p}(1-\hat{p})`.
+
+    >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150,
+    ...                      mean2=0.225, std2=np.sqrt(0.175251), nobs2=200)
+    Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541)
+
+    For comparison, we could compute the t statistic and p-value using
+    arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
+
+    >>> group1 = np.array([1]*30 + [0]*(150-30))
+    >>> group2 = np.array([1]*45 + [0]*(200-45))
+    >>> ttest_ind(group1, group2)
+    TtestResult(statistic=-0.5627179589855622,
+                pvalue=0.573989277115258,
+                df=348.0)
+
+    """
+    xp = array_namespace(mean1, std1, mean2, std2)
+
+    mean1 = xp.asarray(mean1)
+    std1 = xp.asarray(std1)
+    mean2 = xp.asarray(mean2)
+    std2 = xp.asarray(std2)
+
+    if equal_var:
+        df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
+    else:
+        df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
+
+    res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
+    return Ttest_indResult(*res)
+
+
+_ttest_ind_dep_msg = "Use ``method`` to perform a permutation test."
+@_deprecate_positional_args(version='1.17.0',
+                            deprecated_args={'permutations', 'random_state'},
+                            custom_message=_ttest_ind_dep_msg)
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6)
+def ttest_ind(a, b, *, axis=0, equal_var=True, nan_policy='propagate',
+              permutations=None, random_state=None, alternative="two-sided",
+              trim=0, method=None):
+    """
+    Calculate the T-test for the means of *two independent* samples of scores.
+
+    This is a test for the null hypothesis that 2 independent samples
+    have identical average (expected) values. This test assumes that the
+    populations have identical variances by default.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape, except in the dimension
+        corresponding to `axis` (the first, by default).
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    equal_var : bool, optional
+        If True (default), perform a standard independent 2 sample test
+        that assumes equal population variances [1]_.
+        If False, perform Welch's t-test, which does not assume equal
+        population variance [2]_.
+
+        .. versionadded:: 0.11.0
+
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+        The 'omit' option is not currently available for permutation tests or
+        one-sided asymptotic tests.
+
+    permutations : non-negative int, np.inf, or None (default), optional
+        If 0 or None (default), use the t-distribution to calculate p-values.
+        Otherwise, `permutations` is  the number of random permutations that
+        will be used to estimate p-values using a permutation test. If
+        `permutations` equals or exceeds the number of distinct partitions of
+        the pooled data, an exact test is performed instead (i.e. each
+        distinct partition is used exactly once). See Notes for details.
+
+        .. deprecated:: 1.17.0
+            `permutations` is deprecated and will be removed in SciPy 1.7.0.
+            Use the `n_resamples` argument of `PermutationMethod`, instead,
+            and pass the instance as the `method` argument.
+
+    random_state : {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.
+
+        Pseudorandom number generator state used to generate permutations
+        (used only when `permutations` is not None).
+
+        .. deprecated:: 1.17.0
+            `random_state` is deprecated and will be removed in SciPy 1.7.0.
+            Use the `rng` argument of `PermutationMethod`, instead,
+            and pass the instance as the `method` argument.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+    trim : float, optional
+        If nonzero, performs a trimmed (Yuen's) t-test.
+        Defines the fraction of elements to be trimmed from each end of the
+        input samples. If 0 (default), no elements will be trimmed from either
+        side. The number of trimmed elements from each tail is the floor of the
+        trim times the number of elements. Valid range is [0, .5).
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
+        computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed by comparing the test statistic
+        against a theoretical t-distribution.
+
+        .. versionadded:: 1.15.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or ndarray
+            The t-statistic.
+        pvalue : float or ndarray
+            The p-value associated with the given alternative.
+        df : float or ndarray
+            The number of degrees of freedom used in calculation of the
+            t-statistic. This is always NaN for a permutation t-test.
+
+            .. versionadded:: 1.11.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the difference in
+            population means for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields ``low`` and ``high``.
+            When a permutation t-test is performed, the confidence interval
+            is not computed, and fields ``low`` and ``high`` contain NaN.
+
+            .. versionadded:: 1.11.0
+
+    Notes
+    -----
+    Suppose we observe two independent samples, e.g. flower petal lengths, and
+    we are considering whether the two samples were drawn from the same
+    population (e.g. the same species of flower or two species with similar
+    petal characteristics) or two different populations.
+
+    The t-test quantifies the difference between the arithmetic means
+    of the two samples. The p-value quantifies the probability of observing
+    as or more extreme values assuming the null hypothesis, that the
+    samples are drawn from populations with the same population means, is true.
+    A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
+    our observation is not so unlikely to have occurred by chance. Therefore,
+    we do not reject the null hypothesis of equal population means.
+    If the p-value is smaller than our threshold, then we have evidence
+    against the null hypothesis of equal population means.
+
+    By default, the p-value is determined by comparing the t-statistic of the
+    observed data against a theoretical t-distribution.
+
+    (In the following, note that the argument `permutations` itself is
+    deprecated, but a nearly identical test may be performed by creating
+    an instance of `scipy.stats.PermutationMethod` with ``n_resamples=permutuations``
+    and passing it as the `method` argument.)
+    When ``1 < permutations < binom(n, k)``, where
+
+    * ``k`` is the number of observations in `a`,
+    * ``n`` is the total number of observations in `a` and `b`, and
+    * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
+
+    the data are pooled (concatenated), randomly assigned to either group `a`
+    or `b`, and the t-statistic is calculated. This process is performed
+    repeatedly (`permutation` times), generating a distribution of the
+    t-statistic under the null hypothesis, and the t-statistic of the observed
+    data is compared to this distribution to determine the p-value.
+    Specifically, the p-value reported is the "achieved significance level"
+    (ASL) as defined in 4.4 of [3]_. Note that there are other ways of
+    estimating p-values using randomized permutation tests; for other
+    options, see the more general `permutation_test`.
+
+    When ``permutations >= binom(n, k)``, an exact test is performed: the data
+    are partitioned between the groups in each distinct way exactly once.
+
+    The permutation test can be computationally expensive and not necessarily
+    more accurate than the analytical test, but it does not make strong
+    assumptions about the shape of the underlying distribution.
+
+    Use of trimming is commonly referred to as the trimmed t-test. At times
+    called Yuen's t-test, this is an extension of Welch's t-test, with the
+    difference being the use of winsorized means in calculation of the variance
+    and the trimmed sample size in calculation of the statistic. Trimming is
+    recommended if the underlying distribution is long-tailed or contaminated
+    with outliers [4]_.
+
+    The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where
+    ``se`` is the standard error. Therefore, the statistic will be positive
+    when the sample mean of `a` is greater than the sample mean of `b` and
+    negative when the sample mean of `a` is less than the sample mean of
+    `b`.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
+
+    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
+
+    .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016).
+
+    .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population
+           Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR,
+           www.jstor.org/stable/2334299. Accessed 30 Mar. 2021.
+
+    .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and
+           Performance of the Two-Sample Trimmed t." Biometrika, vol. 60,
+           no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550.
+           Accessed 30 Mar. 2021.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Test with sample with identical means:
+
+    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs2)
+    TtestResult(statistic=-0.4390847099199348,
+                pvalue=0.6606952038870015,
+                df=998.0)
+    >>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
+    TtestResult(statistic=-0.4390847099199348,
+                pvalue=0.6606952553131064,
+                df=997.4602304121448)
+
+    `ttest_ind` underestimates p for unequal variances:
+
+    >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs3)
+    TtestResult(statistic=-1.6370984482905417,
+                pvalue=0.1019251574705033,
+                df=998.0)
+    >>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
+    TtestResult(statistic=-1.637098448290542,
+                pvalue=0.10202110497954867,
+                df=765.1098655246868)
+
+    When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
+    unequal variance t-statistic:
+
+    >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs4)
+    TtestResult(statistic=-1.9481646859513422,
+                pvalue=0.05186270935842703,
+                df=598.0)
+    >>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
+    TtestResult(statistic=-1.3146566100751664,
+                pvalue=0.1913495266513811,
+                df=110.41349083985212)
+
+    T-test with different means, variance, and n:
+
+    >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs5)
+    TtestResult(statistic=-2.8415950600298774,
+                pvalue=0.0046418707568707885,
+                df=598.0)
+    >>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
+    TtestResult(statistic=-1.8686598649188084,
+                pvalue=0.06434714193919686,
+                df=109.32167496550137)
+
+    Take these two samples, one of which has an extreme tail.
+
+    >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3)
+    >>> b = (1.1, 2.9, 4.2)
+
+    Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example,
+    using 20% trimming, ``trim=.2``, the test will reduce the impact of one
+    (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will
+    have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0.
+
+    >>> stats.ttest_ind(a, b, trim=.2)
+    TtestResult(statistic=3.4463884028073513,
+                pvalue=0.01369338726499547,
+                df=6.0)
+    """
+    xp = array_namespace(a, b)
+
+    default_float = xp.asarray(1.).dtype
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.astype(a, default_float)
+    if xp.isdtype(b.dtype, 'integral'):
+        b = xp.astype(b, default_float)
+
+    if not (0 <= trim < .5):
+        raise ValueError("Trimming percentage should be 0 <= `trim` < .5.")
+
+    if not isinstance(method, PermutationMethod | MonteCarloMethod | None):
+        message = ("`method` must be an instance of `PermutationMethod`, an instance "
+                   "of `MonteCarloMethod`, or None (default).")
+        raise ValueError(message)
+
+    if not is_numpy(xp) and method is not None:
+        message = "Use of resampling methods is compatible only with NumPy arrays."
+        raise NotImplementedError(message)
+
+    result_shape = _broadcast_array_shapes_remove_axis((a, b), axis=axis)
+    NaN = xp.full(result_shape, _get_nan(a, b, xp=xp))
+    NaN = NaN[()] if NaN.ndim == 0 else NaN
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
+                           standard_error=NaN, estimate=NaN)
+
+    alternative_nums = {"less": -1, "two-sided": 0, "greater": 1}
+
+    # This probably should be deprecated and replaced with a `method` argument
+    if permutations is not None and permutations != 0:
+        message = "Use of `permutations` is compatible only with NumPy arrays."
+        if not is_numpy(xp):
+            raise NotImplementedError(message)
+
+        message = "Use of `permutations` is incompatible with with use of `trim`."
+        if trim != 0:
+            raise NotImplementedError(message)
+
+        t, prob = _permutation_ttest(a, b, permutations=permutations,
+                                     axis=axis, equal_var=equal_var,
+                                     nan_policy=nan_policy,
+                                     random_state=random_state,
+                                     alternative=alternative)
+        df, denom, estimate = NaN, NaN, NaN
+
+        # _axis_nan_policy decorator doesn't play well with strings
+        return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative],
+                           standard_error=denom, estimate=estimate)
+
+    n1 = xp.asarray(a.shape[axis], dtype=a.dtype)
+    n2 = xp.asarray(b.shape[axis], dtype=b.dtype)
+
+    if trim == 0:
+        with np.errstate(divide='ignore', invalid='ignore'):
+            v1 = _var(a, axis, ddof=1, xp=xp)
+            v2 = _var(b, axis, ddof=1, xp=xp)
+
+        m1 = xp.mean(a, axis=axis)
+        m2 = xp.mean(b, axis=axis)
+    else:
+        message = "Use of `trim` is compatible only with NumPy arrays."
+        if not is_numpy(xp):
+            raise NotImplementedError(message)
+
+        v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis)
+        v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis)
+
+    if equal_var:
+        df, denom = _equal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
+    else:
+        df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
+
+    if method is None:
+        t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative)
+    else:
+        # nan_policy is taken care of by axis_nan_policy decorator
+        ttest_kwargs = dict(equal_var=equal_var, trim=trim)
+        t, prob = _ttest_resampling(a, b, axis, alternative, ttest_kwargs, method)
+
+    # when nan_policy='omit', `df` can be different for different axis-slices
+    df = xp.broadcast_to(df, t.shape)
+    df = df[()] if df.ndim ==0 else df
+    estimate = m1 - m2
+
+    return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative],
+                       standard_error=denom, estimate=estimate)
+
+
+def _ttest_resampling(x, y, axis, alternative, ttest_kwargs, method):
+    def statistic(x, y, axis):
+        return ttest_ind(x, y, axis=axis, **ttest_kwargs).statistic
+
+    test = (permutation_test if isinstance(method, PermutationMethod)
+            else monte_carlo_test)
+    method = method._asdict()
+
+    if test is monte_carlo_test:
+        # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
+        # If the user specified an `rng`, replace it with the default callables
+        if (rng := method.pop('rng', None)) is not None:
+            rng = np.random.default_rng(rng)
+            method['rvs'] = rng.normal, rng.normal
+
+    res = test((x, y,), statistic=statistic, axis=axis,
+               alternative=alternative, **method)
+
+    return res.statistic, res.pvalue
+
+
+def _ttest_trim_var_mean_len(a, trim, axis):
+    """Variance, mean, and length of winsorized input along specified axis"""
+    # for use with `ttest_ind` when trimming.
+    # further calculations in this test assume that the inputs are sorted.
+    # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..."
+    a = np.sort(a, axis=axis)
+
+    # `g` is the number of elements to be replaced on each tail, converted
+    # from a percentage amount of trimming
+    n = a.shape[axis]
+    g = int(n * trim)
+
+    # Calculate the Winsorized variance of the input samples according to
+    # specified `g`
+    v = _calculate_winsorized_variance(a, g, axis)
+
+    # the total number of elements in the trimmed samples
+    n -= 2 * g
+
+    # calculate the g-times trimmed mean, as defined in [4] (1-1)
+    m = trim_mean(a, trim, axis=axis)
+    return v, m, n
+
+
+def _calculate_winsorized_variance(a, g, axis):
+    """Calculates g-times winsorized variance along specified axis"""
+    # it is expected that the input `a` is sorted along the correct axis
+    if g == 0:
+        return _var(a, ddof=1, axis=axis)
+    # move the intended axis to the end that way it is easier to manipulate
+    a_win = np.moveaxis(a, axis, -1)
+
+    # save where NaNs are for later use.
+    nans_indices = np.any(np.isnan(a_win), axis=-1)
+
+    # Winsorization and variance calculation are done in one step in [4]
+    # (1-3), but here winsorization is done first; replace the left and
+    # right sides with the repeating value. This can be see in effect in (
+    # 1-3) in [4], where the leftmost and rightmost tails are replaced with
+    # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the
+    # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in
+    # array indexing.
+    a_win[..., :g] = a_win[..., [g]]
+    a_win[..., -g:] = a_win[..., [-g - 1]]
+
+    # Determine the variance. In [4], the degrees of freedom is expressed as
+    # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of
+    # page 369, beginning of page 370). This is converted to NumPy's format,
+    # `n - ddof` for use with `np.var`. The result is converted to an
+    # array to accommodate indexing later.
+    var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1))
+
+    # with `nan_policy='propagate'`, NaNs may be completely trimmed out
+    # because they were sorted into the tail of the array. In these cases,
+    # replace computed variances with `np.nan`.
+    var_win[nans_indices] = np.nan
+    return var_win
+
+
+def _permutation_distribution_t(data, permutations, size_a, equal_var,
+                                random_state=None):
+    """Generation permutation distribution of t statistic"""
+
+    random_state = check_random_state(random_state)
+
+    # prepare permutation indices
+    size = data.shape[-1]
+    # number of distinct combinations
+    n_max = special.comb(size, size_a)
+
+    if permutations < n_max:
+        perm_generator = (random_state.permutation(size)
+                          for i in range(permutations))
+    else:
+        permutations = n_max
+        perm_generator = (np.concatenate(z)
+                          for z in _all_partitions(size_a, size-size_a))
+
+    t_stat = []
+    for indices in _batch_generator(perm_generator, batch=50):
+        # get one batch from perm_generator at a time as a list
+        indices = np.array(indices)
+        # generate permutations
+        data_perm = data[..., indices]
+        # move axis indexing permutations to position 0 to broadcast
+        # nicely with t_stat_observed, which doesn't have this dimension
+        data_perm = np.moveaxis(data_perm, -2, 0)
+
+        a = data_perm[..., :size_a]
+        b = data_perm[..., size_a:]
+        t_stat.append(_calc_t_stat(a, b, equal_var))
+
+    t_stat = np.concatenate(t_stat, axis=0)
+
+    return t_stat, permutations, n_max
+
+
+def _calc_t_stat(a, b, equal_var, axis=-1):
+    """Calculate the t statistic along the given dimension."""
+    na = a.shape[axis]
+    nb = b.shape[axis]
+    avg_a = np.mean(a, axis=axis)
+    avg_b = np.mean(b, axis=axis)
+    var_a = _var(a, axis=axis, ddof=1)
+    var_b = _var(b, axis=axis, ddof=1)
+
+    if not equal_var:
+        _, denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)
+    else:
+        _, denom = _equal_var_ttest_denom(var_a, na, var_b, nb)
+
+    return (avg_a-avg_b)/denom
+
+
+def _permutation_ttest(a, b, permutations, axis=0, equal_var=True,
+                       nan_policy='propagate', random_state=None,
+                       alternative="two-sided"):
+    """
+    Calculates the T-test for the means of TWO INDEPENDENT samples of scores
+    using permutation methods.
+
+    This test is similar to `stats.ttest_ind`, except it doesn't rely on an
+    approximate normality assumption since it uses a permutation test.
+    This function is only called from ttest_ind when permutations is not None.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must be broadcastable, except along the dimension
+        corresponding to `axis` (the zeroth, by default).
+    axis : int, optional
+        The axis over which to operate on a and b.
+    permutations : int, optional
+        Number of permutations used to calculate p-value. If greater than or
+        equal to the number of distinct permutations, perform an exact test.
+    equal_var : bool, optional
+        If False, an equal variance (Welch's) t-test is conducted.  Otherwise,
+        an ordinary t-test is conducted.
+    random_state : {None, int, `numpy.random.Generator`}, optional
+        If `seed` is None the `numpy.random.Generator` singleton is used.
+        If `seed` is an int, a new ``Generator`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` instance then that instance is
+        used.
+        Pseudorandom number generator state used for generating random
+        permutations.
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistic.
+    pvalue : float or array
+        The p-value.
+
+    """
+    if permutations < 0 or (np.isfinite(permutations) and
+                            int(permutations) != permutations):
+        raise ValueError("Permutations must be a non-negative integer.")
+
+    random_state = check_random_state(random_state)
+
+    t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis)
+
+    na = a.shape[axis]
+    mat = _broadcast_concatenate((a, b), axis=axis)
+    mat = np.moveaxis(mat, axis, -1)
+
+    t_stat, permutations, n_max = _permutation_distribution_t(
+        mat, permutations, size_a=na, equal_var=equal_var,
+        random_state=random_state)
+
+    compare = {"less": np.less_equal,
+               "greater": np.greater_equal,
+               "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))}
+
+    # Calculate the p-values
+    cmps = compare[alternative](t_stat, t_stat_observed)
+    # Randomized test p-value calculation should use biased estimate; see e.g.
+    # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/
+    adjustment = 1 if n_max > permutations else 0
+    pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment)
+
+    # nans propagate naturally in statistic calculation, but need to be
+    # propagated manually into pvalues
+    if nan_policy == 'propagate' and np.isnan(t_stat_observed).any():
+        if np.ndim(pvalues) == 0:
+            pvalues = np.float64(np.nan)
+        else:
+            pvalues[np.isnan(t_stat_observed)] = np.nan
+
+    return (t_stat_observed, pvalues)
+
+
+def _get_len(a, axis, msg):
+    try:
+        n = a.shape[axis]
+    except IndexError:
+        raise AxisError(axis, a.ndim, msg) from None
+    return n
+
+
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6,
+                          paired=True)
+def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
+    """Calculate the t-test on TWO RELATED samples of scores, a and b.
+
+    This is a test for the null hypothesis that two related or
+    repeated samples have identical average (expected) values.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape.
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.6.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or array
+            The t-statistic.
+        pvalue : float or array
+            The p-value associated with the given alternative.
+        df : float or array
+            The number of degrees of freedom used in calculation of the
+            t-statistic; this is one less than the size of the sample
+            (``a.shape[axis]``).
+
+            .. versionadded:: 1.10.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the difference in
+            population means for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+            .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    Examples for use are scores of the same set of student in
+    different exams, or repeated sampling from the same units. The
+    test measures whether the average score differs significantly
+    across samples (e.g. exams). If we observe a large p-value, for
+    example greater than 0.05 or 0.1 then we cannot reject the null
+    hypothesis of identical average scores. If the p-value is smaller
+    than the threshold, e.g. 1%, 5% or 10%, then we reject the null
+    hypothesis of equal averages. Small p-values are associated with
+    large t-statistics.
+
+    The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the
+    standard error. Therefore, the t-statistic will be positive when the sample
+    mean of ``a - b`` is greater than zero and negative when the sample mean of
+    ``a - b`` is less than zero.
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
+    >>> stats.ttest_rel(rvs1, rvs2)
+    TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499)
+    >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng)
+    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
+    >>> stats.ttest_rel(rvs1, rvs3)
+    TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499)
+
+    """
+    return ttest_1samp(a - b, popmean=0, axis=axis, alternative=alternative,
+                       _no_deco=True)
+
+
+# Map from names to lambda_ values used in power_divergence().
+_power_div_lambda_names = {
+    "pearson": 1,
+    "log-likelihood": 0,
+    "freeman-tukey": -0.5,
+    "mod-log-likelihood": -1,
+    "neyman": -2,
+    "cressie-read": 2/3,
+}
+
+
+def _m_count(a, *, axis, xp):
+    """Count the number of non-masked elements of an array.
+
+    This function behaves like `np.ma.count`, but is much faster
+    for ndarrays.
+    """
+    if hasattr(a, 'count'):
+        num = a.count(axis=axis)
+        if isinstance(num, np.ndarray) and num.ndim == 0:
+            # In some cases, the `count` method returns a scalar array (e.g.
+            # np.array(3)), but we want a plain integer.
+            num = int(num)
+    else:
+        if axis is None:
+            num = xp_size(a)
+        else:
+            num = a.shape[axis]
+    return num
+
+
+def _m_broadcast_to(a, shape, *, xp):
+    if np.ma.isMaskedArray(a):
+        return np.ma.masked_array(np.broadcast_to(a, shape),
+                                  mask=np.broadcast_to(a.mask, shape))
+    return xp.broadcast_to(a, shape)
+
+
+def _m_sum(a, *, axis, preserve_mask, xp):
+    if np.ma.isMaskedArray(a):
+        sum = a.sum(axis)
+        return sum if preserve_mask else np.asarray(sum)
+    return xp.sum(a, axis=axis)
+
+
+def _m_mean(a, *, axis, keepdims, xp):
+    if np.ma.isMaskedArray(a):
+        return np.asarray(a.mean(axis=axis, keepdims=keepdims))
+    return xp.mean(a, axis=axis, keepdims=keepdims)
+
+
+Power_divergenceResult = namedtuple('Power_divergenceResult',
+                                    ('statistic', 'pvalue'))
+
+
+def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
+    """Cressie-Read power divergence statistic and goodness of fit test.
+
+    This function tests the null hypothesis that the categorical data
+    has the given frequencies, using the Cressie-Read power divergence
+    statistic.
+
+    Parameters
+    ----------
+    f_obs : array_like
+        Observed frequencies in each category.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    f_exp : array_like, optional
+        Expected frequencies in each category.  By default the categories are
+        assumed to be equally likely.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    ddof : int, optional
+        "Delta degrees of freedom": adjustment to the degrees of freedom
+        for the p-value.  The p-value is computed using a chi-squared
+        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
+        is the number of observed frequencies.  The default value of `ddof`
+        is 0.
+    axis : int or None, optional
+        The axis of the broadcast result of `f_obs` and `f_exp` along which to
+        apply the test.  If axis is None, all values in `f_obs` are treated
+        as a single data set.  Default is 0.
+    lambda_ : float or str, optional
+        The power in the Cressie-Read power divergence statistic.  The default
+        is 1.  For convenience, `lambda_` may be assigned one of the following
+        strings, in which case the corresponding numerical value is used:
+
+        * ``"pearson"`` (value 1)
+            Pearson's chi-squared statistic. In this case, the function is
+            equivalent to `chisquare`.
+        * ``"log-likelihood"`` (value 0)
+            Log-likelihood ratio. Also known as the G-test [3]_.
+        * ``"freeman-tukey"`` (value -1/2)
+            Freeman-Tukey statistic.
+        * ``"mod-log-likelihood"`` (value -1)
+            Modified log-likelihood ratio.
+        * ``"neyman"`` (value -2)
+            Neyman's statistic.
+        * ``"cressie-read"`` (value 2/3)
+            The power recommended in [5]_.
+
+    Returns
+    -------
+    res: Power_divergenceResult
+        An object containing attributes:
+
+        statistic : float or ndarray
+            The Cressie-Read power divergence test statistic.  The value is
+            a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
+        pvalue : float or ndarray
+            The p-value of the test.  The value is a float if `ddof` and the
+            return value `stat` are scalars.
+
+    See Also
+    --------
+    chisquare
+
+    Notes
+    -----
+    This test is invalid when the observed or expected frequencies in each
+    category are too small.  A typical rule is that all of the observed
+    and expected frequencies should be at least 5.
+
+    Also, the sum of the observed and expected frequencies must be the same
+    for the test to be valid; `power_divergence` raises an error if the sums
+    do not agree within a relative tolerance of ``eps**0.5``, where ``eps``
+    is the precision of the input dtype.
+
+    When `lambda_` is less than zero, the formula for the statistic involves
+    dividing by `f_obs`, so a warning or error may be generated if any value
+    in `f_obs` is 0.
+
+    Similarly, a warning or error may be generated if any value in `f_exp` is
+    zero when `lambda_` >= 0.
+
+    The default degrees of freedom, k-1, are for the case when no parameters
+    of the distribution are estimated. If p parameters are estimated by
+    efficient maximum likelihood then the correct degrees of freedom are
+    k-1-p. If the parameters are estimated in a different way, then the
+    dof can be between k-1-p and k-1. However, it is also possible that
+    the asymptotic distribution is not a chisquare, in which case this
+    test is not appropriate.
+
+    References
+    ----------
+    .. [1] Lowry, Richard.  "Concepts and Applications of Inferential
+           Statistics". Chapter 8.
+           https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
+    .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
+    .. [3] "G-test", https://en.wikipedia.org/wiki/G-test
+    .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
+           practice of statistics in biological research", New York: Freeman
+           (1981)
+    .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
+           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
+           pp. 440-464.
+
+    Examples
+    --------
+    (See `chisquare` for more examples.)
+
+    When just `f_obs` is given, it is assumed that the expected frequencies
+    are uniform and given by the mean of the observed frequencies.  Here we
+    perform a G-test (i.e. use the log-likelihood ratio statistic):
+
+    >>> import numpy as np
+    >>> from scipy.stats import power_divergence
+    >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
+    (2.006573162632538, 0.84823476779463769)
+
+    The expected frequencies can be given with the `f_exp` argument:
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12],
+    ...                  f_exp=[16, 16, 16, 16, 16, 8],
+    ...                  lambda_='log-likelihood')
+    (3.3281031458963746, 0.6495419288047497)
+
+    When `f_obs` is 2-D, by default the test is applied to each column.
+
+    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
+    >>> obs.shape
+    (6, 2)
+    >>> power_divergence(obs, lambda_="log-likelihood")
+    (array([ 2.00657316,  6.77634498]), array([ 0.84823477,  0.23781225]))
+
+    By setting ``axis=None``, the test is applied to all data in the array,
+    which is equivalent to applying the test to the flattened array.
+
+    >>> power_divergence(obs, axis=None)
+    (23.31034482758621, 0.015975692534127565)
+    >>> power_divergence(obs.ravel())
+    (23.31034482758621, 0.015975692534127565)
+
+    `ddof` is the change to make to the default degrees of freedom.
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
+    (2.0, 0.73575888234288467)
+
+    The calculation of the p-values is done by broadcasting the
+    test statistic with `ddof`.
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
+    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))
+
+    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
+    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
+    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
+    statistics, we must use ``axis=1``:
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12],
+    ...                  f_exp=[[16, 16, 16, 16, 16, 8],
+    ...                         [8, 20, 20, 16, 12, 12]],
+    ...                  axis=1)
+    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))
+
+    """
+    return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_)
+
+
+def _power_divergence(f_obs, f_exp, ddof, axis, lambda_, sum_check=True):
+    xp = array_namespace(f_obs)
+    default_float = xp.asarray(1.).dtype
+
+    # Convert the input argument `lambda_` to a numerical value.
+    if isinstance(lambda_, str):
+        if lambda_ not in _power_div_lambda_names:
+            names = repr(list(_power_div_lambda_names.keys()))[1:-1]
+            raise ValueError(f"invalid string for lambda_: {lambda_!r}. "
+                             f"Valid strings are {names}")
+        lambda_ = _power_div_lambda_names[lambda_]
+    elif lambda_ is None:
+        lambda_ = 1
+
+    def warn_masked(arg):
+        if isinstance(arg, ma.MaskedArray):
+            message = (
+                "`power_divergence` and `chisquare` support for masked array input was "
+                "deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.")
+            warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+    warn_masked(f_obs)
+    f_obs = f_obs if np.ma.isMaskedArray(f_obs) else xp.asarray(f_obs)
+    dtype = default_float if xp.isdtype(f_obs.dtype, 'integral') else f_obs.dtype
+    f_obs = (f_obs.astype(dtype) if np.ma.isMaskedArray(f_obs)
+             else xp.asarray(f_obs, dtype=dtype))
+    f_obs_float = (f_obs.astype(np.float64) if hasattr(f_obs, 'mask')
+                   else xp.asarray(f_obs, dtype=xp.float64))
+
+    if f_exp is not None:
+        warn_masked(f_exp)
+        f_exp = f_exp if np.ma.isMaskedArray(f_obs) else xp.asarray(f_exp)
+        dtype = default_float if xp.isdtype(f_exp.dtype, 'integral') else f_exp.dtype
+        f_exp = (f_exp.astype(dtype) if np.ma.isMaskedArray(f_exp)
+                 else xp.asarray(f_exp, dtype=dtype))
+
+        bshape = _broadcast_shapes((f_obs_float.shape, f_exp.shape))
+        f_obs_float = _m_broadcast_to(f_obs_float, bshape, xp=xp)
+        f_exp = _m_broadcast_to(f_exp, bshape, xp=xp)
+
+        if sum_check:
+            dtype_res = xp.result_type(f_obs.dtype, f_exp.dtype)
+            rtol = xp.finfo(dtype_res).eps**0.5  # to pass existing tests
+            with np.errstate(invalid='ignore'):
+                f_obs_sum = _m_sum(f_obs_float, axis=axis, preserve_mask=False, xp=xp)
+                f_exp_sum = _m_sum(f_exp, axis=axis, preserve_mask=False, xp=xp)
+                relative_diff = (xp.abs(f_obs_sum - f_exp_sum) /
+                                 xp.minimum(f_obs_sum, f_exp_sum))
+                diff_gt_tol = xp.any(relative_diff > rtol, axis=None)
+            if diff_gt_tol:
+                msg = (f"For each axis slice, the sum of the observed "
+                       f"frequencies must agree with the sum of the "
+                       f"expected frequencies to a relative tolerance "
+                       f"of {rtol}, but the percent differences are:\n"
+                       f"{relative_diff}")
+                raise ValueError(msg)
+
+    else:
+        # Ignore 'invalid' errors so the edge case of a data set with length 0
+        # is handled without spurious warnings.
+        with np.errstate(invalid='ignore'):
+            f_exp = _m_mean(f_obs, axis=axis, keepdims=True, xp=xp)
+
+    # `terms` is the array of terms that are summed along `axis` to create
+    # the test statistic.  We use some specialized code for a few special
+    # cases of lambda_.
+    if lambda_ == 1:
+        # Pearson's chi-squared statistic
+        terms = (f_obs - f_exp)**2 / f_exp
+    elif lambda_ == 0:
+        # Log-likelihood ratio (i.e. G-test)
+        terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
+    elif lambda_ == -1:
+        # Modified log-likelihood ratio
+        terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
+    else:
+        # General Cressie-Read power divergence.
+        terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
+        terms /= 0.5 * lambda_ * (lambda_ + 1)
+
+    stat = _m_sum(terms, axis=axis, preserve_mask=True, xp=xp)
+
+    num_obs = _m_count(terms, axis=axis, xp=xp)
+    ddof = xp.asarray(ddof)
+
+    df = xp.asarray(num_obs - 1 - ddof)
+    chi2 = _SimpleChi2(df)
+    pvalue = _get_pvalue(stat, chi2 , alternative='greater', symmetric=False, xp=xp)
+
+    stat = stat[()] if stat.ndim == 0 else stat
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return Power_divergenceResult(stat, pvalue)
+
+
+def chisquare(f_obs, f_exp=None, ddof=0, axis=0, *, sum_check=True):
+    """Perform Pearson's chi-squared test.
+
+    Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial
+    distribution with given probabilities; that is, it assesses the null hypothesis
+    that the observed frequencies (counts) are obtained by independent
+    sampling of *N* observations from a categorical distribution with given
+    expected frequencies.
+
+    Parameters
+    ----------
+    f_obs : array_like
+        Observed frequencies in each category.
+    f_exp : array_like, optional
+        Expected frequencies in each category. By default, the categories are
+        assumed to be equally likely.
+    ddof : int, optional
+        "Delta degrees of freedom": adjustment to the degrees of freedom
+        for the p-value.  The p-value is computed using a chi-squared
+        distribution with ``k - 1 - ddof`` degrees of freedom, where ``k``
+        is the number of categories.  The default value of `ddof` is 0.
+    axis : int or None, optional
+        The axis of the broadcast result of `f_obs` and `f_exp` along which to
+        apply the test.  If axis is None, all values in `f_obs` are treated
+        as a single data set.  Default is 0.
+    sum_check : bool, optional
+        Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True,
+        (default) raise an error when the relative difference exceeds the square root
+        of the precision of the data type. See Notes for rationale and possible
+        exceptions.
+
+    Returns
+    -------
+    res: Power_divergenceResult
+        An object containing attributes:
+
+        statistic : float or ndarray
+            The chi-squared test statistic.  The value is a float if `axis` is
+            None or `f_obs` and `f_exp` are 1-D.
+        pvalue : float or ndarray
+            The p-value of the test.  The value is a float if `ddof` and the
+            result attribute `statistic` are scalars.
+
+    See Also
+    --------
+    scipy.stats.power_divergence
+    scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.
+    scipy.stats.barnard_exact : An unconditional exact test. An alternative
+        to chi-squared test for small sample sizes.
+    :ref:`hypothesis_chisquare` : Extended example
+
+    Notes
+    -----
+    This test is invalid when the observed or expected frequencies in each
+    category are too small.  A typical rule is that all of the observed
+    and expected frequencies should be at least 5. According to [2]_, the
+    total number of observations is recommended to be greater than 13,
+    otherwise exact tests (such as Barnard's Exact test) should be used
+    because they do not overreject.
+
+    The default degrees of freedom, k-1, are for the case when no parameters
+    of the distribution are estimated. If p parameters are estimated by
+    efficient maximum likelihood then the correct degrees of freedom are
+    k-1-p. If the parameters are estimated in a different way, then the
+    dof can be between k-1-p and k-1. However, it is also possible that
+    the asymptotic distribution is not chi-square, in which case this test
+    is not appropriate.
+
+    For Pearson's chi-squared test, the total observed and expected counts must match
+    for the p-value to accurately reflect the probability of observing such an extreme
+    value of the statistic under the null hypothesis.
+    This function may be used to perform other statistical tests that do not require
+    the total counts to be equal. For instance, to test the null hypothesis that
+    ``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1``
+    and ``sum_check=False``. This test follows from the fact that a Poisson random
+    variable with mean and variance ``f_exp[i]`` is approximately normal with the
+    same mean and variance; the chi-squared statistic standardizes, squares, and sums
+    the observations; and the sum of ``n`` squared standard normal variables follows
+    the chi-squared distribution with ``n`` degrees of freedom.
+
+    References
+    ----------
+    .. [1] "Pearson's chi-squared test".
+           *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
+    .. [2] Pearson, Karl. "On the criterion that a given system of deviations from the probable
+           in the case of a correlated system of variables is such that it can be reasonably
+           supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50
+           (1900), pp. 157-175.
+
+    Examples
+    --------
+    When only the mandatory `f_obs` argument is given, it is assumed that the
+    expected frequencies are uniform and given by the mean of the observed
+    frequencies:
+
+    >>> import numpy as np
+    >>> from scipy.stats import chisquare
+    >>> chisquare([16, 18, 16, 14, 12, 12])
+    Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956)
+
+    The optional `f_exp` argument gives the expected frequencies.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
+    Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223)
+
+    When `f_obs` is 2-D, by default the test is applied to each column.
+
+    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
+    >>> obs.shape
+    (6, 2)
+    >>> chisquare(obs)
+    Power_divergenceResult(statistic=array([2.        , 6.66666667]), pvalue=array([0.84914504, 0.24663415]))
+
+    By setting ``axis=None``, the test is applied to all data in the array,
+    which is equivalent to applying the test to the flattened array.
+
+    >>> chisquare(obs, axis=None)
+    Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)
+    >>> chisquare(obs.ravel())
+    Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758)
+
+    `ddof` is the change to make to the default degrees of freedom.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
+    Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847)
+
+    The calculation of the p-values is done by broadcasting the
+    chi-squared statistic with `ddof`.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0, 1, 2])
+    Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ]))
+
+    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
+    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
+    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
+    statistics, we use ``axis=1``:
+
+    >>> chisquare([16, 18, 16, 14, 12, 12],
+    ...           f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
+    ...           axis=1)
+    Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846]))
+
+    For a more detailed example, see :ref:`hypothesis_chisquare`.
+    """  # noqa: E501
+    return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
+                             lambda_="pearson", sum_check=sum_check)
+
+
+KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'],
+                                 ['statistic_location', 'statistic_sign'])
+
+
+def _compute_dplus(cdfvals, x):
+    """Computes D+ as used in the Kolmogorov-Smirnov test.
+
+    Parameters
+    ----------
+    cdfvals : array_like
+        Sorted array of CDF values between 0 and 1
+    x: array_like
+        Sorted array of the stochastic variable itself
+
+    Returns
+    -------
+    res: Pair with the following elements:
+        - The maximum distance of the CDF values below Uniform(0, 1).
+        - The location at which the maximum is reached.
+
+    """
+    n = len(cdfvals)
+    dplus = (np.arange(1.0, n + 1) / n - cdfvals)
+    amax = dplus.argmax()
+    loc_max = x[amax]
+    return (dplus[amax], loc_max)
+
+
+def _compute_dminus(cdfvals, x):
+    """Computes D- as used in the Kolmogorov-Smirnov test.
+
+    Parameters
+    ----------
+    cdfvals : array_like
+        Sorted array of CDF values between 0 and 1
+    x: array_like
+        Sorted array of the stochastic variable itself
+
+    Returns
+    -------
+    res: Pair with the following elements:
+        - Maximum distance of the CDF values above Uniform(0, 1)
+        - The location at which the maximum is reached.
+    """
+    n = len(cdfvals)
+    dminus = (cdfvals - np.arange(0.0, n)/n)
+    amax = dminus.argmax()
+    loc_max = x[amax]
+    return (dminus[amax], loc_max)
+
+
+def _tuple_to_KstestResult(statistic, pvalue,
+                           statistic_location, statistic_sign):
+    return KstestResult(statistic, pvalue,
+                        statistic_location=statistic_location,
+                        statistic_sign=statistic_sign)
+
+
+def _KstestResult_to_tuple(res):
+    return *res, res.statistic_location, res.statistic_sign
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=1, n_outputs=4,
+                          result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'):
+    """
+    Performs the one-sample Kolmogorov-Smirnov test for goodness of fit.
+
+    This test compares the underlying distribution F(x) of a sample
+    against a given continuous distribution G(x). See Notes for a description
+    of the available null and alternative hypotheses.
+
+    Parameters
+    ----------
+    x : array_like
+        a 1-D array of observations of iid random variables.
+    cdf : callable
+        callable used to calculate the cdf.
+    args : tuple, sequence, optional
+        Distribution parameters, used with `cdf`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'approx', 'asymp'}, optional
+        Defines the distribution used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : selects one of the other options.
+          * 'exact' : uses the exact distribution of test statistic.
+          * 'approx' : approximates the two-sided probability with twice
+            the one-sided probability
+          * 'asymp': uses asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic, either D+, D-, or D (the maximum of the two)
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            Value of `x` corresponding with the KS statistic; i.e., the
+            distance between the empirical distribution function and the
+            hypothesized cumulative distribution function is measured at this
+            observation.
+        statistic_sign : int
+            +1 if the KS statistic is the maximum positive difference between
+            the empirical distribution function and the hypothesized cumulative
+            distribution function (D+); -1 if the KS statistic is the maximum
+            negative difference (D-).
+
+
+    See Also
+    --------
+    ks_2samp, kstest
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that a sample is distributed
+    according to the standard normal.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    When testing uniformly distributed data, we would expect the
+    null hypothesis to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng),
+    ...                stats.norm.cdf)
+    KstestResult(statistic=0.5001899973268688,
+                 pvalue=1.1616392184763533e-23,
+                 statistic_location=0.00047625268963724654,
+                 statistic_sign=-1)
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    are *not* distributed according to the standard normal.
+
+    When testing random variates from the standard normal distribution, we
+    expect the data to be consistent with the null hypothesis most of the time.
+
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.ks_1samp(x, stats.norm.cdf)
+    KstestResult(statistic=0.05345882212970396,
+                 pvalue=0.9227159037744717,
+                 statistic_location=-1.2451343873745018,
+                 statistic_sign=1)
+
+    As expected, the p-value of 0.92 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the random variates are distributed according to
+    a normal distribution that is shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF of the standard normal. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
+    >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    """
+    mode = method
+
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+        alternative.lower()[0], alternative)
+    if alternative not in ['two-sided', 'greater', 'less']:
+        raise ValueError(f"Unexpected value {alternative=}")
+
+    N = len(x)
+    x = np.sort(x)
+    cdfvals = cdf(x, *args)
+    np_one = np.int8(1)
+
+    if alternative == 'greater':
+        Dplus, d_location = _compute_dplus(cdfvals, x)
+        return KstestResult(Dplus, distributions.ksone.sf(Dplus, N),
+                            statistic_location=d_location,
+                            statistic_sign=np_one)
+
+    if alternative == 'less':
+        Dminus, d_location = _compute_dminus(cdfvals, x)
+        return KstestResult(Dminus, distributions.ksone.sf(Dminus, N),
+                            statistic_location=d_location,
+                            statistic_sign=-np_one)
+
+    # alternative == 'two-sided':
+    Dplus, dplus_location = _compute_dplus(cdfvals, x)
+    Dminus, dminus_location = _compute_dminus(cdfvals, x)
+    if Dplus > Dminus:
+        D = Dplus
+        d_location = dplus_location
+        d_sign = np_one
+    else:
+        D = Dminus
+        d_location = dminus_location
+        d_sign = -np_one
+
+    if mode == 'auto':  # Always select exact
+        mode = 'exact'
+    if mode == 'exact':
+        prob = distributions.kstwo.sf(D, N)
+    elif mode == 'asymp':
+        prob = distributions.kstwobign.sf(D * np.sqrt(N))
+    else:
+        # mode == 'approx'
+        prob = 2 * distributions.ksone.sf(D, N)
+    prob = np.clip(prob, 0, 1)
+    return KstestResult(D, prob,
+                        statistic_location=d_location,
+                        statistic_sign=d_sign)
+
+
+Ks_2sampResult = KstestResult
+
+
+def _compute_prob_outside_square(n, h):
+    """
+    Compute the proportion of paths that pass outside the two diagonal lines.
+
+    Parameters
+    ----------
+    n : integer
+        n > 0
+    h : integer
+        0 <= h <= n
+
+    Returns
+    -------
+    p : float
+        The proportion of paths that pass outside the lines x-y = +/-h.
+
+    """
+    # Compute Pr(D_{n,n} >= h/n)
+    # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... )
+    # / binom(2n, n)
+    # This formulation exhibits subtractive cancellation.
+    # Instead divide each term by binom(2n, n), then factor common terms
+    # and use a Horner-like algorithm
+    # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
+
+    P = 0.0
+    k = int(np.floor(n / h))
+    while k >= 0:
+        p1 = 1.0
+        # Each of the Ai terms has numerator and denominator with
+        # h simple terms.
+        for j in range(h):
+            p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
+        P = p1 * (1.0 - P)
+        k -= 1
+    return 2 * P
+
+
+def _count_paths_outside_method(m, n, g, h):
+    """Count the number of paths that pass outside the specified diagonal.
+
+    Parameters
+    ----------
+    m : integer
+        m > 0
+    n : integer
+        n > 0
+    g : integer
+        g is greatest common divisor of m and n
+    h : integer
+        0 <= h <= lcm(m,n)
+
+    Returns
+    -------
+    p : float
+        The number of paths that go low.
+        The calculation may overflow - check for a finite answer.
+
+    Notes
+    -----
+    Count the integer lattice paths from (0, 0) to (m, n), which at some
+    point (x, y) along the path, satisfy:
+      m*y <= n*x - h*g
+    The paths make steps of size +1 in either positive x or positive y
+    directions.
+
+    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
+    Hodges, J.L. Jr.,
+    "The Significance Probability of the Smirnov Two-Sample Test,"
+    Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
+
+    """
+    # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
+    # B(x, y) = #{paths from (0,0) to (x,y) without
+    #             previously crossing the boundary}
+    #         = binom(x, y) - #{paths which already reached the boundary}
+    # Multiply by the number of path extensions going from (x, y) to (m, n)
+    # Sum.
+
+    # Probability is symmetrical in m, n.  Computation below assumes m >= n.
+    if m < n:
+        m, n = n, m
+    mg = m // g
+    ng = n // g
+
+    # Not every x needs to be considered.
+    # xj holds the list of x values to be checked.
+    # Wherever n*x/m + ng*h crosses an integer
+    lxj = n + (mg-h)//mg
+    xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
+    # B is an array just holding a few values of B(x,y), the ones needed.
+    # B[j] == B(x_j, j)
+    if lxj == 0:
+        return special.binom(m + n, n)
+    B = np.zeros(lxj)
+    B[0] = 1
+    # Compute the B(x, y) terms
+    for j in range(1, lxj):
+        Bj = special.binom(xj[j] + j, j)
+        for i in range(j):
+            bin = special.binom(xj[j] - xj[i] + j - i, j-i)
+            Bj -= bin * B[i]
+        B[j] = Bj
+    # Compute the number of path extensions...
+    num_paths = 0
+    for j in range(lxj):
+        bin = special.binom((m-xj[j]) + (n - j), n-j)
+        term = B[j] * bin
+        num_paths += term
+    return num_paths
+
+
+def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
+    """Attempts to compute the exact 2sample probability.
+
+    n1, n2 are the sample sizes
+    g is the gcd(n1, n2)
+    d is the computed max difference in ECDFs
+
+    Returns (success, d, probability)
+    """
+    lcm = (n1 // g) * n2
+    h = int(np.round(d * lcm))
+    d = h * 1.0 / lcm
+    if h == 0:
+        return True, d, 1.0
+    saw_fp_error, prob = False, np.nan
+    try:
+        with np.errstate(invalid="raise", over="raise"):
+            if alternative == 'two-sided':
+                if n1 == n2:
+                    prob = _compute_prob_outside_square(n1, h)
+                else:
+                    prob = _compute_outer_prob_inside_method(n1, n2, g, h)
+            else:
+                if n1 == n2:
+                    # prob = binom(2n, n-h) / binom(2n, n)
+                    # Evaluating in that form incurs roundoff errors
+                    # from special.binom. Instead calculate directly
+                    jrange = np.arange(h)
+                    prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
+                else:
+                    with np.errstate(over='raise'):
+                        num_paths = _count_paths_outside_method(n1, n2, g, h)
+                    bin = special.binom(n1 + n2, n1)
+                    if num_paths > bin or np.isinf(bin):
+                        saw_fp_error = True
+                    else:
+                        prob = num_paths / bin
+
+    except (FloatingPointError, OverflowError):
+        saw_fp_error = True
+
+    if saw_fp_error:
+        return False, d, np.nan
+    if not (0 <= prob <= 1):
+        return False, d, prob
+    return True, d, prob
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=2, n_outputs=4,
+                          result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def ks_2samp(data1, data2, alternative='two-sided', method='auto'):
+    """
+    Performs the two-sample Kolmogorov-Smirnov test for goodness of fit.
+
+    This test compares the underlying continuous distributions F(x) and G(x)
+    of two independent samples.  See Notes for a description of the available
+    null and alternative hypotheses.
+
+    Parameters
+    ----------
+    data1, data2 : array_like, 1-Dimensional
+        Two arrays of sample observations assumed to be drawn from a continuous
+        distribution, sample sizes can be different.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic.
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            Value from `data1` or `data2` corresponding with the KS statistic;
+            i.e., the distance between the empirical distribution functions is
+            measured at this observation.
+        statistic_sign : int
+            +1 if the empirical distribution function of `data1` exceeds
+            the empirical distribution function of `data2` at
+            `statistic_location`, otherwise -1.
+
+    See Also
+    --------
+    kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x. The statistic
+      is the magnitude of the minimum (most negative) difference between the
+      empirical distribution functions of the samples.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x. The statistic
+      is the maximum (most positive) difference between the empirical
+      distribution functions of the samples.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical. The statistic is the maximum absolute difference between the
+      empirical distribution functions of the samples.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values of the data. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+    If the KS statistic is large, then the p-value will be small, and this may
+    be taken as evidence against the null hypothesis in favor of the
+    alternative.
+
+    If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value,
+    that is, the probability under the null hypothesis of obtaining a test
+    statistic value as extreme as the value computed from the data.
+    If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is
+    used to compute an approximate p-value.
+    If ``method='auto'``, an exact p-value computation is attempted if both
+    sample sizes are less than 10000; otherwise, the asymptotic method is used.
+    In any case, if an exact p-value calculation is attempted and fails, a
+    warning will be emitted, and the asymptotic p-value will be returned.
+
+    The 'two-sided' 'exact' computation computes the complementary probability
+    and then subtracts from 1.  As such, the minimum probability it can return
+    is about 1e-16.  While the algorithm itself is exact, numerical
+    errors may accumulate for large sample sizes.   It is most suited to
+    situations in which one of the sample sizes is only a few thousand.
+
+    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
+
+    References
+    ----------
+    .. [1] Hodges, J.L. Jr.,  "The Significance Probability of the Smirnov
+           Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-486.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that two samples were drawn
+    from the same distribution.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    If the first sample were drawn from a uniform distribution and the second
+    were drawn from the standard normal, we would expect the null hypothesis
+    to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> sample1 = stats.uniform.rvs(size=100, random_state=rng)
+    >>> sample2 = stats.norm.rvs(size=110, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2)
+    KstestResult(statistic=0.5454545454545454,
+                 pvalue=7.37417839555191e-15,
+                 statistic_location=-0.014071496412861274,
+                 statistic_sign=-1)
+
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    were *not* drawn from the same distribution.
+
+    When both samples are drawn from the same distribution, we expect the data
+    to be consistent with the null hypothesis most of the time.
+
+    >>> sample1 = stats.norm.rvs(size=105, random_state=rng)
+    >>> sample2 = stats.norm.rvs(size=95, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2)
+    KstestResult(statistic=0.10927318295739348,
+                 pvalue=0.5438289009927495,
+                 statistic_location=-0.1670157701848795,
+                 statistic_sign=-1)
+
+    As expected, the p-value of 0.54 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the first sample were drawn from
+    a normal distribution shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF underlying the second sample. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2, alternative='less')
+    KstestResult(statistic=0.4055137844611529,
+                 pvalue=3.5474563068855554e-08,
+                 statistic_location=-0.13249370614972575,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    """
+    mode = method
+
+    if mode not in ['auto', 'exact', 'asymp']:
+        raise ValueError(f'Invalid value for mode: {mode}')
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+        alternative.lower()[0], alternative)
+    if alternative not in ['two-sided', 'less', 'greater']:
+        raise ValueError(f'Invalid value for alternative: {alternative}')
+    MAX_AUTO_N = 10000  # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
+    if np.ma.is_masked(data1):
+        data1 = data1.compressed()
+    if np.ma.is_masked(data2):
+        data2 = data2.compressed()
+    data1 = np.sort(data1)
+    data2 = np.sort(data2)
+    n1 = data1.shape[0]
+    n2 = data2.shape[0]
+    if min(n1, n2) == 0:
+        raise ValueError('Data passed to ks_2samp must not be empty')
+
+    data_all = np.concatenate([data1, data2])
+    # using searchsorted solves equal data problem
+    cdf1 = np.searchsorted(data1, data_all, side='right') / n1
+    cdf2 = np.searchsorted(data2, data_all, side='right') / n2
+    cddiffs = cdf1 - cdf2
+
+    # Identify the location of the statistic
+    argminS = np.argmin(cddiffs)
+    argmaxS = np.argmax(cddiffs)
+    loc_minS = data_all[argminS]
+    loc_maxS = data_all[argmaxS]
+
+    # Ensure sign of minS is not negative.
+    minS = np.clip(-cddiffs[argminS], 0, 1)
+    maxS = cddiffs[argmaxS]
+
+    if alternative == 'less' or (alternative == 'two-sided' and minS > maxS):
+        d = minS
+        d_location = loc_minS
+        d_sign = -1
+    else:
+        d = maxS
+        d_location = loc_maxS
+        d_sign = 1
+    g = gcd(n1, n2)
+    n1g = n1 // g
+    n2g = n2 // g
+    prob = -np.inf
+    if mode == 'auto':
+        mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
+    elif mode == 'exact':
+        # If lcm(n1, n2) is too big, switch from exact to asymp
+        if n1g >= np.iinfo(np.int32).max / n2g:
+            mode = 'asymp'
+            warnings.warn(
+                f"Exact ks_2samp calculation not possible with samples sizes "
+                f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning,
+                stacklevel=3)
+
+    if mode == 'exact':
+        success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
+        if not success:
+            mode = 'asymp'
+            warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
+                          f"Switching to method={mode}.", RuntimeWarning,
+                          stacklevel=3)
+
+    if mode == 'asymp':
+        # The product n1*n2 is large.  Use Smirnov's asymptotic formula.
+        # Ensure float to avoid overflow in multiplication
+        # sorted because the one-sided formula is not symmetric in n1, n2
+        m, n = sorted([float(n1), float(n2)], reverse=True)
+        en = m * n / (m + n)
+        if alternative == 'two-sided':
+            prob = distributions.kstwo.sf(d, np.round(en))
+        else:
+            z = np.sqrt(en) * d
+            # Use Hodges' suggested approximation Eqn 5.3
+            # Requires m to be the larger of (n1, n2)
+            expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
+            prob = np.exp(expt)
+
+    prob = np.clip(prob, 0, 1)
+    # Currently, `d` is a Python float. We want it to be a NumPy type, so
+    # float64 is appropriate. An enhancement would be for `d` to respect the
+    # dtype of the input.
+    return KstestResult(np.float64(d), prob, statistic_location=d_location,
+                        statistic_sign=np.int8(d_sign))
+
+
+def _parse_kstest_args(data1, data2, args, N):
+    # kstest allows many different variations of arguments.
+    # Pull out the parsing into a separate function
+    # (xvals, yvals, )  # 2sample
+    # (xvals, cdf function,..)
+    # (xvals, name of distribution, ...)
+    # (name of distribution, name of distribution, ...)
+
+    # Returns xvals, yvals, cdf
+    # where cdf is a cdf function, or None
+    # and yvals is either an array_like of values, or None
+    # and xvals is array_like.
+    rvsfunc, cdf = None, None
+    if isinstance(data1, str):
+        rvsfunc = getattr(distributions, data1).rvs
+    elif callable(data1):
+        rvsfunc = data1
+
+    if isinstance(data2, str):
+        cdf = getattr(distributions, data2).cdf
+        data2 = None
+    elif callable(data2):
+        cdf = data2
+        data2 = None
+
+    data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
+    return data1, data2, cdf
+
+
+def _kstest_n_samples(kwargs):
+    cdf = kwargs['cdf']
+    return 1 if (isinstance(cdf, str) or callable(cdf)) else 2
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=_kstest_n_samples,
+                          n_outputs=4, result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'):
+    """
+    Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for
+    goodness of fit.
+
+    The one-sample test compares the underlying distribution F(x) of a sample
+    against a given distribution G(x). The two-sample test compares the
+    underlying distributions of two independent samples. Both tests are valid
+    only for continuous distributions.
+
+    Parameters
+    ----------
+    rvs : str, array_like, or callable
+        If an array, it should be a 1-D array of observations of random
+        variables.
+        If a callable, it should be a function to generate random variables;
+        it is required to have a keyword argument `size`.
+        If a string, it should be the name of a distribution in `scipy.stats`,
+        which will be used to generate random variables.
+    cdf : str, array_like or callable
+        If array_like, it should be a 1-D array of observations of random
+        variables, and the two-sample test is performed
+        (and rvs must be array_like).
+        If a callable, that callable is used to calculate the cdf.
+        If a string, it should be the name of a distribution in `scipy.stats`,
+        which will be used as the cdf function.
+    args : tuple, sequence, optional
+        Distribution parameters, used if `rvs` or `cdf` are strings or
+        callables.
+    N : int, optional
+        Sample size if `rvs` is string or callable.  Default is 20.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'approx', 'asymp'}, optional
+        Defines the distribution used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : selects one of the other options.
+          * 'exact' : uses the exact distribution of test statistic.
+          * 'approx' : approximates the two-sided probability with twice the
+            one-sided probability
+          * 'asymp': uses asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic, either D+, D-, or D (the maximum of the two)
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            In a one-sample test, this is the value of `rvs`
+            corresponding with the KS statistic; i.e., the distance between
+            the empirical distribution function and the hypothesized cumulative
+            distribution function is measured at this observation.
+
+            In a two-sample test, this is the value from `rvs` or `cdf`
+            corresponding with the KS statistic; i.e., the distance between
+            the empirical distribution functions is measured at this
+            observation.
+        statistic_sign : int
+            In a one-sample test, this is +1 if the KS statistic is the
+            maximum positive difference between the empirical distribution
+            function and the hypothesized cumulative distribution function
+            (D+); it is -1 if the KS statistic is the maximum negative
+            difference (D-).
+
+            In a two-sample test, this is +1 if the empirical distribution
+            function of `rvs` exceeds the empirical distribution
+            function of `cdf` at `statistic_location`, otherwise -1.
+
+    See Also
+    --------
+    ks_1samp, ks_2samp
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that a sample is distributed
+    according to the standard normal.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    When testing uniformly distributed data, we would expect the
+    null hypothesis to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng),
+    ...              stats.norm.cdf)
+    KstestResult(statistic=0.5001899973268688,
+                 pvalue=1.1616392184763533e-23,
+                 statistic_location=0.00047625268963724654,
+                 statistic_sign=-1)
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    are *not* distributed according to the standard normal.
+
+    When testing random variates from the standard normal distribution, we
+    expect the data to be consistent with the null hypothesis most of the time.
+
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.kstest(x, stats.norm.cdf)
+    KstestResult(statistic=0.05345882212970396,
+                 pvalue=0.9227159037744717,
+                 statistic_location=-1.2451343873745018,
+                 statistic_sign=1)
+
+
+    As expected, the p-value of 0.92 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the random variates are distributed according to
+    a normal distribution that is shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF of the standard normal. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
+    >>> stats.kstest(x, stats.norm.cdf, alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    For convenience, the previous test can be performed using the name of the
+    distribution as the second argument.
+
+    >>> stats.kstest(x, "norm", alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    The examples above have all been one-sample tests identical to those
+    performed by `ks_1samp`. Note that `kstest` can also perform two-sample
+    tests identical to those performed by `ks_2samp`. For example, when two
+    samples are drawn from the same distribution, we expect the data to be
+    consistent with the null hypothesis most of the time.
+
+    >>> sample1 = stats.laplace.rvs(size=105, random_state=rng)
+    >>> sample2 = stats.laplace.rvs(size=95, random_state=rng)
+    >>> stats.kstest(sample1, sample2)
+    KstestResult(statistic=0.11779448621553884,
+                 pvalue=0.4494256912629795,
+                 statistic_location=0.6138814275424155,
+                 statistic_sign=1)
+
+    As expected, the p-value of 0.45 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    """
+    # to not break compatibility with existing code
+    if alternative == 'two_sided':
+        alternative = 'two-sided'
+    if alternative not in ['two-sided', 'greater', 'less']:
+        raise ValueError(f"Unexpected alternative: {alternative}")
+    xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
+    if cdf:
+        return ks_1samp(xvals, cdf, args=args, alternative=alternative,
+                        method=method, _no_deco=True)
+    return ks_2samp(xvals, yvals, alternative=alternative, method=method,
+                    _no_deco=True)
+
+
+def tiecorrect(rankvals):
+    """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
+
+    Parameters
+    ----------
+    rankvals : array_like
+        A 1-D sequence of ranks.  Typically this will be the array
+        returned by `~scipy.stats.rankdata`.
+
+    Returns
+    -------
+    factor : float
+        Correction factor for U or H.
+
+    See Also
+    --------
+    rankdata : Assign ranks to the data
+    mannwhitneyu : Mann-Whitney rank test
+    kruskal : Kruskal-Wallis H test
+
+    References
+    ----------
+    .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
+           Sciences.  New York: McGraw-Hill.
+
+    Examples
+    --------
+    >>> from scipy.stats import tiecorrect, rankdata
+    >>> tiecorrect([1, 2.5, 2.5, 4])
+    0.9
+    >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
+    >>> ranks
+    array([ 1. ,  4. ,  2.5,  5.5,  7. ,  8. ,  2.5,  9. ,  5.5])
+    >>> tiecorrect(ranks)
+    0.9833333333333333
+
+    """
+    arr = np.sort(rankvals)
+    idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
+    cnt = np.diff(idx).astype(np.float64)
+
+    size = np.float64(arr.size)
+    return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
+
+
+RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(RanksumsResult, n_samples=2)
+def ranksums(x, y, alternative='two-sided'):
+    """Compute the Wilcoxon rank-sum statistic for two samples.
+
+    The Wilcoxon rank-sum test tests the null hypothesis that two sets
+    of measurements are drawn from the same distribution.  The alternative
+    hypothesis is that values in one sample are more likely to be
+    larger than the values in the other sample.
+
+    This test should be used to compare two samples from continuous
+    distributions.  It does not handle ties between measurements
+    in x and y.  For tie-handling and an optional continuity correction
+    see `scipy.stats.mannwhitneyu`.
+
+    Parameters
+    ----------
+    x,y : array_like
+        The data from the two samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': one of the distributions (underlying `x` or `y`) is
+          stochastically greater than the other.
+        * 'less': the distribution underlying `x` is stochastically less
+          than the distribution underlying `y`.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The test statistic under the large-sample approximation that the
+        rank sum statistic is normally distributed.
+    pvalue : float
+        The p-value of the test.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
+
+    Examples
+    --------
+    We can test the hypothesis that two independent unequal-sized samples are
+    drawn from the same distribution with computing the Wilcoxon rank-sum
+    statistic.
+
+    >>> import numpy as np
+    >>> from scipy.stats import ranksums
+    >>> rng = np.random.default_rng()
+    >>> sample1 = rng.uniform(-1, 1, 200)
+    >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution
+    >>> ranksums(sample1, sample2)
+    RanksumsResult(statistic=-7.887059,
+                   pvalue=3.09390448e-15) # may vary
+    >>> ranksums(sample1, sample2, alternative='less')
+    RanksumsResult(statistic=-7.750585297581713,
+                   pvalue=4.573497606342543e-15) # may vary
+    >>> ranksums(sample1, sample2, alternative='greater')
+    RanksumsResult(statistic=-7.750585297581713,
+                   pvalue=0.9999999999999954) # may vary
+
+    The p-value of less than ``0.05`` indicates that this test rejects the
+    hypothesis at the 5% significance level.
+
+    """
+    x, y = map(np.asarray, (x, y))
+    n1 = len(x)
+    n2 = len(y)
+    alldata = np.concatenate((x, y))
+    ranked = rankdata(alldata)
+    x = ranked[:n1]
+    s = np.sum(x, axis=0)
+    expected = n1 * (n1+n2+1) / 2.0
+    z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
+    pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+
+    return RanksumsResult(z[()], pvalue[()])
+
+
+KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(KruskalResult, n_samples=None)
+def kruskal(*samples, nan_policy='propagate'):
+    """Compute the Kruskal-Wallis H-test for independent samples.
+
+    The Kruskal-Wallis H-test tests the null hypothesis that the population
+    median of all of the groups are equal.  It is a non-parametric version of
+    ANOVA.  The test works on 2 or more independent samples, which may have
+    different sizes.  Note that rejecting the null hypothesis does not
+    indicate which of the groups differs.  Post hoc comparisons between
+    groups are required to determine which groups are different.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+       Two or more arrays with the sample measurements can be given as
+       arguments. Samples must be one-dimensional.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float
+       The Kruskal-Wallis H statistic, corrected for ties.
+    pvalue : float
+       The p-value for the test using the assumption that H has a chi
+       square distribution. The p-value returned is the survival function of
+       the chi square distribution evaluated at H.
+
+    See Also
+    --------
+    f_oneway : 1-way ANOVA.
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+    friedmanchisquare : Friedman test for repeated measurements.
+
+    Notes
+    -----
+    Due to the assumption that H has a chi square distribution, the number
+    of samples in each group must not be too small.  A typical rule is
+    that each sample must have at least 5 measurements.
+
+    References
+    ----------
+    .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
+       One-Criterion Variance Analysis", Journal of the American Statistical
+       Association, Vol. 47, Issue 260, pp. 583-621, 1952.
+    .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> x = [1, 3, 5, 7, 9]
+    >>> y = [2, 4, 6, 8, 10]
+    >>> stats.kruskal(x, y)
+    KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
+
+    >>> x = [1, 1, 1]
+    >>> y = [2, 2, 2]
+    >>> z = [2, 2]
+    >>> stats.kruskal(x, y, z)
+    KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
+
+    """
+    samples = list(map(np.asarray, samples))
+
+    num_groups = len(samples)
+    if num_groups < 2:
+        raise ValueError("Need at least two groups in stats.kruskal()")
+
+    n = np.asarray(list(map(len, samples)))
+
+    alldata = np.concatenate(samples)
+    ranked = rankdata(alldata)
+    ties = tiecorrect(ranked)
+    if ties == 0:
+        raise ValueError('All numbers are identical in kruskal')
+
+    # Compute sum^2/n for each group and sum
+    j = np.insert(np.cumsum(n), 0, 0)
+    ssbn = 0
+    for i in range(num_groups):
+        ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i]
+
+    totaln = np.sum(n, dtype=float)
+    h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
+    df = num_groups - 1
+    h /= ties
+
+    chi2 = _SimpleChi2(df)
+    pvalue = _get_pvalue(h, chi2, alternative='greater', symmetric=False, xp=np)
+    return KruskalResult(h, pvalue)
+
+
+FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
+                                     ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(FriedmanchisquareResult, n_samples=None, paired=True)
+def friedmanchisquare(*samples):
+    """Compute the Friedman test for repeated samples.
+
+    The Friedman test tests the null hypothesis that repeated samples of
+    the same individuals have the same distribution.  It is often used
+    to test for consistency among samples obtained in different ways.
+    For example, if two sampling techniques are used on the same set of
+    individuals, the Friedman test can be used to determine if the two
+    sampling techniques are consistent.
+
+    Parameters
+    ----------
+    sample1, sample2, sample3... : array_like
+        Arrays of observations.  All of the arrays must have the same number
+        of elements.  At least three samples must be given.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic, correcting for ties.
+    pvalue : float
+        The associated p-value assuming that the test statistic has a chi
+        squared distribution.
+
+    See Also
+    --------
+    :ref:`hypothesis_friedmanchisquare` : Extended example
+
+    Notes
+    -----
+    Due to the assumption that the test statistic has a chi squared
+    distribution, the p-value is only reliable for n > 10 and more than
+    6 repeated samples.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Friedman_test
+    .. [2] Demsar, J. (2006). Statistical comparisons of classifiers over
+           multiple data sets. Journal of Machine Learning Research, 7, 1-30.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng(seed=18)
+    >>> x = rng.random((6, 10))
+    >>> from scipy.stats import friedmanchisquare
+    >>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5])
+    >>> res.statistic, res.pvalue
+    (11.428571428571416, 0.043514520866727614)
+
+    The p-value is less than 0.05; however, as noted above, the results may not
+    be reliable since we have a small number of repeated samples.
+
+    For a more detailed example, see :ref:`hypothesis_friedmanchisquare`.
+    """
+    k = len(samples)
+    if k < 3:
+        raise ValueError('At least 3 sets of samples must be given '
+                         f'for Friedman test, got {k}.')
+
+    n = len(samples[0])
+    for i in range(1, k):
+        if len(samples[i]) != n:
+            raise ValueError('Unequal N in friedmanchisquare.  Aborting.')
+
+    # Rank data
+    data = np.vstack(samples).T
+    data = data.astype(float)
+    for i in range(len(data)):
+        data[i] = rankdata(data[i])
+
+    # Handle ties
+    ties = 0
+    for d in data:
+        _, repnum = _find_repeats(np.array(d, dtype=np.float64))
+        for t in repnum:
+            ties += t * (t*t - 1)
+    c = 1 - ties / (k*(k*k - 1)*n)
+
+    ssbn = np.sum(data.sum(axis=0)**2)
+    statistic = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
+
+    chi2 = _SimpleChi2(k - 1)
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np)
+    return FriedmanchisquareResult(statistic, pvalue)
+
+
+BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
+                                 ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(BrunnerMunzelResult, n_samples=2)
+def brunnermunzel(x, y, alternative="two-sided", distribution="t",
+                  nan_policy='propagate'):
+    """Compute the Brunner-Munzel test on samples x and y.
+
+    The Brunner-Munzel test is a nonparametric test of the null hypothesis that
+    when values are taken one by one from each group, the probabilities of
+    getting large values in both groups are equal.
+    Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
+    assumption of equivariance of two groups. Note that this does not assume
+    the distributions are same. This test works on two independent samples,
+    which may have different sizes.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Array of samples, should be one-dimensional.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+          * 'two-sided'
+          * 'less': one-sided
+          * 'greater': one-sided
+    distribution : {'t', 'normal'}, optional
+        Defines how to get the p-value.
+        The following options are available (default is 't'):
+
+          * 't': get the p-value by t-distribution
+          * 'normal': get the p-value by standard normal distribution.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float
+        The Brunner-Munzer W statistic.
+    pvalue : float
+        p-value assuming an t distribution. One-sided or
+        two-sided, depending on the choice of `alternative` and `distribution`.
+
+    See Also
+    --------
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+
+    Notes
+    -----
+    Brunner and Munzel recommended to estimate the p-value by t-distribution
+    when the size of data is 50 or less. If the size is lower than 10, it would
+    be better to use permuted Brunner Munzel test (see [2]_).
+
+    References
+    ----------
+    .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
+           problem: Asymptotic theory and a small-sample approximation".
+           Biometrical Journal. Vol. 42(2000): 17-25.
+    .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
+           non-parametric Behrens-Fisher problem". Computational Statistics and
+           Data Analysis. Vol. 51(2007): 5192-5204.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
+    >>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
+    >>> w, p_value = stats.brunnermunzel(x1, x2)
+    >>> w
+    3.1374674823029505
+    >>> p_value
+    0.0057862086661515377
+
+    """
+    nx = len(x)
+    ny = len(y)
+
+    rankc = rankdata(np.concatenate((x, y)))
+    rankcx = rankc[0:nx]
+    rankcy = rankc[nx:nx+ny]
+    rankcx_mean = np.mean(rankcx)
+    rankcy_mean = np.mean(rankcy)
+    rankx = rankdata(x)
+    ranky = rankdata(y)
+    rankx_mean = np.mean(rankx)
+    ranky_mean = np.mean(ranky)
+
+    Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
+    Sx /= nx - 1
+    Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
+    Sy /= ny - 1
+
+    wbfn = nx * ny * (rankcy_mean - rankcx_mean)
+    wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
+
+    if distribution == "t":
+        df_numer = np.power(nx * Sx + ny * Sy, 2.0)
+        df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
+        df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
+        df = df_numer / df_denom
+
+        if (df_numer == 0) and (df_denom == 0):
+            message = ("p-value cannot be estimated with `distribution='t' "
+                       "because degrees of freedom parameter is undefined "
+                       "(0/0). Try using `distribution='normal'")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        distribution = _SimpleStudentT(df)
+    elif distribution == "normal":
+        distribution = _SimpleNormal()
+    else:
+        raise ValueError(
+            "distribution should be 't' or 'normal'")
+
+    p = _get_pvalue(-wbfn, distribution, alternative, xp=np)
+
+    return BrunnerMunzelResult(wbfn, p)
+
+
+@_axis_nan_policy_factory(SignificanceResult, kwd_samples=['weights'], paired=True)
+def combine_pvalues(pvalues, method='fisher', weights=None, *, axis=0):
+    """
+    Combine p-values from independent tests that bear upon the same hypothesis.
+
+    These methods are intended only for combining p-values from hypothesis
+    tests based upon continuous distributions.
+
+    Each method assumes that under the null hypothesis, the p-values are
+    sampled independently and uniformly from the interval [0, 1]. A test
+    statistic (different for each method) is computed and a combined
+    p-value is calculated based upon the distribution of this test statistic
+    under the null hypothesis.
+
+    Parameters
+    ----------
+    pvalues : array_like
+        Array of p-values assumed to come from independent tests based on
+        continuous distributions.
+    method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}
+
+        Name of method to use to combine p-values.
+
+        The available methods are (see Notes for details):
+
+        * 'fisher': Fisher's method (Fisher's combined probability test)
+        * 'pearson': Pearson's method
+        * 'mudholkar_george': Mudholkar's and George's method
+        * 'tippett': Tippett's method
+        * 'stouffer': Stouffer's Z-score method
+    weights : array_like, optional
+        Optional array of weights used only for Stouffer's Z-score method.
+        Ignored by other methods.
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The statistic calculated by the specified method.
+        pvalue : float
+            The combined p-value.
+
+    Examples
+    --------
+    Suppose we wish to combine p-values from four independent tests
+    of the same null hypothesis using Fisher's method (default).
+
+    >>> from scipy.stats import combine_pvalues
+    >>> pvalues = [0.1, 0.05, 0.02, 0.3]
+    >>> combine_pvalues(pvalues)
+    SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092)
+
+    When the individual p-values carry different weights, consider Stouffer's
+    method.
+
+    >>> weights = [1, 2, 3, 4]
+    >>> res = combine_pvalues(pvalues, method='stouffer', weights=weights)
+    >>> res.pvalue
+    0.009578891494533616
+
+    Notes
+    -----
+    If this function is applied to tests with a discrete statistics such as
+    any rank test or contingency-table test, it will yield systematically
+    wrong results, e.g. Fisher's method will systematically overestimate the
+    p-value [1]_. This problem becomes less severe for large sample sizes
+    when the discrete distributions become approximately continuous.
+
+    The differences between the methods can be best illustrated by their
+    statistics and what aspects of a combination of p-values they emphasise
+    when considering significance [2]_. For example, methods emphasising large
+    p-values are more sensitive to strong false and true negatives; conversely
+    methods focussing on small p-values are sensitive to positives.
+
+    * The statistics of Fisher's method (also known as Fisher's combined
+      probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is
+      equivalent (as a test statistics) to the product of individual p-values:
+      :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows
+      a :math:`\\chi^2` distribution. This method emphasises small p-values.
+    * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent
+      to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_.
+      It thus emphasises large p-values.
+    * Mudholkar and George compromise between Fisher's and Pearson's method by
+      averaging their statistics [4]_. Their method emphasises extreme
+      p-values, both close to 1 and 0.
+    * Stouffer's method [5]_ uses Z-scores and the statistic:
+      :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the
+      standard normal distribution. The advantage of this method is that it is
+      straightforward to introduce weights, which can make Stouffer's method
+      more powerful than Fisher's method when the p-values are from studies
+      of different size [6]_ [7]_.
+    * Tippett's method uses the smallest p-value as a statistic.
+      (Mind that this minimum is not the combined p-value.)
+
+    Fisher's method may be extended to combine p-values from dependent tests
+    [8]_. Extensions such as Brown's method and Kost's method are not currently
+    implemented.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete
+           Distributions." Journal of the American Statistical Association 57,
+           no. 297 (1962), 10-19.
+    .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
+           combining p-values."  Biometrika 105.1 (2018): 239-246.
+    .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method
+    .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
+           random variables." Metrika 30.1 (1983): 1-13.
+    .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
+    .. [6] Whitlock, M. C. "Combining probability from independent tests: the
+           weighted Z-method is superior to Fisher's approach." Journal of
+           Evolutionary Biology 18, no. 5 (2005): 1368-1373.
+    .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
+           for combining probabilities in meta-analysis." Journal of
+           Evolutionary Biology 24, no. 8 (2011): 1836-1841.
+    .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
+
+    """
+    xp = array_namespace(pvalues)
+    pvalues = xp.asarray(pvalues)
+    if xp_size(pvalues) == 0:
+        # This is really only needed for *testing* _axis_nan_policy decorator
+        # It won't happen when the decorator is used.
+        NaN = _get_nan(pvalues)
+        return SignificanceResult(NaN, NaN)
+
+    n = pvalues.shape[axis]
+    # used to convert Python scalar to the right dtype
+    one = xp.asarray(1, dtype=pvalues.dtype)
+
+    if method == 'fisher':
+        statistic = -2 * xp.sum(xp.log(pvalues), axis=axis)
+        chi2 = _SimpleChi2(2*n*one)
+        pval = _get_pvalue(statistic, chi2, alternative='greater',
+                           symmetric=False, xp=xp)
+    elif method == 'pearson':
+        statistic = 2 * xp.sum(xp.log1p(-pvalues), axis=axis)
+        chi2 = _SimpleChi2(2*n*one)
+        pval = _get_pvalue(-statistic, chi2, alternative='less', symmetric=False, xp=xp)
+    elif method == 'mudholkar_george':
+        normalizing_factor = math.sqrt(3/n)/xp.pi
+        statistic = (-xp.sum(xp.log(pvalues), axis=axis)
+                     + xp.sum(xp.log1p(-pvalues), axis=axis))
+        nu = 5*n  + 4
+        approx_factor = math.sqrt(nu / (nu - 2))
+        t = _SimpleStudentT(nu*one)
+        pval = _get_pvalue(statistic * normalizing_factor * approx_factor, t,
+                           alternative="greater", xp=xp)
+    elif method == 'tippett':
+        statistic = xp.min(pvalues, axis=axis)
+        beta = _SimpleBeta(one, n*one)
+        pval = _get_pvalue(statistic, beta, alternative='less', symmetric=False, xp=xp)
+    elif method == 'stouffer':
+        if weights is None:
+            weights = xp.ones_like(pvalues, dtype=pvalues.dtype)
+        elif weights.shape[axis] != n:
+            raise ValueError("pvalues and weights must be of the same "
+                             "length along `axis`.")
+
+        norm = _SimpleNormal()
+        Zi = norm.isf(pvalues)
+        # could use `einsum` or clever `matmul` for performance,
+        # but this is the most readable
+        statistic = (xp.sum(weights * Zi, axis=axis)
+                     / xp_vector_norm(weights, axis=axis))
+        pval = _get_pvalue(statistic, norm, alternative="greater", xp=xp)
+
+    else:
+        raise ValueError(
+            f"Invalid method {method!r}. Valid methods are 'fisher', "
+            "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'"
+        )
+
+    return SignificanceResult(statistic, pval)
+
+
+@dataclass
+class QuantileTestResult:
+    r"""
+    Result of `scipy.stats.quantile_test`.
+
+    Attributes
+    ----------
+    statistic: float
+        The statistic used to calculate the p-value; either ``T1``, the
+        number of observations less than or equal to the hypothesized quantile,
+        or ``T2``, the number of observations strictly less than the
+        hypothesized quantile. Two test statistics are required to handle the
+        possibility the data was generated from a discrete or mixed
+        distribution.
+
+    statistic_type : int
+        ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to
+        calculate the p-value respectively. ``T1`` corresponds to the
+        ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``.  For
+        the ``"two-sided"`` case, the statistic type that leads to smallest
+        p-value is used.  For significant tests, ``statistic_type = 1`` means
+        there is evidence that the population quantile is significantly greater
+        than the hypothesized value and ``statistic_type = 2`` means there is
+        evidence that it is significantly less than the hypothesized value.
+
+    pvalue : float
+        The p-value of the hypothesis test.
+    """
+    statistic: float
+    statistic_type: int
+    pvalue: float
+    _alternative: list[str] = field(repr=False)
+    _x : np.ndarray = field(repr=False)
+    _p : float = field(repr=False)
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Compute the confidence interval of the quantile.
+
+        Parameters
+        ----------
+        confidence_level : float, default: 0.95
+            Confidence level for the computed confidence interval
+            of the quantile. Default is 0.95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence interval.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.stats as stats
+        >>> p = 0.75  # quantile of interest
+        >>> q = 0  # hypothesized value of the quantile
+        >>> x = np.exp(np.arange(0, 1.01, 0.01))
+        >>> res = stats.quantile_test(x, q=q, p=p, alternative='less')
+        >>> lb, ub = res.confidence_interval()
+        >>> lb, ub
+        (-inf, 2.293318740264183)
+        >>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided')
+        >>> lb, ub = res.confidence_interval(0.9)
+        >>> lb, ub
+        (1.9542373206359396, 2.293318740264183)
+        """
+
+        alternative = self._alternative
+        p = self._p
+        x = np.sort(self._x)
+        n = len(x)
+        bd = stats.binom(n, p)
+
+        if confidence_level <= 0 or confidence_level >= 1:
+            message = "`confidence_level` must be a number between 0 and 1."
+            raise ValueError(message)
+
+        low_index = np.nan
+        high_index = np.nan
+
+        if alternative == 'less':
+            p = 1 - confidence_level
+            low = -np.inf
+            high_index = int(bd.isf(p))
+            high = x[high_index] if high_index < n else np.nan
+        elif alternative == 'greater':
+            p = 1 - confidence_level
+            low_index = int(bd.ppf(p)) - 1
+            low = x[low_index] if low_index >= 0 else np.nan
+            high = np.inf
+        elif alternative == 'two-sided':
+            p = (1 - confidence_level) / 2
+            low_index = int(bd.ppf(p)) - 1
+            low = x[low_index] if low_index >= 0 else np.nan
+            high_index = int(bd.isf(p))
+            high = x[high_index] if high_index < n else np.nan
+
+        return ConfidenceInterval(low, high)
+
+
+def quantile_test_iv(x, q, p, alternative):
+
+    x = np.atleast_1d(x)
+    message = '`x` must be a one-dimensional array of numbers.'
+    if x.ndim != 1 or not np.issubdtype(x.dtype, np.number):
+        raise ValueError(message)
+
+    q = np.array(q)[()]
+    message = "`q` must be a scalar."
+    if q.ndim != 0 or not np.issubdtype(q.dtype, np.number):
+        raise ValueError(message)
+
+    p = np.array(p)[()]
+    message = "`p` must be a float strictly between 0 and 1."
+    if p.ndim != 0 or p >= 1 or p <= 0:
+        raise ValueError(message)
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    message = f"`alternative` must be one of {alternatives}"
+    if alternative not in alternatives:
+        raise ValueError(message)
+
+    return x, q, p, alternative
+
+
+def quantile_test(x, *, q=0, p=0.5, alternative='two-sided'):
+    r"""
+    Perform a quantile test and compute a confidence interval of the quantile.
+
+    This function tests the null hypothesis that `q` is the value of the
+    quantile associated with probability `p` of the population underlying
+    sample `x`. For example, with default parameters, it tests that the
+    median of the population underlying `x` is zero. The function returns an
+    object including the test statistic, a p-value, and a method for computing
+    the confidence interval around the quantile.
+
+    Parameters
+    ----------
+    x : array_like
+        A one-dimensional sample.
+    q : float, default: 0
+        The hypothesized value of the quantile.
+    p : float, default: 0.5
+        The probability associated with the quantile; i.e. the proportion of
+        the population less than `q` is `p`. Must be strictly between 0 and
+        1.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the quantile associated with the probability `p`
+          is not `q`.
+        * 'less': the quantile associated with the probability `p` is less
+          than `q`.
+        * 'greater': the quantile associated with the probability `p` is
+          greater than `q`.
+
+    Returns
+    -------
+    result : QuantileTestResult
+        An object with the following attributes:
+
+        statistic : float
+            One of two test statistics that may be used in the quantile test.
+            The first test statistic, ``T1``, is the proportion of samples in
+            `x` that are less than or equal to the hypothesized quantile
+            `q`. The second test statistic, ``T2``, is the proportion of
+            samples in `x` that are strictly less than the hypothesized
+            quantile `q`.
+
+            When ``alternative = 'greater'``, ``T1`` is used to calculate the
+            p-value and ``statistic`` is set to ``T1``.
+
+            When ``alternative = 'less'``, ``T2`` is used to calculate the
+            p-value and ``statistic`` is set to ``T2``.
+
+            When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are
+            considered, and the one that leads to the smallest p-value is used.
+
+        statistic_type : int
+            Either `1` or `2` depending on which of ``T1`` or ``T2`` was
+            used to calculate the p-value.
+
+        pvalue : float
+            The p-value associated with the given alternative.
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the the
+            population quantile associated with the probability `p`. The
+            confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.  Values are `nan` when there are
+            not enough observations to compute the confidence interval at
+            the desired confidence.
+
+    Notes
+    -----
+    This test and its method for computing confidence intervals are
+    non-parametric. They are valid if and only if the observations are i.i.d.
+
+    The implementation of the test follows Conover [1]_. Two test statistics
+    are considered.
+
+    ``T1``: The number of observations in `x` less than or equal to `q`.
+
+        ``T1 = (x <= q).sum()``
+
+    ``T2``: The number of observations in `x` strictly less than `q`.
+
+        ``T2 = (x < q).sum()``
+
+    The use of two test statistics is necessary to handle the possibility that
+    `x` was generated from a discrete or mixed distribution.
+
+    The null hypothesis for the test is:
+
+        H0: The :math:`p^{\mathrm{th}}` population quantile is `q`.
+
+    and the null distribution for each test statistic is
+    :math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``,
+    the alternative hypothesis is:
+
+        H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`.
+
+    and the p-value is the probability that the binomial random variable
+
+    .. math::
+        Y \sim \mathrm{binom}\left(n, p\right)
+
+    is greater than or equal to the observed value ``T2``.
+
+    When ``alternative='greater'``, the alternative hypothesis is:
+
+        H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q`
+
+    and the p-value is the probability that the binomial random variable Y
+    is less than or equal to the observed value ``T1``.
+
+    When ``alternative='two-sided'``, the alternative hypothesis is
+
+        H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile.
+
+    and the p-value is twice the smaller of the p-values for the ``'less'``
+    and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same
+    data, so the value is clipped into the interval :math:`[0, 1]`.
+
+    The approach for confidence intervals is attributed to Thompson [2]_ and
+    later proven to be applicable to any set of i.i.d. samples [3]_. The
+    computation is based on the observation that the probability of a quantile
+    :math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)`
+    can be computed as
+
+    .. math::
+
+        \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k}
+        q^k(1-q)^{N-k}
+
+    By default, confidence intervals are computed for a 95% confidence level.
+    A common interpretation of a 95% confidence intervals is that if i.i.d.
+    samples are drawn repeatedly from the same population and confidence
+    intervals are formed each time, the confidence interval will contain the
+    true value of the specified quantile in approximately 95% of trials.
+
+    A similar function is available in the QuantileNPCI R package [4]_. The
+    foundation is the same, but it computes the confidence interval bounds by
+    doing interpolations between the sample values, whereas this function uses
+    only sample values as bounds. Thus, ``quantile_test.confidence_interval``
+    returns more conservative intervals (i.e., larger).
+
+    The same computation of confidence intervals for quantiles is included in
+    the confintr package [5]_.
+
+    Two-sided confidence intervals are not guaranteed to be optimal; i.e.,
+    there may exist a tighter interval that may contain the quantile of
+    interest with probability larger than the confidence level.
+    Without further assumption on the samples (e.g., the nature of the
+    underlying distribution), the one-sided intervals are optimally tight.
+
+    References
+    ----------
+    .. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999.
+    .. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other
+       Expectation Distributions for Populations of Unknown Distribution
+       Form," The Annals of Mathematical Statistics, vol. 7, no. 3,
+       pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available:
+       https://www.jstor.org/stable/2957563.
+    .. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric
+       Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp.
+       159-170. Available:
+       https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7.
+    .. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric
+       Confidence Intervals for Quantiles," R package,
+       https://cran.r-project.org/package=QuantileNPCI
+    .. [5] M. Mayer, "confintr: Confidence Intervals," R package,
+       https://cran.r-project.org/package=confintr
+
+
+    Examples
+    --------
+
+    Suppose we wish to test the null hypothesis that the median of a population
+    is equal to 0.5. We choose a confidence level of 99%; that is, we will
+    reject the null hypothesis in favor of the alternative if the p-value is
+    less than 0.01.
+
+    When testing random variates from the standard uniform distribution, which
+    has a median of 0.5, we expect the data to be consistent with the null
+    hypothesis most of the time.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(6981396440634228121)
+    >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5)
+    QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576)
+
+    As expected, the p-value is not below our threshold of 0.01, so
+    we cannot reject the null hypothesis.
+
+    When testing data from the standard *normal* distribution, which has a
+    median of 0, we would expect the null hypothesis to be rejected.
+
+    >>> rvs = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5)
+    QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724)
+
+    Indeed, the p-value is lower than our threshold of 0.01, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the median
+    of the population is *not* equal to 0.5.
+
+    However, suppose we were to test the null hypothesis against the
+    one-sided alternative that the median of the population is *greater* than
+    0.5. Since the median of the standard normal is less than 0.5, we would not
+    expect the null hypothesis to be rejected.
+
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater')
+    QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866)
+
+    Unsurprisingly, with a p-value greater than our threshold, we would not
+    reject the null hypothesis in favor of the chosen alternative.
+
+    The quantile test can be used for any quantile, not only the median. For
+    example, we can test whether the third quartile of the distribution
+    underlying the sample is greater than 0.6.
+
+    >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater')
+    QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271)
+
+    The p-value is lower than the threshold. We reject the null hypothesis in
+    favor of the alternative: the third quartile of the distribution underlying
+    our sample is greater than 0.6.
+
+    `quantile_test` can also compute confidence intervals for any quantile.
+
+    >>> rvs = stats.norm.rvs(size=100, random_state=rng)
+    >>> res = stats.quantile_test(rvs, q=0.6, p=0.75)
+    >>> ci = res.confidence_interval(confidence_level=0.95)
+    >>> ci
+    ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844)
+
+    When testing a one-sided alternative, the confidence interval contains
+    all observations such that if passed as `q`, the p-value of the
+    test would be greater than 0.05, and therefore the null hypothesis
+    would not be rejected. For example:
+
+    >>> rvs.sort()
+    >>> q, p, alpha = 0.6, 0.75, 0.95
+    >>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less')
+    >>> ci = res.confidence_interval(confidence_level=alpha)
+    >>> for x in rvs[rvs <= ci.high]:
+    ...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
+    ...     assert res.pvalue > 1-alpha
+    >>> for x in rvs[rvs > ci.high]:
+    ...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
+    ...     assert res.pvalue < 1-alpha
+
+    Also, if a 95% confidence interval is repeatedly generated for random
+    samples, the confidence interval will contain the true quantile value in
+    approximately 95% of replications.
+
+    >>> dist = stats.rayleigh() # our "unknown" distribution
+    >>> p = 0.2
+    >>> true_stat = dist.ppf(p) # the true value of the statistic
+    >>> n_trials = 1000
+    >>> quantile_ci_contains_true_stat = 0
+    >>> for i in range(n_trials):
+    ...     data = dist.rvs(size=100, random_state=rng)
+    ...     res = stats.quantile_test(data, p=p)
+    ...     ci = res.confidence_interval(0.95)
+    ...     if ci[0] < true_stat < ci[1]:
+    ...         quantile_ci_contains_true_stat += 1
+    >>> quantile_ci_contains_true_stat >= 950
+    True
+
+    This works with any distribution and any quantile, as long as the samples
+    are i.i.d.
+    """
+    # Implementation carefully follows [1] 3.2
+    # "H0: the p*th quantile of X is x*"
+    # To facilitate comparison with [1], we'll use variable names that
+    # best match Conover's notation
+    X, x_star, p_star, H1 = quantile_test_iv(x, q, p, alternative)
+
+    # "We will use two test statistics in this test. Let T1 equal "
+    # "the number of observations less than or equal to x*, and "
+    # "let T2 equal the number of observations less than x*."
+    T1 = (X <= x_star).sum()
+    T2 = (X < x_star).sum()
+
+    # "The null distribution of the test statistics T1 and T2 is "
+    # "the binomial distribution, with parameters n = sample size, and "
+    # "p = p* as given in the null hypothesis.... Y has the binomial "
+    # "distribution with parameters n and p*."
+    n = len(X)
+    Y = stats.binom(n=n, p=p_star)
+
+    # "H1: the p* population quantile is less than x*"
+    if H1 == 'less':
+        # "The p-value is the probability that a binomial random variable Y "
+        # "is greater than *or equal to* the observed value of T2...using p=p*"
+        pvalue = Y.sf(T2-1)  # Y.pmf(T2) + Y.sf(T2)
+        statistic = T2
+        statistic_type = 2
+    # "H1: the p* population quantile is greater than x*"
+    elif H1 == 'greater':
+        # "The p-value is the probability that a binomial random variable Y "
+        # "is less than or equal to the observed value of T1... using p = p*"
+        pvalue = Y.cdf(T1)
+        statistic = T1
+        statistic_type = 1
+    # "H1: x* is not the p*th population quantile"
+    elif H1 == 'two-sided':
+        # "The p-value is twice the smaller of the probabilities that a
+        # binomial random variable Y is less than or equal to the observed
+        # value of T1 or greater than or equal to the observed value of T2
+        # using p=p*."
+        # Note: both one-sided p-values can exceed 0.5 for the same data, so
+        # `clip`
+        pvalues = [Y.cdf(T1), Y.sf(T2 - 1)]  # [greater, less]
+        sorted_idx = np.argsort(pvalues)
+        pvalue = np.clip(2*pvalues[sorted_idx[0]], 0, 1)
+        if sorted_idx[0]:
+            statistic, statistic_type = T2, 2
+        else:
+            statistic, statistic_type = T1, 1
+
+    return QuantileTestResult(
+        statistic=statistic,
+        statistic_type=statistic_type,
+        pvalue=pvalue,
+        _alternative=H1,
+        _x=X,
+        _p=p_star
+    )
+
+
+#####################################
+#       STATISTICAL DISTANCES       #
+#####################################
+
+
+def wasserstein_distance_nd(u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute the Wasserstein-1 distance between two N-D discrete distributions.
+
+    The Wasserstein distance, also called the Earth mover's distance or the
+    optimal transport distance, is a similarity metric between two probability
+    distributions [1]_. In the discrete case, the Wasserstein distance can be
+    understood as the cost of an optimal transport plan to convert one
+    distribution into the other. The cost is calculated as the product of the
+    amount of probability mass being moved and the distance it is being moved.
+    A brief and intuitive introduction can be found at [2]_.
+
+    .. versionadded:: 1.13.0
+
+    Parameters
+    ----------
+    u_values : 2d array_like
+        A sample from a probability distribution or the support (set of all
+        possible values) of a probability distribution. Each element along
+        axis 0 is an observation or possible value, and axis 1 represents the
+        dimensionality of the distribution; i.e., each row is a vector
+        observation or possible value.
+
+    v_values : 2d array_like
+        A sample from or the support of a second distribution.
+
+    u_weights, v_weights : 1d array_like, optional
+        Weights or counts corresponding with the sample or probability masses
+        corresponding with the support values. Sum of elements must be positive
+        and finite. If unspecified, each value is assigned the same weight.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    Given two probability mass functions, :math:`u`
+    and :math:`v`, the first Wasserstein distance between the distributions
+    using the Euclidean norm is:
+
+    .. math::
+
+        l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y)
+
+    where :math:`\Gamma (u, v)` is the set of (probability) distributions on
+    :math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and
+    :math:`v` on the first and second factors respectively. For a given value
+    :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
+    :math:`x`, and the same for :math:`v(x)`.
+
+    This is also called the optimal transport problem or the Monge problem.
+    Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote
+    the support set of probability mass function :math:`u` and :math:`v`
+    respectively. The Monge problem can be expressed as follows,
+
+    Let :math:`\Gamma` denote the transport plan, :math:`D` denote the
+    distance matrix and,
+
+    .. math::
+
+        x = \text{vec}(\Gamma)          \\
+        c = \text{vec}(D)               \\
+        b = \begin{bmatrix}
+                u\\
+                v\\
+            \end{bmatrix}
+
+    The :math:`\text{vec}()` function denotes the Vectorization function
+    that transforms a matrix into a column vector by vertically stacking
+    the columns of the matrix.
+    The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in
+    which :math:`\gamma_{ij}` is a positive value representing the amount of
+    probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`.
+    Summing over the rows of :math:`\Gamma` should give the source distribution
+    :math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i`
+    and summing over the columns of :math:`\Gamma` should give the target
+    distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all
+    :math:`j`.
+    The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which
+    :math:`d_{ij} = d(x_i, y_j)`.
+
+    Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be
+    transformed into a linear programming problem by
+    taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization
+    target (sum of costs) , where matrix :math:`A` has the form
+
+    .. math::
+
+        \begin{array} {rrrr|rrrr|r|rrrr}
+            1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots &
+                0 \cr
+            0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots &
+                0 \cr
+            \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots
+                & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots  \cr
+            0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots &
+                1 \cr \hline
+
+            1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots &
+                0 \cr
+            0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots &
+                0 \cr
+            \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots &
+                \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr
+            0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1
+        \end{array}
+
+    By solving the dual form of the above linear programming problem (with
+    solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can
+    be computed as :math:`b^T y^*`.
+
+    The above solution is inspired by Vincent Herrmann's blog [3]_ . For a
+    more thorough explanation, see [4]_ .
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] "Wasserstein metric",
+           https://en.wikipedia.org/wiki/Wasserstein_metric
+    .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
+           https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
+    .. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein
+           Duality". https://vincentherrmann.github.io/blog/wasserstein/.
+    .. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal
+           transport." Center for Research in Economics and Statistics
+           Working Papers 2017-86 (2017).
+
+    See Also
+    --------
+    wasserstein_distance: Compute the Wasserstein-1 distance between two
+        1D discrete distributions.
+
+    Examples
+    --------
+    Compute the Wasserstein distance between two three-dimensional samples,
+    each with two observations.
+
+    >>> from scipy.stats import wasserstein_distance_nd
+    >>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]])
+    3.0
+
+    Compute the Wasserstein distance between two two-dimensional distributions
+    with three and two weighted observations, respectively.
+
+    >>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]],
+    ...                      [[0.2, 0.322], [4.5, 25.1808]],
+    ...                      [0.4, 5.2, 0.114], [0.8, 1.5])
+    174.15840245217169
+    """
+    m, n = len(u_values), len(v_values)
+    u_values = asarray(u_values)
+    v_values = asarray(v_values)
+
+    if u_values.ndim > 2 or v_values.ndim > 2:
+        raise ValueError('Invalid input values. The inputs must have either '
+                         'one or two dimensions.')
+    # if dimensions are not equal throw error
+    if u_values.ndim != v_values.ndim:
+        raise ValueError('Invalid input values. Dimensions of inputs must be '
+                         'equal.')
+    # if data is 1D then call the cdf_distance function
+    if u_values.ndim == 1 and v_values.ndim == 1:
+        return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
+
+    u_values, u_weights = _validate_distribution(u_values, u_weights)
+    v_values, v_weights = _validate_distribution(v_values, v_weights)
+    # if number of columns is not equal throw error
+    if u_values.shape[1] != v_values.shape[1]:
+        raise ValueError('Invalid input values. If two-dimensional, '
+                         '`u_values` and `v_values` must have the same '
+                         'number of columns.')
+
+    # if data contains np.inf then return inf or nan
+    if np.any(np.isinf(u_values)) ^ np.any(np.isinf(v_values)):
+        return np.inf
+    elif np.any(np.isinf(u_values)) and np.any(np.isinf(v_values)):
+        return np.nan
+
+    # create constraints
+    A_upper_part = sparse.block_diag((np.ones((1, n)), ) * m)
+    A_lower_part = sparse.hstack((sparse.eye(n), ) * m)
+    # sparse constraint matrix of size (m + n)*(m * n)
+    A = sparse.vstack((A_upper_part, A_lower_part))
+    A = sparse.coo_array(A)
+
+    # get cost matrix
+    D = distance_matrix(u_values, v_values, p=2)
+    cost = D.ravel()
+
+    # create the minimization target
+    p_u = np.full(m, 1/m) if u_weights is None else u_weights/np.sum(u_weights)
+    p_v = np.full(n, 1/n) if v_weights is None else v_weights/np.sum(v_weights)
+    b = np.concatenate((p_u, p_v), axis=0)
+
+    # solving LP
+    constraints = LinearConstraint(A=A.T, ub=cost)
+    opt_res = milp(c=-b, constraints=constraints, bounds=(-np.inf, np.inf))
+    return -opt_res.fun
+
+
+def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute the Wasserstein-1 distance between two 1D discrete distributions.
+
+    The Wasserstein distance, also called the Earth mover's distance or the
+    optimal transport distance, is a similarity metric between two probability
+    distributions [1]_. In the discrete case, the Wasserstein distance can be
+    understood as the cost of an optimal transport plan to convert one
+    distribution into the other. The cost is calculated as the product of the
+    amount of probability mass being moved and the distance it is being moved.
+    A brief and intuitive introduction can be found at [2]_.
+
+    .. versionadded:: 1.0.0
+
+    Parameters
+    ----------
+    u_values : 1d array_like
+        A sample from a probability distribution or the support (set of all
+        possible values) of a probability distribution. Each element is an
+        observation or possible value.
+
+    v_values : 1d array_like
+        A sample from or the support of a second distribution.
+
+    u_weights, v_weights : 1d array_like, optional
+        Weights or counts corresponding with the sample or probability masses
+        corresponding with the support values. Sum of elements must be positive
+        and finite. If unspecified, each value is assigned the same weight.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    Given two 1D probability mass functions, :math:`u` and :math:`v`, the first
+    Wasserstein distance between the distributions is:
+
+    .. math::
+
+        l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
+        \mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
+
+    where :math:`\Gamma (u, v)` is the set of (probability) distributions on
+    :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
+    :math:`v` on the first and second factors respectively. For a given value
+    :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
+    :math:`x`, and the same for :math:`v(x)`.
+
+    If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
+    :math:`v`, this distance also equals to:
+
+    .. math::
+
+        l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
+
+    See [3]_ for a proof of the equivalence of both definitions.
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
+    .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
+           https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
+    .. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
+           Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
+
+    See Also
+    --------
+    wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D
+        discrete distributions.
+
+    Examples
+    --------
+    >>> from scipy.stats import wasserstein_distance
+    >>> wasserstein_distance([0, 1, 3], [5, 6, 8])
+    5.0
+    >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
+    0.25
+    >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
+    ...                      [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
+    4.0781331438047861
+
+    """
+    return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
+
+
+def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
+    r"""Compute the energy distance between two 1D distributions.
+
+    .. versionadded:: 1.0.0
+
+    Parameters
+    ----------
+    u_values, v_values : array_like
+        Values observed in the (empirical) distribution.
+    u_weights, v_weights : array_like, optional
+        Weight for each value. If unspecified, each value is assigned the same
+        weight.
+        `u_weights` (resp. `v_weights`) must have the same length as
+        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
+        must still be positive and finite so that the weights can be normalized
+        to sum to 1.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    The energy distance between two distributions :math:`u` and :math:`v`, whose
+    respective CDFs are :math:`U` and :math:`V`, equals to:
+
+    .. math::
+
+        D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
+        \mathbb E|Y - Y'| \right)^{1/2}
+
+    where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
+    independent random variables whose probability distribution is :math:`u`
+    (resp. :math:`v`).
+
+    Sometimes the square of this quantity is referred to as the "energy
+    distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the
+    definition above satisfies the axioms of a distance function (metric).
+
+    As shown in [2]_, for one-dimensional real-valued variables, the energy
+    distance is linked to the non-distribution-free version of the Cramér-von
+    Mises distance:
+
+    .. math::
+
+        D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
+        \right)^{1/2}
+
+    Note that the common Cramér-von Mises criterion uses the distribution-free
+    version of the distance. See [2]_ (section 2), for more details about both
+    versions of the distance.
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
+           Computational Statistics, 8(1):27-38 (2015).
+    .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
+           Green State University, Department of Mathematics and Statistics,
+           Technical Report 02-16 (2002).
+    .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
+    .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
+           Munos "The Cramer Distance as a Solution to Biased Wasserstein
+           Gradients" (2017). :arXiv:`1705.10743`.
+
+    Examples
+    --------
+    >>> from scipy.stats import energy_distance
+    >>> energy_distance([0], [2])
+    2.0000000000000004
+    >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
+    1.0000000000000002
+    >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
+    ...                 [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
+    0.88003340976158217
+
+    """
+    return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
+                                      u_weights, v_weights)
+
+
+def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute, between two one-dimensional distributions :math:`u` and
+    :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
+    statistical distance that is defined as:
+
+    .. math::
+
+        l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
+
+    p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
+    gives the energy distance.
+
+    Parameters
+    ----------
+    u_values, v_values : array_like
+        Values observed in the (empirical) distribution.
+    u_weights, v_weights : array_like, optional
+        Weight for each value. If unspecified, each value is assigned the same
+        weight.
+        `u_weights` (resp. `v_weights`) must have the same length as
+        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
+        must still be positive and finite so that the weights can be normalized
+        to sum to 1.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
+           Munos "The Cramer Distance as a Solution to Biased Wasserstein
+           Gradients" (2017). :arXiv:`1705.10743`.
+
+    """
+    u_values, u_weights = _validate_distribution(u_values, u_weights)
+    v_values, v_weights = _validate_distribution(v_values, v_weights)
+
+    u_sorter = np.argsort(u_values)
+    v_sorter = np.argsort(v_values)
+
+    all_values = np.concatenate((u_values, v_values))
+    all_values.sort(kind='mergesort')
+
+    # Compute the differences between pairs of successive values of u and v.
+    deltas = np.diff(all_values)
+
+    # Get the respective positions of the values of u and v among the values of
+    # both distributions.
+    u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
+    v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
+
+    # Calculate the CDFs of u and v using their weights, if specified.
+    if u_weights is None:
+        u_cdf = u_cdf_indices / u_values.size
+    else:
+        u_sorted_cumweights = np.concatenate(([0],
+                                              np.cumsum(u_weights[u_sorter])))
+        u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
+
+    if v_weights is None:
+        v_cdf = v_cdf_indices / v_values.size
+    else:
+        v_sorted_cumweights = np.concatenate(([0],
+                                              np.cumsum(v_weights[v_sorter])))
+        v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
+
+    # Compute the value of the integral based on the CDFs.
+    # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
+    # of about 15%.
+    if p == 1:
+        return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas))
+    if p == 2:
+        return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas)))
+    return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p),
+                                       deltas)), 1/p)
+
+
+def _validate_distribution(values, weights):
+    """
+    Validate the values and weights from a distribution input of `cdf_distance`
+    and return them as ndarray objects.
+
+    Parameters
+    ----------
+    values : array_like
+        Values observed in the (empirical) distribution.
+    weights : array_like
+        Weight for each value.
+
+    Returns
+    -------
+    values : ndarray
+        Values as ndarray.
+    weights : ndarray
+        Weights as ndarray.
+
+    """
+    # Validate the value array.
+    values = np.asarray(values, dtype=float)
+    if len(values) == 0:
+        raise ValueError("Distribution can't be empty.")
+
+    # Validate the weight array, if specified.
+    if weights is not None:
+        weights = np.asarray(weights, dtype=float)
+        if len(weights) != len(values):
+            raise ValueError('Value and weight array-likes for the same '
+                             'empirical distribution must be of the same size.')
+        if np.any(weights < 0):
+            raise ValueError('All weights must be non-negative.')
+        if not 0 < np.sum(weights) < np.inf:
+            raise ValueError('Weight array-like sum must be positive and '
+                             'finite. Set as None for an equal distribution of '
+                             'weight.')
+
+        return values, weights
+
+    return values, None
+
+
+#####################################
+#         SUPPORT FUNCTIONS         #
+#####################################
+
+RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts'))
+
+
+@_deprecated("`scipy.stats.find_repeats` is deprecated as of SciPy 1.15.0 "
+             "and will be removed in SciPy 1.17.0. Please use "
+             "`numpy.unique`/`numpy.unique_counts` instead.")
+def find_repeats(arr):
+    """Find repeats and repeat counts.
+
+    .. deprecated:: 1.15.0
+
+        This function is deprecated as of SciPy 1.15.0 and will be removed
+        in SciPy 1.17.0. Please use `numpy.unique` / `numpy.unique_counts` instead.
+
+    Parameters
+    ----------
+    arr : array_like
+        Input array. This is cast to float64.
+
+    Returns
+    -------
+    values : ndarray
+        The unique values from the (flattened) input that are repeated.
+
+    counts : ndarray
+        Number of times the corresponding 'value' is repeated.
+
+    Notes
+    -----
+    In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
+    difference is that `find_repeats` only returns repeated values.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
+    RepeatedResults(values=array([2.]), counts=array([4]))
+
+    >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
+    RepeatedResults(values=array([4.,  5.]), counts=array([2, 2]))
+
+    """
+    # Note: always copies.
+    return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64)))
+
+
+def _sum_of_squares(a, axis=0):
+    """Square each element of the input array, and return the sum(s) of that.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    sum_of_squares : ndarray
+        The sum along the given axis for (a**2).
+
+    See Also
+    --------
+    _square_of_sums : The square(s) of the sum(s) (the opposite of
+        `_sum_of_squares`).
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    return np.sum(a*a, axis)
+
+
+def _square_of_sums(a, axis=0):
+    """Sum elements of the input array, and return the square(s) of that sum.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    square_of_sums : float or ndarray
+        The square of the sum over `axis`.
+
+    See Also
+    --------
+    _sum_of_squares : The sum of squares (the opposite of `square_of_sums`).
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    s = np.sum(a, axis)
+    if not np.isscalar(s):
+        return s.astype(float) * s
+    else:
+        return float(s) * s
+
+
+def rankdata(a, method='average', *, axis=None, nan_policy='propagate'):
+    """Assign ranks to data, dealing with ties appropriately.
+
+    By default (``axis=None``), the data array is first flattened, and a flat
+    array of ranks is returned. Separately reshape the rank array to the
+    shape of the data array if desired (see Examples).
+
+    Ranks begin at 1.  The `method` argument controls how ranks are assigned
+    to equal values.  See [1]_ for further discussion of ranking methods.
+
+    Parameters
+    ----------
+    a : array_like
+        The array of values to be ranked.
+    method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
+        The method used to assign ranks to tied elements.
+        The following methods are available (default is 'average'):
+
+          * 'average': The average of the ranks that would have been assigned to
+            all the tied values is assigned to each value.
+          * 'min': The minimum of the ranks that would have been assigned to all
+            the tied values is assigned to each value.  (This is also
+            referred to as "competition" ranking.)
+          * 'max': The maximum of the ranks that would have been assigned to all
+            the tied values is assigned to each value.
+          * 'dense': Like 'min', but the rank of the next highest element is
+            assigned the rank immediately after those assigned to the tied
+            elements.
+          * 'ordinal': All values are given a distinct rank, corresponding to
+            the order that the values occur in `a`.
+    axis : {None, int}, optional
+        Axis along which to perform the ranking. If ``None``, the data array
+        is first flattened.
+    nan_policy : {'propagate', 'omit', 'raise'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': propagates nans through the rank calculation
+          * 'omit': performs the calculations ignoring nan values
+          * 'raise': raises an error
+
+        .. note::
+
+            When `nan_policy` is 'propagate', the output is an array of *all*
+            nans because ranks relative to nans in the input are undefined.
+            When `nan_policy` is 'omit', nans in `a` are ignored when ranking
+            the other values, and the corresponding locations of the output
+            are nan.
+
+        .. versionadded:: 1.10
+
+    Returns
+    -------
+    ranks : ndarray
+         An array of size equal to the size of `a`, containing rank
+         scores.
+
+    References
+    ----------
+    .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import rankdata
+    >>> rankdata([0, 2, 3, 2])
+    array([ 1. ,  2.5,  4. ,  2.5])
+    >>> rankdata([0, 2, 3, 2], method='min')
+    array([ 1,  2,  4,  2])
+    >>> rankdata([0, 2, 3, 2], method='max')
+    array([ 1,  3,  4,  3])
+    >>> rankdata([0, 2, 3, 2], method='dense')
+    array([ 1,  2,  3,  2])
+    >>> rankdata([0, 2, 3, 2], method='ordinal')
+    array([ 1,  2,  4,  3])
+    >>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
+    array([[1. , 2.5],
+          [4. , 2.5]])
+    >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
+    array([[1. , 2.5, 2.5],
+           [2. , 1. , 3. ]])
+    >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate")
+    array([nan, nan, nan, nan, nan, nan])
+    >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit")
+    array([ 2.,  3.,  4., nan,  1., nan])
+
+    """
+    methods = ('average', 'min', 'max', 'dense', 'ordinal')
+    if method not in methods:
+        raise ValueError(f'unknown method "{method}"')
+
+    x = np.asarray(a)
+
+    if axis is None:
+        x = x.ravel()
+        axis = -1
+
+    if x.size == 0:
+        dtype = float if method == 'average' else np.dtype("long")
+        return np.empty(x.shape, dtype=dtype)
+
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    x = np.swapaxes(x, axis, -1)
+    ranks = _rankdata(x, method)
+
+    if contains_nan:
+        i_nan = (np.isnan(x) if nan_policy == 'omit'
+                 else np.isnan(x).any(axis=-1))
+        ranks = ranks.astype(float, copy=False)
+        ranks[i_nan] = np.nan
+
+    ranks = np.swapaxes(ranks, axis, -1)
+    return ranks
+
+
+def _order_ranks(ranks, j):
+    # Reorder ascending order `ranks` according to `j`
+    ordered_ranks = np.empty(j.shape, dtype=ranks.dtype)
+    np.put_along_axis(ordered_ranks, j, ranks, axis=-1)
+    return ordered_ranks
+
+
+def _rankdata(x, method, return_ties=False):
+    # Rank data `x` by desired `method`; `return_ties` if desired
+    shape = x.shape
+
+    # Get sort order
+    kind = 'mergesort' if method == 'ordinal' else 'quicksort'
+    j = np.argsort(x, axis=-1, kind=kind)
+    ordinal_ranks = np.broadcast_to(np.arange(1, shape[-1]+1, dtype=int), shape)
+
+    # Ordinal ranks is very easy because ties don't matter. We're done.
+    if method == 'ordinal':
+        return _order_ranks(ordinal_ranks, j)  # never return ties
+
+    # Sort array
+    y = np.take_along_axis(x, j, axis=-1)
+    # Logical indices of unique elements
+    i = np.concatenate([np.ones(shape[:-1] + (1,), dtype=np.bool_),
+                       y[..., :-1] != y[..., 1:]], axis=-1)
+
+    # Integer indices of unique elements
+    indices = np.arange(y.size)[i.ravel()]
+    # Counts of unique elements
+    counts = np.diff(indices, append=y.size)
+
+    # Compute `'min'`, `'max'`, and `'mid'` ranks of unique elements
+    if method == 'min':
+        ranks = ordinal_ranks[i]
+    elif method == 'max':
+        ranks = ordinal_ranks[i] + counts - 1
+    elif method == 'average':
+        ranks = ordinal_ranks[i] + (counts - 1)/2
+    elif method == 'dense':
+        ranks = np.cumsum(i, axis=-1)[i]
+
+    ranks = np.repeat(ranks, counts).reshape(shape)
+    ranks = _order_ranks(ranks, j)
+
+    if return_ties:
+        # Tie information is returned in a format that is useful to functions that
+        # rely on this (private) function. Example:
+        # >>> x = np.asarray([3, 2, 1, 2, 2, 2, 1])
+        # >>> _, t = _rankdata(x, 'average', return_ties=True)
+        # >>> t  # array([2., 0., 4., 0., 0., 0., 1.])  # two 1s, four 2s, and one 3
+        # Unlike ranks, tie counts are *not* reordered to correspond with the order of
+        # the input; e.g. the number of appearances of the lowest rank element comes
+        # first. This is a useful format because:
+        # - The shape of the result is the shape of the input. Different slices can
+        #   have different numbers of tied elements but not result in a ragged array.
+        # - Functions that use `t` usually don't need to which each element of the
+        #   original array is associated with each tie count; they perform a reduction
+        #   over the tie counts onnly. The tie counts are naturally computed in a
+        #   sorted order, so this does not unnecessarily reorder them.
+        # - One exception is `wilcoxon`, which needs the number of zeros. Zeros always
+        #   have the lowest rank, so it is easy to find them at the zeroth index.
+        t = np.zeros(shape, dtype=float)
+        t[i] = counts
+        return ranks, t
+    return ranks
+
+
+def expectile(a, alpha=0.5, *, weights=None):
+    r"""Compute the expectile at the specified level.
+
+    Expectiles are a generalization of the expectation in the same way as
+    quantiles are a generalization of the median. The expectile at level
+    `alpha = 0.5` is the mean (average). See Notes for more details.
+
+    Parameters
+    ----------
+    a : array_like
+        Array containing numbers whose expectile is desired.
+    alpha : float, default: 0.5
+        The level of the expectile; e.g., ``alpha=0.5`` gives the mean.
+    weights : array_like, optional
+        An array of weights associated with the values in `a`.
+        The `weights` must be broadcastable to the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+        An integer valued weight element acts like repeating the corresponding
+        observation in `a` that many times. See Notes for more details.
+
+    Returns
+    -------
+    expectile : ndarray
+        The empirical expectile at level `alpha`.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.quantile : Quantile
+
+    Notes
+    -----
+    In general, the expectile at level :math:`\alpha` of a random variable
+    :math:`X` with cumulative distribution function (CDF) :math:`F` is given
+    by the unique solution :math:`t` of:
+
+    .. math::
+
+        \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,.
+
+    Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`.
+    This equation can be equivalently written as:
+
+    .. math::
+
+        \alpha \int_t^\infty (x - t)\mathrm{d}F(x)
+        = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,.
+
+    The empirical expectile at level :math:`\alpha` (`alpha`) of a sample
+    :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of
+    `a`. Given sample or case weights :math:`w` (the array `weights`), it
+    reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}`
+    with indicator function :math:`1_{A}`. This leads to the definition of the
+    empirical expectile at level `alpha` as the unique solution :math:`t` of:
+
+    .. math::
+
+        \alpha \sum_{i=1}^n w_i (a_i - t)_+ =
+            (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,.
+
+    For :math:`\alpha=0.5`, this simplifies to the weighted average.
+    Furthermore, the larger :math:`\alpha`, the larger the value of the
+    expectile.
+
+    As a final remark, the expectile at level :math:`\alpha` can also be
+    written as a minimization problem. One often used choice is
+
+    .. math::
+
+        \operatorname{argmin}_t
+        E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,.
+
+    References
+    ----------
+    .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares
+           Estimation and Testing," Econometrica, 55, 819-847.
+    .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts,"
+           Journal of the American Statistical Association, 106, 746 - 762.
+           :doi:`10.48550/arXiv.0912.0902`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import expectile
+    >>> a = [1, 4, 2, -1]
+    >>> expectile(a, alpha=0.5) == np.mean(a)
+    True
+    >>> expectile(a, alpha=0.2)
+    0.42857142857142855
+    >>> expectile(a, alpha=0.8)
+    2.5714285714285716
+    >>> weights = [1, 3, 1, 1]
+
+    """
+    if alpha < 0 or alpha > 1:
+        raise ValueError(
+            "The expectile level alpha must be in the range [0, 1]."
+        )
+    a = np.asarray(a)
+
+    if weights is not None:
+        weights = np.broadcast_to(weights, a.shape)
+
+    # This is the empirical equivalent of Eq. (13) with identification
+    # function from Table 9 (omitting a factor of 2) in [2] (their y is our
+    # data a, their x is our t)
+    def first_order(t):
+        return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights)
+
+    if alpha >= 0.5:
+        x0 = np.average(a, weights=weights)
+        x1 = np.amax(a)
+    else:
+        x1 = np.average(a, weights=weights)
+        x0 = np.amin(a)
+
+    if x0 == x1:
+        # a has a single unique element
+        return x0
+
+    # Note that the expectile is the unique solution, so no worries about
+    # finding a wrong root.
+    res = root_scalar(first_order, x0=x0, x1=x1)
+    return res.root
+
+
+def _lmoment_iv(sample, order, axis, sorted, standardize):
+    # input validation/standardization for `lmoment`
+    sample = np.asarray(sample)
+    message = "`sample` must be an array of real numbers."
+    if np.issubdtype(sample.dtype, np.integer):
+        sample = sample.astype(np.float64)
+    if not np.issubdtype(sample.dtype, np.floating):
+        raise ValueError(message)
+
+    message = "`order` must be a scalar or a non-empty array of positive integers."
+    order = np.arange(1, 5) if order is None else np.asarray(order)
+    if not np.issubdtype(order.dtype, np.integer) or np.any(order <= 0):
+        raise ValueError(message)
+
+    axis = np.asarray(axis)[()]
+    message = "`axis` must be an integer."
+    if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
+        raise ValueError(message)
+
+    sorted = np.asarray(sorted)[()]
+    message = "`sorted` must be True or False."
+    if not np.issubdtype(sorted.dtype, np.bool_) or sorted.ndim != 0:
+        raise ValueError(message)
+
+    standardize = np.asarray(standardize)[()]
+    message = "`standardize` must be True or False."
+    if not np.issubdtype(standardize.dtype, np.bool_) or standardize.ndim != 0:
+        raise ValueError(message)
+
+    sample = np.moveaxis(sample, axis, -1)
+    sample = np.sort(sample, axis=-1) if not sorted else sample
+
+    return sample, order, axis, sorted, standardize
+
+
+def _br(x, *, r=0):
+    n = x.shape[-1]
+    x = np.expand_dims(x, axis=-2)
+    x = np.broadcast_to(x, x.shape[:-2] + (len(r), n))
+    x = np.triu(x)
+    j = np.arange(n, dtype=x.dtype)
+    n = np.asarray(n, dtype=x.dtype)[()]
+    return (np.sum(special.binom(j, r[:, np.newaxis])*x, axis=-1)
+            / special.binom(n-1, r) / n)
+
+
+def _prk(r, k):
+    # Writen to match [1] Equation 27 closely to facilitate review.
+    # This does not protect against overflow, so improvements to
+    # robustness would be a welcome follow-up.
+    return (-1)**(r-k)*special.binom(r, k)*special.binom(r+k, k)
+
+
+@_axis_nan_policy_factory(  # noqa: E302
+    _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
+    n_outputs=lambda kwds: _moment_outputs(kwds, [1, 2, 3, 4])
+)
+def lmoment(sample, order=None, *, axis=0, sorted=False, standardize=True):
+    r"""Compute L-moments of a sample from a continuous distribution
+
+    The L-moments of a probability distribution are summary statistics with
+    uses similar to those of conventional moments, but they are defined in
+    terms of the expected values of order statistics.
+    Sample L-moments are defined analogously to population L-moments, and
+    they can serve as estimators of population L-moments. They tend to be less
+    sensitive to extreme observations than conventional moments.
+
+    Parameters
+    ----------
+    sample : array_like
+        The real-valued sample whose L-moments are desired.
+    order : array_like, optional
+        The (positive integer) orders of the desired L-moments.
+        Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4].
+    axis : int or None, default=0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If None, the input will be
+        raveled before computing the statistic.
+    sorted : bool, default=False
+        Whether `sample` is already sorted in increasing order along `axis`.
+        If False (default), `sample` will be sorted.
+    standardize : bool, default=True
+        Whether to return L-moment ratios for orders 3 and higher.
+        L-moment ratios are analogous to standardized conventional
+        moments: they are the non-standardized L-moments divided
+        by the L-moment of order 2.
+
+    Returns
+    -------
+    lmoments : ndarray
+        The sample L-moments of order `order`.
+
+    See Also
+    --------
+    moment
+
+    References
+    ----------
+    .. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of
+           Statistical Data Analysis". Journal of Applied Mathematics and
+           Physics. 2014. :doi:`10.4236/jamp.2014.210104`
+    .. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions
+           Using Linear Combinations of Order Statistics". Journal of the Royal
+           Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x`
+    .. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(328458568356392)
+    >>> sample = rng.exponential(size=100000)
+    >>> stats.lmoment(sample)
+    array([1.00124272, 0.50111437, 0.3340092 , 0.16755338])
+
+    Note that the first four standardized population L-moments of the standard
+    exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments
+    provide reasonable estimates.
+
+    """
+    args = _lmoment_iv(sample, order, axis, sorted, standardize)
+    sample, order, axis, sorted, standardize = args
+
+    n_moments = np.max(order)
+    k = np.arange(n_moments, dtype=sample.dtype)
+    prk = _prk(np.expand_dims(k, tuple(range(1, sample.ndim+1))), k)
+    bk = _br(sample, r=k)
+
+    n = sample.shape[-1]
+    bk[..., n:] = 0  # remove NaNs due to n_moments > n
+
+    lmoms = np.sum(prk * bk, axis=-1)
+    if standardize and n_moments > 2:
+        lmoms[2:] /= lmoms[1]
+
+    lmoms[n:] = np.nan  # add NaNs where appropriate
+    return lmoms[order-1]
+
+
+LinregressResult = _make_tuple_bunch('LinregressResult',
+                                     ['slope', 'intercept', 'rvalue',
+                                      'pvalue', 'stderr'],
+                                     extra_field_names=['intercept_stderr'])
+
+
+def linregress(x, y=None, alternative='two-sided'):
+    """
+    Calculate a linear least-squares regression for two sets of measurements.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Two sets of measurements.  Both arrays should have the same length N.  If
+        only `x` is given (and ``y=None``), then it must be a two-dimensional
+        array where one dimension has length 2.  The two sets of measurements
+        are then found by splitting the array along the length-2 dimension. In
+        the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is
+        equivalent to ``linregress(x[0], x[1])``.
+
+        .. deprecated:: 1.14.0
+            Inference of the two sets of measurements from a single argument `x`
+            is deprecated will result in an error in SciPy 1.16.0; the sets
+            must be specified separately as `x` and `y`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the slope of the regression line is nonzero
+        * 'less': the slope of the regression line is less than zero
+        * 'greater':  the slope of the regression line is greater than zero
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    result : ``LinregressResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Slope of the regression line.
+        intercept : float
+            Intercept of the regression line.
+        rvalue : float
+            The Pearson correlation coefficient. The square of ``rvalue``
+            is equal to the coefficient of determination.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis is
+            that the slope is zero, using Wald Test with t-distribution of
+            the test statistic. See `alternative` above for alternative
+            hypotheses.
+        stderr : float
+            Standard error of the estimated slope (gradient), under the
+            assumption of residual normality.
+        intercept_stderr : float
+            Standard error of the estimated intercept, under the assumption
+            of residual normality.
+
+    See Also
+    --------
+    scipy.optimize.curve_fit :
+        Use non-linear least squares to fit a function to data.
+    scipy.optimize.leastsq :
+        Minimize the sum of squares of a set of equations.
+
+    Notes
+    -----
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
+    ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::
+
+        slope, intercept, r, p, se = linregress(x, y)
+
+    With that style, however, the standard error of the intercept is not
+    available.  To have access to all the computed values, including the
+    standard error of the intercept, use the return value as an object
+    with attributes, e.g.::
+
+        result = linregress(x, y)
+        print(result.intercept, result.intercept_stderr)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Generate some data:
+
+    >>> x = rng.random(10)
+    >>> y = 1.6*x + rng.random(10)
+
+    Perform the linear regression:
+
+    >>> res = stats.linregress(x, y)
+
+    Coefficient of determination (R-squared):
+
+    >>> print(f"R-squared: {res.rvalue**2:.6f}")
+    R-squared: 0.717533
+
+    Plot the data along with the fitted line:
+
+    >>> plt.plot(x, y, 'o', label='original data')
+    >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Calculate 95% confidence interval on slope and intercept:
+
+    >>> # Two-sided inverse Students t-distribution
+    >>> # p - probability, df - degrees of freedom
+    >>> from scipy.stats import t
+    >>> tinv = lambda p, df: abs(t.ppf(p/2, df))
+
+    >>> ts = tinv(0.05, len(x)-2)
+    >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
+    slope (95%): 1.453392 +/- 0.743465
+    >>> print(f"intercept (95%): {res.intercept:.6f}"
+    ...       f" +/- {ts*res.intercept_stderr:.6f}")
+    intercept (95%): 0.616950 +/- 0.544475
+
+    """
+    TINY = 1.0e-20
+    if y is None:  # x is a (2, N) or (N, 2) shaped array_like
+        message = ('Inference of the two sets of measurements from a single "'
+                   'argument `x` is deprecated will result in an error in "'
+                   'SciPy 1.16.0; the sets must be specified separately as "'
+                   '`x` and `y`.')
+        warnings.warn(message, DeprecationWarning, stacklevel=2)
+        x = np.asarray(x)
+        if x.shape[0] == 2:
+            x, y = x
+        elif x.shape[1] == 2:
+            x, y = x.T
+        else:
+            raise ValueError("If only `x` is given as input, it has to "
+                             "be of shape (2, N) or (N, 2); provided shape "
+                             f"was {x.shape}.")
+    else:
+        x = np.asarray(x)
+        y = np.asarray(y)
+
+    if x.size == 0 or y.size == 0:
+        raise ValueError("Inputs must not be empty.")
+
+    if np.amax(x) == np.amin(x) and len(x) > 1:
+        raise ValueError("Cannot calculate a linear regression "
+                         "if all x values are identical")
+
+    n = len(x)
+    xmean = np.mean(x, None)
+    ymean = np.mean(y, None)
+
+    # Average sums of square differences from the mean
+    #   ssxm = mean( (x-mean(x))^2 )
+    #   ssxym = mean( (x-mean(x)) * (y-mean(y)) )
+    ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat
+
+    # R-value
+    #   r = ssxym / sqrt( ssxm * ssym )
+    if ssxm == 0.0 or ssym == 0.0:
+        # If the denominator was going to be 0
+        r = 0.0
+    else:
+        r = ssxym / np.sqrt(ssxm * ssym)
+        # Test for numerical error propagation (make sure -1 < r < 1)
+        if r > 1.0:
+            r = 1.0
+        elif r < -1.0:
+            r = -1.0
+
+    slope = ssxym / ssxm
+    intercept = ymean - slope*xmean
+    if n == 2:
+        # handle case when only two points are passed in
+        if y[0] == y[1]:
+            prob = 1.0
+        else:
+            prob = 0.0
+        slope_stderr = 0.0
+        intercept_stderr = 0.0
+    else:
+        df = n - 2  # Number of degrees of freedom
+        # n-2 degrees of freedom because 2 has been used up
+        # to estimate the mean and standard deviation
+        t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
+
+        dist = _SimpleStudentT(df)
+        prob = _get_pvalue(t, dist, alternative, xp=np)
+        prob = prob[()] if prob.ndim == 0 else prob
+
+        slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df)
+
+        # Also calculate the standard error of the intercept
+        # The following relationship is used:
+        #   ssxm = mean( (x-mean(x))^2 )
+        #        = ssx - sx*sx
+        #        = mean( x^2 ) - mean(x)^2
+        intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2)
+
+    return LinregressResult(slope=slope, intercept=intercept, rvalue=r,
+                            pvalue=prob, stderr=slope_stderr,
+                            intercept_stderr=intercept_stderr)
+
+
+def _xp_mean(x, /, *, axis=None, weights=None, keepdims=False, nan_policy='propagate',
+             dtype=None, xp=None):
+    r"""Compute the arithmetic mean along the specified axis.
+
+    Parameters
+    ----------
+    x : real array
+        Array containing real numbers whose mean is desired.
+    axis : int or tuple of ints, default: None
+        If an int or tuple of ints, the axis or axes of the input along which
+        to compute the statistic. The statistic of each axis-slice (e.g. row)
+        of the input will appear in a corresponding element of the output.
+        If ``None``, the input will be raveled before computing the statistic.
+    weights : real array, optional
+        If specified, an array of weights associated with the values in `x`;
+        otherwise ``1``. If `weights` and `x` do not have the same shape, the
+        arrays will be broadcasted before performing the calculation. See
+        Notes for details.
+    keepdims : boolean, optional
+        If this is set to ``True``, the axes which are reduced are left
+        in the result as dimensions with length one. With this option,
+        the result will broadcast correctly against the input array.
+    nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate'
+        Defines how to handle input NaNs.
+
+        - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
+          which the statistic is computed, the corresponding entry of the output
+          will be NaN.
+        - ``omit``: NaNs will be omitted when performing the calculation.
+          If insufficient data remains in the axis slice along which the
+          statistic is computed, the corresponding entry of the output will be
+          NaN.
+        - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
+
+    dtype : dtype, optional
+        Type to use in computing the mean. For integer inputs, the default is
+        the default float type of the array library; for floating point inputs,
+        the dtype is that of the input.
+
+    Returns
+    -------
+    out : array
+        The mean of each slice
+
+    Notes
+    -----
+    Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i`
+    represent the corresponding element of `weights` after broadcasting. Then the
+    (weighted) mean :math:`\bar{x}_w` is given by:
+
+    .. math::
+
+        \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i }
+                         { \sum_{i=0}^{n-1} w_i }
+
+    where :math:`n` is the number of elements along a slice. Note that this simplifies
+    to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default).
+
+    The behavior of this function with respect to weights is somewhat different
+    from that of `np.average`. For instance,
+    `np.average` raises an error when `axis` is not specified and the shapes of `x`
+    and the `weights` array are not the same; `xp_mean` simply broadcasts the two.
+    Also, `np.average` raises an error when weights sum to zero along a slice;
+    `xp_mean` computes the appropriate result. The intent is for this function's
+    interface to be consistent with the rest of `scipy.stats`.
+
+    Note that according to the formula, including NaNs with zero weights is not
+    the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case,
+    the NaNs will continue to propagate through the calculation whereas in the
+    latter case, the NaNs are excluded entirely.
+
+    """
+    # ensure that `x` and `weights` are array-API compatible arrays of identical shape
+    xp = array_namespace(x) if xp is None else xp
+    x = _asarray(x, dtype=dtype, subok=True)
+    weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights
+
+    # to ensure that this matches the behavior of decorated functions when one of the
+    # arguments has size zero, it's easiest to call a similar decorated function.
+    if is_numpy(xp) and (xp_size(x) == 0
+                         or (weights is not None and xp_size(weights) == 0)):
+        return gmean(x, weights=weights, axis=axis, keepdims=keepdims)
+
+    x, weights = xp_broadcast_promote(x, weights, force_floating=True)
+
+    # handle the special case of zero-sized arrays
+    message = (too_small_1d_not_omit if (x.ndim == 1 or axis is None)
+               else too_small_nd_not_omit)
+    if xp_size(x) == 0:
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore")
+            res = xp.mean(x, axis=axis, keepdims=keepdims)
+        if xp_size(res) != 0:
+            warnings.warn(message, SmallSampleWarning, stacklevel=2)
+        return res
+
+    contains_nan, _ = _contains_nan(x, nan_policy, xp_omit_okay=True, xp=xp)
+    if weights is not None:
+        contains_nan_w, _ = _contains_nan(weights, nan_policy, xp_omit_okay=True, xp=xp)
+        contains_nan = contains_nan | contains_nan_w
+
+    # Handle `nan_policy='omit'` by giving zero weight to NaNs, whether they
+    # appear in `x` or `weights`. Emit warning if there is an all-NaN slice.
+    message = (too_small_1d_omit if (x.ndim == 1 or axis is None)
+               else too_small_nd_omit)
+    if contains_nan and nan_policy == 'omit':
+        nan_mask = xp.isnan(x)
+        if weights is not None:
+            nan_mask |= xp.isnan(weights)
+        if xp.any(xp.all(nan_mask, axis=axis)):
+            warnings.warn(message, SmallSampleWarning, stacklevel=2)
+        weights = xp.ones_like(x) if weights is None else weights
+        x = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), x)
+        weights = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), weights)
+
+    # Perform the mean calculation itself
+    if weights is None:
+        return xp.mean(x, axis=axis, keepdims=keepdims)
+
+    norm = xp.sum(weights, axis=axis)
+    wsum = xp.sum(x * weights, axis=axis)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        res = wsum/norm
+
+    # Respect `keepdims` and convert NumPy 0-D arrays to scalars
+    if keepdims:
+
+        if axis is None:
+            final_shape = (1,) * len(x.shape)
+        else:
+            # axis can be a scalar or sequence
+            axes = (axis,) if not isinstance(axis, Sequence) else axis
+            final_shape = list(x.shape)
+            for i in axes:
+                final_shape[i] = 1
+
+        res = xp.reshape(res, final_shape)
+
+    return res[()] if res.ndim == 0 else res
+
+
+def _xp_var(x, /, *, axis=None, correction=0, keepdims=False, nan_policy='propagate',
+            dtype=None, xp=None):
+    # an array-api compatible function for variance with scipy.stats interface
+    # and features (e.g. `nan_policy`).
+    xp = array_namespace(x) if xp is None else xp
+    x = _asarray(x, subok=True)
+
+    # use `_xp_mean` instead of `xp.var` for desired warning behavior
+    # it would be nice to combine this with `_var`, which uses `_moment`
+    # and therefore warns when precision is lost, but that does not support
+    # `axis` tuples or keepdims. Eventually, `_axis_nan_policy` will simplify
+    # `axis` tuples and implement `keepdims` for non-NumPy arrays; then it will
+    # be easy.
+    kwargs = dict(axis=axis, nan_policy=nan_policy, dtype=dtype, xp=xp)
+    mean = _xp_mean(x, keepdims=True, **kwargs)
+    x = _asarray(x, dtype=mean.dtype, subok=True)
+    x_mean = _demean(x, mean, axis, xp=xp)
+    x_mean_conj = (xp.conj(x_mean) if xp.isdtype(x_mean.dtype, 'complex floating')
+                   else x_mean)  # crossref data-apis/array-api#824
+    var = _xp_mean(x_mean * x_mean_conj, keepdims=keepdims, **kwargs)
+
+    if correction != 0:
+        if axis is None:
+            n = xp_size(x)
+        elif np.iterable(axis):  # note: using NumPy on `axis` is OK
+            n = math.prod(x.shape[i] for i in axis)
+        else:
+            n = x.shape[axis]
+        # Or two lines with ternaries : )
+        # axis = range(x.ndim) if axis is None else axis
+        # n = math.prod(x.shape[i] for i in axis) if iterable(axis) else x.shape[axis]
+
+        n = xp.asarray(n, dtype=var.dtype)
+
+        if nan_policy == 'omit':
+            nan_mask = xp.astype(xp.isnan(x), var.dtype)
+            n = n - xp.sum(nan_mask, axis=axis, keepdims=keepdims)
+
+        # Produce NaNs silently when n - correction <= 0
+        factor = _lazywhere(n-correction > 0, (n, n-correction), xp.divide, xp.nan)
+        var *= factor
+
+    return var[()] if var.ndim == 0 else var
+
+
+class _SimpleNormal:
+    # A very simple, array-API compatible normal distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure Normal
+    # distribution in due time.
+
+    def cdf(self, x):
+        return special.ndtr(x)
+
+    def sf(self, x):
+        return special.ndtr(-x)
+
+    def isf(self, x):
+        return -special.ndtri(x)
+
+
+class _SimpleChi2:
+    # A very simple, array-API compatible chi-squared distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure chi-squared
+    # distribution in due time.
+    def __init__(self, df):
+        self.df = df
+
+    def cdf(self, x):
+        return special.chdtr(self.df, x)
+
+    def sf(self, x):
+        return special.chdtrc(self.df, x)
+
+
+class _SimpleBeta:
+    # A very simple, array-API compatible beta distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure beta
+    # distribution in due time.
+    def __init__(self, a, b, *, loc=None, scale=None):
+        self.a = a
+        self.b = b
+        self.loc = loc
+        self.scale = scale
+
+    def cdf(self, x):
+        if self.loc is not None or self.scale is not None:
+            loc = 0 if self.loc is None else self.loc
+            scale = 1 if self.scale is None else self.scale
+            return special.betainc(self.a, self.b, (x - loc)/scale)
+        return special.betainc(self.a, self.b, x)
+
+    def sf(self, x):
+        if self.loc is not None or self.scale is not None:
+            loc = 0 if self.loc is None else self.loc
+            scale = 1 if self.scale is None else self.scale
+            return special.betaincc(self.a, self.b, (x - loc)/scale)
+        return special.betaincc(self.a, self.b, x)
+
+
+class _SimpleStudentT:
+    # A very simple, array-API compatible t distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure t
+    # distribution in due time.
+    def __init__(self, df):
+        self.df = df
+
+    def cdf(self, t):
+        return special.stdtr(self.df, t)
+
+    def sf(self, t):
+        return special.stdtr(self.df, -t)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_stats_pythran.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/stats/_stats_pythran.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..9960807a6f227427396f483270fe4a998db939fc
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/stats/_stats_pythran.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_survival.py b/python_embeded/Lib/site-packages/scipy/stats/_survival.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5166691a3a77330e1e25d238a83d8a6b557805
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_survival.py
@@ -0,0 +1,683 @@
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Literal
+import warnings
+
+import numpy as np
+from scipy import special, interpolate, stats
+from scipy.stats._censored_data import CensoredData
+from scipy.stats._common import ConfidenceInterval
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+
+__all__ = ['ecdf', 'logrank']
+
+
+@dataclass
+class EmpiricalDistributionFunction:
+    """An empirical distribution function produced by `scipy.stats.ecdf`
+
+    Attributes
+    ----------
+    quantiles : ndarray
+        The unique values of the sample from which the
+        `EmpiricalDistributionFunction` was estimated.
+    probabilities : ndarray
+        The point estimates of the cumulative distribution function (CDF) or
+        its complement, the survival function (SF), corresponding with
+        `quantiles`.
+    """
+    quantiles: np.ndarray
+    probabilities: np.ndarray
+    # Exclude these from __str__
+    _n: np.ndarray = field(repr=False)  # number "at risk"
+    _d: np.ndarray = field(repr=False)  # number of "deaths"
+    _sf: np.ndarray = field(repr=False)  # survival function for var estimate
+    _kind: str = field(repr=False)  # type of function: "cdf" or "sf"
+
+    def __init__(self, q, p, n, d, kind):
+        self.probabilities = p
+        self.quantiles = q
+        self._n = n
+        self._d = d
+        self._sf = p if kind == 'sf' else 1 - p
+        self._kind = kind
+
+        f0 = 1 if kind == 'sf' else 0  # leftmost function value
+        f1 = 1 - f0
+        # fill_value can't handle edge cases at infinity
+        x = np.insert(q, [0, len(q)], [-np.inf, np.inf])
+        y = np.insert(p, [0, len(p)], [f0, f1])
+        # `or` conditions handle the case of empty x, points
+        self._f = interpolate.interp1d(x, y, kind='previous',
+                                       assume_sorted=True)
+
+    def evaluate(self, x):
+        """Evaluate the empirical CDF/SF function at the input.
+
+        Parameters
+        ----------
+        x : ndarray
+            Argument to the CDF/SF
+
+        Returns
+        -------
+        y : ndarray
+            The CDF/SF evaluated at the input
+        """
+        return self._f(x)
+
+    def plot(self, ax=None, **matplotlib_kwargs):
+        """Plot the empirical distribution function
+
+        Available only if ``matplotlib`` is installed.
+
+        Parameters
+        ----------
+        ax : matplotlib.axes.Axes
+            Axes object to draw the plot onto, otherwise uses the current Axes.
+
+        **matplotlib_kwargs : dict, optional
+            Keyword arguments passed directly to `matplotlib.axes.Axes.step`.
+            Unless overridden, ``where='post'``.
+
+        Returns
+        -------
+        lines : list of `matplotlib.lines.Line2D`
+            Objects representing the plotted data
+        """
+        try:
+            import matplotlib  # noqa: F401
+        except ModuleNotFoundError as exc:
+            message = "matplotlib must be installed to use method `plot`."
+            raise ModuleNotFoundError(message) from exc
+
+        if ax is None:
+            import matplotlib.pyplot as plt
+            ax = plt.gca()
+
+        kwargs = {'where': 'post'}
+        kwargs.update(matplotlib_kwargs)
+
+        delta = np.ptp(self.quantiles)*0.05  # how far past sample edge to plot
+        q = self.quantiles
+        q = [q[0] - delta] + list(q) + [q[-1] + delta]
+
+        return ax.step(q, self.evaluate(q), **kwargs)
+
+    def confidence_interval(self, confidence_level=0.95, *, method='linear'):
+        """Compute a confidence interval around the CDF/SF point estimate
+
+        Parameters
+        ----------
+        confidence_level : float, default: 0.95
+            Confidence level for the computed confidence interval
+
+        method : str, {"linear", "log-log"}
+            Method used to compute the confidence interval. Options are
+            "linear" for the conventional Greenwood confidence interval
+            (default)  and "log-log" for the "exponential Greenwood",
+            log-negative-log-transformed confidence interval.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval``
+            An object with attributes ``low`` and ``high``, instances of
+            `~scipy.stats._result_classes.EmpiricalDistributionFunction` that
+            represent the lower and upper bounds (respectively) of the
+            confidence interval.
+
+        Notes
+        -----
+        Confidence intervals are computed according to the Greenwood formula
+        (``method='linear'``) or the more recent "exponential Greenwood"
+        formula (``method='log-log'``) as described in [1]_. The conventional
+        Greenwood formula can result in lower confidence limits less than 0
+        and upper confidence limits greater than 1; these are clipped to the
+        unit interval. NaNs may be produced by either method; these are
+        features of the formulas.
+
+        References
+        ----------
+        .. [1] Sawyer, Stanley. "The Greenwood and Exponential Greenwood
+               Confidence Intervals in Survival Analysis."
+               https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
+
+        """
+        message = ("Confidence interval bounds do not implement a "
+                   "`confidence_interval` method.")
+        if self._n is None:
+            raise NotImplementedError(message)
+
+        methods = {'linear': self._linear_ci,
+                   'log-log': self._loglog_ci}
+
+        message = f"`method` must be one of {set(methods)}."
+        if method.lower() not in methods:
+            raise ValueError(message)
+
+        message = "`confidence_level` must be a scalar between 0 and 1."
+        confidence_level = np.asarray(confidence_level)[()]
+        if confidence_level.shape or not (0 <= confidence_level <= 1):
+            raise ValueError(message)
+
+        method_fun = methods[method.lower()]
+        low, high = method_fun(confidence_level)
+
+        message = ("The confidence interval is undefined at some observations."
+                   " This is a feature of the mathematical formula used, not"
+                   " an error in its implementation.")
+        if np.any(np.isnan(low) | np.isnan(high)):
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        low, high = np.clip(low, 0, 1), np.clip(high, 0, 1)
+        low = EmpiricalDistributionFunction(self.quantiles, low, None, None,
+                                            self._kind)
+        high = EmpiricalDistributionFunction(self.quantiles, high, None, None,
+                                             self._kind)
+        return ConfidenceInterval(low, high)
+
+    def _linear_ci(self, confidence_level):
+        sf, d, n = self._sf, self._d, self._n
+        # When n == d, Greenwood's formula divides by zero.
+        # When s != 0, this can be ignored: var == inf, and CI is [0, 1]
+        # When s == 0, this results in NaNs. Produce an informative warning.
+        with np.errstate(divide='ignore', invalid='ignore'):
+            var = sf ** 2 * np.cumsum(d / (n * (n - d)))
+
+        se = np.sqrt(var)
+        z = special.ndtri(1 / 2 + confidence_level / 2)
+
+        z_se = z * se
+        low = self.probabilities - z_se
+        high = self.probabilities + z_se
+
+        return low, high
+
+    def _loglog_ci(self, confidence_level):
+        sf, d, n = self._sf, self._d, self._n
+
+        with np.errstate(divide='ignore', invalid='ignore'):
+            var = 1 / np.log(sf) ** 2 * np.cumsum(d / (n * (n - d)))
+
+        se = np.sqrt(var)
+        z = special.ndtri(1 / 2 + confidence_level / 2)
+
+        with np.errstate(divide='ignore'):
+            lnl_points = np.log(-np.log(sf))
+
+        z_se = z * se
+        low = np.exp(-np.exp(lnl_points + z_se))
+        high = np.exp(-np.exp(lnl_points - z_se))
+        if self._kind == "cdf":
+            low, high = 1-high, 1-low
+
+        return low, high
+
+
+@dataclass
+class ECDFResult:
+    """ Result object returned by `scipy.stats.ecdf`
+
+    Attributes
+    ----------
+    cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+        An object representing the empirical cumulative distribution function.
+    sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+        An object representing the complement of the empirical cumulative
+        distribution function.
+    """
+    cdf: EmpiricalDistributionFunction
+    sf: EmpiricalDistributionFunction
+
+    def __init__(self, q, cdf, sf, n, d):
+        self.cdf = EmpiricalDistributionFunction(q, cdf, n, d, "cdf")
+        self.sf = EmpiricalDistributionFunction(q, sf, n, d, "sf")
+
+
+def _iv_CensoredData(
+    sample: "npt.ArrayLike | CensoredData", param_name: str = "sample"
+) -> CensoredData:
+    """Attempt to convert `sample` to `CensoredData`."""
+    if not isinstance(sample, CensoredData):
+        try:  # takes care of input standardization/validation
+            sample = CensoredData(uncensored=sample)
+        except ValueError as e:
+            message = str(e).replace('uncensored', param_name)
+            raise type(e)(message) from e
+    return sample
+
+
+def ecdf(sample: "npt.ArrayLike | CensoredData") -> ECDFResult:
+    """Empirical cumulative distribution function of a sample.
+
+    The empirical cumulative distribution function (ECDF) is a step function
+    estimate of the CDF of the distribution underlying a sample. This function
+    returns objects representing both the empirical distribution function and
+    its complement, the empirical survival function.
+
+    Parameters
+    ----------
+    sample : 1D array_like or `scipy.stats.CensoredData`
+        Besides array_like, instances of `scipy.stats.CensoredData` containing
+        uncensored and right-censored observations are supported. Currently,
+        other instances of `scipy.stats.CensoredData` will result in a
+        ``NotImplementedError``.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.ECDFResult`
+        An object with the following attributes.
+
+        cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+            An object representing the empirical cumulative distribution
+            function.
+        sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+            An object representing the empirical survival function.
+
+        The `cdf` and `sf` attributes themselves have the following attributes.
+
+        quantiles : ndarray
+            The unique values in the sample that defines the empirical CDF/SF.
+        probabilities : ndarray
+            The point estimates of the probabilities corresponding with
+            `quantiles`.
+
+        And the following methods:
+
+        evaluate(x) :
+            Evaluate the CDF/SF at the argument.
+
+        plot(ax) :
+            Plot the CDF/SF on the provided axes.
+
+        confidence_interval(confidence_level=0.95) :
+            Compute the confidence interval around the CDF/SF at the values in
+            `quantiles`.
+
+    Notes
+    -----
+    When each observation of the sample is a precise measurement, the ECDF
+    steps up by ``1/len(sample)`` at each of the observations [1]_.
+
+    When observations are lower bounds, upper bounds, or both upper and lower
+    bounds, the data is said to be "censored", and `sample` may be provided as
+    an instance of `scipy.stats.CensoredData`.
+
+    For right-censored data, the ECDF is given by the Kaplan-Meier estimator
+    [2]_; other forms of censoring are not supported at this time.
+
+    Confidence intervals are computed according to the Greenwood formula or the
+    more recent "Exponential Greenwood" formula as described in [4]_.
+
+    References
+    ----------
+    .. [1] Conover, William Jay. Practical nonparametric statistics. Vol. 350.
+           John Wiley & Sons, 1999.
+
+    .. [2] Kaplan, Edward L., and Paul Meier. "Nonparametric estimation from
+           incomplete observations." Journal of the American statistical
+           association 53.282 (1958): 457-481.
+
+    .. [3] Goel, Manish Kumar, Pardeep Khanna, and Jugal Kishore.
+           "Understanding survival analysis: Kaplan-Meier estimate."
+           International journal of Ayurveda research 1.4 (2010): 274.
+
+    .. [4] Sawyer, Stanley. "The Greenwood and Exponential Greenwood Confidence
+           Intervals in Survival Analysis."
+           https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
+
+    Examples
+    --------
+    **Uncensored Data**
+
+    As in the example from [1]_ page 79, five boys were selected at random from
+    those in a single high school. Their one-mile run times were recorded as
+    follows.
+
+    >>> sample = [6.23, 5.58, 7.06, 6.42, 5.20]  # one-mile run times (minutes)
+
+    The empirical distribution function, which approximates the distribution
+    function of one-mile run times of the population from which the boys were
+    sampled, is calculated as follows.
+
+    >>> from scipy import stats
+    >>> res = stats.ecdf(sample)
+    >>> res.cdf.quantiles
+    array([5.2 , 5.58, 6.23, 6.42, 7.06])
+    >>> res.cdf.probabilities
+    array([0.2, 0.4, 0.6, 0.8, 1. ])
+
+    To plot the result as a step function:
+
+    >>> import matplotlib.pyplot as plt
+    >>> ax = plt.subplot()
+    >>> res.cdf.plot(ax)
+    >>> ax.set_xlabel('One-Mile Run Time (minutes)')
+    >>> ax.set_ylabel('Empirical CDF')
+    >>> plt.show()
+
+    **Right-censored Data**
+
+    As in the example from [1]_ page 91, the lives of ten car fanbelts were
+    tested. Five tests concluded because the fanbelt being tested broke, but
+    the remaining tests concluded for other reasons (e.g. the study ran out of
+    funding, but the fanbelt was still functional). The mileage driven
+    with the fanbelts were recorded as follows.
+
+    >>> broken = [77, 47, 81, 56, 80]  # in thousands of miles driven
+    >>> unbroken = [62, 60, 43, 71, 37]
+
+    Precise survival times of the fanbelts that were still functional at the
+    end of the tests are unknown, but they are known to exceed the values
+    recorded in ``unbroken``. Therefore, these observations are said to be
+    "right-censored", and the data is represented using
+    `scipy.stats.CensoredData`.
+
+    >>> sample = stats.CensoredData(uncensored=broken, right=unbroken)
+
+    The empirical survival function is calculated as follows.
+
+    >>> res = stats.ecdf(sample)
+    >>> res.sf.quantiles
+    array([37., 43., 47., 56., 60., 62., 71., 77., 80., 81.])
+    >>> res.sf.probabilities
+    array([1.   , 1.   , 0.875, 0.75 , 0.75 , 0.75 , 0.75 , 0.5  , 0.25 , 0.   ])
+
+    To plot the result as a step function:
+
+    >>> ax = plt.subplot()
+    >>> res.sf.plot(ax)
+    >>> ax.set_xlabel('Fanbelt Survival Time (thousands of miles)')
+    >>> ax.set_ylabel('Empirical SF')
+    >>> plt.show()
+
+    """
+    sample = _iv_CensoredData(sample)
+
+    if sample.num_censored() == 0:
+        res = _ecdf_uncensored(sample._uncensor())
+    elif sample.num_censored() == sample._right.size:
+        res = _ecdf_right_censored(sample)
+    else:
+        # Support additional censoring options in follow-up PRs
+        message = ("Currently, only uncensored and right-censored data is "
+                   "supported.")
+        raise NotImplementedError(message)
+
+    t, cdf, sf, n, d = res
+    return ECDFResult(t, cdf, sf, n, d)
+
+
+def _ecdf_uncensored(sample):
+    sample = np.sort(sample)
+    x, counts = np.unique(sample, return_counts=True)
+
+    # [1].81 "the fraction of [observations] that are less than or equal to x
+    events = np.cumsum(counts)
+    n = sample.size
+    cdf = events / n
+
+    # [1].89 "the relative frequency of the sample that exceeds x in value"
+    sf = 1 - cdf
+
+    at_risk = np.concatenate(([n], n - events[:-1]))
+    return x, cdf, sf, at_risk, counts
+
+
+def _ecdf_right_censored(sample):
+    # It is conventional to discuss right-censored data in terms of
+    # "survival time", "death", and "loss" (e.g. [2]). We'll use that
+    # terminology here.
+    # This implementation was influenced by the references cited and also
+    # https://www.youtube.com/watch?v=lxoWsVco_iM
+    # https://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator
+    # In retrospect it is probably most easily compared against [3].
+    # Ultimately, the data needs to be sorted, so this implementation is
+    # written to avoid a separate call to `unique` after sorting. In hope of
+    # better performance on large datasets, it also computes survival
+    # probabilities at unique times only rather than at each observation.
+    tod = sample._uncensored  # time of "death"
+    tol = sample._right  # time of "loss"
+    times = np.concatenate((tod, tol))
+    died = np.asarray([1]*tod.size + [0]*tol.size)
+
+    # sort by times
+    i = np.argsort(times)
+    times = times[i]
+    died = died[i]
+    at_risk = np.arange(times.size, 0, -1)
+
+    # logical indices of unique times
+    j = np.diff(times, prepend=-np.inf, append=np.inf) > 0
+    j_l = j[:-1]  # first instances of unique times
+    j_r = j[1:]  # last instances of unique times
+
+    # get number at risk and deaths at each unique time
+    t = times[j_l]  # unique times
+    n = at_risk[j_l]  # number at risk at each unique time
+    cd = np.cumsum(died)[j_r]  # cumulative deaths up to/including unique times
+    d = np.diff(cd, prepend=0)  # deaths at each unique time
+
+    # compute survival function
+    sf = np.cumprod((n - d) / n)
+    cdf = 1 - sf
+    return t, cdf, sf, n, d
+
+
+@dataclass
+class LogRankResult:
+    """Result object returned by `scipy.stats.logrank`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic (defined below). Its magnitude is the
+        square root of the magnitude returned by most other logrank test
+        implementations.
+    pvalue : float ndarray
+        The computed p-value of the test.
+    """
+    statistic: np.ndarray
+    pvalue: np.ndarray
+
+
+def logrank(
+    x: "npt.ArrayLike | CensoredData",
+    y: "npt.ArrayLike | CensoredData",
+    alternative: Literal['two-sided', 'less', 'greater'] = "two-sided"
+) -> LogRankResult:
+    r"""Compare the survival distributions of two samples via the logrank test.
+
+    Parameters
+    ----------
+    x, y : array_like or CensoredData
+        Samples to compare based on their empirical survival functions.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+
+        The null hypothesis is that the survival distributions of the two
+        groups, say *X* and *Y*, are identical.
+
+        The following alternative hypotheses [4]_ are available (default is
+        'two-sided'):
+
+        * 'two-sided': the survival distributions of the two groups are not
+          identical.
+        * 'less': survival of group *X* is favored: the group *X* failure rate
+          function is less than the group *Y* failure rate function at some
+          times.
+        * 'greater': survival of group *Y* is favored: the group *X* failure
+          rate function is greater than the group *Y* failure rate function at
+          some times.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.LogRankResult`
+        An object containing attributes:
+
+        statistic : float ndarray
+            The computed statistic (defined below). Its magnitude is the
+            square root of the magnitude returned by most other logrank test
+            implementations.
+        pvalue : float ndarray
+            The computed p-value of the test.
+
+    See Also
+    --------
+    scipy.stats.ecdf
+
+    Notes
+    -----
+    The logrank test [1]_ compares the observed number of events to
+    the expected number of events under the null hypothesis that the two
+    samples were drawn from the same distribution. The statistic is
+
+    .. math::
+
+        Z_i = \frac{\sum_{j=1}^J(O_{i,j}-E_{i,j})}{\sqrt{\sum_{j=1}^J V_{i,j}}}
+        \rightarrow \mathcal{N}(0,1)
+
+    where
+
+    .. math::
+
+        E_{i,j} = O_j \frac{N_{i,j}}{N_j},
+        \qquad
+        V_{i,j} = E_{i,j} \left(\frac{N_j-O_j}{N_j}\right)
+        \left(\frac{N_j-N_{i,j}}{N_j-1}\right),
+
+    :math:`i` denotes the group (i.e. it may assume values :math:`x` or
+    :math:`y`, or it may be omitted to refer to the combined sample)
+    :math:`j` denotes the time (at which an event occurred),
+    :math:`N` is the number of subjects at risk just before an event occurred,
+    and :math:`O` is the observed number of events at that time.
+
+    The ``statistic`` :math:`Z_x` returned by `logrank` is the (signed) square
+    root of the statistic returned by many other implementations. Under the
+    null hypothesis, :math:`Z_x**2` is asymptotically distributed according to
+    the chi-squared distribution with one degree of freedom. Consequently,
+    :math:`Z_x` is asymptotically distributed according to the standard normal
+    distribution. The advantage of using :math:`Z_x` is that the sign
+    information (i.e. whether the observed number of events tends to be less
+    than or greater than the number expected under the null hypothesis) is
+    preserved, allowing `scipy.stats.logrank` to offer one-sided alternative
+    hypotheses.
+
+    References
+    ----------
+    .. [1] Mantel N. "Evaluation of survival data and two new rank order
+           statistics arising in its consideration."
+           Cancer Chemotherapy Reports, 50(3):163-170, PMID: 5910392, 1966
+    .. [2] Bland, Altman, "The logrank test", BMJ, 328:1073,
+           :doi:`10.1136/bmj.328.7447.1073`, 2004
+    .. [3] "Logrank test", Wikipedia,
+           https://en.wikipedia.org/wiki/Logrank_test
+    .. [4] Brown, Mark. "On the choice of variance for the log rank test."
+           Biometrika 71.1 (1984): 65-74.
+    .. [5] Klein, John P., and Melvin L. Moeschberger. Survival analysis:
+           techniques for censored and truncated data. Vol. 1230. New York:
+           Springer, 2003.
+
+    Examples
+    --------
+    Reference [2]_ compared the survival times of patients with two different
+    types of recurrent malignant gliomas. The samples below record the time
+    (number of weeks) for which each patient participated in the study. The
+    `scipy.stats.CensoredData` class is used because the data is
+    right-censored: the uncensored observations correspond with observed deaths
+    whereas the censored observations correspond with the patient leaving the
+    study for another reason.
+
+    >>> from scipy import stats
+    >>> x = stats.CensoredData(
+    ...     uncensored=[6, 13, 21, 30, 37, 38, 49, 50,
+    ...                 63, 79, 86, 98, 202, 219],
+    ...     right=[31, 47, 80, 82, 82, 149]
+    ... )
+    >>> y = stats.CensoredData(
+    ...     uncensored=[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24,
+    ...                 25, 28,30, 33, 35, 37, 40, 40, 46, 48, 76, 81,
+    ...                 82, 91, 112, 181],
+    ...     right=[34, 40, 70]
+    ... )
+
+    We can calculate and visualize the empirical survival functions
+    of both groups as follows.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> ax = plt.subplot()
+    >>> ecdf_x = stats.ecdf(x)
+    >>> ecdf_x.sf.plot(ax, label='Astrocytoma')
+    >>> ecdf_y = stats.ecdf(y)
+    >>> ecdf_y.sf.plot(ax, label='Glioblastoma')
+    >>> ax.set_xlabel('Time to death (weeks)')
+    >>> ax.set_ylabel('Empirical SF')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Visual inspection of the empirical survival functions suggests that the
+    survival times tend to be different between the two groups. To formally
+    assess whether the difference is significant at the 1% level, we use the
+    logrank test.
+
+    >>> res = stats.logrank(x=x, y=y)
+    >>> res.statistic
+    -2.73799
+    >>> res.pvalue
+    0.00618
+
+    The p-value is less than 1%, so we can consider the data to be evidence
+    against the null hypothesis in favor of the alternative that there is a
+    difference between the two survival functions.
+
+    """
+    # Input validation. `alternative` IV handled in `_get_pvalue` below.
+    x = _iv_CensoredData(sample=x, param_name='x')
+    y = _iv_CensoredData(sample=y, param_name='y')
+
+    # Combined sample. (Under H0, the two groups are identical.)
+    xy = CensoredData(
+        uncensored=np.concatenate((x._uncensored, y._uncensored)),
+        right=np.concatenate((x._right, y._right))
+    )
+
+    # Extract data from the combined sample
+    res = ecdf(xy)
+    idx = res.sf._d.astype(bool)  # indices of observed events
+    times_xy = res.sf.quantiles[idx]  # unique times of observed events
+    at_risk_xy = res.sf._n[idx]  # combined number of subjects at risk
+    deaths_xy = res.sf._d[idx]  # combined number of events
+
+    # Get the number at risk within each sample.
+    # First compute the number at risk in group X at each of the `times_xy`.
+    # Could use `interpolate_1d`, but this is more compact.
+    res_x = ecdf(x)
+    i = np.searchsorted(res_x.sf.quantiles, times_xy)
+    at_risk_x = np.append(res_x.sf._n, 0)[i]  # 0 at risk after last time
+    # Subtract from the combined number at risk to get number at risk in Y
+    at_risk_y = at_risk_xy - at_risk_x
+
+    # Compute the variance.
+    num = at_risk_x * at_risk_y * deaths_xy * (at_risk_xy - deaths_xy)
+    den = at_risk_xy**2 * (at_risk_xy - 1)
+    # Note: when `at_risk_xy == 1`, we would have `at_risk_xy - 1 == 0` in the
+    # numerator and denominator. Simplifying the fraction symbolically, we
+    # would always find the overall quotient to be zero, so don't compute it.
+    i = at_risk_xy > 1
+    sum_var = np.sum(num[i]/den[i])
+
+    # Get the observed and expected number of deaths in group X
+    n_died_x = x._uncensored.size
+    sum_exp_deaths_x = np.sum(at_risk_x * (deaths_xy/at_risk_xy))
+
+    # Compute the statistic. This is the square root of that in references.
+    statistic = (n_died_x - sum_exp_deaths_x)/np.sqrt(sum_var)
+
+    # Equivalent to chi2(df=1).sf(statistic**2) when alternative='two-sided'
+    norm = stats._stats_py._SimpleNormal()
+    pvalue = stats._stats_py._get_pvalue(statistic, norm, alternative, xp=np)
+
+    return LogRankResult(statistic=statistic[()], pvalue=pvalue[()])
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_tukeylambda_stats.py b/python_embeded/Lib/site-packages/scipy/stats/_tukeylambda_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..be2802905746a24c26a04188914498931c8d888c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_tukeylambda_stats.py
@@ -0,0 +1,199 @@
+import numpy as np
+from numpy import poly1d
+from scipy.special import beta
+
+
+# The following code was used to generate the Pade coefficients for the
+# Tukey Lambda variance function.  Version 0.17 of mpmath was used.
+#---------------------------------------------------------------------------
+# import mpmath as mp
+#
+# mp.mp.dps = 60
+#
+# one   = mp.mpf(1)
+# two   = mp.mpf(2)
+#
+# def mpvar(lam):
+#     if lam == 0:
+#         v = mp.pi**2 / three
+#     else:
+#         v = (two / lam**2) * (one / (one + two*lam) -
+#                               mp.beta(lam + one, lam + one))
+#     return v
+#
+# t = mp.taylor(mpvar, 0, 8)
+# p, q = mp.pade(t, 4, 4)
+# print("p =", [mp.fp.mpf(c) for c in p])
+# print("q =", [mp.fp.mpf(c) for c in q])
+#---------------------------------------------------------------------------
+
+# Pade coefficients for the Tukey Lambda variance function.
+_tukeylambda_var_pc = [3.289868133696453, 0.7306125098871127,
+                       -0.5370742306855439, 0.17292046290190008,
+                       -0.02371146284628187]
+_tukeylambda_var_qc = [1.0, 3.683605511659861, 4.184152498888124,
+                       1.7660926747377275, 0.2643989311168465]
+
+# numpy.poly1d instances for the numerator and denominator of the
+# Pade approximation to the Tukey Lambda variance.
+_tukeylambda_var_p = poly1d(_tukeylambda_var_pc[::-1])
+_tukeylambda_var_q = poly1d(_tukeylambda_var_qc[::-1])
+
+
+def tukeylambda_variance(lam):
+    """Variance of the Tukey Lambda distribution.
+
+    Parameters
+    ----------
+    lam : array_like
+        The lambda values at which to compute the variance.
+
+    Returns
+    -------
+    v : ndarray
+        The variance.  For lam < -0.5, the variance is not defined, so
+        np.nan is returned.  For lam = 0.5, np.inf is returned.
+
+    Notes
+    -----
+    In an interval around lambda=0, this function uses the [4,4] Pade
+    approximation to compute the variance.  Otherwise it uses the standard
+    formula (https://en.wikipedia.org/wiki/Tukey_lambda_distribution).  The
+    Pade approximation is used because the standard formula has a removable
+    discontinuity at lambda = 0, and does not produce accurate numerical
+    results near lambda = 0.
+    """
+    lam = np.asarray(lam)
+    shp = lam.shape
+    lam = np.atleast_1d(lam).astype(np.float64)
+
+    # For absolute values of lam less than threshold, use the Pade
+    # approximation.
+    threshold = 0.075
+
+    # Play games with masks to implement the conditional evaluation of
+    # the distribution.
+    # lambda < -0.5:  var = nan
+    low_mask = lam < -0.5
+    # lambda == -0.5: var = inf
+    neghalf_mask = lam == -0.5
+    # abs(lambda) < threshold:  use Pade approximation
+    small_mask = np.abs(lam) < threshold
+    # else the "regular" case:  use the explicit formula.
+    reg_mask = ~(low_mask | neghalf_mask | small_mask)
+
+    # Get the 'lam' values for the cases where they are needed.
+    small = lam[small_mask]
+    reg = lam[reg_mask]
+
+    # Compute the function for each case.
+    v = np.empty_like(lam)
+    v[low_mask] = np.nan
+    v[neghalf_mask] = np.inf
+    if small.size > 0:
+        # Use the Pade approximation near lambda = 0.
+        v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small)
+    if reg.size > 0:
+        v[reg_mask] = (2.0 / reg**2) * (1.0 / (1.0 + 2 * reg) -
+                                        beta(reg + 1, reg + 1))
+    v.shape = shp
+    return v
+
+
+# The following code was used to generate the Pade coefficients for the
+# Tukey Lambda kurtosis function.  Version 0.17 of mpmath was used.
+#---------------------------------------------------------------------------
+# import mpmath as mp
+#
+# mp.mp.dps = 60
+#
+# one   = mp.mpf(1)
+# two   = mp.mpf(2)
+# three = mp.mpf(3)
+# four  = mp.mpf(4)
+#
+# def mpkurt(lam):
+#     if lam == 0:
+#         k = mp.mpf(6)/5
+#     else:
+#         numer = (one/(four*lam+one) - four*mp.beta(three*lam+one, lam+one) +
+#                  three*mp.beta(two*lam+one, two*lam+one))
+#         denom = two*(one/(two*lam+one) - mp.beta(lam+one,lam+one))**2
+#         k = numer / denom - three
+#     return k
+#
+# # There is a bug in mpmath 0.17: when we use the 'method' keyword of the
+# # taylor function and we request a degree 9 Taylor polynomial, we actually
+# # get degree 8.
+# t = mp.taylor(mpkurt, 0, 9, method='quad', radius=0.01)
+# t = [mp.chop(c, tol=1e-15) for c in t]
+# p, q = mp.pade(t, 4, 4)
+# print("p =", [mp.fp.mpf(c) for c in p])
+# print("q =", [mp.fp.mpf(c) for c in q])
+#---------------------------------------------------------------------------
+
+# Pade coefficients for the Tukey Lambda kurtosis function.
+_tukeylambda_kurt_pc = [1.2, -5.853465139719495, -22.653447381131077,
+                        0.20601184383406815, 4.59796302262789]
+_tukeylambda_kurt_qc = [1.0, 7.171149192233599, 12.96663094361842,
+                        0.43075235247853005, -2.789746758009912]
+
+# numpy.poly1d instances for the numerator and denominator of the
+# Pade approximation to the Tukey Lambda kurtosis.
+_tukeylambda_kurt_p = poly1d(_tukeylambda_kurt_pc[::-1])
+_tukeylambda_kurt_q = poly1d(_tukeylambda_kurt_qc[::-1])
+
+
+def tukeylambda_kurtosis(lam):
+    """Kurtosis of the Tukey Lambda distribution.
+
+    Parameters
+    ----------
+    lam : array_like
+        The lambda values at which to compute the variance.
+
+    Returns
+    -------
+    v : ndarray
+        The variance.  For lam < -0.25, the variance is not defined, so
+        np.nan is returned.  For lam = 0.25, np.inf is returned.
+
+    """
+    lam = np.asarray(lam)
+    shp = lam.shape
+    lam = np.atleast_1d(lam).astype(np.float64)
+
+    # For absolute values of lam less than threshold, use the Pade
+    # approximation.
+    threshold = 0.055
+
+    # Use masks to implement the conditional evaluation of the kurtosis.
+    # lambda < -0.25:  kurtosis = nan
+    low_mask = lam < -0.25
+    # lambda == -0.25: kurtosis = inf
+    negqrtr_mask = lam == -0.25
+    # lambda near 0:  use Pade approximation
+    small_mask = np.abs(lam) < threshold
+    # else the "regular" case:  use the explicit formula.
+    reg_mask = ~(low_mask | negqrtr_mask | small_mask)
+
+    # Get the 'lam' values for the cases where they are needed.
+    small = lam[small_mask]
+    reg = lam[reg_mask]
+
+    # Compute the function for each case.
+    k = np.empty_like(lam)
+    k[low_mask] = np.nan
+    k[negqrtr_mask] = np.inf
+    if small.size > 0:
+        k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small)
+    if reg.size > 0:
+        numer = (1.0 / (4 * reg + 1) - 4 * beta(3 * reg + 1, reg + 1) +
+                 3 * beta(2 * reg + 1, 2 * reg + 1))
+        denom = 2 * (1.0/(2 * reg + 1) - beta(reg + 1, reg + 1))**2
+        k[reg_mask] = numer / denom - 3
+
+    # The return value will be a numpy array; resetting the shape ensures that
+    # if `lam` was a scalar, the return value is a 0-d array.
+    k.shape = shp
+    return k
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_variation.py b/python_embeded/Lib/site-packages/scipy/stats/_variation.py
new file mode 100644
index 0000000000000000000000000000000000000000..24500caaf2f40dcc440326067eaecaad1399946c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_variation.py
@@ -0,0 +1,128 @@
+import numpy as np
+
+from scipy._lib._util import _get_nan
+from scipy._lib._array_api import array_namespace, xp_copysign
+
+from ._axis_nan_policy import _axis_nan_policy_factory
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def variation(a, axis=0, nan_policy='propagate', ddof=0, *, keepdims=False):
+    """
+    Compute the coefficient of variation.
+
+    The coefficient of variation is the standard deviation divided by the
+    mean.  This function is equivalent to::
+
+        np.std(x, axis=axis, ddof=ddof) / np.mean(x)
+
+    The default for ``ddof`` is 0, but many definitions of the coefficient
+    of variation use the square root of the unbiased sample variance
+    for the sample standard deviation, which corresponds to ``ddof=1``.
+
+    The function does not take the absolute value of the mean of the data,
+    so the return value is negative if the mean is negative.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate the coefficient of variation.
+        Default is 0. If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains ``nan``.
+        The following options are available:
+
+          * 'propagate': return ``nan``
+          * 'raise': raise an exception
+          * 'omit': perform the calculation with ``nan`` values omitted
+
+        The default is 'propagate'.
+    ddof : int, optional
+        Gives the "Delta Degrees Of Freedom" used when computing the
+        standard deviation.  The divisor used in the calculation of the
+        standard deviation is ``N - ddof``, where ``N`` is the number of
+        elements.  `ddof` must be less than ``N``; if it isn't, the result
+        will be ``nan`` or ``inf``, depending on ``N`` and the values in
+        the array.  By default `ddof` is zero for backwards compatibility,
+        but it is recommended to use ``ddof=1`` to ensure that the sample
+        standard deviation is computed as the square root of the unbiased
+        sample variance.
+
+    Returns
+    -------
+    variation : ndarray
+        The calculated variation along the requested axis.
+
+    Notes
+    -----
+    There are several edge cases that are handled without generating a
+    warning:
+
+    * If both the mean and the standard deviation are zero, ``nan``
+      is returned.
+    * If the mean is zero and the standard deviation is nonzero, ``inf``
+      is returned.
+    * If the input has length zero (either because the array has zero
+      length, or all the input values are ``nan`` and ``nan_policy`` is
+      ``'omit'``), ``nan`` is returned.
+    * If the input contains ``inf``, ``nan`` is returned.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import variation
+    >>> variation([1, 2, 3, 4, 5], ddof=1)
+    0.5270462766947299
+
+    Compute the variation along a given dimension of an array that contains
+    a few ``nan`` values:
+
+    >>> x = np.array([[  10.0, np.nan, 11.0, 19.0, 23.0, 29.0, 98.0],
+    ...               [  29.0,   30.0, 32.0, 33.0, 35.0, 56.0, 57.0],
+    ...               [np.nan, np.nan, 12.0, 13.0, 16.0, 16.0, 17.0]])
+    >>> variation(x, axis=1, ddof=1, nan_policy='omit')
+    array([1.05109361, 0.31428986, 0.146483  ])
+
+    """
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+    # `nan_policy` and `keepdims` are handled by `_axis_nan_policy`
+    # `axis=None` is only handled for NumPy backend
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        axis = 0
+
+    n = a.shape[axis]
+    NaN = _get_nan(a)
+
+    if a.size == 0 or ddof > n:
+        # Handle as a special case to avoid spurious warnings.
+        # The return values, if any, are all nan.
+        shp = list(a.shape)
+        shp.pop(axis)
+        result = xp.full(shp, fill_value=NaN)
+        return result[()] if result.ndim == 0 else result
+
+    mean_a = xp.mean(a, axis=axis)
+
+    if ddof == n:
+        # Another special case.  Result is either inf or nan.
+        std_a = xp.std(a, axis=axis, correction=0)
+        result = xp.where(std_a > 0, xp_copysign(xp.asarray(xp.inf), mean_a), NaN)
+        return result[()] if result.ndim == 0 else result
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        std_a = xp.std(a, axis=axis, correction=ddof)
+        result = std_a / mean_a
+
+    return result[()] if result.ndim == 0 else result
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_warnings_errors.py b/python_embeded/Lib/site-packages/scipy/stats/_warnings_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3c16ee7ed9111cce4fa931eb983fee46aea3007
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_warnings_errors.py
@@ -0,0 +1,38 @@
+# Warnings
+
+
+class DegenerateDataWarning(RuntimeWarning):
+    """Warns when data is degenerate and results may not be reliable."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("Degenerate data encountered; results may not be reliable.")
+        self.args = (msg,)
+
+
+class ConstantInputWarning(DegenerateDataWarning):
+    """Warns when all values in data are exactly equal."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("All values in data are exactly equal; "
+                   "results may not be reliable.")
+        self.args = (msg,)
+
+
+class NearConstantInputWarning(DegenerateDataWarning):
+    """Warns when all values in data are nearly equal."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("All values in data are nearly equal; "
+                   "results may not be reliable.")
+        self.args = (msg,)
+
+
+# Errors
+
+
+class FitError(RuntimeError):
+    """Represents an error condition when fitting a distribution to data."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("An error occurred when fitting a distribution to data.")
+        self.args = (msg,)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/_wilcoxon.py b/python_embeded/Lib/site-packages/scipy/stats/_wilcoxon.py
new file mode 100644
index 0000000000000000000000000000000000000000..fad2a1f370e37b6316d4774cd1ff0006ffb5351f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/_wilcoxon.py
@@ -0,0 +1,259 @@
+import numpy as np
+
+from scipy import stats
+from ._stats_py import _get_pvalue, _rankdata, _SimpleNormal
+from . import _morestats
+from ._axis_nan_policy import _broadcast_arrays
+from ._hypotests import _get_wilcoxon_distr
+from scipy._lib._util import _lazywhere, _get_nan
+
+
+class WilcoxonDistribution:
+
+    def __init__(self, n):
+        n = np.asarray(n).astype(int, copy=False)
+        self.n = n
+        self._dists = {ni: _get_wilcoxon_distr(ni) for ni in np.unique(n)}
+
+    def _cdf1(self, k, n):
+        pmfs = self._dists[n]
+        return pmfs[:k + 1].sum()
+
+    def _cdf(self, k, n):
+        return np.vectorize(self._cdf1, otypes=[float])(k, n)
+
+    def _sf1(self, k, n):
+        pmfs = self._dists[n]
+        return pmfs[k:].sum()
+
+    def _sf(self, k, n):
+        return np.vectorize(self._sf1, otypes=[float])(k, n)
+
+    def mean(self):
+        return self.n * (self.n + 1) / 4
+
+    def _prep(self, k):
+        k = np.asarray(k).astype(int, copy=False)
+        mn = self.mean()
+        out = np.empty(k.shape, dtype=np.float64)
+        return k, mn, out
+
+    def cdf(self, k):
+        k, mn, out = self._prep(k)
+        return _lazywhere(k <= mn, (k, self.n), self._cdf,
+                          f2=lambda k, n: 1 - self._sf(k+1, n))[()]
+
+    def sf(self, k):
+        k, mn, out = self._prep(k)
+        return _lazywhere(k <= mn, (k, self.n), self._sf,
+                          f2=lambda k, n: 1 - self._cdf(k-1, n))[()]
+
+
+def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis):
+
+    axis = np.asarray(axis)[()]
+    message = "`axis` must be an integer."
+    if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
+        raise ValueError(message)
+
+    message = '`axis` must be compatible with the shape(s) of `x` (and `y`)'
+    try:
+        if y is None:
+            x = np.asarray(x)
+            d = x
+        else:
+            x, y = _broadcast_arrays((x, y), axis=axis)
+            d = x - y
+        d = np.moveaxis(d, axis, -1)
+    except np.AxisError as e:
+        raise ValueError(message) from e
+
+    message = "`x` and `y` must have the same length along `axis`."
+    if y is not None and x.shape[axis] != y.shape[axis]:
+        raise ValueError(message)
+
+    message = "`x` (and `y`, if provided) must be an array of real numbers."
+    if np.issubdtype(d.dtype, np.integer):
+        d = d.astype(np.float64)
+    if not np.issubdtype(d.dtype, np.floating):
+        raise ValueError(message)
+
+    zero_method = str(zero_method).lower()
+    zero_methods = {"wilcox", "pratt", "zsplit"}
+    message = f"`zero_method` must be one of {zero_methods}."
+    if zero_method not in zero_methods:
+        raise ValueError(message)
+
+    corrections = {True, False}
+    message = f"`correction` must be one of {corrections}."
+    if correction not in corrections:
+        raise ValueError(message)
+
+    alternative = str(alternative).lower()
+    alternatives = {"two-sided", "less", "greater"}
+    message = f"`alternative` must be one of {alternatives}."
+    if alternative not in alternatives:
+        raise ValueError(message)
+
+    if not isinstance(method, stats.PermutationMethod):
+        methods = {"auto", "asymptotic", "exact"}
+        message = (f"`method` must be one of {methods} or "
+                   "an instance of `stats.PermutationMethod`.")
+        if method not in methods:
+            raise ValueError(message)
+    output_z = True if method == 'asymptotic' else False
+
+    # For small samples, we decide later whether to perform an exact test or a
+    # permutation test. The reason is that the presence of ties is not
+    # known at the input validation stage.
+    n_zero = np.sum(d == 0)
+    if method == "auto" and d.shape[-1] > 50:
+        method = "asymptotic"
+
+    return d, zero_method, correction, alternative, method, axis, output_z, n_zero
+
+
+def _wilcoxon_statistic(d, method, zero_method='wilcox'):
+
+    i_zeros = (d == 0)
+
+    if zero_method == 'wilcox':
+        # Wilcoxon's method for treating zeros was to remove them from
+        # the calculation. We do this by replacing 0s with NaNs, which
+        # are ignored anyway.
+        if not d.flags['WRITEABLE']:
+            d = d.copy()
+        d[i_zeros] = np.nan
+
+    i_nan = np.isnan(d)
+    n_nan = np.sum(i_nan, axis=-1)
+    count = d.shape[-1] - n_nan
+
+    r, t = _rankdata(abs(d), 'average', return_ties=True)
+
+    r_plus = np.sum((d > 0) * r, axis=-1)
+    r_minus = np.sum((d < 0) * r, axis=-1)
+
+    has_ties = (t == 0).any()
+
+    if zero_method == "zsplit":
+        # The "zero-split" method for treating zeros is to add half their contribution
+        # to r_plus and half to r_minus.
+        # See gh-2263 for the origin of this method.
+        r_zero_2 = np.sum(i_zeros * r, axis=-1) / 2
+        r_plus += r_zero_2
+        r_minus += r_zero_2
+
+    mn = count * (count + 1.) * 0.25
+    se = count * (count + 1.) * (2. * count + 1.)
+
+    if zero_method == "pratt":
+        # Pratt's method for treating zeros was just to modify the z-statistic.
+
+        # normal approximation needs to be adjusted, see Cureton (1967)
+        n_zero = i_zeros.sum(axis=-1)
+        mn -= n_zero * (n_zero + 1.) * 0.25
+        se -= n_zero * (n_zero + 1.) * (2. * n_zero + 1.)
+
+        # zeros are not to be included in tie-correction.
+        # any tie counts corresponding with zeros are in the 0th column
+        t[i_zeros.any(axis=-1), 0] = 0
+
+    tie_correct = (t**3 - t).sum(axis=-1)
+    se -= tie_correct/2
+    se = np.sqrt(se / 24)
+
+    # se = 0 means that no non-zero values are left in d. we only need z
+    # if method is asymptotic. however, if method="auto", the switch to
+    # asymptotic might only happen after the statistic is calculated, so z
+    # needs to be computed. in all other cases, avoid division by zero warning
+    # (z is not needed anyways)
+    if method in ["asymptotic", "auto"]:
+        z = (r_plus - mn) / se
+    else:
+        z = np.nan
+
+    return r_plus, r_minus, se, z, count, has_ties
+
+
+def _correction_sign(z, alternative):
+    if alternative == 'greater':
+        return 1
+    elif alternative == 'less':
+        return -1
+    else:
+        return np.sign(z)
+
+
+def _wilcoxon_nd(x, y=None, zero_method='wilcox', correction=True,
+                 alternative='two-sided', method='auto', axis=0):
+
+    temp = _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis)
+    d, zero_method, correction, alternative, method, axis, output_z, n_zero = temp
+
+    if d.size == 0:
+        NaN = _get_nan(d)
+        res = _morestats.WilcoxonResult(statistic=NaN, pvalue=NaN)
+        if method == 'asymptotic':
+            res.zstatistic = NaN
+        return res
+
+    r_plus, r_minus, se, z, count, has_ties = _wilcoxon_statistic(
+        d, method, zero_method
+    )
+
+    # we only know if there are ties after computing the statistic and not
+    # at the input validation stage. if the original method was auto and
+    # the decision was to use an exact test, we override this to
+    # a permutation test now (since method='exact' is not exact in the
+    # presence of ties)
+    if method == "auto":
+        if not (has_ties or n_zero > 0):
+            method = "exact"
+        elif d.shape[-1] <= 13:
+            # the possible outcomes to be simulated by the permutation test
+            # are 2**n, where n is the sample size.
+            # if n <= 13, the p-value is deterministic since 2**13 is less
+            # than 9999, the default number of n_resamples
+            method = stats.PermutationMethod()
+        else:
+            # if there are ties and the sample size is too large to
+            # run a deterministic permutation test, fall back to asymptotic
+            method = "asymptotic"
+
+    if method == 'asymptotic':
+        if correction:
+            sign = _correction_sign(z, alternative)
+            z -= sign * 0.5 / se
+        p = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    elif method == 'exact':
+        dist = WilcoxonDistribution(count)
+        # The null distribution in `dist` is exact only if there are no ties
+        # or zeros. If there are ties or zeros, the statistic can be non-
+        # integral, but the null distribution is only defined for integral
+        # values of the statistic. Therefore, we're conservative: round
+        # non-integral statistic up before computing CDF and down before
+        # computing SF. This preserves symmetry w.r.t. alternatives and
+        # order of the input arguments. See gh-19872.
+        if alternative == 'less':
+            p = dist.cdf(np.ceil(r_plus))
+        elif alternative == 'greater':
+            p = dist.sf(np.floor(r_plus))
+        else:
+            p = 2 * np.minimum(dist.sf(np.floor(r_plus)),
+                               dist.cdf(np.ceil(r_plus)))
+            p = np.clip(p, 0, 1)
+    else:  # `PermutationMethod` instance (already validated)
+        p = stats.permutation_test(
+            (d,), lambda d: _wilcoxon_statistic(d, method, zero_method)[0],
+            permutation_type='samples', **method._asdict(),
+            alternative=alternative, axis=-1).pvalue
+
+    # for backward compatibility...
+    statistic = np.minimum(r_plus, r_minus) if alternative=='two-sided' else r_plus
+    z = -np.abs(z) if (alternative == 'two-sided' and method == 'asymptotic') else z
+
+    res = _morestats.WilcoxonResult(statistic=statistic, pvalue=p[()])
+    if output_z:
+        res.zstatistic = z[()]
+    return res
diff --git a/python_embeded/Lib/site-packages/scipy/stats/biasedurn.py b/python_embeded/Lib/site-packages/scipy/stats/biasedurn.py
new file mode 100644
index 0000000000000000000000000000000000000000..54eaeb91568537aaa7d2718bb3f3beefebcd0a1d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/biasedurn.py
@@ -0,0 +1,16 @@
+# 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="stats", module="biasedurn",
+                                   private_modules=["_biasedurn"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/contingency.py b/python_embeded/Lib/site-packages/scipy/stats/contingency.py
new file mode 100644
index 0000000000000000000000000000000000000000..7deb34d10d23a284e79d3b66a1cb06727b6b237e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/contingency.py
@@ -0,0 +1,521 @@
+"""
+Contingency table functions (:mod:`scipy.stats.contingency`)
+============================================================
+
+Functions for creating and analyzing contingency tables.
+
+.. currentmodule:: scipy.stats.contingency
+
+.. autosummary::
+   :toctree: generated/
+
+   chi2_contingency
+   relative_risk
+   odds_ratio
+   crosstab
+   association
+
+   expected_freq
+   margins
+
+"""
+
+
+from functools import reduce
+import math
+import numpy as np
+from ._stats_py import power_divergence, _untabulate
+from ._relative_risk import relative_risk
+from ._crosstab import crosstab
+from ._odds_ratio import odds_ratio
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy import stats
+
+
+__all__ = ['margins', 'expected_freq', 'chi2_contingency', 'crosstab',
+           'association', 'relative_risk', 'odds_ratio']
+
+
+def margins(a):
+    """Return a list of the marginal sums of the array `a`.
+
+    Parameters
+    ----------
+    a : ndarray
+        The array for which to compute the marginal sums.
+
+    Returns
+    -------
+    margsums : list of ndarrays
+        A list of length `a.ndim`.  `margsums[k]` is the result
+        of summing `a` over all axes except `k`; it has the same
+        number of dimensions as `a`, but the length of each axis
+        except axis `k` will be 1.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import margins
+
+    >>> a = np.arange(12).reshape(2, 6)
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11]])
+    >>> m0, m1 = margins(a)
+    >>> m0
+    array([[15],
+           [51]])
+    >>> m1
+    array([[ 6,  8, 10, 12, 14, 16]])
+
+    >>> b = np.arange(24).reshape(2,3,4)
+    >>> m0, m1, m2 = margins(b)
+    >>> m0
+    array([[[ 66]],
+           [[210]]])
+    >>> m1
+    array([[[ 60],
+            [ 92],
+            [124]]])
+    >>> m2
+    array([[[60, 66, 72, 78]]])
+    """
+    margsums = []
+    ranged = list(range(a.ndim))
+    for k in ranged:
+        marg = np.apply_over_axes(np.sum, a, [j for j in ranged if j != k])
+        margsums.append(marg)
+    return margsums
+
+
+def expected_freq(observed):
+    """
+    Compute the expected frequencies from a contingency table.
+
+    Given an n-dimensional contingency table of observed frequencies,
+    compute the expected frequencies for the table based on the marginal
+    sums under the assumption that the groups associated with each
+    dimension are independent.
+
+    Parameters
+    ----------
+    observed : array_like
+        The table of observed frequencies.  (While this function can handle
+        a 1-D array, that case is trivial.  Generally `observed` is at
+        least 2-D.)
+
+    Returns
+    -------
+    expected : ndarray of float64
+        The expected frequencies, based on the marginal sums of the table.
+        Same shape as `observed`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import expected_freq
+    >>> observed = np.array([[10, 10, 20],[20, 20, 20]])
+    >>> expected_freq(observed)
+    array([[ 12.,  12.,  16.],
+           [ 18.,  18.,  24.]])
+
+    """
+    # Typically `observed` is an integer array. If `observed` has a large
+    # number of dimensions or holds large values, some of the following
+    # computations may overflow, so we first switch to floating point.
+    observed = np.asarray(observed, dtype=np.float64)
+
+    # Create a list of the marginal sums.
+    margsums = margins(observed)
+
+    # Create the array of expected frequencies.  The shapes of the
+    # marginal sums returned by apply_over_axes() are just what we
+    # need for broadcasting in the following product.
+    d = observed.ndim
+    expected = reduce(np.multiply, margsums) / observed.sum() ** (d - 1)
+    return expected
+
+
+Chi2ContingencyResult = _make_tuple_bunch(
+    'Chi2ContingencyResult',
+    ['statistic', 'pvalue', 'dof', 'expected_freq'], []
+)
+
+
+def chi2_contingency(observed, correction=True, lambda_=None, *, method=None):
+    """Chi-square test of independence of variables in a contingency table.
+
+    This function computes the chi-square statistic and p-value for the
+    hypothesis test of independence of the observed frequencies in the
+    contingency table [1]_ `observed`.  The expected frequencies are computed
+    based on the marginal sums under the assumption of independence; see
+    `scipy.stats.contingency.expected_freq`.  The number of degrees of
+    freedom is (expressed using numpy functions and attributes)::
+
+        dof = observed.size - sum(observed.shape) + observed.ndim - 1
+
+
+    Parameters
+    ----------
+    observed : array_like
+        The contingency table. The table contains the observed frequencies
+        (i.e. number of occurrences) in each category.  In the two-dimensional
+        case, the table is often described as an "R x C table".
+    correction : bool, optional
+        If True, *and* the degrees of freedom is 1, apply Yates' correction
+        for continuity.  The effect of the correction is to adjust each
+        observed value by 0.5 towards the corresponding expected value.
+    lambda_ : float or str, optional
+        By default, the statistic computed in this test is Pearson's
+        chi-squared statistic [2]_.  `lambda_` allows a statistic from the
+        Cressie-Read power divergence family [3]_ to be used instead.  See
+        `scipy.stats.power_divergence` for details.
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. Compatible only with
+        `correction=False`,  default `lambda_`, and two-way tables.
+        If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
+        the p-value is computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed as documented in the notes.
+        Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
+        attribute must be left unspecified; Monte Carlo samples are always drawn
+        using the ``rvs`` method of `scipy.stats.random_table`.
+
+        .. versionadded:: 1.15.0
+
+
+    Returns
+    -------
+    res : Chi2ContingencyResult
+        An object containing attributes:
+
+        statistic : float
+            The test statistic.
+        pvalue : float
+            The p-value of the test.
+        dof : int
+            The degrees of freedom. NaN if `method` is not ``None``.
+        expected_freq : ndarray, same shape as `observed`
+            The expected frequencies, based on the marginal sums of the table.
+
+    See Also
+    --------
+    scipy.stats.contingency.expected_freq
+    scipy.stats.fisher_exact
+    scipy.stats.chisquare
+    scipy.stats.power_divergence
+    scipy.stats.barnard_exact
+    scipy.stats.boschloo_exact
+    :ref:`hypothesis_chi2_contingency` : Extended example
+
+    Notes
+    -----
+    An often quoted guideline for the validity of this calculation is that
+    the test should be used only if the observed and expected frequencies
+    in each cell are at least 5.
+
+    This is a test for the independence of different categories of a
+    population. The test is only meaningful when the dimension of
+    `observed` is two or more.  Applying the test to a one-dimensional
+    table will always result in `expected` equal to `observed` and a
+    chi-square statistic equal to 0.
+
+    This function does not handle masked arrays, because the calculation
+    does not make sense with missing values.
+
+    Like `scipy.stats.chisquare`, this function computes a chi-square
+    statistic; the convenience this function provides is to figure out the
+    expected frequencies and degrees of freedom from the given contingency
+    table. If these were already known, and if the Yates' correction was not
+    required, one could use `scipy.stats.chisquare`.  That is, if one calls::
+
+        res = chi2_contingency(obs, correction=False)
+
+    then the following is true::
+
+        (res.statistic, res.pvalue) == stats.chisquare(obs.ravel(),
+                                                       f_exp=ex.ravel(),
+                                                       ddof=obs.size - 1 - dof)
+
+    The `lambda_` argument was added in version 0.13.0 of scipy.
+
+    References
+    ----------
+    .. [1] "Contingency table",
+           https://en.wikipedia.org/wiki/Contingency_table
+    .. [2] "Pearson's chi-squared test",
+           https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
+    .. [3] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
+           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
+           pp. 440-464.
+
+    Examples
+    --------
+    A two-way example (2 x 3):
+
+    >>> import numpy as np
+    >>> from scipy.stats import chi2_contingency
+    >>> obs = np.array([[10, 10, 20], [20, 20, 20]])
+    >>> res = chi2_contingency(obs)
+    >>> res.statistic
+    2.7777777777777777
+    >>> res.pvalue
+    0.24935220877729619
+    >>> res.dof
+    2
+    >>> res.expected_freq
+    array([[ 12.,  12.,  16.],
+           [ 18.,  18.,  24.]])
+
+    Perform the test using the log-likelihood ratio (i.e. the "G-test")
+    instead of Pearson's chi-squared statistic.
+
+    >>> res = chi2_contingency(obs, lambda_="log-likelihood")
+    >>> res.statistic
+    2.7688587616781319
+    >>> res.pvalue
+    0.25046668010954165
+
+    A four-way example (2 x 2 x 2 x 2):
+
+    >>> obs = np.array(
+    ...     [[[[12, 17],
+    ...        [11, 16]],
+    ...       [[11, 12],
+    ...        [15, 16]]],
+    ...      [[[23, 15],
+    ...        [30, 22]],
+    ...       [[14, 17],
+    ...        [15, 16]]]])
+    >>> res = chi2_contingency(obs)
+    >>> res.statistic
+    8.7584514426741897
+    >>> res.pvalue
+    0.64417725029295503
+
+    When the sum of the elements in a two-way table is small, the p-value
+    produced by the default asymptotic approximation may be inaccurate.
+    Consider passing a `PermutationMethod` or `MonteCarloMethod` as the
+    `method` parameter with `correction=False`.
+
+    >>> from scipy.stats import PermutationMethod
+    >>> obs = np.asarray([[12, 3],
+    ...                   [17, 16]])
+    >>> res = chi2_contingency(obs, correction=False)
+    >>> ref = chi2_contingency(obs, correction=False, method=PermutationMethod())
+    >>> res.pvalue, ref.pvalue
+    (0.0614122539870913, 0.1074)  # may vary
+
+    For a more detailed example, see :ref:`hypothesis_chi2_contingency`.
+
+    """
+    observed = np.asarray(observed)
+    if np.any(observed < 0):
+        raise ValueError("All values in `observed` must be nonnegative.")
+    if observed.size == 0:
+        raise ValueError("No data; `observed` has size 0.")
+
+    expected = expected_freq(observed)
+    if np.any(expected == 0):
+        # Include one of the positions where expected is zero in
+        # the exception message.
+        zeropos = list(zip(*np.nonzero(expected == 0)))[0]
+        raise ValueError("The internally computed table of expected "
+                         f"frequencies has a zero element at {zeropos}.")
+
+    if method is not None:
+        return _chi2_resampling_methods(observed, expected, correction, lambda_, method)
+
+    # The degrees of freedom
+    dof = expected.size - sum(expected.shape) + expected.ndim - 1
+
+    if dof == 0:
+        # Degenerate case; this occurs when `observed` is 1D (or, more
+        # generally, when it has only one nontrivial dimension).  In this
+        # case, we also have observed == expected, so chi2 is 0.
+        chi2 = 0.0
+        p = 1.0
+    else:
+        if dof == 1 and correction:
+            # Adjust `observed` according to Yates' correction for continuity.
+            # Magnitude of correction no bigger than difference; see gh-13875
+            diff = expected - observed
+            direction = np.sign(diff)
+            magnitude = np.minimum(0.5, np.abs(diff))
+            observed = observed + magnitude * direction
+
+        chi2, p = power_divergence(observed, expected,
+                                   ddof=observed.size - 1 - dof, axis=None,
+                                   lambda_=lambda_)
+
+    return Chi2ContingencyResult(chi2, p, dof, expected)
+
+
+def _chi2_resampling_methods(observed, expected, correction, lambda_, method):
+
+    if observed.ndim != 2:
+        message = 'Use of `method` is only compatible with two-way tables.'
+        raise ValueError(message)
+
+    if correction:
+        message = f'`{correction=}` is not compatible with `{method=}.`'
+        raise ValueError(message)
+
+    if lambda_ is not None:
+        message = f'`{lambda_=}` is not compatible with `{method=}.`'
+        raise ValueError(message)
+
+    if isinstance(method, stats.PermutationMethod):
+        res = _chi2_permutation_method(observed, expected, method)
+    elif isinstance(method, stats.MonteCarloMethod):
+        res = _chi2_monte_carlo_method(observed, expected, method)
+    else:
+        message = (f'`{method=}` not recognized; if provided, `method` must be an '
+                   'instance of `PermutationMethod` or `MonteCarloMethod`.')
+        raise ValueError(message)
+
+    return Chi2ContingencyResult(res.statistic, res.pvalue, np.nan, expected)
+
+
+def _chi2_permutation_method(observed, expected, method):
+    x, y = _untabulate(observed)
+    # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
+    # which pairs observations in `x` with different observations in `y`.
+    def statistic(x):
+        # crosstab the resample and compute the statistic
+        table = crosstab(x, y)[1]
+        return np.sum((table - expected)**2/expected)
+
+    return stats.permutation_test((x,), statistic, permutation_type='pairings',
+                                  alternative='greater', **method._asdict())
+
+
+def _chi2_monte_carlo_method(observed, expected, method):
+    method = method._asdict()
+
+    if method.pop('rvs', None) is not None:
+        message = ('If the `method` argument of `chi2_contingency` is an '
+                   'instance of `MonteCarloMethod`, its `rvs` attribute '
+                   'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
+                   'to control the random state.')
+        raise ValueError(message)
+    rng = np.random.default_rng(method.pop('rng', None))
+
+    # `random_table.rvs` produces random contingency tables with the given marginals
+    # under the null hypothesis of independence
+    rowsums, colsums = stats.contingency.margins(observed)
+    X = stats.random_table(rowsums.ravel(), colsums.ravel(), seed=rng)
+    def rvs(size):
+        n_resamples = size[0]
+        return X.rvs(size=n_resamples).reshape(size)
+
+    expected = expected.ravel()
+    def statistic(table, axis):
+        return np.sum((table - expected)**2/expected, axis=axis)
+
+    return stats.monte_carlo_test(observed.ravel(), rvs, statistic,
+                                  alternative='greater', **method)
+
+
+def association(observed, method="cramer", correction=False, lambda_=None):
+    """Calculates degree of association between two nominal variables.
+
+    The function provides the option for computing one of three measures of
+    association between two nominal variables from the data given in a 2d
+    contingency table: Tschuprow's T, Pearson's Contingency Coefficient
+    and Cramer's V.
+
+    Parameters
+    ----------
+    observed : array-like
+        The array of observed values
+    method : {"cramer", "tschuprow", "pearson"} (default = "cramer")
+        The association test statistic.
+    correction : bool, optional
+        Inherited from `scipy.stats.contingency.chi2_contingency()`
+    lambda_ : float or str, optional
+        Inherited from `scipy.stats.contingency.chi2_contingency()`
+
+    Returns
+    -------
+    statistic : float
+        Value of the test statistic
+
+    Notes
+    -----
+    Cramer's V, Tschuprow's T and Pearson's Contingency Coefficient, all
+    measure the degree to which two nominal or ordinal variables are related,
+    or the level of their association. This differs from correlation, although
+    many often mistakenly consider them equivalent. Correlation measures in
+    what way two variables are related, whereas, association measures how
+    related the variables are. As such, association does not subsume
+    independent variables, and is rather a test of independence. A value of
+    1.0 indicates perfect association, and 0.0 means the variables have no
+    association.
+
+    Both the Cramer's V and Tschuprow's T are extensions of the phi
+    coefficient.  Moreover, due to the close relationship between the
+    Cramer's V and Tschuprow's T the returned values can often be similar
+    or even equivalent.  They are likely to diverge more as the array shape
+    diverges from a 2x2.
+
+    References
+    ----------
+    .. [1] "Tschuprow's T",
+           https://en.wikipedia.org/wiki/Tschuprow's_T
+    .. [2] Tschuprow, A. A. (1939)
+           Principles of the Mathematical Theory of Correlation;
+           translated by M. Kantorowitsch. W. Hodge & Co.
+    .. [3] "Cramer's V", https://en.wikipedia.org/wiki/Cramer's_V
+    .. [4] "Nominal Association: Phi and Cramer's V",
+           http://www.people.vcu.edu/~pdattalo/702SuppRead/MeasAssoc/NominalAssoc.html
+    .. [5] Gingrich, Paul, "Association Between Variables",
+           http://uregina.ca/~gingrich/ch11a.pdf
+
+    Examples
+    --------
+    An example with a 4x2 contingency table:
+
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import association
+    >>> obs4x2 = np.array([[100, 150], [203, 322], [420, 700], [320, 210]])
+
+    Pearson's contingency coefficient
+
+    >>> association(obs4x2, method="pearson")
+    0.18303298140595667
+
+    Cramer's V
+
+    >>> association(obs4x2, method="cramer")
+    0.18617813077483678
+
+    Tschuprow's T
+
+    >>> association(obs4x2, method="tschuprow")
+    0.14146478765062995
+    """
+    arr = np.asarray(observed)
+    if not np.issubdtype(arr.dtype, np.integer):
+        raise ValueError("`observed` must be an integer array.")
+
+    if len(arr.shape) != 2:
+        raise ValueError("method only accepts 2d arrays")
+
+    chi2_stat = chi2_contingency(arr, correction=correction,
+                                 lambda_=lambda_)
+
+    phi2 = chi2_stat.statistic / arr.sum()
+    n_rows, n_cols = arr.shape
+    if method == "cramer":
+        value = phi2 / min(n_cols - 1, n_rows - 1)
+    elif method == "tschuprow":
+        value = phi2 / math.sqrt((n_rows - 1) * (n_cols - 1))
+    elif method == 'pearson':
+        value = phi2 / (1 + phi2)
+    else:
+        raise ValueError("Invalid argument value: 'method' argument must "
+                         "be 'cramer', 'tschuprow', or 'pearson'")
+
+    return math.sqrt(value)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/distributions.py b/python_embeded/Lib/site-packages/scipy/stats/distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5702e88eb5aa675eec6468073c09005f86411c91
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/distributions.py
@@ -0,0 +1,24 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+# NOTE: To look at history using `git blame`, use `git blame -M -C -C`
+#       instead of `git blame -Lxxx,+x`.
+#
+from ._distn_infrastructure import (rv_discrete, rv_continuous, rv_frozen)  # noqa: F401
+
+from . import _continuous_distns
+from . import _discrete_distns
+
+from ._continuous_distns import *  # noqa: F403
+from ._levy_stable import levy_stable
+from ._discrete_distns import *  # noqa: F403
+from ._entropy import entropy
+
+# For backwards compatibility e.g. pymc expects distributions.__all__.
+__all__ = ['rv_discrete', 'rv_continuous', 'rv_histogram', 'entropy']  # noqa: F405
+
+# Add only the distribution names, not the *_gen names.
+__all__ += _continuous_distns._distn_names
+__all__ += ['levy_stable']
+__all__ += _discrete_distns._distn_names
diff --git a/python_embeded/Lib/site-packages/scipy/stats/kde.py b/python_embeded/Lib/site-packages/scipy/stats/kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..26e058bb5eb9e32c8d7940dbe860712cdaadcfcc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/kde.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["gaussian_kde"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="kde",
+                                   private_modules=["_kde"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/morestats.py b/python_embeded/Lib/site-packages/scipy/stats/morestats.py
new file mode 100644
index 0000000000000000000000000000000000000000..924d9d757fb180a276ec2a434f8d647bbee2f64f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/morestats.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.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'mvsdist',
+    'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
+    'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
+    'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
+    'fligner', 'mood', 'wilcoxon', 'median_test',
+    'circmean', 'circvar', 'circstd', 'anderson_ksamp',
+    'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
+    'yeojohnson_normplot', 'find_repeats', 'chi2_contingency', 'distributions',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="morestats",
+                                   private_modules=["_morestats"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/mstats.py b/python_embeded/Lib/site-packages/scipy/stats/mstats.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1fa00b7108f3c78b61e9587922a0a36698d379f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/mstats.py
@@ -0,0 +1,140 @@
+"""
+===================================================================
+Statistical functions for masked arrays (:mod:`scipy.stats.mstats`)
+===================================================================
+
+.. currentmodule:: scipy.stats.mstats
+
+This module contains a large number of statistical functions that can
+be used with masked arrays.
+
+Most of these functions are similar to those in `scipy.stats` but might
+have small differences in the API or in the algorithm used. Since this
+is a relatively new package, some API changes are still possible.
+
+Summary statistics
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   describe
+   gmean
+   hmean
+   kurtosis
+   mode
+   mquantiles
+   hdmedian
+   hdquantiles
+   hdquantiles_sd
+   idealfourths
+   plotting_positions
+   meppf
+   moment
+   skew
+   tmean
+   tvar
+   tmin
+   tmax
+   tsem
+   variation
+   find_repeats
+   sem
+   trimmed_mean
+   trimmed_mean_ci
+   trimmed_std
+   trimmed_var
+
+Frequency statistics
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   scoreatpercentile
+
+Correlation functions
+=====================
+
+.. autosummary::
+   :toctree: generated/
+
+   f_oneway
+   pearsonr
+   spearmanr
+   pointbiserialr
+   kendalltau
+   kendalltau_seasonal
+   linregress
+   siegelslopes
+   theilslopes
+   sen_seasonal_slopes
+
+Statistical tests
+=================
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_1samp
+   ttest_onesamp
+   ttest_ind
+   ttest_rel
+   chisquare
+   kstest
+   ks_2samp
+   ks_1samp
+   ks_twosamp
+   mannwhitneyu
+   rankdata
+   kruskal
+   kruskalwallis
+   friedmanchisquare
+   brunnermunzel
+   skewtest
+   kurtosistest
+   normaltest
+
+Transformations
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   obrientransform
+   trim
+   trima
+   trimmed_stde
+   trimr
+   trimtail
+   trimboth
+   winsorize
+   zmap
+   zscore
+
+Other
+=====
+
+.. autosummary::
+   :toctree: generated/
+
+   argstoarray
+   count_tied_groups
+   msign
+   compare_medians_ms
+   median_cihs
+   mjci
+   mquantiles_cimj
+   rsh
+
+"""
+from . import _mstats_basic
+from . import _mstats_extras
+from ._mstats_basic import *  # noqa: F403
+from ._mstats_extras import *  # noqa: F403
+# Functions that support masked array input in stats but need to be kept in the
+# mstats namespace for backwards compatibility:
+from scipy.stats import gmean, hmean, zmap, zscore, chisquare
+
+__all__ = _mstats_basic.__all__ + _mstats_extras.__all__
+__all__ += ['gmean', 'hmean', 'zmap', 'zscore', 'chisquare']
diff --git a/python_embeded/Lib/site-packages/scipy/stats/mstats_basic.py b/python_embeded/Lib/site-packages/scipy/stats/mstats_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc294d6e5cfe4e2702e32cb2185da17763c07295
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/mstats_basic.py
@@ -0,0 +1,42 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'argstoarray',
+    'count_tied_groups',
+    'describe',
+    'f_oneway', 'find_repeats','friedmanchisquare',
+    'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis',
+    'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest',
+    'ks_1samp', 'kstest',
+    'linregress',
+    'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign',
+    'normaltest',
+    'obrientransform',
+    'pearsonr','plotting_positions','pointbiserialr',
+    'rankdata',
+    'scoreatpercentile','sem',
+    'sen_seasonal_slopes','skew','skewtest','spearmanr',
+    'siegelslopes', 'theilslopes',
+    'tmax','tmean','tmin','trim','trimboth',
+    'trimtail','trima','trimr','trimmed_mean','trimmed_std',
+    'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp',
+    'ttest_ind','ttest_rel','tvar',
+    'variation',
+    'winsorize',
+    'brunnermunzel',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="mstats_basic",
+                                   private_modules=["_mstats_basic"], all=__all__,
+                                   attribute=name, correct_module="mstats")
diff --git a/python_embeded/Lib/site-packages/scipy/stats/mstats_extras.py b/python_embeded/Lib/site-packages/scipy/stats/mstats_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..b741bda1dd958c40b30c6a40353cbbdd2c7ba16f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/mstats_extras.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'compare_medians_ms',
+    'hdquantiles', 'hdmedian', 'hdquantiles_sd',
+    'idealfourths',
+    'median_cihs','mjci','mquantiles_cimj',
+    'rsh',
+    'trimmed_mean_ci',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="mstats_extras",
+                                   private_modules=["_mstats_extras"], all=__all__,
+                                   attribute=name, correct_module="mstats")
diff --git a/python_embeded/Lib/site-packages/scipy/stats/mvn.py b/python_embeded/Lib/site-packages/scipy/stats/mvn.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c91109eb36cfc9bdb91d1be1cbc4d38a1ace3d9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/mvn.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.stats` 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="stats", module="mvn",
+                                   private_modules=["_mvn"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/scipy/stats/qmc.py b/python_embeded/Lib/site-packages/scipy/stats/qmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..8db3d298f927e542f1230642ab6e6c65c49b25ae
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/qmc.py
@@ -0,0 +1,236 @@
+r"""
+====================================================
+Quasi-Monte Carlo submodule (:mod:`scipy.stats.qmc`)
+====================================================
+
+.. currentmodule:: scipy.stats.qmc
+
+This module provides Quasi-Monte Carlo generators and associated helper
+functions.
+
+
+Quasi-Monte Carlo
+=================
+
+Engines
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   QMCEngine
+   Sobol
+   Halton
+   LatinHypercube
+   PoissonDisk
+   MultinomialQMC
+   MultivariateNormalQMC
+
+Helpers
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   discrepancy
+   geometric_discrepancy
+   update_discrepancy
+   scale
+
+
+Introduction to Quasi-Monte Carlo
+=================================
+
+Quasi-Monte Carlo (QMC) methods [1]_, [2]_, [3]_ provide an
+:math:`n \times d` array of numbers in :math:`[0,1]`. They can be used in
+place of :math:`n` points from the :math:`U[0,1]^{d}` distribution. Compared to
+random points, QMC points are designed to have fewer gaps and clumps. This is
+quantified by discrepancy measures [4]_. From the Koksma-Hlawka
+inequality [5]_ we know that low discrepancy reduces a bound on
+integration error. Averaging a function :math:`f` over :math:`n` QMC points
+can achieve an integration error close to :math:`O(n^{-1})` for well
+behaved functions [2]_.
+
+Most QMC constructions are designed for special values of :math:`n`
+such as powers of 2 or large primes. Changing the sample
+size by even one can degrade their performance, even their
+rate of convergence [6]_. For instance :math:`n=100` points may give less
+accuracy than :math:`n=64` if the method was designed for :math:`n=2^m`.
+
+Some QMC constructions are extensible in :math:`n`: we can find
+another special sample size :math:`n' > n` and often an infinite
+sequence of increasing special sample sizes. Some QMC
+constructions are extensible in :math:`d`: we can increase the dimension,
+possibly to some upper bound, and typically without requiring
+special values of :math:`d`. Some QMC methods are extensible in
+both :math:`n` and :math:`d`.
+
+QMC points are deterministic. That makes it hard to estimate the accuracy of
+integrals estimated by averages over QMC points. Randomized QMC (RQMC) [7]_
+points are constructed so that each point is individually :math:`U[0,1]^{d}`
+while collectively the :math:`n` points retain their low discrepancy.
+One can make :math:`R` independent replications of RQMC points to
+see how stable a computation is. From :math:`R` independent values,
+a t-test (or bootstrap t-test [8]_) then gives approximate confidence
+intervals on the mean value. Some RQMC methods produce a
+root mean squared error that is actually :math:`o(1/n)` and smaller than
+the rate seen in unrandomized QMC. An intuitive explanation is
+that the error is a sum of many small ones and random errors
+cancel in a way that deterministic ones do not. RQMC also
+has advantages on integrands that are singular or, for other
+reasons, fail to be Riemann integrable.
+
+(R)QMC cannot beat Bahkvalov's curse of dimension (see [9]_). For
+any random or deterministic method, there are worst case functions
+that will give it poor performance in high dimensions. A worst
+case function for QMC might be 0 at all n points but very
+large elsewhere. Worst case analyses get very pessimistic
+in high dimensions. (R)QMC can bring a great improvement over
+MC when the functions on which it is used are not worst case.
+For instance (R)QMC can be especially effective on integrands
+that are well approximated by sums of functions of
+some small number of their input variables at a time [10]_, [11]_.
+That property is often a surprising finding about those functions.
+
+Also, to see an improvement over IID MC, (R)QMC requires a bit of smoothness of
+the integrand, roughly the mixed first order derivative in each direction,
+:math:`\partial^d f/\partial x_1 \cdots \partial x_d`, must be integral.
+For instance, a function that is 1 inside the hypersphere and 0 outside of it
+has infinite variation in the sense of Hardy and Krause for any dimension
+:math:`d = 2`.
+
+Scrambled nets are a kind of RQMC that have some valuable robustness
+properties [12]_. If the integrand is square integrable, they give variance
+:math:`var_{SNET} = o(1/n)`. There is a finite upper bound on
+:math:`var_{SNET} / var_{MC}` that holds simultaneously for every square
+integrable integrand. Scrambled nets satisfy a strong law of large numbers
+for :math:`f` in :math:`L^p` when :math:`p>1`. In some
+special cases there is a central limit theorem [13]_. For smooth enough
+integrands they can achieve RMSE nearly :math:`O(n^{-3})`. See [12]_
+for references about these properties.
+
+The main kinds of QMC methods are lattice rules [14]_ and digital
+nets and sequences [2]_, [15]_. The theories meet up in polynomial
+lattice rules [16]_ which can produce digital nets. Lattice rules
+require some form of search for good constructions. For digital
+nets there are widely used default constructions.
+
+The most widely used QMC methods are Sobol' sequences [17]_.
+These are digital nets. They are extensible in both :math:`n` and :math:`d`.
+They can be scrambled. The special sample sizes are powers
+of 2. Another popular method are Halton sequences [18]_.
+The constructions resemble those of digital nets. The earlier
+dimensions have much better equidistribution properties than
+later ones. There are essentially no special sample sizes.
+They are not thought to be as accurate as Sobol' sequences.
+They can be scrambled. The nets of Faure [19]_ are also widely
+used. All dimensions are equally good, but the special sample
+sizes grow rapidly with dimension :math:`d`. They can be scrambled.
+The nets of Niederreiter and Xing [20]_ have the best asymptotic
+properties but have not shown good empirical performance [21]_.
+
+Higher order digital nets are formed by a digit interleaving process
+in the digits of the constructed points. They can achieve higher
+levels of asymptotic accuracy given higher smoothness conditions on :math:`f`
+and they can be scrambled [22]_. There is little or no empirical work
+showing the improved rate to be attained.
+
+Using QMC is like using the entire period of a small random
+number generator. The constructions are similar and so
+therefore are the computational costs [23]_.
+
+(R)QMC is sometimes improved by passing the points through
+a baker's transformation (tent function) prior to using them.
+That function has the form :math:`1-2|x-1/2|`. As :math:`x` goes from 0 to
+1, this function goes from 0 to 1 and then back. It is very
+useful to produce a periodic function for lattice rules [14]_,
+and sometimes it improves the convergence rate [24]_.
+
+It is not straightforward to apply QMC methods to Markov
+chain Monte Carlo (MCMC).  We can think of MCMC as using
+:math:`n=1` point in :math:`[0,1]^{d}` for very large :math:`d`, with
+ergodic results corresponding to :math:`d \to \infty`. One proposal is
+in [25]_ and under strong conditions an improved rate of convergence
+has been shown [26]_.
+
+Returning to Sobol' points: there are many versions depending
+on what are called direction numbers. Those are the result of
+searches and are tabulated. A very widely used set of direction
+numbers come from [27]_. It is extensible in dimension up to
+:math:`d=21201`.
+
+References
+----------
+.. [1] Owen, Art B. "Monte Carlo Book: the Quasi-Monte Carlo parts." 2019.
+.. [2] Niederreiter, Harald. "Random number generation and quasi-Monte Carlo
+   methods." Society for Industrial and Applied Mathematics, 1992.
+.. [3] Dick, Josef, Frances Y. Kuo, and Ian H. Sloan. "High-dimensional
+   integration: the quasi-Monte Carlo way." Acta Numerica no. 22: 133, 2013.
+.. [4] Aho, A. V., C. Aistleitner, T. Anderson, K. Appel, V. Arnol'd, N.
+   Aronszajn, D. Asotsky et al. "W. Chen et al.(eds.), "A Panorama of
+   Discrepancy Theory", Sringer International Publishing,
+   Switzerland: 679, 2014.
+.. [5] Hickernell, Fred J. "Koksma-Hlawka Inequality." Wiley StatsRef:
+   Statistics Reference Online, 2014.
+.. [6] Owen, Art B. "On dropping the first Sobol' point." :arxiv:`2008.08051`,
+   2020.
+.. [7] L'Ecuyer, Pierre, and Christiane Lemieux. "Recent advances in randomized
+   quasi-Monte Carlo methods." In Modeling uncertainty, pp. 419-474. Springer,
+   New York, NY, 2002.
+.. [8] DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence
+   intervals." Statistical science: 189-212, 1996.
+.. [9] Dimov, Ivan T. "Monte Carlo methods for applied scientists." World
+   Scientific, 2008.
+.. [10] Caflisch, Russel E., William J. Morokoff, and Art B. Owen. "Valuation
+   of mortgage backed securities using Brownian bridges to reduce effective
+   dimension." Journal of Computational Finance: no. 1 27-46, 1997.
+.. [11] Sloan, Ian H., and Henryk Wozniakowski. "When are quasi-Monte Carlo
+   algorithms efficient for high dimensional integrals?." Journal of Complexity
+   14, no. 1 (1998): 1-33.
+.. [12] Owen, Art B., and Daniel Rudolf, "A strong law of large numbers for
+   scrambled net integration." SIAM Review, to appear.
+.. [13] Loh, Wei-Liem. "On the asymptotic distribution of scrambled net
+   quadrature." The Annals of Statistics 31, no. 4: 1282-1324, 2003.
+.. [14] Sloan, Ian H. and S. Joe. "Lattice methods for multiple integration."
+   Oxford University Press, 1994.
+.. [15] Dick, Josef, and Friedrich Pillichshammer. "Digital nets and sequences:
+   discrepancy theory and quasi-Monte Carlo integration." Cambridge University
+   Press, 2010.
+.. [16] Dick, Josef, F. Kuo, Friedrich Pillichshammer, and I. Sloan.
+   "Construction algorithms for polynomial lattice rules for multivariate
+   integration." Mathematics of computation 74, no. 252: 1895-1921, 2005.
+.. [17] Sobol', Il'ya Meerovich. "On the distribution of points in a cube and
+   the approximate evaluation of integrals." Zhurnal Vychislitel'noi Matematiki
+   i Matematicheskoi Fiziki 7, no. 4: 784-802, 1967.
+.. [18] Halton, John H. "On the efficiency of certain quasi-random sequences of
+   points in evaluating multi-dimensional integrals." Numerische Mathematik 2,
+   no. 1: 84-90, 1960.
+.. [19] Faure, Henri. "Discrepance de suites associees a un systeme de
+   numeration (en dimension s)." Acta arithmetica 41, no. 4: 337-351, 1982.
+.. [20] Niederreiter, Harold, and Chaoping Xing. "Low-discrepancy sequences and
+   global function fields with many rational places." Finite Fields and their
+   applications 2, no. 3: 241-273, 1996.
+.. [21] Hong, Hee Sun, and Fred J. Hickernell. "Algorithm 823: Implementing
+   scrambled digital sequences." ACM Transactions on Mathematical Software
+   (TOMS) 29, no. 2: 95-109, 2003.
+.. [22] Dick, Josef. "Higher order scrambled digital nets achieve the optimal
+   rate of the root mean square error for smooth integrands." The Annals of
+   Statistics 39, no. 3: 1372-1398, 2011.
+.. [23] Niederreiter, Harald. "Multidimensional numerical integration using
+   pseudorandom numbers." In Stochastic Programming 84 Part I, pp. 17-38.
+   Springer, Berlin, Heidelberg, 1986.
+.. [24] Hickernell, Fred J. "Obtaining O (N-2+e) Convergence for Lattice
+   Quadrature Rules." In Monte Carlo and Quasi-Monte Carlo Methods 2000,
+   pp. 274-289. Springer, Berlin, Heidelberg, 2002.
+.. [25] Owen, Art B., and Seth D. Tribble. "A quasi-Monte Carlo Metropolis
+   algorithm." Proceedings of the National Academy of Sciences 102,
+   no. 25: 8844-8849, 2005.
+.. [26] Chen, Su. "Consistency and convergence rate of Markov chain quasi Monte
+   Carlo with examples." PhD diss., Stanford University, 2011.
+.. [27] Joe, Stephen, and Frances Y. Kuo. "Constructing Sobol sequences with
+   better two-dimensional projections." SIAM Journal on Scientific Computing
+   30, no. 5: 2635-2654, 2008.
+
+"""
+from ._qmc import *  # noqa: F403
+from ._qmc import __all__  # noqa: F401
diff --git a/python_embeded/Lib/site-packages/scipy/stats/sampling.py b/python_embeded/Lib/site-packages/scipy/stats/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b2cdf57445f3368f03619f97290dff92d41a6af
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/sampling.py
@@ -0,0 +1,73 @@
+"""
+======================================================
+Random Number Generators (:mod:`scipy.stats.sampling`)
+======================================================
+
+.. currentmodule:: scipy.stats.sampling
+
+This module contains a collection of random number generators to sample
+from univariate continuous and discrete distributions. It uses the
+implementation of a C library called "UNU.RAN". The only exception is
+RatioUniforms, which is a pure Python implementation of the
+Ratio-of-Uniforms method.
+
+Generators Wrapped
+==================
+
+For continuous distributions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   NumericalInverseHermite
+   NumericalInversePolynomial
+   TransformedDensityRejection
+   SimpleRatioUniforms
+   RatioUniforms
+
+For discrete distributions
+--------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   DiscreteAliasUrn
+   DiscreteGuideTable
+
+Warnings / Errors used in :mod:`scipy.stats.sampling`
+-----------------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   UNURANError
+
+
+Generators for pre-defined distributions
+========================================
+
+To easily apply the above methods for some of the continuous distributions
+in :mod:`scipy.stats`, the following functionality can be used:
+
+.. autosummary::
+   :toctree: generated/
+
+   FastGeneratorInversion
+
+"""
+from ._sampling import FastGeneratorInversion, RatioUniforms  # noqa: F401
+from ._unuran.unuran_wrapper import (  # noqa: F401
+   TransformedDensityRejection,
+   DiscreteAliasUrn,
+   DiscreteGuideTable,
+   NumericalInversePolynomial,
+   NumericalInverseHermite,
+   SimpleRatioUniforms,
+   UNURANError
+)
+
+__all__ = ["NumericalInverseHermite", "NumericalInversePolynomial",
+           "TransformedDensityRejection", "SimpleRatioUniforms",
+           "RatioUniforms", "DiscreteAliasUrn", "DiscreteGuideTable",
+           "UNURANError", "FastGeneratorInversion"]
diff --git a/python_embeded/Lib/site-packages/scipy/stats/stats.py b/python_embeded/Lib/site-packages/scipy/stats/stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9f89516d53a4c40ce98b687d668c15d952a1ee5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/stats/stats.py
@@ -0,0 +1,41 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
+    'tmin', 'tmax', 'tstd', 'tsem', 'moment',
+    'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
+    'normaltest', 'jarque_bera',
+    'scoreatpercentile', 'percentileofscore',
+    'cumfreq', 'relfreq', 'obrientransform',
+    'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
+    'median_abs_deviation',
+    'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
+    'f_oneway',
+    'pearsonr', 'fisher_exact',
+    'spearmanr', 'pointbiserialr',
+    'kendalltau', 'weightedtau', 'multiscale_graphcorr',
+    'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
+    'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
+    'kstest', 'ks_1samp', 'ks_2samp',
+    'chisquare', 'power_divergence',
+    'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
+    'rankdata',
+    'combine_pvalues', 'wasserstein_distance', 'energy_distance',
+    'brunnermunzel', 'alexandergovern', 'distributions',
+    'mstats_basic',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="stats",
+                                   private_modules=["_stats_py", "_mgc"], all=__all__,
+                                   attribute=name)
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/__init__.py b/python_embeded/Lib/site-packages/segment_anything/modeling/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..38e906243d898d7fc071c0fe218338c5cace3ea1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .sam import Sam
+from .image_encoder import ImageEncoderViT
+from .mask_decoder import MaskDecoder
+from .prompt_encoder import PromptEncoder
+from .transformer import TwoWayTransformer
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/common.py b/python_embeded/Lib/site-packages/segment_anything/modeling/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bf15236a3eb24d8526073bc4fa2b274cccb3f96
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/common.py
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+
+from typing import Type
+
+
+class MLPBlock(nn.Module):
+    def __init__(
+        self,
+        embedding_dim: int,
+        mlp_dim: int,
+        act: Type[nn.Module] = nn.GELU,
+    ) -> None:
+        super().__init__()
+        self.lin1 = nn.Linear(embedding_dim, mlp_dim)
+        self.lin2 = nn.Linear(mlp_dim, embedding_dim)
+        self.act = act()
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return self.lin2(self.act(self.lin1(x)))
+
+
+# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
+# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119  # noqa
+class LayerNorm2d(nn.Module):
+    def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
+        super().__init__()
+        self.weight = nn.Parameter(torch.ones(num_channels))
+        self.bias = nn.Parameter(torch.zeros(num_channels))
+        self.eps = eps
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        u = x.mean(1, keepdim=True)
+        s = (x - u).pow(2).mean(1, keepdim=True)
+        x = (x - u) / torch.sqrt(s + self.eps)
+        x = self.weight[:, None, None] * x + self.bias[:, None, None]
+        return x
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/image_encoder.py b/python_embeded/Lib/site-packages/segment_anything/modeling/image_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6ad9ad2938842308e482a05c9d35ab08db9b2c3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/image_encoder.py
@@ -0,0 +1,395 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from typing import Optional, Tuple, Type
+
+from .common import LayerNorm2d, MLPBlock
+
+
+# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
+class ImageEncoderViT(nn.Module):
+    def __init__(
+        self,
+        img_size: int = 1024,
+        patch_size: int = 16,
+        in_chans: int = 3,
+        embed_dim: int = 768,
+        depth: int = 12,
+        num_heads: int = 12,
+        mlp_ratio: float = 4.0,
+        out_chans: int = 256,
+        qkv_bias: bool = True,
+        norm_layer: Type[nn.Module] = nn.LayerNorm,
+        act_layer: Type[nn.Module] = nn.GELU,
+        use_abs_pos: bool = True,
+        use_rel_pos: bool = False,
+        rel_pos_zero_init: bool = True,
+        window_size: int = 0,
+        global_attn_indexes: Tuple[int, ...] = (),
+    ) -> None:
+        """
+        Args:
+            img_size (int): Input image size.
+            patch_size (int): Patch size.
+            in_chans (int): Number of input image channels.
+            embed_dim (int): Patch embedding dimension.
+            depth (int): Depth of ViT.
+            num_heads (int): Number of attention heads in each ViT block.
+            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+            qkv_bias (bool): If True, add a learnable bias to query, key, value.
+            norm_layer (nn.Module): Normalization layer.
+            act_layer (nn.Module): Activation layer.
+            use_abs_pos (bool): If True, use absolute positional embeddings.
+            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
+            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+            window_size (int): Window size for window attention blocks.
+            global_attn_indexes (list): Indexes for blocks using global attention.
+        """
+        super().__init__()
+        self.img_size = img_size
+
+        self.patch_embed = PatchEmbed(
+            kernel_size=(patch_size, patch_size),
+            stride=(patch_size, patch_size),
+            in_chans=in_chans,
+            embed_dim=embed_dim,
+        )
+
+        self.pos_embed: Optional[nn.Parameter] = None
+        if use_abs_pos:
+            # Initialize absolute positional embedding with pretrain image size.
+            self.pos_embed = nn.Parameter(
+                torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
+            )
+
+        self.blocks = nn.ModuleList()
+        for i in range(depth):
+            block = Block(
+                dim=embed_dim,
+                num_heads=num_heads,
+                mlp_ratio=mlp_ratio,
+                qkv_bias=qkv_bias,
+                norm_layer=norm_layer,
+                act_layer=act_layer,
+                use_rel_pos=use_rel_pos,
+                rel_pos_zero_init=rel_pos_zero_init,
+                window_size=window_size if i not in global_attn_indexes else 0,
+                input_size=(img_size // patch_size, img_size // patch_size),
+            )
+            self.blocks.append(block)
+
+        self.neck = nn.Sequential(
+            nn.Conv2d(
+                embed_dim,
+                out_chans,
+                kernel_size=1,
+                bias=False,
+            ),
+            LayerNorm2d(out_chans),
+            nn.Conv2d(
+                out_chans,
+                out_chans,
+                kernel_size=3,
+                padding=1,
+                bias=False,
+            ),
+            LayerNorm2d(out_chans),
+        )
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        x = self.patch_embed(x)
+        if self.pos_embed is not None:
+            x = x + self.pos_embed
+
+        for blk in self.blocks:
+            x = blk(x)
+
+        x = self.neck(x.permute(0, 3, 1, 2))
+
+        return x
+
+
+class Block(nn.Module):
+    """Transformer blocks with support of window attention and residual propagation blocks"""
+
+    def __init__(
+        self,
+        dim: int,
+        num_heads: int,
+        mlp_ratio: float = 4.0,
+        qkv_bias: bool = True,
+        norm_layer: Type[nn.Module] = nn.LayerNorm,
+        act_layer: Type[nn.Module] = nn.GELU,
+        use_rel_pos: bool = False,
+        rel_pos_zero_init: bool = True,
+        window_size: int = 0,
+        input_size: Optional[Tuple[int, int]] = None,
+    ) -> None:
+        """
+        Args:
+            dim (int): Number of input channels.
+            num_heads (int): Number of attention heads in each ViT block.
+            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+            qkv_bias (bool): If True, add a learnable bias to query, key, value.
+            norm_layer (nn.Module): Normalization layer.
+            act_layer (nn.Module): Activation layer.
+            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
+            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+            window_size (int): Window size for window attention blocks. If it equals 0, then
+                use global attention.
+            input_size (int or None): Input resolution for calculating the relative positional
+                parameter size.
+        """
+        super().__init__()
+        self.norm1 = norm_layer(dim)
+        self.attn = Attention(
+            dim,
+            num_heads=num_heads,
+            qkv_bias=qkv_bias,
+            use_rel_pos=use_rel_pos,
+            rel_pos_zero_init=rel_pos_zero_init,
+            input_size=input_size if window_size == 0 else (window_size, window_size),
+        )
+
+        self.norm2 = norm_layer(dim)
+        self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
+
+        self.window_size = window_size
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        shortcut = x
+        x = self.norm1(x)
+        # Window partition
+        if self.window_size > 0:
+            H, W = x.shape[1], x.shape[2]
+            x, pad_hw = window_partition(x, self.window_size)
+
+        x = self.attn(x)
+        # Reverse window partition
+        if self.window_size > 0:
+            x = window_unpartition(x, self.window_size, pad_hw, (H, W))
+
+        x = shortcut + x
+        x = x + self.mlp(self.norm2(x))
+
+        return x
+
+
+class Attention(nn.Module):
+    """Multi-head Attention block with relative position embeddings."""
+
+    def __init__(
+        self,
+        dim: int,
+        num_heads: int = 8,
+        qkv_bias: bool = True,
+        use_rel_pos: bool = False,
+        rel_pos_zero_init: bool = True,
+        input_size: Optional[Tuple[int, int]] = None,
+    ) -> None:
+        """
+        Args:
+            dim (int): Number of input channels.
+            num_heads (int): Number of attention heads.
+            qkv_bias (bool:  If True, add a learnable bias to query, key, value.
+            rel_pos (bool): If True, add relative positional embeddings to the attention map.
+            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+            input_size (int or None): Input resolution for calculating the relative positional
+                parameter size.
+        """
+        super().__init__()
+        self.num_heads = num_heads
+        head_dim = dim // num_heads
+        self.scale = head_dim**-0.5
+
+        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+        self.proj = nn.Linear(dim, dim)
+
+        self.use_rel_pos = use_rel_pos
+        if self.use_rel_pos:
+            assert (
+                input_size is not None
+            ), "Input size must be provided if using relative positional encoding."
+            # initialize relative positional embeddings
+            self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
+            self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        B, H, W, _ = x.shape
+        # qkv with shape (3, B, nHead, H * W, C)
+        qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
+        # q, k, v with shape (B * nHead, H * W, C)
+        q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
+
+        attn = (q * self.scale) @ k.transpose(-2, -1)
+
+        if self.use_rel_pos:
+            attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
+
+        attn = attn.softmax(dim=-1)
+        x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
+        x = self.proj(x)
+
+        return x
+
+
+def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
+    """
+    Partition into non-overlapping windows with padding if needed.
+    Args:
+        x (tensor): input tokens with [B, H, W, C].
+        window_size (int): window size.
+
+    Returns:
+        windows: windows after partition with [B * num_windows, window_size, window_size, C].
+        (Hp, Wp): padded height and width before partition
+    """
+    B, H, W, C = x.shape
+
+    pad_h = (window_size - H % window_size) % window_size
+    pad_w = (window_size - W % window_size) % window_size
+    if pad_h > 0 or pad_w > 0:
+        x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
+    Hp, Wp = H + pad_h, W + pad_w
+
+    x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
+    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+    return windows, (Hp, Wp)
+
+
+def window_unpartition(
+    windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
+) -> torch.Tensor:
+    """
+    Window unpartition into original sequences and removing padding.
+    Args:
+        x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
+        window_size (int): window size.
+        pad_hw (Tuple): padded height and width (Hp, Wp).
+        hw (Tuple): original height and width (H, W) before padding.
+
+    Returns:
+        x: unpartitioned sequences with [B, H, W, C].
+    """
+    Hp, Wp = pad_hw
+    H, W = hw
+    B = windows.shape[0] // (Hp * Wp // window_size // window_size)
+    x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
+    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
+
+    if Hp > H or Wp > W:
+        x = x[:, :H, :W, :].contiguous()
+    return x
+
+
+def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
+    """
+    Get relative positional embeddings according to the relative positions of
+        query and key sizes.
+    Args:
+        q_size (int): size of query q.
+        k_size (int): size of key k.
+        rel_pos (Tensor): relative position embeddings (L, C).
+
+    Returns:
+        Extracted positional embeddings according to relative positions.
+    """
+    max_rel_dist = int(2 * max(q_size, k_size) - 1)
+    # Interpolate rel pos if needed.
+    if rel_pos.shape[0] != max_rel_dist:
+        # Interpolate rel pos.
+        rel_pos_resized = F.interpolate(
+            rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
+            size=max_rel_dist,
+            mode="linear",
+        )
+        rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+    else:
+        rel_pos_resized = rel_pos
+
+    # Scale the coords with short length if shapes for q and k are different.
+    q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+    k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+    relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+    return rel_pos_resized[relative_coords.long()]
+
+
+def add_decomposed_rel_pos(
+    attn: torch.Tensor,
+    q: torch.Tensor,
+    rel_pos_h: torch.Tensor,
+    rel_pos_w: torch.Tensor,
+    q_size: Tuple[int, int],
+    k_size: Tuple[int, int],
+) -> torch.Tensor:
+    """
+    Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
+    https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py   # noqa B950
+    Args:
+        attn (Tensor): attention map.
+        q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
+        rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
+        rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
+        q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
+        k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
+
+    Returns:
+        attn (Tensor): attention map with added relative positional embeddings.
+    """
+    q_h, q_w = q_size
+    k_h, k_w = k_size
+    Rh = get_rel_pos(q_h, k_h, rel_pos_h)
+    Rw = get_rel_pos(q_w, k_w, rel_pos_w)
+
+    B, _, dim = q.shape
+    r_q = q.reshape(B, q_h, q_w, dim)
+    rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
+    rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
+
+    attn = (
+        attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
+    ).view(B, q_h * q_w, k_h * k_w)
+
+    return attn
+
+
+class PatchEmbed(nn.Module):
+    """
+    Image to Patch Embedding.
+    """
+
+    def __init__(
+        self,
+        kernel_size: Tuple[int, int] = (16, 16),
+        stride: Tuple[int, int] = (16, 16),
+        padding: Tuple[int, int] = (0, 0),
+        in_chans: int = 3,
+        embed_dim: int = 768,
+    ) -> None:
+        """
+        Args:
+            kernel_size (Tuple): kernel size of the projection layer.
+            stride (Tuple): stride of the projection layer.
+            padding (Tuple): padding size of the projection layer.
+            in_chans (int): Number of input image channels.
+            embed_dim (int):  embed_dim (int): Patch embedding dimension.
+        """
+        super().__init__()
+
+        self.proj = nn.Conv2d(
+            in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
+        )
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        x = self.proj(x)
+        # B C H W -> B H W C
+        x = x.permute(0, 2, 3, 1)
+        return x
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/mask_decoder.py b/python_embeded/Lib/site-packages/segment_anything/modeling/mask_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e86f7cc9ad95582a08ef2531c68d03fa4af8d99
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/mask_decoder.py
@@ -0,0 +1,176 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from typing import List, Tuple, Type
+
+from .common import LayerNorm2d
+
+
+class MaskDecoder(nn.Module):
+    def __init__(
+        self,
+        *,
+        transformer_dim: int,
+        transformer: nn.Module,
+        num_multimask_outputs: int = 3,
+        activation: Type[nn.Module] = nn.GELU,
+        iou_head_depth: int = 3,
+        iou_head_hidden_dim: int = 256,
+    ) -> None:
+        """
+        Predicts masks given an image and prompt embeddings, using a
+        tranformer architecture.
+
+        Arguments:
+          transformer_dim (int): the channel dimension of the transformer
+          transformer (nn.Module): the transformer used to predict masks
+          num_multimask_outputs (int): the number of masks to predict
+            when disambiguating masks
+          activation (nn.Module): the type of activation to use when
+            upscaling masks
+          iou_head_depth (int): the depth of the MLP used to predict
+            mask quality
+          iou_head_hidden_dim (int): the hidden dimension of the MLP
+            used to predict mask quality
+        """
+        super().__init__()
+        self.transformer_dim = transformer_dim
+        self.transformer = transformer
+
+        self.num_multimask_outputs = num_multimask_outputs
+
+        self.iou_token = nn.Embedding(1, transformer_dim)
+        self.num_mask_tokens = num_multimask_outputs + 1
+        self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
+
+        self.output_upscaling = nn.Sequential(
+            nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
+            LayerNorm2d(transformer_dim // 4),
+            activation(),
+            nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
+            activation(),
+        )
+        self.output_hypernetworks_mlps = nn.ModuleList(
+            [
+                MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
+                for i in range(self.num_mask_tokens)
+            ]
+        )
+
+        self.iou_prediction_head = MLP(
+            transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
+        )
+
+    def forward(
+        self,
+        image_embeddings: torch.Tensor,
+        image_pe: torch.Tensor,
+        sparse_prompt_embeddings: torch.Tensor,
+        dense_prompt_embeddings: torch.Tensor,
+        multimask_output: bool,
+    ) -> Tuple[torch.Tensor, torch.Tensor]:
+        """
+        Predict masks given image and prompt embeddings.
+
+        Arguments:
+          image_embeddings (torch.Tensor): the embeddings from the image encoder
+          image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
+          sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
+          dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
+          multimask_output (bool): Whether to return multiple masks or a single
+            mask.
+
+        Returns:
+          torch.Tensor: batched predicted masks
+          torch.Tensor: batched predictions of mask quality
+        """
+        masks, iou_pred = self.predict_masks(
+            image_embeddings=image_embeddings,
+            image_pe=image_pe,
+            sparse_prompt_embeddings=sparse_prompt_embeddings,
+            dense_prompt_embeddings=dense_prompt_embeddings,
+        )
+
+        # Select the correct mask or masks for outptu
+        if multimask_output:
+            mask_slice = slice(1, None)
+        else:
+            mask_slice = slice(0, 1)
+        masks = masks[:, mask_slice, :, :]
+        iou_pred = iou_pred[:, mask_slice]
+
+        # Prepare output
+        return masks, iou_pred
+
+    def predict_masks(
+        self,
+        image_embeddings: torch.Tensor,
+        image_pe: torch.Tensor,
+        sparse_prompt_embeddings: torch.Tensor,
+        dense_prompt_embeddings: torch.Tensor,
+    ) -> Tuple[torch.Tensor, torch.Tensor]:
+        """Predicts masks. See 'forward' for more details."""
+        # Concatenate output tokens
+        output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
+        output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
+        tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
+
+        # Expand per-image data in batch direction to be per-mask
+        src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
+        src = src + dense_prompt_embeddings
+        pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
+        b, c, h, w = src.shape
+
+        # Run the transformer
+        hs, src = self.transformer(src, pos_src, tokens)
+        iou_token_out = hs[:, 0, :]
+        mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
+
+        # Upscale mask embeddings and predict masks using the mask tokens
+        src = src.transpose(1, 2).view(b, c, h, w)
+        upscaled_embedding = self.output_upscaling(src)
+        hyper_in_list: List[torch.Tensor] = []
+        for i in range(self.num_mask_tokens):
+            hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
+        hyper_in = torch.stack(hyper_in_list, dim=1)
+        b, c, h, w = upscaled_embedding.shape
+        masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
+
+        # Generate mask quality predictions
+        iou_pred = self.iou_prediction_head(iou_token_out)
+
+        return masks, iou_pred
+
+
+# Lightly adapted from
+# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
+class MLP(nn.Module):
+    def __init__(
+        self,
+        input_dim: int,
+        hidden_dim: int,
+        output_dim: int,
+        num_layers: int,
+        sigmoid_output: bool = False,
+    ) -> None:
+        super().__init__()
+        self.num_layers = num_layers
+        h = [hidden_dim] * (num_layers - 1)
+        self.layers = nn.ModuleList(
+            nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
+        )
+        self.sigmoid_output = sigmoid_output
+
+    def forward(self, x):
+        for i, layer in enumerate(self.layers):
+            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+        if self.sigmoid_output:
+            x = F.sigmoid(x)
+        return x
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/prompt_encoder.py b/python_embeded/Lib/site-packages/segment_anything/modeling/prompt_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3143f4f8e02ddd7ca8587b40ff5d47c3a6b7ef3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/prompt_encoder.py
@@ -0,0 +1,214 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+from torch import nn
+
+from typing import Any, Optional, Tuple, Type
+
+from .common import LayerNorm2d
+
+
+class PromptEncoder(nn.Module):
+    def __init__(
+        self,
+        embed_dim: int,
+        image_embedding_size: Tuple[int, int],
+        input_image_size: Tuple[int, int],
+        mask_in_chans: int,
+        activation: Type[nn.Module] = nn.GELU,
+    ) -> None:
+        """
+        Encodes prompts for input to SAM's mask decoder.
+
+        Arguments:
+          embed_dim (int): The prompts' embedding dimension
+          image_embedding_size (tuple(int, int)): The spatial size of the
+            image embedding, as (H, W).
+          input_image_size (int): The padded size of the image as input
+            to the image encoder, as (H, W).
+          mask_in_chans (int): The number of hidden channels used for
+            encoding input masks.
+          activation (nn.Module): The activation to use when encoding
+            input masks.
+        """
+        super().__init__()
+        self.embed_dim = embed_dim
+        self.input_image_size = input_image_size
+        self.image_embedding_size = image_embedding_size
+        self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
+
+        self.num_point_embeddings: int = 4  # pos/neg point + 2 box corners
+        point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
+        self.point_embeddings = nn.ModuleList(point_embeddings)
+        self.not_a_point_embed = nn.Embedding(1, embed_dim)
+
+        self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
+        self.mask_downscaling = nn.Sequential(
+            nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
+            LayerNorm2d(mask_in_chans // 4),
+            activation(),
+            nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
+            LayerNorm2d(mask_in_chans),
+            activation(),
+            nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
+        )
+        self.no_mask_embed = nn.Embedding(1, embed_dim)
+
+    def get_dense_pe(self) -> torch.Tensor:
+        """
+        Returns the positional encoding used to encode point prompts,
+        applied to a dense set of points the shape of the image encoding.
+
+        Returns:
+          torch.Tensor: Positional encoding with shape
+            1x(embed_dim)x(embedding_h)x(embedding_w)
+        """
+        return self.pe_layer(self.image_embedding_size).unsqueeze(0)
+
+    def _embed_points(
+        self,
+        points: torch.Tensor,
+        labels: torch.Tensor,
+        pad: bool,
+    ) -> torch.Tensor:
+        """Embeds point prompts."""
+        points = points + 0.5  # Shift to center of pixel
+        if pad:
+            padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
+            padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
+            points = torch.cat([points, padding_point], dim=1)
+            labels = torch.cat([labels, padding_label], dim=1)
+        point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
+        point_embedding[labels == -1] = 0.0
+        point_embedding[labels == -1] += self.not_a_point_embed.weight
+        point_embedding[labels == 0] += self.point_embeddings[0].weight
+        point_embedding[labels == 1] += self.point_embeddings[1].weight
+        return point_embedding
+
+    def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
+        """Embeds box prompts."""
+        boxes = boxes + 0.5  # Shift to center of pixel
+        coords = boxes.reshape(-1, 2, 2)
+        corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
+        corner_embedding[:, 0, :] += self.point_embeddings[2].weight
+        corner_embedding[:, 1, :] += self.point_embeddings[3].weight
+        return corner_embedding
+
+    def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
+        """Embeds mask inputs."""
+        mask_embedding = self.mask_downscaling(masks)
+        return mask_embedding
+
+    def _get_batch_size(
+        self,
+        points: Optional[Tuple[torch.Tensor, torch.Tensor]],
+        boxes: Optional[torch.Tensor],
+        masks: Optional[torch.Tensor],
+    ) -> int:
+        """
+        Gets the batch size of the output given the batch size of the input prompts.
+        """
+        if points is not None:
+            return points[0].shape[0]
+        elif boxes is not None:
+            return boxes.shape[0]
+        elif masks is not None:
+            return masks.shape[0]
+        else:
+            return 1
+
+    def _get_device(self) -> torch.device:
+        return self.point_embeddings[0].weight.device
+
+    def forward(
+        self,
+        points: Optional[Tuple[torch.Tensor, torch.Tensor]],
+        boxes: Optional[torch.Tensor],
+        masks: Optional[torch.Tensor],
+    ) -> Tuple[torch.Tensor, torch.Tensor]:
+        """
+        Embeds different types of prompts, returning both sparse and dense
+        embeddings.
+
+        Arguments:
+          points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
+            and labels to embed.
+          boxes (torch.Tensor or none): boxes to embed
+          masks (torch.Tensor or none): masks to embed
+
+        Returns:
+          torch.Tensor: sparse embeddings for the points and boxes, with shape
+            BxNx(embed_dim), where N is determined by the number of input points
+            and boxes.
+          torch.Tensor: dense embeddings for the masks, in the shape
+            Bx(embed_dim)x(embed_H)x(embed_W)
+        """
+        bs = self._get_batch_size(points, boxes, masks)
+        sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
+        if points is not None:
+            coords, labels = points
+            point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
+            sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
+        if boxes is not None:
+            box_embeddings = self._embed_boxes(boxes)
+            sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
+
+        if masks is not None:
+            dense_embeddings = self._embed_masks(masks)
+        else:
+            dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
+                bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
+            )
+
+        return sparse_embeddings, dense_embeddings
+
+
+class PositionEmbeddingRandom(nn.Module):
+    """
+    Positional encoding using random spatial frequencies.
+    """
+
+    def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
+        super().__init__()
+        if scale is None or scale <= 0.0:
+            scale = 1.0
+        self.register_buffer(
+            "positional_encoding_gaussian_matrix",
+            scale * torch.randn((2, num_pos_feats)),
+        )
+
+    def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
+        """Positionally encode points that are normalized to [0,1]."""
+        # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
+        coords = 2 * coords - 1
+        coords = coords @ self.positional_encoding_gaussian_matrix
+        coords = 2 * np.pi * coords
+        # outputs d_1 x ... x d_n x C shape
+        return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
+
+    def forward(self, size: Tuple[int, int]) -> torch.Tensor:
+        """Generate positional encoding for a grid of the specified size."""
+        h, w = size
+        device: Any = self.positional_encoding_gaussian_matrix.device
+        grid = torch.ones((h, w), device=device, dtype=torch.float32)
+        y_embed = grid.cumsum(dim=0) - 0.5
+        x_embed = grid.cumsum(dim=1) - 0.5
+        y_embed = y_embed / h
+        x_embed = x_embed / w
+
+        pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
+        return pe.permute(2, 0, 1)  # C x H x W
+
+    def forward_with_coords(
+        self, coords_input: torch.Tensor, image_size: Tuple[int, int]
+    ) -> torch.Tensor:
+        """Positionally encode points that are not normalized to [0,1]."""
+        coords = coords_input.clone()
+        coords[:, :, 0] = coords[:, :, 0] / image_size[1]
+        coords[:, :, 1] = coords[:, :, 1] / image_size[0]
+        return self._pe_encoding(coords.to(torch.float))  # B x N x C
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/sam.py b/python_embeded/Lib/site-packages/segment_anything/modeling/sam.py
new file mode 100644
index 0000000000000000000000000000000000000000..303bc2f40c3dbc84f5d4286bb73336e075a86589
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/sam.py
@@ -0,0 +1,174 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from typing import Any, Dict, List, Tuple
+
+from .image_encoder import ImageEncoderViT
+from .mask_decoder import MaskDecoder
+from .prompt_encoder import PromptEncoder
+
+
+class Sam(nn.Module):
+    mask_threshold: float = 0.0
+    image_format: str = "RGB"
+
+    def __init__(
+        self,
+        image_encoder: ImageEncoderViT,
+        prompt_encoder: PromptEncoder,
+        mask_decoder: MaskDecoder,
+        pixel_mean: List[float] = [123.675, 116.28, 103.53],
+        pixel_std: List[float] = [58.395, 57.12, 57.375],
+    ) -> None:
+        """
+        SAM predicts object masks from an image and input prompts.
+
+        Arguments:
+          image_encoder (ImageEncoderViT): The backbone used to encode the
+            image into image embeddings that allow for efficient mask prediction.
+          prompt_encoder (PromptEncoder): Encodes various types of input prompts.
+          mask_decoder (MaskDecoder): Predicts masks from the image embeddings
+            and encoded prompts.
+          pixel_mean (list(float)): Mean values for normalizing pixels in the input image.
+          pixel_std (list(float)): Std values for normalizing pixels in the input image.
+        """
+        super().__init__()
+        self.image_encoder = image_encoder
+        self.prompt_encoder = prompt_encoder
+        self.mask_decoder = mask_decoder
+        self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False)
+        self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False)
+
+    @property
+    def device(self) -> Any:
+        return self.pixel_mean.device
+
+    @torch.no_grad()
+    def forward(
+        self,
+        batched_input: List[Dict[str, Any]],
+        multimask_output: bool,
+    ) -> List[Dict[str, torch.Tensor]]:
+        """
+        Predicts masks end-to-end from provided images and prompts.
+        If prompts are not known in advance, using SamPredictor is
+        recommended over calling the model directly.
+
+        Arguments:
+          batched_input (list(dict)): A list over input images, each a
+            dictionary with the following keys. A prompt key can be
+            excluded if it is not present.
+              'image': The image as a torch tensor in 3xHxW format,
+                already transformed for input to the model.
+              'original_size': (tuple(int, int)) The original size of
+                the image before transformation, as (H, W).
+              'point_coords': (torch.Tensor) Batched point prompts for
+                this image, with shape BxNx2. Already transformed to the
+                input frame of the model.
+              'point_labels': (torch.Tensor) Batched labels for point prompts,
+                with shape BxN.
+              'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.
+                Already transformed to the input frame of the model.
+              'mask_inputs': (torch.Tensor) Batched mask inputs to the model,
+                in the form Bx1xHxW.
+          multimask_output (bool): Whether the model should predict multiple
+            disambiguating masks, or return a single mask.
+
+        Returns:
+          (list(dict)): A list over input images, where each element is
+            as dictionary with the following keys.
+              'masks': (torch.Tensor) Batched binary mask predictions,
+                with shape BxCxHxW, where B is the number of input promts,
+                C is determiend by multimask_output, and (H, W) is the
+                original size of the image.
+              'iou_predictions': (torch.Tensor) The model's predictions
+                of mask quality, in shape BxC.
+              'low_res_logits': (torch.Tensor) Low resolution logits with
+                shape BxCxHxW, where H=W=256. Can be passed as mask input
+                to subsequent iterations of prediction.
+        """
+        input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0)
+        image_embeddings = self.image_encoder(input_images)
+
+        outputs = []
+        for image_record, curr_embedding in zip(batched_input, image_embeddings):
+            if "point_coords" in image_record:
+                points = (image_record["point_coords"], image_record["point_labels"])
+            else:
+                points = None
+            sparse_embeddings, dense_embeddings = self.prompt_encoder(
+                points=points,
+                boxes=image_record.get("boxes", None),
+                masks=image_record.get("mask_inputs", None),
+            )
+            low_res_masks, iou_predictions = self.mask_decoder(
+                image_embeddings=curr_embedding.unsqueeze(0),
+                image_pe=self.prompt_encoder.get_dense_pe(),
+                sparse_prompt_embeddings=sparse_embeddings,
+                dense_prompt_embeddings=dense_embeddings,
+                multimask_output=multimask_output,
+            )
+            masks = self.postprocess_masks(
+                low_res_masks,
+                input_size=image_record["image"].shape[-2:],
+                original_size=image_record["original_size"],
+            )
+            masks = masks > self.mask_threshold
+            outputs.append(
+                {
+                    "masks": masks,
+                    "iou_predictions": iou_predictions,
+                    "low_res_logits": low_res_masks,
+                }
+            )
+        return outputs
+
+    def postprocess_masks(
+        self,
+        masks: torch.Tensor,
+        input_size: Tuple[int, ...],
+        original_size: Tuple[int, ...],
+    ) -> torch.Tensor:
+        """
+        Remove padding and upscale masks to the original image size.
+
+        Arguments:
+          masks (torch.Tensor): Batched masks from the mask_decoder,
+            in BxCxHxW format.
+          input_size (tuple(int, int)): The size of the image input to the
+            model, in (H, W) format. Used to remove padding.
+          original_size (tuple(int, int)): The original size of the image
+            before resizing for input to the model, in (H, W) format.
+
+        Returns:
+          (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)
+            is given by original_size.
+        """
+        masks = F.interpolate(
+            masks,
+            (self.image_encoder.img_size, self.image_encoder.img_size),
+            mode="bilinear",
+            align_corners=False,
+        )
+        masks = masks[..., : input_size[0], : input_size[1]]
+        masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False)
+        return masks
+
+    def preprocess(self, x: torch.Tensor) -> torch.Tensor:
+        """Normalize pixel values and pad to a square input."""
+        # Normalize colors
+        x = (x - self.pixel_mean) / self.pixel_std
+
+        # Pad
+        h, w = x.shape[-2:]
+        padh = self.image_encoder.img_size - h
+        padw = self.image_encoder.img_size - w
+        x = F.pad(x, (0, padw, 0, padh))
+        return x
diff --git a/python_embeded/Lib/site-packages/segment_anything/modeling/transformer.py b/python_embeded/Lib/site-packages/segment_anything/modeling/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1a2812f613cc55b1d0b3e3e1d0c84a760d1fb87
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/modeling/transformer.py
@@ -0,0 +1,240 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import Tensor, nn
+
+import math
+from typing import Tuple, Type
+
+from .common import MLPBlock
+
+
+class TwoWayTransformer(nn.Module):
+    def __init__(
+        self,
+        depth: int,
+        embedding_dim: int,
+        num_heads: int,
+        mlp_dim: int,
+        activation: Type[nn.Module] = nn.ReLU,
+        attention_downsample_rate: int = 2,
+    ) -> None:
+        """
+        A transformer decoder that attends to an input image using
+        queries whose positional embedding is supplied.
+
+        Args:
+          depth (int): number of layers in the transformer
+          embedding_dim (int): the channel dimension for the input embeddings
+          num_heads (int): the number of heads for multihead attention. Must
+            divide embedding_dim
+          mlp_dim (int): the channel dimension internal to the MLP block
+          activation (nn.Module): the activation to use in the MLP block
+        """
+        super().__init__()
+        self.depth = depth
+        self.embedding_dim = embedding_dim
+        self.num_heads = num_heads
+        self.mlp_dim = mlp_dim
+        self.layers = nn.ModuleList()
+
+        for i in range(depth):
+            self.layers.append(
+                TwoWayAttentionBlock(
+                    embedding_dim=embedding_dim,
+                    num_heads=num_heads,
+                    mlp_dim=mlp_dim,
+                    activation=activation,
+                    attention_downsample_rate=attention_downsample_rate,
+                    skip_first_layer_pe=(i == 0),
+                )
+            )
+
+        self.final_attn_token_to_image = Attention(
+            embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+        )
+        self.norm_final_attn = nn.LayerNorm(embedding_dim)
+
+    def forward(
+        self,
+        image_embedding: Tensor,
+        image_pe: Tensor,
+        point_embedding: Tensor,
+    ) -> Tuple[Tensor, Tensor]:
+        """
+        Args:
+          image_embedding (torch.Tensor): image to attend to. Should be shape
+            B x embedding_dim x h x w for any h and w.
+          image_pe (torch.Tensor): the positional encoding to add to the image. Must
+            have the same shape as image_embedding.
+          point_embedding (torch.Tensor): the embedding to add to the query points.
+            Must have shape B x N_points x embedding_dim for any N_points.
+
+        Returns:
+          torch.Tensor: the processed point_embedding
+          torch.Tensor: the processed image_embedding
+        """
+        # BxCxHxW -> BxHWxC == B x N_image_tokens x C
+        bs, c, h, w = image_embedding.shape
+        image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
+        image_pe = image_pe.flatten(2).permute(0, 2, 1)
+
+        # Prepare queries
+        queries = point_embedding
+        keys = image_embedding
+
+        # Apply transformer blocks and final layernorm
+        for layer in self.layers:
+            queries, keys = layer(
+                queries=queries,
+                keys=keys,
+                query_pe=point_embedding,
+                key_pe=image_pe,
+            )
+
+        # Apply the final attenion layer from the points to the image
+        q = queries + point_embedding
+        k = keys + image_pe
+        attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
+        queries = queries + attn_out
+        queries = self.norm_final_attn(queries)
+
+        return queries, keys
+
+
+class TwoWayAttentionBlock(nn.Module):
+    def __init__(
+        self,
+        embedding_dim: int,
+        num_heads: int,
+        mlp_dim: int = 2048,
+        activation: Type[nn.Module] = nn.ReLU,
+        attention_downsample_rate: int = 2,
+        skip_first_layer_pe: bool = False,
+    ) -> None:
+        """
+        A transformer block with four layers: (1) self-attention of sparse
+        inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
+        block on sparse inputs, and (4) cross attention of dense inputs to sparse
+        inputs.
+
+        Arguments:
+          embedding_dim (int): the channel dimension of the embeddings
+          num_heads (int): the number of heads in the attention layers
+          mlp_dim (int): the hidden dimension of the mlp block
+          activation (nn.Module): the activation of the mlp block
+          skip_first_layer_pe (bool): skip the PE on the first layer
+        """
+        super().__init__()
+        self.self_attn = Attention(embedding_dim, num_heads)
+        self.norm1 = nn.LayerNorm(embedding_dim)
+
+        self.cross_attn_token_to_image = Attention(
+            embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+        )
+        self.norm2 = nn.LayerNorm(embedding_dim)
+
+        self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
+        self.norm3 = nn.LayerNorm(embedding_dim)
+
+        self.norm4 = nn.LayerNorm(embedding_dim)
+        self.cross_attn_image_to_token = Attention(
+            embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+        )
+
+        self.skip_first_layer_pe = skip_first_layer_pe
+
+    def forward(
+        self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
+    ) -> Tuple[Tensor, Tensor]:
+        # Self attention block
+        if self.skip_first_layer_pe:
+            queries = self.self_attn(q=queries, k=queries, v=queries)
+        else:
+            q = queries + query_pe
+            attn_out = self.self_attn(q=q, k=q, v=queries)
+            queries = queries + attn_out
+        queries = self.norm1(queries)
+
+        # Cross attention block, tokens attending to image embedding
+        q = queries + query_pe
+        k = keys + key_pe
+        attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
+        queries = queries + attn_out
+        queries = self.norm2(queries)
+
+        # MLP block
+        mlp_out = self.mlp(queries)
+        queries = queries + mlp_out
+        queries = self.norm3(queries)
+
+        # Cross attention block, image embedding attending to tokens
+        q = queries + query_pe
+        k = keys + key_pe
+        attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
+        keys = keys + attn_out
+        keys = self.norm4(keys)
+
+        return queries, keys
+
+
+class Attention(nn.Module):
+    """
+    An attention layer that allows for downscaling the size of the embedding
+    after projection to queries, keys, and values.
+    """
+
+    def __init__(
+        self,
+        embedding_dim: int,
+        num_heads: int,
+        downsample_rate: int = 1,
+    ) -> None:
+        super().__init__()
+        self.embedding_dim = embedding_dim
+        self.internal_dim = embedding_dim // downsample_rate
+        self.num_heads = num_heads
+        assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
+
+        self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
+        self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
+        self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
+        self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
+
+    def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
+        b, n, c = x.shape
+        x = x.reshape(b, n, num_heads, c // num_heads)
+        return x.transpose(1, 2)  # B x N_heads x N_tokens x C_per_head
+
+    def _recombine_heads(self, x: Tensor) -> Tensor:
+        b, n_heads, n_tokens, c_per_head = x.shape
+        x = x.transpose(1, 2)
+        return x.reshape(b, n_tokens, n_heads * c_per_head)  # B x N_tokens x C
+
+    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
+        # Input projections
+        q = self.q_proj(q)
+        k = self.k_proj(k)
+        v = self.v_proj(v)
+
+        # Separate into heads
+        q = self._separate_heads(q, self.num_heads)
+        k = self._separate_heads(k, self.num_heads)
+        v = self._separate_heads(v, self.num_heads)
+
+        # Attention
+        _, _, _, c_per_head = q.shape
+        attn = q @ k.permute(0, 1, 3, 2)  # B x N_heads x N_tokens x N_tokens
+        attn = attn / math.sqrt(c_per_head)
+        attn = torch.softmax(attn, dim=-1)
+
+        # Get output
+        out = attn @ v
+        out = self._recombine_heads(out)
+        out = self.out_proj(out)
+
+        return out
diff --git a/python_embeded/Lib/site-packages/segment_anything/utils/__init__.py b/python_embeded/Lib/site-packages/segment_anything/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/utils/__init__.py
@@ -0,0 +1,5 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
diff --git a/python_embeded/Lib/site-packages/segment_anything/utils/amg.py b/python_embeded/Lib/site-packages/segment_anything/utils/amg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a137778e45c464c079658ecb87ec53270e789f7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/utils/amg.py
@@ -0,0 +1,346 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+
+import math
+from copy import deepcopy
+from itertools import product
+from typing import Any, Dict, Generator, ItemsView, List, Tuple
+
+
+class MaskData:
+    """
+    A structure for storing masks and their related data in batched format.
+    Implements basic filtering and concatenation.
+    """
+
+    def __init__(self, **kwargs) -> None:
+        for v in kwargs.values():
+            assert isinstance(
+                v, (list, np.ndarray, torch.Tensor)
+            ), "MaskData only supports list, numpy arrays, and torch tensors."
+        self._stats = dict(**kwargs)
+
+    def __setitem__(self, key: str, item: Any) -> None:
+        assert isinstance(
+            item, (list, np.ndarray, torch.Tensor)
+        ), "MaskData only supports list, numpy arrays, and torch tensors."
+        self._stats[key] = item
+
+    def __delitem__(self, key: str) -> None:
+        del self._stats[key]
+
+    def __getitem__(self, key: str) -> Any:
+        return self._stats[key]
+
+    def items(self) -> ItemsView[str, Any]:
+        return self._stats.items()
+
+    def filter(self, keep: torch.Tensor) -> None:
+        for k, v in self._stats.items():
+            if v is None:
+                self._stats[k] = None
+            elif isinstance(v, torch.Tensor):
+                self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
+            elif isinstance(v, np.ndarray):
+                self._stats[k] = v[keep.detach().cpu().numpy()]
+            elif isinstance(v, list) and keep.dtype == torch.bool:
+                self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
+            elif isinstance(v, list):
+                self._stats[k] = [v[i] for i in keep]
+            else:
+                raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
+
+    def cat(self, new_stats: "MaskData") -> None:
+        for k, v in new_stats.items():
+            if k not in self._stats or self._stats[k] is None:
+                self._stats[k] = deepcopy(v)
+            elif isinstance(v, torch.Tensor):
+                self._stats[k] = torch.cat([self._stats[k], v], dim=0)
+            elif isinstance(v, np.ndarray):
+                self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
+            elif isinstance(v, list):
+                self._stats[k] = self._stats[k] + deepcopy(v)
+            else:
+                raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
+
+    def to_numpy(self) -> None:
+        for k, v in self._stats.items():
+            if isinstance(v, torch.Tensor):
+                self._stats[k] = v.detach().cpu().numpy()
+
+
+def is_box_near_crop_edge(
+    boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
+) -> torch.Tensor:
+    """Filter masks at the edge of a crop, but not at the edge of the original image."""
+    crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
+    orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
+    boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
+    near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
+    near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
+    near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
+    return torch.any(near_crop_edge, dim=1)
+
+
+def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
+    box_xywh = deepcopy(box_xyxy)
+    box_xywh[2] = box_xywh[2] - box_xywh[0]
+    box_xywh[3] = box_xywh[3] - box_xywh[1]
+    return box_xywh
+
+
+def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
+    assert len(args) > 0 and all(
+        len(a) == len(args[0]) for a in args
+    ), "Batched iteration must have inputs of all the same size."
+    n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
+    for b in range(n_batches):
+        yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
+
+
+def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
+    """
+    Encodes masks to an uncompressed RLE, in the format expected by
+    pycoco tools.
+    """
+    # Put in fortran order and flatten h,w
+    b, h, w = tensor.shape
+    tensor = tensor.permute(0, 2, 1).flatten(1)
+
+    # Compute change indices
+    diff = tensor[:, 1:] ^ tensor[:, :-1]
+    change_indices = diff.nonzero()
+
+    # Encode run length
+    out = []
+    for i in range(b):
+        cur_idxs = change_indices[change_indices[:, 0] == i, 1]
+        cur_idxs = torch.cat(
+            [
+                torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
+                cur_idxs + 1,
+                torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
+            ]
+        )
+        btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
+        counts = [] if tensor[i, 0] == 0 else [0]
+        counts.extend(btw_idxs.detach().cpu().tolist())
+        out.append({"size": [h, w], "counts": counts})
+    return out
+
+
+def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
+    """Compute a binary mask from an uncompressed RLE."""
+    h, w = rle["size"]
+    mask = np.empty(h * w, dtype=bool)
+    idx = 0
+    parity = False
+    for count in rle["counts"]:
+        mask[idx : idx + count] = parity
+        idx += count
+        parity ^= True
+    mask = mask.reshape(w, h)
+    return mask.transpose()  # Put in C order
+
+
+def area_from_rle(rle: Dict[str, Any]) -> int:
+    return sum(rle["counts"][1::2])
+
+
+def calculate_stability_score(
+    masks: torch.Tensor, mask_threshold: float, threshold_offset: float
+) -> torch.Tensor:
+    """
+    Computes the stability score for a batch of masks. The stability
+    score is the IoU between the binary masks obtained by thresholding
+    the predicted mask logits at high and low values.
+    """
+    # One mask is always contained inside the other.
+    # Save memory by preventing unnecesary cast to torch.int64
+    intersections = (
+        (masks > (mask_threshold + threshold_offset))
+        .sum(-1, dtype=torch.int16)
+        .sum(-1, dtype=torch.int32)
+    )
+    unions = (
+        (masks > (mask_threshold - threshold_offset))
+        .sum(-1, dtype=torch.int16)
+        .sum(-1, dtype=torch.int32)
+    )
+    return intersections / unions
+
+
+def build_point_grid(n_per_side: int) -> np.ndarray:
+    """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
+    offset = 1 / (2 * n_per_side)
+    points_one_side = np.linspace(offset, 1 - offset, n_per_side)
+    points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
+    points_y = np.tile(points_one_side[:, None], (1, n_per_side))
+    points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
+    return points
+
+
+def build_all_layer_point_grids(
+    n_per_side: int, n_layers: int, scale_per_layer: int
+) -> List[np.ndarray]:
+    """Generates point grids for all crop layers."""
+    points_by_layer = []
+    for i in range(n_layers + 1):
+        n_points = int(n_per_side / (scale_per_layer**i))
+        points_by_layer.append(build_point_grid(n_points))
+    return points_by_layer
+
+
+def generate_crop_boxes(
+    im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
+) -> Tuple[List[List[int]], List[int]]:
+    """
+    Generates a list of crop boxes of different sizes. Each layer
+    has (2**i)**2 boxes for the ith layer.
+    """
+    crop_boxes, layer_idxs = [], []
+    im_h, im_w = im_size
+    short_side = min(im_h, im_w)
+
+    # Original image
+    crop_boxes.append([0, 0, im_w, im_h])
+    layer_idxs.append(0)
+
+    def crop_len(orig_len, n_crops, overlap):
+        return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
+
+    for i_layer in range(n_layers):
+        n_crops_per_side = 2 ** (i_layer + 1)
+        overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
+
+        crop_w = crop_len(im_w, n_crops_per_side, overlap)
+        crop_h = crop_len(im_h, n_crops_per_side, overlap)
+
+        crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
+        crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
+
+        # Crops in XYWH format
+        for x0, y0 in product(crop_box_x0, crop_box_y0):
+            box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
+            crop_boxes.append(box)
+            layer_idxs.append(i_layer + 1)
+
+    return crop_boxes, layer_idxs
+
+
+def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
+    x0, y0, _, _ = crop_box
+    offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
+    # Check if boxes has a channel dimension
+    if len(boxes.shape) == 3:
+        offset = offset.unsqueeze(1)
+    return boxes + offset
+
+
+def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
+    x0, y0, _, _ = crop_box
+    offset = torch.tensor([[x0, y0]], device=points.device)
+    # Check if points has a channel dimension
+    if len(points.shape) == 3:
+        offset = offset.unsqueeze(1)
+    return points + offset
+
+
+def uncrop_masks(
+    masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
+) -> torch.Tensor:
+    x0, y0, x1, y1 = crop_box
+    if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
+        return masks
+    # Coordinate transform masks
+    pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
+    pad = (x0, pad_x - x0, y0, pad_y - y0)
+    return torch.nn.functional.pad(masks, pad, value=0)
+
+
+def remove_small_regions(
+    mask: np.ndarray, area_thresh: float, mode: str
+) -> Tuple[np.ndarray, bool]:
+    """
+    Removes small disconnected regions and holes in a mask. Returns the
+    mask and an indicator of if the mask has been modified.
+    """
+    import cv2  # type: ignore
+
+    assert mode in ["holes", "islands"]
+    correct_holes = mode == "holes"
+    working_mask = (correct_holes ^ mask).astype(np.uint8)
+    n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
+    sizes = stats[:, -1][1:]  # Row 0 is background label
+    small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
+    if len(small_regions) == 0:
+        return mask, False
+    fill_labels = [0] + small_regions
+    if not correct_holes:
+        fill_labels = [i for i in range(n_labels) if i not in fill_labels]
+        # If every region is below threshold, keep largest
+        if len(fill_labels) == 0:
+            fill_labels = [int(np.argmax(sizes)) + 1]
+    mask = np.isin(regions, fill_labels)
+    return mask, True
+
+
+def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
+    from pycocotools import mask as mask_utils  # type: ignore
+
+    h, w = uncompressed_rle["size"]
+    rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
+    rle["counts"] = rle["counts"].decode("utf-8")  # Necessary to serialize with json
+    return rle
+
+
+def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
+    """
+    Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
+    an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
+    """
+    # torch.max below raises an error on empty inputs, just skip in this case
+    if torch.numel(masks) == 0:
+        return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
+
+    # Normalize shape to CxHxW
+    shape = masks.shape
+    h, w = shape[-2:]
+    if len(shape) > 2:
+        masks = masks.flatten(0, -3)
+    else:
+        masks = masks.unsqueeze(0)
+
+    # Get top and bottom edges
+    in_height, _ = torch.max(masks, dim=-1)
+    in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
+    bottom_edges, _ = torch.max(in_height_coords, dim=-1)
+    in_height_coords = in_height_coords + h * (~in_height)
+    top_edges, _ = torch.min(in_height_coords, dim=-1)
+
+    # Get left and right edges
+    in_width, _ = torch.max(masks, dim=-2)
+    in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
+    right_edges, _ = torch.max(in_width_coords, dim=-1)
+    in_width_coords = in_width_coords + w * (~in_width)
+    left_edges, _ = torch.min(in_width_coords, dim=-1)
+
+    # If the mask is empty the right edge will be to the left of the left edge.
+    # Replace these boxes with [0, 0, 0, 0]
+    empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
+    out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
+    out = out * (~empty_filter).unsqueeze(-1)
+
+    # Return to original shape
+    if len(shape) > 2:
+        out = out.reshape(*shape[:-2], 4)
+    else:
+        out = out[0]
+
+    return out
diff --git a/python_embeded/Lib/site-packages/segment_anything/utils/onnx.py b/python_embeded/Lib/site-packages/segment_anything/utils/onnx.py
new file mode 100644
index 0000000000000000000000000000000000000000..4297b31291e036700d6ad0b818afb7dd72da3054
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/utils/onnx.py
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+
+from typing import Tuple
+
+from ..modeling import Sam
+from .amg import calculate_stability_score
+
+
+class SamOnnxModel(nn.Module):
+    """
+    This model should not be called directly, but is used in ONNX export.
+    It combines the prompt encoder, mask decoder, and mask postprocessing of Sam,
+    with some functions modified to enable model tracing. Also supports extra
+    options controlling what information. See the ONNX export script for details.
+    """
+
+    def __init__(
+        self,
+        model: Sam,
+        return_single_mask: bool,
+        use_stability_score: bool = False,
+        return_extra_metrics: bool = False,
+    ) -> None:
+        super().__init__()
+        self.mask_decoder = model.mask_decoder
+        self.model = model
+        self.img_size = model.image_encoder.img_size
+        self.return_single_mask = return_single_mask
+        self.use_stability_score = use_stability_score
+        self.stability_score_offset = 1.0
+        self.return_extra_metrics = return_extra_metrics
+
+    @staticmethod
+    def resize_longest_image_size(
+        input_image_size: torch.Tensor, longest_side: int
+    ) -> torch.Tensor:
+        input_image_size = input_image_size.to(torch.float32)
+        scale = longest_side / torch.max(input_image_size)
+        transformed_size = scale * input_image_size
+        transformed_size = torch.floor(transformed_size + 0.5).to(torch.int64)
+        return transformed_size
+
+    def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor:
+        point_coords = point_coords + 0.5
+        point_coords = point_coords / self.img_size
+        point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords)
+        point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding)
+
+        point_embedding = point_embedding * (point_labels != -1)
+        point_embedding = point_embedding + self.model.prompt_encoder.not_a_point_embed.weight * (
+            point_labels == -1
+        )
+
+        for i in range(self.model.prompt_encoder.num_point_embeddings):
+            point_embedding = point_embedding + self.model.prompt_encoder.point_embeddings[
+                i
+            ].weight * (point_labels == i)
+
+        return point_embedding
+
+    def _embed_masks(self, input_mask: torch.Tensor, has_mask_input: torch.Tensor) -> torch.Tensor:
+        mask_embedding = has_mask_input * self.model.prompt_encoder.mask_downscaling(input_mask)
+        mask_embedding = mask_embedding + (
+            1 - has_mask_input
+        ) * self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1)
+        return mask_embedding
+
+    def mask_postprocessing(self, masks: torch.Tensor, orig_im_size: torch.Tensor) -> torch.Tensor:
+        masks = F.interpolate(
+            masks,
+            size=(self.img_size, self.img_size),
+            mode="bilinear",
+            align_corners=False,
+        )
+
+        prepadded_size = self.resize_longest_image_size(orig_im_size, self.img_size)
+        masks = masks[..., : int(prepadded_size[0]), : int(prepadded_size[1])]
+
+        orig_im_size = orig_im_size.to(torch.int64)
+        h, w = orig_im_size[0], orig_im_size[1]
+        masks = F.interpolate(masks, size=(h, w), mode="bilinear", align_corners=False)
+        return masks
+
+    def select_masks(
+        self, masks: torch.Tensor, iou_preds: torch.Tensor, num_points: int
+    ) -> Tuple[torch.Tensor, torch.Tensor]:
+        # Determine if we should return the multiclick mask or not from the number of points.
+        # The reweighting is used to avoid control flow.
+        score_reweight = torch.tensor(
+            [[1000] + [0] * (self.model.mask_decoder.num_mask_tokens - 1)]
+        ).to(iou_preds.device)
+        score = iou_preds + (num_points - 2.5) * score_reweight
+        best_idx = torch.argmax(score, dim=1)
+        masks = masks[torch.arange(masks.shape[0]), best_idx, :, :].unsqueeze(1)
+        iou_preds = iou_preds[torch.arange(masks.shape[0]), best_idx].unsqueeze(1)
+
+        return masks, iou_preds
+
+    @torch.no_grad()
+    def forward(
+        self,
+        image_embeddings: torch.Tensor,
+        point_coords: torch.Tensor,
+        point_labels: torch.Tensor,
+        mask_input: torch.Tensor,
+        has_mask_input: torch.Tensor,
+        orig_im_size: torch.Tensor,
+    ):
+        sparse_embedding = self._embed_points(point_coords, point_labels)
+        dense_embedding = self._embed_masks(mask_input, has_mask_input)
+
+        masks, scores = self.model.mask_decoder.predict_masks(
+            image_embeddings=image_embeddings,
+            image_pe=self.model.prompt_encoder.get_dense_pe(),
+            sparse_prompt_embeddings=sparse_embedding,
+            dense_prompt_embeddings=dense_embedding,
+        )
+
+        if self.use_stability_score:
+            scores = calculate_stability_score(
+                masks, self.model.mask_threshold, self.stability_score_offset
+            )
+
+        if self.return_single_mask:
+            masks, scores = self.select_masks(masks, scores, point_coords.shape[1])
+
+        upscaled_masks = self.mask_postprocessing(masks, orig_im_size)
+
+        if self.return_extra_metrics:
+            stability_scores = calculate_stability_score(
+                upscaled_masks, self.model.mask_threshold, self.stability_score_offset
+            )
+            areas = (upscaled_masks > self.model.mask_threshold).sum(-1).sum(-1)
+            return upscaled_masks, scores, stability_scores, areas, masks
+
+        return upscaled_masks, scores, masks
diff --git a/python_embeded/Lib/site-packages/segment_anything/utils/transforms.py b/python_embeded/Lib/site-packages/segment_anything/utils/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad346661f84b0647026e130a552c4b38b83e2ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/segment_anything/utils/transforms.py
@@ -0,0 +1,102 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+from torch.nn import functional as F
+from torchvision.transforms.functional import resize, to_pil_image  # type: ignore
+
+from copy import deepcopy
+from typing import Tuple
+
+
+class ResizeLongestSide:
+    """
+    Resizes images to longest side 'target_length', as well as provides
+    methods for resizing coordinates and boxes. Provides methods for
+    transforming both numpy array and batched torch tensors.
+    """
+
+    def __init__(self, target_length: int) -> None:
+        self.target_length = target_length
+
+    def apply_image(self, image: np.ndarray) -> np.ndarray:
+        """
+        Expects a numpy array with shape HxWxC in uint8 format.
+        """
+        target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
+        return np.array(resize(to_pil_image(image), target_size))
+
+    def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
+        """
+        Expects a numpy array of length 2 in the final dimension. Requires the
+        original image size in (H, W) format.
+        """
+        old_h, old_w = original_size
+        new_h, new_w = self.get_preprocess_shape(
+            original_size[0], original_size[1], self.target_length
+        )
+        coords = deepcopy(coords).astype(float)
+        coords[..., 0] = coords[..., 0] * (new_w / old_w)
+        coords[..., 1] = coords[..., 1] * (new_h / old_h)
+        return coords
+
+    def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
+        """
+        Expects a numpy array shape Bx4. Requires the original image size
+        in (H, W) format.
+        """
+        boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)
+        return boxes.reshape(-1, 4)
+
+    def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:
+        """
+        Expects batched images with shape BxCxHxW and float format. This
+        transformation may not exactly match apply_image. apply_image is
+        the transformation expected by the model.
+        """
+        # Expects an image in BCHW format. May not exactly match apply_image.
+        target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
+        return F.interpolate(
+            image, target_size, mode="bilinear", align_corners=False, antialias=True
+        )
+
+    def apply_coords_torch(
+        self, coords: torch.Tensor, original_size: Tuple[int, ...]
+    ) -> torch.Tensor:
+        """
+        Expects a torch tensor with length 2 in the last dimension. Requires the
+        original image size in (H, W) format.
+        """
+        old_h, old_w = original_size
+        new_h, new_w = self.get_preprocess_shape(
+            original_size[0], original_size[1], self.target_length
+        )
+        coords = deepcopy(coords).to(torch.float)
+        coords[..., 0] = coords[..., 0] * (new_w / old_w)
+        coords[..., 1] = coords[..., 1] * (new_h / old_h)
+        return coords
+
+    def apply_boxes_torch(
+        self, boxes: torch.Tensor, original_size: Tuple[int, ...]
+    ) -> torch.Tensor:
+        """
+        Expects a torch tensor with shape Bx4. Requires the original image
+        size in (H, W) format.
+        """
+        boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)
+        return boxes.reshape(-1, 4)
+
+    @staticmethod
+    def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:
+        """
+        Compute the output size given input size and target long side length.
+        """
+        scale = long_side_length * 1.0 / max(oldh, oldw)
+        newh, neww = oldh * scale, oldw * scale
+        neww = int(neww + 0.5)
+        newh = int(newh + 0.5)
+        return (newh, neww)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/__init__.py b/python_embeded/Lib/site-packages/setuptools/_distutils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e374d5c5604d0eeed555e68b7523bfac72fd9101
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/__init__.py
@@ -0,0 +1,14 @@
+import importlib
+import sys
+
+__version__, _, _ = sys.version.partition(' ')
+
+
+try:
+    # Allow Debian and pkgsrc (only) to customize system
+    # behavior. Ref pypa/distutils#2 and pypa/distutils#16.
+    # This hook is deprecated and no other environments
+    # should use it.
+    importlib.import_module('_distutils_system_mod')
+except ImportError:
+    pass
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/_log.py b/python_embeded/Lib/site-packages/setuptools/_distutils/_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..0148f157ff3bf8bd728c82f49cd3d1cd9cb5a43e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/_log.py
@@ -0,0 +1,3 @@
+import logging
+
+log = logging.getLogger()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/_macos_compat.py b/python_embeded/Lib/site-packages/setuptools/_distutils/_macos_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..76ecb96abe478313ce7d09342b2643bf4a765331
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/_macos_compat.py
@@ -0,0 +1,12 @@
+import importlib
+import sys
+
+
+def bypass_compiler_fixup(cmd, args):
+    return cmd
+
+
+if sys.platform == 'darwin':
+    compiler_fixup = importlib.import_module('_osx_support').compiler_fixup
+else:
+    compiler_fixup = bypass_compiler_fixup
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/_modified.py b/python_embeded/Lib/site-packages/setuptools/_distutils/_modified.py
new file mode 100644
index 0000000000000000000000000000000000000000..f64cab7d61ae20dd0c425b8843b068f39faa6961
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/_modified.py
@@ -0,0 +1,95 @@
+"""Timestamp comparison of files and groups of files."""
+
+from __future__ import annotations
+
+import functools
+import os.path
+from collections.abc import Callable, Iterable
+from typing import Literal, TypeVar
+
+from jaraco.functools import splat
+
+from .compat.py39 import zip_strict
+from .errors import DistutilsFileError
+
+_SourcesT = TypeVar(
+    "_SourcesT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]"
+)
+_TargetsT = TypeVar(
+    "_TargetsT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]"
+)
+
+
+def _newer(source, target):
+    return not os.path.exists(target) or (
+        os.path.getmtime(source) > os.path.getmtime(target)
+    )
+
+
+def newer(
+    source: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+    target: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+) -> bool:
+    """
+    Is source modified more recently than target.
+
+    Returns True if 'source' is modified more recently than
+    'target' or if 'target' does not exist.
+
+    Raises DistutilsFileError if 'source' does not exist.
+    """
+    if not os.path.exists(source):
+        raise DistutilsFileError(f"file {os.path.abspath(source)!r} does not exist")
+
+    return _newer(source, target)
+
+
+def newer_pairwise(
+    sources: Iterable[_SourcesT],
+    targets: Iterable[_TargetsT],
+    newer: Callable[[_SourcesT, _TargetsT], bool] = newer,
+) -> tuple[list[_SourcesT], list[_TargetsT]]:
+    """
+    Filter filenames where sources are newer than targets.
+
+    Walk two filename iterables in parallel, testing if each source is newer
+    than its corresponding target.  Returns a pair of lists (sources,
+    targets) where source is newer than target, according to the semantics
+    of 'newer()'.
+    """
+    newer_pairs = filter(splat(newer), zip_strict(sources, targets))
+    return tuple(map(list, zip(*newer_pairs))) or ([], [])
+
+
+def newer_group(
+    sources: Iterable[str | bytes | os.PathLike[str] | os.PathLike[bytes]],
+    target: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+    missing: Literal["error", "ignore", "newer"] = "error",
+) -> bool:
+    """
+    Is target out-of-date with respect to any file in sources.
+
+    Return True if 'target' is out-of-date with respect to any file
+    listed in 'sources'. In other words, if 'target' exists and is newer
+    than every file in 'sources', return False; otherwise return True.
+    ``missing`` controls how to handle a missing source file:
+
+    - error (default): allow the ``stat()`` call to fail.
+    - ignore: silently disregard any missing source files.
+    - newer: treat missing source files as "target out of date". This
+      mode is handy in "dry-run" mode: it will pretend to carry out
+      commands that wouldn't work because inputs are missing, but
+      that doesn't matter because dry-run won't run the commands.
+    """
+
+    def missing_as_newer(source):
+        return missing == 'newer' and not os.path.exists(source)
+
+    ignored = os.path.exists if missing == 'ignore' else None
+    return not os.path.exists(target) or any(
+        missing_as_newer(source) or _newer(source, target)
+        for source in filter(ignored, sources)
+    )
+
+
+newer_pairwise_group = functools.partial(newer_pairwise, newer=newer_group)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/_msvccompiler.py b/python_embeded/Lib/site-packages/setuptools/_distutils/_msvccompiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..d07c86ef8e41fc31357c989133d51e9618c3e43d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/_msvccompiler.py
@@ -0,0 +1,16 @@
+import warnings
+
+from .compilers.C import msvc
+
+__all__ = ["MSVCCompiler"]
+
+MSVCCompiler = msvc.Compiler
+
+
+def __getattr__(name):
+    if name == '_get_vc_env':
+        warnings.warn(
+            "_get_vc_env is private; find an alternative (pypa/distutils#340)"
+        )
+        return msvc._get_vc_env
+    raise AttributeError(name)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/archive_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/archive_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..d860f5527234567a0b726ea07116ae2c8e6bc3d2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/archive_util.py
@@ -0,0 +1,294 @@
+"""distutils.archive_util
+
+Utility functions for creating archive files (tarballs, zip files,
+that sort of thing)."""
+
+from __future__ import annotations
+
+import os
+from typing import Literal, overload
+
+try:
+    import zipfile
+except ImportError:
+    zipfile = None
+
+
+from ._log import log
+from .dir_util import mkpath
+from .errors import DistutilsExecError
+from .spawn import spawn
+
+try:
+    from pwd import getpwnam
+except ImportError:
+    getpwnam = None
+
+try:
+    from grp import getgrnam
+except ImportError:
+    getgrnam = None
+
+
+def _get_gid(name):
+    """Returns a gid, given a group name."""
+    if getgrnam is None or name is None:
+        return None
+    try:
+        result = getgrnam(name)
+    except KeyError:
+        result = None
+    if result is not None:
+        return result[2]
+    return None
+
+
+def _get_uid(name):
+    """Returns an uid, given a user name."""
+    if getpwnam is None or name is None:
+        return None
+    try:
+        result = getpwnam(name)
+    except KeyError:
+        result = None
+    if result is not None:
+        return result[2]
+    return None
+
+
+def make_tarball(
+    base_name: str,
+    base_dir: str | os.PathLike[str],
+    compress: Literal["gzip", "bzip2", "xz"] | None = "gzip",
+    verbose: bool = False,
+    dry_run: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str:
+    """Create a (possibly compressed) tar file from all the files under
+    'base_dir'.
+
+    'compress' must be "gzip" (the default), "bzip2", "xz", or None.
+
+    'owner' and 'group' can be used to define an owner and a group for the
+    archive that is being built. If not provided, the current owner and group
+    will be used.
+
+    The output tar file will be named 'base_dir' +  ".tar", possibly plus
+    the appropriate compression extension (".gz", ".bz2", ".xz" or ".Z").
+
+    Returns the output filename.
+    """
+    tar_compression = {
+        'gzip': 'gz',
+        'bzip2': 'bz2',
+        'xz': 'xz',
+        None: '',
+    }
+    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'}
+
+    # flags for compression program, each element of list will be an argument
+    if compress is not None and compress not in compress_ext.keys():
+        raise ValueError(
+            "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'"
+        )
+
+    archive_name = base_name + '.tar'
+    archive_name += compress_ext.get(compress, '')
+
+    mkpath(os.path.dirname(archive_name), dry_run=dry_run)
+
+    # creating the tarball
+    import tarfile  # late import so Python build itself doesn't break
+
+    log.info('Creating tar archive')
+
+    uid = _get_uid(owner)
+    gid = _get_gid(group)
+
+    def _set_uid_gid(tarinfo):
+        if gid is not None:
+            tarinfo.gid = gid
+            tarinfo.gname = group
+        if uid is not None:
+            tarinfo.uid = uid
+            tarinfo.uname = owner
+        return tarinfo
+
+    if not dry_run:
+        tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}')
+        try:
+            tar.add(base_dir, filter=_set_uid_gid)
+        finally:
+            tar.close()
+
+    return archive_name
+
+
+def make_zipfile(  # noqa: C901
+    base_name: str,
+    base_dir: str | os.PathLike[str],
+    verbose: bool = False,
+    dry_run: bool = False,
+) -> str:
+    """Create a zip file from all the files under 'base_dir'.
+
+    The output zip file will be named 'base_name' + ".zip".  Uses either the
+    "zipfile" Python module (if available) or the InfoZIP "zip" utility
+    (if installed and found on the default search path).  If neither tool is
+    available, raises DistutilsExecError.  Returns the name of the output zip
+    file.
+    """
+    zip_filename = base_name + ".zip"
+    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
+
+    # If zipfile module is not available, try spawning an external
+    # 'zip' command.
+    if zipfile is None:
+        if verbose:
+            zipoptions = "-r"
+        else:
+            zipoptions = "-rq"
+
+        try:
+            spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
+        except DistutilsExecError:
+            # XXX really should distinguish between "couldn't find
+            # external 'zip' command" and "zip failed".
+            raise DistutilsExecError(
+                f"unable to create zip file '{zip_filename}': "
+                "could neither import the 'zipfile' module nor "
+                "find a standalone zip utility"
+            )
+
+    else:
+        log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
+
+        if not dry_run:
+            try:
+                zip = zipfile.ZipFile(
+                    zip_filename, "w", compression=zipfile.ZIP_DEFLATED
+                )
+            except RuntimeError:
+                zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
+
+            with zip:
+                if base_dir != os.curdir:
+                    path = os.path.normpath(os.path.join(base_dir, ''))
+                    zip.write(path, path)
+                    log.info("adding '%s'", path)
+                for dirpath, dirnames, filenames in os.walk(base_dir):
+                    for name in dirnames:
+                        path = os.path.normpath(os.path.join(dirpath, name, ''))
+                        zip.write(path, path)
+                        log.info("adding '%s'", path)
+                    for name in filenames:
+                        path = os.path.normpath(os.path.join(dirpath, name))
+                        if os.path.isfile(path):
+                            zip.write(path, path)
+                            log.info("adding '%s'", path)
+
+    return zip_filename
+
+
+ARCHIVE_FORMATS = {
+    'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
+    'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
+    'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"),
+    'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
+    'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
+    'zip': (make_zipfile, [], "ZIP file"),
+}
+
+
+def check_archive_formats(formats):
+    """Returns the first format from the 'format' list that is unknown.
+
+    If all formats are known, returns None
+    """
+    for format in formats:
+        if format not in ARCHIVE_FORMATS:
+            return format
+    return None
+
+
+@overload
+def make_archive(
+    base_name: str,
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+    base_dir: str | None = None,
+    verbose: bool = False,
+    dry_run: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str: ...
+@overload
+def make_archive(
+    base_name: str | os.PathLike[str],
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+    base_dir: str | None = None,
+    verbose: bool = False,
+    dry_run: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str: ...
+def make_archive(
+    base_name: str | os.PathLike[str],
+    format: str,
+    root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+    base_dir: str | None = None,
+    verbose: bool = False,
+    dry_run: bool = False,
+    owner: str | None = None,
+    group: str | None = None,
+) -> str:
+    """Create an archive file (eg. zip or tar).
+
+    'base_name' is the name of the file to create, minus any format-specific
+    extension; 'format' is the archive format: one of "zip", "tar", "gztar",
+    "bztar", "xztar", or "ztar".
+
+    'root_dir' is a directory that will be the root directory of the
+    archive; ie. we typically chdir into 'root_dir' before creating the
+    archive.  'base_dir' is the directory where we start archiving from;
+    ie. 'base_dir' will be the common prefix of all files and
+    directories in the archive.  'root_dir' and 'base_dir' both default
+    to the current directory.  Returns the name of the archive file.
+
+    'owner' and 'group' are used when creating a tar archive. By default,
+    uses the current owner and group.
+    """
+    save_cwd = os.getcwd()
+    if root_dir is not None:
+        log.debug("changing into '%s'", root_dir)
+        base_name = os.path.abspath(base_name)
+        if not dry_run:
+            os.chdir(root_dir)
+
+    if base_dir is None:
+        base_dir = os.curdir
+
+    kwargs = {'dry_run': dry_run}
+
+    try:
+        format_info = ARCHIVE_FORMATS[format]
+    except KeyError:
+        raise ValueError(f"unknown archive format '{format}'")
+
+    func = format_info[0]
+    kwargs.update(format_info[1])
+
+    if format != 'zip':
+        kwargs['owner'] = owner
+        kwargs['group'] = group
+
+    try:
+        filename = func(base_name, base_dir, **kwargs)
+    finally:
+        if root_dir is not None:
+            log.debug("changing back to '%s'", save_cwd)
+            os.chdir(save_cwd)
+
+    return filename
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/ccompiler.py b/python_embeded/Lib/site-packages/setuptools/_distutils/ccompiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..58bc6a55e24fd2b0b170e4499c6095e934313827
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/ccompiler.py
@@ -0,0 +1,26 @@
+from .compat.numpy import (  # noqa: F401
+    _default_compilers,
+    compiler_class,
+)
+from .compilers.C import base
+from .compilers.C.base import (
+    gen_lib_options,
+    gen_preprocess_options,
+    get_default_compiler,
+    new_compiler,
+    show_compilers,
+)
+from .compilers.C.errors import CompileError, LinkError
+
+__all__ = [
+    'CompileError',
+    'LinkError',
+    'gen_lib_options',
+    'gen_preprocess_options',
+    'get_default_compiler',
+    'new_compiler',
+    'show_compilers',
+]
+
+
+CCompiler = base.Compiler
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/cmd.py b/python_embeded/Lib/site-packages/setuptools/_distutils/cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..241621bd51340819c5216883a0e73929c9fd20b0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/cmd.py
@@ -0,0 +1,554 @@
+"""distutils.cmd
+
+Provides the Command class, the base class for the command classes
+in the distutils.command package.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import sys
+from abc import abstractmethod
+from collections.abc import Callable, MutableSequence
+from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload
+
+from . import _modified, archive_util, dir_util, file_util, util
+from ._log import log
+from .errors import DistutilsOptionError
+
+if TYPE_CHECKING:
+    # type-only import because of mutual dependence between these classes
+    from distutils.dist import Distribution
+
+    from typing_extensions import TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
+
+_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
+_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
+_CommandT = TypeVar("_CommandT", bound="Command")
+
+
+class Command:
+    """Abstract base class for defining command classes, the "worker bees"
+    of the Distutils.  A useful analogy for command classes is to think of
+    them as subroutines with local variables called "options".  The options
+    are "declared" in 'initialize_options()' and "defined" (given their
+    final values, aka "finalized") in 'finalize_options()', both of which
+    must be defined by every command class.  The distinction between the
+    two is necessary because option values might come from the outside
+    world (command line, config file, ...), and any options dependent on
+    other options must be computed *after* these outside influences have
+    been processed -- hence 'finalize_options()'.  The "body" of the
+    subroutine, where it does all its work based on the values of its
+    options, is the 'run()' method, which must also be implemented by every
+    command class.
+    """
+
+    # 'sub_commands' formalizes the notion of a "family" of commands,
+    # eg. "install" as the parent with sub-commands "install_lib",
+    # "install_headers", etc.  The parent of a family of commands
+    # defines 'sub_commands' as a class attribute; it's a list of
+    #    (command_name : string, predicate : unbound_method | string | None)
+    # tuples, where 'predicate' is a method of the parent command that
+    # determines whether the corresponding command is applicable in the
+    # current situation.  (Eg. we "install_headers" is only applicable if
+    # we have any C header files to install.)  If 'predicate' is None,
+    # that command is always applicable.
+    #
+    # 'sub_commands' is usually defined at the *end* of a class, because
+    # predicates can be unbound methods, so they must already have been
+    # defined.  The canonical example is the "install" command.
+    sub_commands: ClassVar[  # Any to work around variance issues
+        list[tuple[str, Callable[[Any], bool] | None]]
+    ] = []
+
+    user_options: ClassVar[
+        # Specifying both because list is invariant. Avoids mypy override assignment issues
+        list[tuple[str, str, str]] | list[tuple[str, str | None, str]]
+    ] = []
+
+    # -- Creation/initialization methods -------------------------------
+
+    def __init__(self, dist: Distribution) -> None:
+        """Create and initialize a new Command object.  Most importantly,
+        invokes the 'initialize_options()' method, which is the real
+        initializer and depends on the actual command being
+        instantiated.
+        """
+        # late import because of mutual dependence between these classes
+        from distutils.dist import Distribution
+
+        if not isinstance(dist, Distribution):
+            raise TypeError("dist must be a Distribution instance")
+        if self.__class__ is Command:
+            raise RuntimeError("Command is an abstract class")
+
+        self.distribution = dist
+        self.initialize_options()
+
+        # Per-command versions of the global flags, so that the user can
+        # customize Distutils' behaviour command-by-command and let some
+        # commands fall back on the Distribution's behaviour.  None means
+        # "not defined, check self.distribution's copy", while 0 or 1 mean
+        # false and true (duh).  Note that this means figuring out the real
+        # value of each flag is a touch complicated -- hence "self._dry_run"
+        # will be handled by __getattr__, below.
+        # XXX This needs to be fixed.
+        self._dry_run = None
+
+        # verbose is largely ignored, but needs to be set for
+        # backwards compatibility (I think)?
+        self.verbose = dist.verbose
+
+        # Some commands define a 'self.force' option to ignore file
+        # timestamps, but methods defined *here* assume that
+        # 'self.force' exists for all commands.  So define it here
+        # just to be safe.
+        self.force = None
+
+        # The 'help' flag is just used for command-line parsing, so
+        # none of that complicated bureaucracy is needed.
+        self.help = False
+
+        # 'finalized' records whether or not 'finalize_options()' has been
+        # called.  'finalize_options()' itself should not pay attention to
+        # this flag: it is the business of 'ensure_finalized()', which
+        # always calls 'finalize_options()', to respect/update it.
+        self.finalized = False
+
+    # XXX A more explicit way to customize dry_run would be better.
+    def __getattr__(self, attr):
+        if attr == 'dry_run':
+            myval = getattr(self, "_" + attr)
+            if myval is None:
+                return getattr(self.distribution, attr)
+            else:
+                return myval
+        else:
+            raise AttributeError(attr)
+
+    def ensure_finalized(self) -> None:
+        if not self.finalized:
+            self.finalize_options()
+        self.finalized = True
+
+    # Subclasses must define:
+    #   initialize_options()
+    #     provide default values for all options; may be customized by
+    #     setup script, by options from config file(s), or by command-line
+    #     options
+    #   finalize_options()
+    #     decide on the final values for all options; this is called
+    #     after all possible intervention from the outside world
+    #     (command-line, option file, etc.) has been processed
+    #   run()
+    #     run the command: do whatever it is we're here to do,
+    #     controlled by the command's various option values
+
+    @abstractmethod
+    def initialize_options(self) -> None:
+        """Set default values for all the options that this command
+        supports.  Note that these defaults may be overridden by other
+        commands, by the setup script, by config files, or by the
+        command-line.  Thus, this is not the place to code dependencies
+        between options; generally, 'initialize_options()' implementations
+        are just a bunch of "self.foo = None" assignments.
+
+        This method must be implemented by all command classes.
+        """
+        raise RuntimeError(
+            f"abstract method -- subclass {self.__class__} must override"
+        )
+
+    @abstractmethod
+    def finalize_options(self) -> None:
+        """Set final values for all the options that this command supports.
+        This is always called as late as possible, ie.  after any option
+        assignments from the command-line or from other commands have been
+        done.  Thus, this is the place to code option dependencies: if
+        'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
+        long as 'foo' still has the same value it was assigned in
+        'initialize_options()'.
+
+        This method must be implemented by all command classes.
+        """
+        raise RuntimeError(
+            f"abstract method -- subclass {self.__class__} must override"
+        )
+
+    def dump_options(self, header=None, indent=""):
+        from distutils.fancy_getopt import longopt_xlate
+
+        if header is None:
+            header = f"command options for '{self.get_command_name()}':"
+        self.announce(indent + header, level=logging.INFO)
+        indent = indent + "  "
+        for option, _, _ in self.user_options:
+            option = option.translate(longopt_xlate)
+            if option[-1] == "=":
+                option = option[:-1]
+            value = getattr(self, option)
+            self.announce(indent + f"{option} = {value}", level=logging.INFO)
+
+    @abstractmethod
+    def run(self) -> None:
+        """A command's raison d'etre: carry out the action it exists to
+        perform, controlled by the options initialized in
+        'initialize_options()', customized by other commands, the setup
+        script, the command-line, and config files, and finalized in
+        'finalize_options()'.  All terminal output and filesystem
+        interaction should be done by 'run()'.
+
+        This method must be implemented by all command classes.
+        """
+        raise RuntimeError(
+            f"abstract method -- subclass {self.__class__} must override"
+        )
+
+    def announce(self, msg: object, level: int = logging.DEBUG) -> None:
+        log.log(level, msg)
+
+    def debug_print(self, msg: object) -> None:
+        """Print 'msg' to stdout if the global DEBUG (taken from the
+        DISTUTILS_DEBUG environment variable) flag is true.
+        """
+        from distutils.debug import DEBUG
+
+        if DEBUG:
+            print(msg)
+            sys.stdout.flush()
+
+    # -- Option validation methods -------------------------------------
+    # (these are very handy in writing the 'finalize_options()' method)
+    #
+    # NB. the general philosophy here is to ensure that a particular option
+    # value meets certain type and value constraints.  If not, we try to
+    # force it into conformance (eg. if we expect a list but have a string,
+    # split the string on comma and/or whitespace).  If we can't force the
+    # option into conformance, raise DistutilsOptionError.  Thus, command
+    # classes need do nothing more than (eg.)
+    #   self.ensure_string_list('foo')
+    # and they can be guaranteed that thereafter, self.foo will be
+    # a list of strings.
+
+    def _ensure_stringlike(self, option, what, default=None):
+        val = getattr(self, option)
+        if val is None:
+            setattr(self, option, default)
+            return default
+        elif not isinstance(val, str):
+            raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
+        return val
+
+    def ensure_string(self, option: str, default: str | None = None) -> None:
+        """Ensure that 'option' is a string; if not defined, set it to
+        'default'.
+        """
+        self._ensure_stringlike(option, "string", default)
+
+    def ensure_string_list(self, option: str) -> None:
+        r"""Ensure that 'option' is a list of strings.  If 'option' is
+        currently a string, we split it either on /,\s*/ or /\s+/, so
+        "foo bar baz", "foo,bar,baz", and "foo,   bar baz" all become
+        ["foo", "bar", "baz"].
+        """
+        val = getattr(self, option)
+        if val is None:
+            return
+        elif isinstance(val, str):
+            setattr(self, option, re.split(r',\s*|\s+', val))
+        else:
+            if isinstance(val, list):
+                ok = all(isinstance(v, str) for v in val)
+            else:
+                ok = False
+            if not ok:
+                raise DistutilsOptionError(
+                    f"'{option}' must be a list of strings (got {val!r})"
+                )
+
+    def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
+        val = self._ensure_stringlike(option, what, default)
+        if val is not None and not tester(val):
+            raise DistutilsOptionError(
+                ("error in '%s' option: " + error_fmt) % (option, val)
+            )
+
+    def ensure_filename(self, option: str) -> None:
+        """Ensure that 'option' is the name of an existing file."""
+        self._ensure_tested_string(
+            option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
+        )
+
+    def ensure_dirname(self, option: str) -> None:
+        self._ensure_tested_string(
+            option,
+            os.path.isdir,
+            "directory name",
+            "'%s' does not exist or is not a directory",
+        )
+
+    # -- Convenience methods for commands ------------------------------
+
+    def get_command_name(self) -> str:
+        if hasattr(self, 'command_name'):
+            return self.command_name
+        else:
+            return self.__class__.__name__
+
+    def set_undefined_options(
+        self, src_cmd: str, *option_pairs: tuple[str, str]
+    ) -> None:
+        """Set the values of any "undefined" options from corresponding
+        option values in some other command object.  "Undefined" here means
+        "is None", which is the convention used to indicate that an option
+        has not been changed between 'initialize_options()' and
+        'finalize_options()'.  Usually called from 'finalize_options()' for
+        options that depend on some other command rather than another
+        option of the same command.  'src_cmd' is the other command from
+        which option values will be taken (a command object will be created
+        for it if necessary); the remaining arguments are
+        '(src_option,dst_option)' tuples which mean "take the value of
+        'src_option' in the 'src_cmd' command object, and copy it to
+        'dst_option' in the current command object".
+        """
+        # Option_pairs: list of (src_option, dst_option) tuples
+        src_cmd_obj = self.distribution.get_command_obj(src_cmd)
+        src_cmd_obj.ensure_finalized()
+        for src_option, dst_option in option_pairs:
+            if getattr(self, dst_option) is None:
+                setattr(self, dst_option, getattr(src_cmd_obj, src_option))
+
+    # NOTE: Because distutils is private to Setuptools and not all commands are exposed here,
+    # not every possible command is enumerated in the signature.
+    def get_finalized_command(self, command: str, create: bool = True) -> Command:
+        """Wrapper around Distribution's 'get_command_obj()' method: find
+        (create if necessary and 'create' is true) the command object for
+        'command', call its 'ensure_finalized()' method, and return the
+        finalized command object.
+        """
+        cmd_obj = self.distribution.get_command_obj(command, create)
+        cmd_obj.ensure_finalized()
+        return cmd_obj
+
+    # XXX rename to 'get_reinitialized_command()'? (should do the
+    # same in dist.py, if so)
+    @overload
+    def reinitialize_command(
+        self, command: str, reinit_subcommands: bool = False
+    ) -> Command: ...
+    @overload
+    def reinitialize_command(
+        self, command: _CommandT, reinit_subcommands: bool = False
+    ) -> _CommandT: ...
+    def reinitialize_command(
+        self, command: str | Command, reinit_subcommands=False
+    ) -> Command:
+        return self.distribution.reinitialize_command(command, reinit_subcommands)
+
+    def run_command(self, command: str) -> None:
+        """Run some other command: uses the 'run_command()' method of
+        Distribution, which creates and finalizes the command object if
+        necessary and then invokes its 'run()' method.
+        """
+        self.distribution.run_command(command)
+
+    def get_sub_commands(self) -> list[str]:
+        """Determine the sub-commands that are relevant in the current
+        distribution (ie., that need to be run).  This is based on the
+        'sub_commands' class attribute: each tuple in that list may include
+        a method that we call to determine if the subcommand needs to be
+        run for the current distribution.  Return a list of command names.
+        """
+        commands = []
+        for cmd_name, method in self.sub_commands:
+            if method is None or method(self):
+                commands.append(cmd_name)
+        return commands
+
+    # -- External world manipulation -----------------------------------
+
+    def warn(self, msg: object) -> None:
+        log.warning("warning: %s: %s\n", self.get_command_name(), msg)
+
+    def execute(
+        self,
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        msg: object = None,
+        level: int = 1,
+    ) -> None:
+        util.execute(func, args, msg, dry_run=self.dry_run)
+
+    def mkpath(self, name: str, mode: int = 0o777) -> None:
+        dir_util.mkpath(name, mode, dry_run=self.dry_run)
+
+    @overload
+    def copy_file(
+        self,
+        infile: str | os.PathLike[str],
+        outfile: _StrPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[_StrPathT | str, bool]: ...
+    @overload
+    def copy_file(
+        self,
+        infile: bytes | os.PathLike[bytes],
+        outfile: _BytesPathT,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[_BytesPathT | bytes, bool]: ...
+    def copy_file(
+        self,
+        infile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        link: str | None = None,
+        level: int = 1,
+    ) -> tuple[str | os.PathLike[str] | bytes | os.PathLike[bytes], bool]:
+        """Copy a file respecting verbose, dry-run and force flags.  (The
+        former two default to whatever is in the Distribution object, and
+        the latter defaults to false for commands that don't define it.)"""
+        return file_util.copy_file(
+            infile,
+            outfile,
+            preserve_mode,
+            preserve_times,
+            not self.force,
+            link,
+            dry_run=self.dry_run,
+        )
+
+    def copy_tree(
+        self,
+        infile: str | os.PathLike[str],
+        outfile: str,
+        preserve_mode: bool = True,
+        preserve_times: bool = True,
+        preserve_symlinks: bool = False,
+        level: int = 1,
+    ) -> list[str]:
+        """Copy an entire directory tree respecting verbose, dry-run,
+        and force flags.
+        """
+        return dir_util.copy_tree(
+            infile,
+            outfile,
+            preserve_mode,
+            preserve_times,
+            preserve_symlinks,
+            not self.force,
+            dry_run=self.dry_run,
+        )
+
+    @overload
+    def move_file(
+        self, src: str | os.PathLike[str], dst: _StrPathT, level: int = 1
+    ) -> _StrPathT | str: ...
+    @overload
+    def move_file(
+        self, src: bytes | os.PathLike[bytes], dst: _BytesPathT, level: int = 1
+    ) -> _BytesPathT | bytes: ...
+    def move_file(
+        self,
+        src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        level: int = 1,
+    ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
+        """Move a file respecting dry-run flag."""
+        return file_util.move_file(src, dst, dry_run=self.dry_run)
+
+    def spawn(
+        self, cmd: MutableSequence[str], search_path: bool = True, level: int = 1
+    ) -> None:
+        """Spawn an external command respecting dry-run flag."""
+        from distutils.spawn import spawn
+
+        spawn(cmd, search_path, dry_run=self.dry_run)
+
+    @overload
+    def make_archive(
+        self,
+        base_name: str,
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str: ...
+    @overload
+    def make_archive(
+        self,
+        base_name: str | os.PathLike[str],
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str: ...
+    def make_archive(
+        self,
+        base_name: str | os.PathLike[str],
+        format: str,
+        root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
+        base_dir: str | None = None,
+        owner: str | None = None,
+        group: str | None = None,
+    ) -> str:
+        return archive_util.make_archive(
+            base_name,
+            format,
+            root_dir,
+            base_dir,
+            dry_run=self.dry_run,
+            owner=owner,
+            group=group,
+        )
+
+    def make_file(
+        self,
+        infiles: str | list[str] | tuple[str, ...],
+        outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        exec_msg: object = None,
+        skip_msg: object = None,
+        level: int = 1,
+    ) -> None:
+        """Special case of 'execute()' for operations that process one or
+        more input files and generate one output file.  Works just like
+        'execute()', except the operation is skipped and a different
+        message printed if 'outfile' already exists and is newer than all
+        files listed in 'infiles'.  If the command defined 'self.force',
+        and it is true, then the command is unconditionally run -- does no
+        timestamp checks.
+        """
+        if skip_msg is None:
+            skip_msg = f"skipping {outfile} (inputs unchanged)"
+
+        # Allow 'infiles' to be a single string
+        if isinstance(infiles, str):
+            infiles = (infiles,)
+        elif not isinstance(infiles, (list, tuple)):
+            raise TypeError("'infiles' must be a string, or a list or tuple of strings")
+
+        if exec_msg is None:
+            exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles))
+
+        # If 'outfile' must be regenerated (either because it doesn't
+        # exist, is out-of-date, or the 'force' flag is true) then
+        # perform the action that presumably regenerates it
+        if self.force or _modified.newer_group(infiles, outfile):
+            self.execute(func, args, exec_msg, level)
+        # Otherwise, print the "skip" message
+        else:
+            log.debug(skip_msg)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/__init__.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f8a1692ba96f5e03167e7307c1c2ff5776b74d6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/__init__.py
@@ -0,0 +1,23 @@
+"""distutils.command
+
+Package containing implementation of all the standard Distutils
+commands."""
+
+__all__ = [
+    'build',
+    'build_py',
+    'build_ext',
+    'build_clib',
+    'build_scripts',
+    'clean',
+    'install',
+    'install_lib',
+    'install_headers',
+    'install_scripts',
+    'install_data',
+    'sdist',
+    'bdist',
+    'bdist_dumb',
+    'bdist_rpm',
+    'check',
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/_framework_compat.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/_framework_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..00d34bc7d8c85126dbae716ebfa48e35b0833222
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/_framework_compat.py
@@ -0,0 +1,54 @@
+"""
+Backward compatibility for homebrew builds on macOS.
+"""
+
+import functools
+import os
+import subprocess
+import sys
+import sysconfig
+
+
+@functools.lru_cache
+def enabled():
+    """
+    Only enabled for Python 3.9 framework homebrew builds
+    except ensurepip and venv.
+    """
+    PY39 = (3, 9) < sys.version_info < (3, 10)
+    framework = sys.platform == 'darwin' and sys._framework
+    homebrew = "Cellar" in sysconfig.get_config_var('projectbase')
+    venv = sys.prefix != sys.base_prefix
+    ensurepip = os.environ.get("ENSUREPIP_OPTIONS")
+    return PY39 and framework and homebrew and not venv and not ensurepip
+
+
+schemes = dict(
+    osx_framework_library=dict(
+        stdlib='{installed_base}/{platlibdir}/python{py_version_short}',
+        platstdlib='{platbase}/{platlibdir}/python{py_version_short}',
+        purelib='{homebrew_prefix}/lib/python{py_version_short}/site-packages',
+        platlib='{homebrew_prefix}/{platlibdir}/python{py_version_short}/site-packages',
+        include='{installed_base}/include/python{py_version_short}{abiflags}',
+        platinclude='{installed_platbase}/include/python{py_version_short}{abiflags}',
+        scripts='{homebrew_prefix}/bin',
+        data='{homebrew_prefix}',
+    )
+)
+
+
+@functools.lru_cache
+def vars():
+    if not enabled():
+        return {}
+    homebrew_prefix = subprocess.check_output(['brew', '--prefix'], text=True).strip()
+    return locals()
+
+
+def scheme(name):
+    """
+    Override the selected scheme for posix_prefix.
+    """
+    if not enabled() or not name.endswith('_prefix'):
+        return name
+    return 'osx_framework_library'
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..07811aab27ad7fcd2303883024243e2f52c2bbcb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist.py
@@ -0,0 +1,167 @@
+"""distutils.command.bdist
+
+Implements the Distutils 'bdist' command (create a built [binary]
+distribution)."""
+
+from __future__ import annotations
+
+import os
+import warnings
+from collections.abc import Callable
+from typing import TYPE_CHECKING, ClassVar
+
+from ..core import Command
+from ..errors import DistutilsOptionError, DistutilsPlatformError
+from ..util import get_platform
+
+if TYPE_CHECKING:
+    from typing_extensions import deprecated
+else:
+
+    def deprecated(message):
+        return lambda fn: fn
+
+
+def show_formats():
+    """Print list of available formats (arguments to "--format" option)."""
+    from ..fancy_getopt import FancyGetopt
+
+    formats = [
+        ("formats=" + format, None, bdist.format_commands[format][1])
+        for format in bdist.format_commands
+    ]
+    pretty_printer = FancyGetopt(formats)
+    pretty_printer.print_help("List of available distribution formats:")
+
+
+class ListCompat(dict[str, tuple[str, str]]):
+    # adapter to allow for Setuptools compatibility in format_commands
+    @deprecated("format_commands is now a dict. append is deprecated.")
+    def append(self, item: object) -> None:
+        warnings.warn(
+            "format_commands is now a dict. append is deprecated.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+
+class bdist(Command):
+    description = "create a built (binary) distribution"
+
+    user_options = [
+        ('bdist-base=', 'b', "temporary directory for creating built distributions"),
+        (
+            'plat-name=',
+            'p',
+            "platform name to embed in generated filenames "
+            f"[default: {get_platform()}]",
+        ),
+        ('formats=', None, "formats for distribution (comma-separated list)"),
+        (
+            'dist-dir=',
+            'd',
+            "directory to put final built distributions in [default: dist]",
+        ),
+        ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            'owner=',
+            'u',
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            'group=',
+            'g',
+            "Group name used when creating a tar file [default: current group]",
+        ),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['skip-build']
+
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
+        ('help-formats', None, "lists available distribution formats", show_formats),
+    ]
+
+    # The following commands do not take a format option from bdist
+    no_format_option: ClassVar[tuple[str, ...]] = ('bdist_rpm',)
+
+    # This won't do in reality: will need to distinguish RPM-ish Linux,
+    # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
+    default_format: ClassVar[dict[str, str]] = {'posix': 'gztar', 'nt': 'zip'}
+
+    # Define commands in preferred order for the --help-formats option
+    format_commands = ListCompat({
+        'rpm': ('bdist_rpm', "RPM distribution"),
+        'gztar': ('bdist_dumb', "gzip'ed tar file"),
+        'bztar': ('bdist_dumb', "bzip2'ed tar file"),
+        'xztar': ('bdist_dumb', "xz'ed tar file"),
+        'ztar': ('bdist_dumb', "compressed tar file"),
+        'tar': ('bdist_dumb', "tar file"),
+        'zip': ('bdist_dumb', "ZIP file"),
+    })
+
+    # for compatibility until consumers only reference format_commands
+    format_command = format_commands
+
+    def initialize_options(self):
+        self.bdist_base = None
+        self.plat_name = None
+        self.formats = None
+        self.dist_dir = None
+        self.skip_build = False
+        self.group = None
+        self.owner = None
+
+    def finalize_options(self) -> None:
+        # have to finalize 'plat_name' before 'bdist_base'
+        if self.plat_name is None:
+            if self.skip_build:
+                self.plat_name = get_platform()
+            else:
+                self.plat_name = self.get_finalized_command('build').plat_name
+
+        # 'bdist_base' -- parent of per-built-distribution-format
+        # temporary directories (eg. we'll probably have
+        # "build/bdist./dumb", "build/bdist./rpm", etc.)
+        if self.bdist_base is None:
+            build_base = self.get_finalized_command('build').build_base
+            self.bdist_base = os.path.join(build_base, 'bdist.' + self.plat_name)
+
+        self.ensure_string_list('formats')
+        if self.formats is None:
+            try:
+                self.formats = [self.default_format[os.name]]
+            except KeyError:
+                raise DistutilsPlatformError(
+                    "don't know how to create built distributions "
+                    f"on platform {os.name}"
+                )
+
+        if self.dist_dir is None:
+            self.dist_dir = "dist"
+
+    def run(self) -> None:
+        # Figure out which sub-commands we need to run.
+        commands = []
+        for format in self.formats:
+            try:
+                commands.append(self.format_commands[format][0])
+            except KeyError:
+                raise DistutilsOptionError(f"invalid format '{format}'")
+
+        # Reinitialize and run each command.
+        for i in range(len(self.formats)):
+            cmd_name = commands[i]
+            sub_cmd = self.reinitialize_command(cmd_name)
+            if cmd_name not in self.no_format_option:
+                sub_cmd.format = self.formats[i]
+
+            # passing the owner and group names for tar archiving
+            if cmd_name == 'bdist_dumb':
+                sub_cmd.owner = self.owner
+                sub_cmd.group = self.group
+
+            # If we're going to need to run this command again, tell it to
+            # keep its temporary files around so subsequent runs go faster.
+            if cmd_name in commands[i + 1 :]:
+                sub_cmd.keep_temp = True
+            self.run_command(cmd_name)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_dumb.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_dumb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccad66f43127cb18b8e592810995a7092f843041
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_dumb.py
@@ -0,0 +1,141 @@
+"""distutils.command.bdist_dumb
+
+Implements the Distutils 'bdist_dumb' command (create a "dumb" built
+distribution -- i.e., just an archive to be unpacked under $prefix or
+$exec_prefix)."""
+
+import os
+from distutils._log import log
+from typing import ClassVar
+
+from ..core import Command
+from ..dir_util import ensure_relative, remove_tree
+from ..errors import DistutilsPlatformError
+from ..sysconfig import get_python_version
+from ..util import get_platform
+
+
+class bdist_dumb(Command):
+    description = "create a \"dumb\" built distribution"
+
+    user_options = [
+        ('bdist-dir=', 'd', "temporary directory for creating the distribution"),
+        (
+            'plat-name=',
+            'p',
+            "platform name to embed in generated filenames "
+            f"[default: {get_platform()}]",
+        ),
+        (
+            'format=',
+            'f',
+            "archive format to create (tar, gztar, bztar, xztar, ztar, zip)",
+        ),
+        (
+            'keep-temp',
+            'k',
+            "keep the pseudo-installation tree around after creating the distribution archive",
+        ),
+        ('dist-dir=', 'd', "directory to put final built distributions in"),
+        ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            'relative',
+            None,
+            "build the archive using relative paths [default: false]",
+        ),
+        (
+            'owner=',
+            'u',
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            'group=',
+            'g',
+            "Group name used when creating a tar file [default: current group]",
+        ),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['keep-temp', 'skip-build', 'relative']
+
+    default_format = {'posix': 'gztar', 'nt': 'zip'}
+
+    def initialize_options(self):
+        self.bdist_dir = None
+        self.plat_name = None
+        self.format = None
+        self.keep_temp = False
+        self.dist_dir = None
+        self.skip_build = None
+        self.relative = False
+        self.owner = None
+        self.group = None
+
+    def finalize_options(self):
+        if self.bdist_dir is None:
+            bdist_base = self.get_finalized_command('bdist').bdist_base
+            self.bdist_dir = os.path.join(bdist_base, 'dumb')
+
+        if self.format is None:
+            try:
+                self.format = self.default_format[os.name]
+            except KeyError:
+                raise DistutilsPlatformError(
+                    "don't know how to create dumb built distributions "
+                    f"on platform {os.name}"
+                )
+
+        self.set_undefined_options(
+            'bdist',
+            ('dist_dir', 'dist_dir'),
+            ('plat_name', 'plat_name'),
+            ('skip_build', 'skip_build'),
+        )
+
+    def run(self):
+        if not self.skip_build:
+            self.run_command('build')
+
+        install = self.reinitialize_command('install', reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        log.info("installing to %s", self.bdist_dir)
+        self.run_command('install')
+
+        # And make an archive relative to the root of the
+        # pseudo-installation tree.
+        archive_basename = f"{self.distribution.get_fullname()}.{self.plat_name}"
+
+        pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            if self.distribution.has_ext_modules() and (
+                install.install_base != install.install_platbase
+            ):
+                raise DistutilsPlatformError(
+                    "can't make a dumb built distribution where "
+                    f"base and platbase are different ({install.install_base!r}, {install.install_platbase!r})"
+                )
+            else:
+                archive_root = os.path.join(
+                    self.bdist_dir, ensure_relative(install.install_base)
+                )
+
+        # Make the archive
+        filename = self.make_archive(
+            pseudoinstall_root,
+            self.format,
+            root_dir=archive_root,
+            owner=self.owner,
+            group=self.group,
+        )
+        if self.distribution.has_ext_modules():
+            pyversion = get_python_version()
+        else:
+            pyversion = 'any'
+        self.distribution.dist_files.append(('bdist_dumb', pyversion, filename))
+
+        if not self.keep_temp:
+            remove_tree(self.bdist_dir, dry_run=self.dry_run)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_rpm.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_rpm.py
new file mode 100644
index 0000000000000000000000000000000000000000..357b4e861e2e0ec44a0bf1dda6c2dd35db8b9ca8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/bdist_rpm.py
@@ -0,0 +1,598 @@
+"""distutils.command.bdist_rpm
+
+Implements the Distutils 'bdist_rpm' command (create RPM source and binary
+distributions)."""
+
+import os
+import subprocess
+import sys
+from distutils._log import log
+from typing import ClassVar
+
+from ..core import Command
+from ..debug import DEBUG
+from ..errors import (
+    DistutilsExecError,
+    DistutilsFileError,
+    DistutilsOptionError,
+    DistutilsPlatformError,
+)
+from ..file_util import write_file
+from ..sysconfig import get_python_version
+
+
+class bdist_rpm(Command):
+    description = "create an RPM distribution"
+
+    user_options = [
+        ('bdist-base=', None, "base directory for creating built distributions"),
+        (
+            'rpm-base=',
+            None,
+            "base directory for creating RPMs (defaults to \"rpm\" under "
+            "--bdist-base; must be specified for RPM 2)",
+        ),
+        (
+            'dist-dir=',
+            'd',
+            "directory to put final RPM files in (and .spec files if --spec-only)",
+        ),
+        (
+            'python=',
+            None,
+            "path to Python interpreter to hard-code in the .spec file "
+            "[default: \"python\"]",
+        ),
+        (
+            'fix-python',
+            None,
+            "hard-code the exact path to the current Python interpreter in "
+            "the .spec file",
+        ),
+        ('spec-only', None, "only regenerate spec file"),
+        ('source-only', None, "only generate source RPM"),
+        ('binary-only', None, "only generate binary RPM"),
+        ('use-bzip2', None, "use bzip2 instead of gzip to create source distribution"),
+        # More meta-data: too RPM-specific to put in the setup script,
+        # but needs to go in the .spec file -- so we make these options
+        # to "bdist_rpm".  The idea is that packagers would put this
+        # info in setup.cfg, although they are of course free to
+        # supply it on the command line.
+        (
+            'distribution-name=',
+            None,
+            "name of the (Linux) distribution to which this "
+            "RPM applies (*not* the name of the module distribution!)",
+        ),
+        ('group=', None, "package classification [default: \"Development/Libraries\"]"),
+        ('release=', None, "RPM release number"),
+        ('serial=', None, "RPM serial number"),
+        (
+            'vendor=',
+            None,
+            "RPM \"vendor\" (eg. \"Joe Blow \") "
+            "[default: maintainer or author from setup script]",
+        ),
+        (
+            'packager=',
+            None,
+            "RPM packager (eg. \"Jane Doe \") [default: vendor]",
+        ),
+        ('doc-files=', None, "list of documentation files (space or comma-separated)"),
+        ('changelog=', None, "RPM changelog"),
+        ('icon=', None, "name of icon file"),
+        ('provides=', None, "capabilities provided by this package"),
+        ('requires=', None, "capabilities required by this package"),
+        ('conflicts=', None, "capabilities which conflict with this package"),
+        ('build-requires=', None, "capabilities required to build this package"),
+        ('obsoletes=', None, "capabilities made obsolete by this package"),
+        ('no-autoreq', None, "do not automatically calculate dependencies"),
+        # Actions to take when building RPM
+        ('keep-temp', 'k', "don't clean up RPM build directory"),
+        ('no-keep-temp', None, "clean up RPM build directory [default]"),
+        (
+            'use-rpm-opt-flags',
+            None,
+            "compile with RPM_OPT_FLAGS when building from source RPM",
+        ),
+        ('no-rpm-opt-flags', None, "do not pass any RPM CFLAGS to compiler"),
+        ('rpm3-mode', None, "RPM 3 compatibility mode (default)"),
+        ('rpm2-mode', None, "RPM 2 compatibility mode"),
+        # Add the hooks necessary for specifying custom scripts
+        ('prep-script=', None, "Specify a script for the PREP phase of RPM building"),
+        ('build-script=', None, "Specify a script for the BUILD phase of RPM building"),
+        (
+            'pre-install=',
+            None,
+            "Specify a script for the pre-INSTALL phase of RPM building",
+        ),
+        (
+            'install-script=',
+            None,
+            "Specify a script for the INSTALL phase of RPM building",
+        ),
+        (
+            'post-install=',
+            None,
+            "Specify a script for the post-INSTALL phase of RPM building",
+        ),
+        (
+            'pre-uninstall=',
+            None,
+            "Specify a script for the pre-UNINSTALL phase of RPM building",
+        ),
+        (
+            'post-uninstall=',
+            None,
+            "Specify a script for the post-UNINSTALL phase of RPM building",
+        ),
+        ('clean-script=', None, "Specify a script for the CLEAN phase of RPM building"),
+        (
+            'verify-script=',
+            None,
+            "Specify a script for the VERIFY phase of the RPM build",
+        ),
+        # Allow a packager to explicitly force an architecture
+        ('force-arch=', None, "Force an architecture onto the RPM build process"),
+        ('quiet', 'q', "Run the INSTALL phase of RPM building in quiet mode"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = [
+        'keep-temp',
+        'use-rpm-opt-flags',
+        'rpm3-mode',
+        'no-autoreq',
+        'quiet',
+    ]
+
+    negative_opt: ClassVar[dict[str, str]] = {
+        'no-keep-temp': 'keep-temp',
+        'no-rpm-opt-flags': 'use-rpm-opt-flags',
+        'rpm2-mode': 'rpm3-mode',
+    }
+
+    def initialize_options(self):
+        self.bdist_base = None
+        self.rpm_base = None
+        self.dist_dir = None
+        self.python = None
+        self.fix_python = None
+        self.spec_only = None
+        self.binary_only = None
+        self.source_only = None
+        self.use_bzip2 = None
+
+        self.distribution_name = None
+        self.group = None
+        self.release = None
+        self.serial = None
+        self.vendor = None
+        self.packager = None
+        self.doc_files = None
+        self.changelog = None
+        self.icon = None
+
+        self.prep_script = None
+        self.build_script = None
+        self.install_script = None
+        self.clean_script = None
+        self.verify_script = None
+        self.pre_install = None
+        self.post_install = None
+        self.pre_uninstall = None
+        self.post_uninstall = None
+        self.prep = None
+        self.provides = None
+        self.requires = None
+        self.conflicts = None
+        self.build_requires = None
+        self.obsoletes = None
+
+        self.keep_temp = False
+        self.use_rpm_opt_flags = True
+        self.rpm3_mode = True
+        self.no_autoreq = False
+
+        self.force_arch = None
+        self.quiet = False
+
+    def finalize_options(self) -> None:
+        self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
+        if self.rpm_base is None:
+            if not self.rpm3_mode:
+                raise DistutilsOptionError("you must specify --rpm-base in RPM 2 mode")
+            self.rpm_base = os.path.join(self.bdist_base, "rpm")
+
+        if self.python is None:
+            if self.fix_python:
+                self.python = sys.executable
+            else:
+                self.python = "python3"
+        elif self.fix_python:
+            raise DistutilsOptionError(
+                "--python and --fix-python are mutually exclusive options"
+            )
+
+        if os.name != 'posix':
+            raise DistutilsPlatformError(
+                f"don't know how to create RPM distributions on platform {os.name}"
+            )
+        if self.binary_only and self.source_only:
+            raise DistutilsOptionError(
+                "cannot supply both '--source-only' and '--binary-only'"
+            )
+
+        # don't pass CFLAGS to pure python distributions
+        if not self.distribution.has_ext_modules():
+            self.use_rpm_opt_flags = False
+
+        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
+        self.finalize_package_data()
+
+    def finalize_package_data(self) -> None:
+        self.ensure_string('group', "Development/Libraries")
+        self.ensure_string(
+            'vendor',
+            f"{self.distribution.get_contact()} <{self.distribution.get_contact_email()}>",
+        )
+        self.ensure_string('packager')
+        self.ensure_string_list('doc_files')
+        if isinstance(self.doc_files, list):
+            for readme in ('README', 'README.txt'):
+                if os.path.exists(readme) and readme not in self.doc_files:
+                    self.doc_files.append(readme)
+
+        self.ensure_string('release', "1")
+        self.ensure_string('serial')  # should it be an int?
+
+        self.ensure_string('distribution_name')
+
+        self.ensure_string('changelog')
+        # Format changelog correctly
+        self.changelog = self._format_changelog(self.changelog)
+
+        self.ensure_filename('icon')
+
+        self.ensure_filename('prep_script')
+        self.ensure_filename('build_script')
+        self.ensure_filename('install_script')
+        self.ensure_filename('clean_script')
+        self.ensure_filename('verify_script')
+        self.ensure_filename('pre_install')
+        self.ensure_filename('post_install')
+        self.ensure_filename('pre_uninstall')
+        self.ensure_filename('post_uninstall')
+
+        # XXX don't forget we punted on summaries and descriptions -- they
+        # should be handled here eventually!
+
+        # Now *this* is some meta-data that belongs in the setup script...
+        self.ensure_string_list('provides')
+        self.ensure_string_list('requires')
+        self.ensure_string_list('conflicts')
+        self.ensure_string_list('build_requires')
+        self.ensure_string_list('obsoletes')
+
+        self.ensure_string('force_arch')
+
+    def run(self) -> None:  # noqa: C901
+        if DEBUG:
+            print("before _get_package_data():")
+            print("vendor =", self.vendor)
+            print("packager =", self.packager)
+            print("doc_files =", self.doc_files)
+            print("changelog =", self.changelog)
+
+        # make directories
+        if self.spec_only:
+            spec_dir = self.dist_dir
+            self.mkpath(spec_dir)
+        else:
+            rpm_dir = {}
+            for d in ('SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS'):
+                rpm_dir[d] = os.path.join(self.rpm_base, d)
+                self.mkpath(rpm_dir[d])
+            spec_dir = rpm_dir['SPECS']
+
+        # Spec file goes into 'dist_dir' if '--spec-only specified',
+        # build/rpm. otherwise.
+        spec_path = os.path.join(spec_dir, f"{self.distribution.get_name()}.spec")
+        self.execute(
+            write_file, (spec_path, self._make_spec_file()), f"writing '{spec_path}'"
+        )
+
+        if self.spec_only:  # stop if requested
+            return
+
+        # Make a source distribution and copy to SOURCES directory with
+        # optional icon.
+        saved_dist_files = self.distribution.dist_files[:]
+        sdist = self.reinitialize_command('sdist')
+        if self.use_bzip2:
+            sdist.formats = ['bztar']
+        else:
+            sdist.formats = ['gztar']
+        self.run_command('sdist')
+        self.distribution.dist_files = saved_dist_files
+
+        source = sdist.get_archive_files()[0]
+        source_dir = rpm_dir['SOURCES']
+        self.copy_file(source, source_dir)
+
+        if self.icon:
+            if os.path.exists(self.icon):
+                self.copy_file(self.icon, source_dir)
+            else:
+                raise DistutilsFileError(f"icon file '{self.icon}' does not exist")
+
+        # build package
+        log.info("building RPMs")
+        rpm_cmd = ['rpmbuild']
+
+        if self.source_only:  # what kind of RPMs?
+            rpm_cmd.append('-bs')
+        elif self.binary_only:
+            rpm_cmd.append('-bb')
+        else:
+            rpm_cmd.append('-ba')
+        rpm_cmd.extend(['--define', f'__python {self.python}'])
+        if self.rpm3_mode:
+            rpm_cmd.extend(['--define', f'_topdir {os.path.abspath(self.rpm_base)}'])
+        if not self.keep_temp:
+            rpm_cmd.append('--clean')
+
+        if self.quiet:
+            rpm_cmd.append('--quiet')
+
+        rpm_cmd.append(spec_path)
+        # Determine the binary rpm names that should be built out of this spec
+        # file
+        # Note that some of these may not be really built (if the file
+        # list is empty)
+        nvr_string = "%{name}-%{version}-%{release}"
+        src_rpm = nvr_string + ".src.rpm"
+        non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm"
+        q_cmd = rf"rpm -q --qf '{src_rpm} {non_src_rpm}\n' --specfile '{spec_path}'"
+
+        out = os.popen(q_cmd)
+        try:
+            binary_rpms = []
+            source_rpm = None
+            while True:
+                line = out.readline()
+                if not line:
+                    break
+                ell = line.strip().split()
+                assert len(ell) == 2
+                binary_rpms.append(ell[1])
+                # The source rpm is named after the first entry in the spec file
+                if source_rpm is None:
+                    source_rpm = ell[0]
+
+            status = out.close()
+            if status:
+                raise DistutilsExecError(f"Failed to execute: {q_cmd!r}")
+
+        finally:
+            out.close()
+
+        self.spawn(rpm_cmd)
+
+        if not self.dry_run:
+            if self.distribution.has_ext_modules():
+                pyversion = get_python_version()
+            else:
+                pyversion = 'any'
+
+            if not self.binary_only:
+                srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
+                assert os.path.exists(srpm)
+                self.move_file(srpm, self.dist_dir)
+                filename = os.path.join(self.dist_dir, source_rpm)
+                self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))
+
+            if not self.source_only:
+                for rpm in binary_rpms:
+                    rpm = os.path.join(rpm_dir['RPMS'], rpm)
+                    if os.path.exists(rpm):
+                        self.move_file(rpm, self.dist_dir)
+                        filename = os.path.join(self.dist_dir, os.path.basename(rpm))
+                        self.distribution.dist_files.append((
+                            'bdist_rpm',
+                            pyversion,
+                            filename,
+                        ))
+
+    def _dist_path(self, path):
+        return os.path.join(self.dist_dir, os.path.basename(path))
+
+    def _make_spec_file(self):  # noqa: C901
+        """Generate the text of an RPM spec file and return it as a
+        list of strings (one per line).
+        """
+        # definitions and headers
+        spec_file = [
+            '%define name ' + self.distribution.get_name(),
+            '%define version ' + self.distribution.get_version().replace('-', '_'),
+            '%define unmangled_version ' + self.distribution.get_version(),
+            '%define release ' + self.release.replace('-', '_'),
+            '',
+            'Summary: ' + (self.distribution.get_description() or "UNKNOWN"),
+        ]
+
+        # Workaround for #14443 which affects some RPM based systems such as
+        # RHEL6 (and probably derivatives)
+        vendor_hook = subprocess.getoutput('rpm --eval %{__os_install_post}')
+        # Generate a potential replacement value for __os_install_post (whilst
+        # normalizing the whitespace to simplify the test for whether the
+        # invocation of brp-python-bytecompile passes in __python):
+        vendor_hook = '\n'.join([
+            f'  {line.strip()} \\' for line in vendor_hook.splitlines()
+        ])
+        problem = "brp-python-bytecompile \\\n"
+        fixed = "brp-python-bytecompile %{__python} \\\n"
+        fixed_hook = vendor_hook.replace(problem, fixed)
+        if fixed_hook != vendor_hook:
+            spec_file.append('# Workaround for https://bugs.python.org/issue14443')
+            spec_file.append('%define __os_install_post ' + fixed_hook + '\n')
+
+        # put locale summaries into spec file
+        # XXX not supported for now (hard to put a dictionary
+        # in a config file -- arg!)
+        # for locale in self.summaries.keys():
+        #    spec_file.append('Summary(%s): %s' % (locale,
+        #                                          self.summaries[locale]))
+
+        spec_file.extend([
+            'Name: %{name}',
+            'Version: %{version}',
+            'Release: %{release}',
+        ])
+
+        # XXX yuck! this filename is available from the "sdist" command,
+        # but only after it has run: and we create the spec file before
+        # running "sdist", in case of --spec-only.
+        if self.use_bzip2:
+            spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')
+        else:
+            spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
+
+        spec_file.extend([
+            'License: ' + (self.distribution.get_license() or "UNKNOWN"),
+            'Group: ' + self.group,
+            'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
+            'Prefix: %{_prefix}',
+        ])
+
+        if not self.force_arch:
+            # noarch if no extension modules
+            if not self.distribution.has_ext_modules():
+                spec_file.append('BuildArch: noarch')
+        else:
+            spec_file.append(f'BuildArch: {self.force_arch}')
+
+        for field in (
+            'Vendor',
+            'Packager',
+            'Provides',
+            'Requires',
+            'Conflicts',
+            'Obsoletes',
+        ):
+            val = getattr(self, field.lower())
+            if isinstance(val, list):
+                spec_file.append('{}: {}'.format(field, ' '.join(val)))
+            elif val is not None:
+                spec_file.append(f'{field}: {val}')
+
+        if self.distribution.get_url():
+            spec_file.append('Url: ' + self.distribution.get_url())
+
+        if self.distribution_name:
+            spec_file.append('Distribution: ' + self.distribution_name)
+
+        if self.build_requires:
+            spec_file.append('BuildRequires: ' + ' '.join(self.build_requires))
+
+        if self.icon:
+            spec_file.append('Icon: ' + os.path.basename(self.icon))
+
+        if self.no_autoreq:
+            spec_file.append('AutoReq: 0')
+
+        spec_file.extend([
+            '',
+            '%description',
+            self.distribution.get_long_description() or "",
+        ])
+
+        # put locale descriptions into spec file
+        # XXX again, suppressed because config file syntax doesn't
+        # easily support this ;-(
+        # for locale in self.descriptions.keys():
+        #    spec_file.extend([
+        #        '',
+        #        '%description -l ' + locale,
+        #        self.descriptions[locale],
+        #        ])
+
+        # rpm scripts
+        # figure out default build script
+        def_setup_call = f"{self.python} {os.path.basename(sys.argv[0])}"
+        def_build = f"{def_setup_call} build"
+        if self.use_rpm_opt_flags:
+            def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
+
+        # insert contents of files
+
+        # XXX this is kind of misleading: user-supplied options are files
+        # that we open and interpolate into the spec file, but the defaults
+        # are just text that we drop in as-is.  Hmmm.
+
+        install_cmd = f'{def_setup_call} install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES'
+
+        script_options = [
+            ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
+            ('build', 'build_script', def_build),
+            ('install', 'install_script', install_cmd),
+            ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"),
+            ('verifyscript', 'verify_script', None),
+            ('pre', 'pre_install', None),
+            ('post', 'post_install', None),
+            ('preun', 'pre_uninstall', None),
+            ('postun', 'post_uninstall', None),
+        ]
+
+        for rpm_opt, attr, default in script_options:
+            # Insert contents of file referred to, if no file is referred to
+            # use 'default' as contents of script
+            val = getattr(self, attr)
+            if val or default:
+                spec_file.extend([
+                    '',
+                    '%' + rpm_opt,
+                ])
+                if val:
+                    with open(val) as f:
+                        spec_file.extend(f.read().split('\n'))
+                else:
+                    spec_file.append(default)
+
+        # files section
+        spec_file.extend([
+            '',
+            '%files -f INSTALLED_FILES',
+            '%defattr(-,root,root)',
+        ])
+
+        if self.doc_files:
+            spec_file.append('%doc ' + ' '.join(self.doc_files))
+
+        if self.changelog:
+            spec_file.extend([
+                '',
+                '%changelog',
+            ])
+            spec_file.extend(self.changelog)
+
+        return spec_file
+
+    def _format_changelog(self, changelog):
+        """Format the changelog correctly and convert it to a list of strings"""
+        if not changelog:
+            return changelog
+        new_changelog = []
+        for line in changelog.strip().split('\n'):
+            line = line.strip()
+            if line[0] == '*':
+                new_changelog.extend(['', line])
+            elif line[0] == '-':
+                new_changelog.append(line)
+            else:
+                new_changelog.append('  ' + line)
+
+        # strip trailing newline inserted by first changelog entry
+        if not new_changelog[0]:
+            del new_changelog[0]
+
+        return new_changelog
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/build.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a8303a954ea705c547e2014dc6b51d9d987a532
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build.py
@@ -0,0 +1,156 @@
+"""distutils.command.build
+
+Implements the Distutils 'build' command."""
+
+from __future__ import annotations
+
+import os
+import sys
+import sysconfig
+from collections.abc import Callable
+from typing import ClassVar
+
+from ..ccompiler import show_compilers
+from ..core import Command
+from ..errors import DistutilsOptionError
+from ..util import get_platform
+
+
+class build(Command):
+    description = "build everything needed to install"
+
+    user_options = [
+        ('build-base=', 'b', "base directory for build library"),
+        ('build-purelib=', None, "build directory for platform-neutral distributions"),
+        ('build-platlib=', None, "build directory for platform-specific distributions"),
+        (
+            'build-lib=',
+            None,
+            "build directory for all distribution (defaults to either build-purelib or build-platlib",
+        ),
+        ('build-scripts=', None, "build directory for scripts"),
+        ('build-temp=', 't', "temporary build directory"),
+        (
+            'plat-name=',
+            'p',
+            f"platform name to build for, if supported [default: {get_platform()}]",
+        ),
+        ('compiler=', 'c', "specify the compiler type"),
+        ('parallel=', 'j', "number of parallel build jobs"),
+        ('debug', 'g', "compile extensions and libraries with debugging information"),
+        ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+        ('executable=', 'e', "specify final destination interpreter path (build.py)"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['debug', 'force']
+
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
+        ('help-compiler', None, "list available compilers", show_compilers),
+    ]
+
+    def initialize_options(self):
+        self.build_base = 'build'
+        # these are decided only after 'build_base' has its final value
+        # (unless overridden by the user or client)
+        self.build_purelib = None
+        self.build_platlib = None
+        self.build_lib = None
+        self.build_temp = None
+        self.build_scripts = None
+        self.compiler = None
+        self.plat_name = None
+        self.debug = None
+        self.force = False
+        self.executable = None
+        self.parallel = None
+
+    def finalize_options(self) -> None:  # noqa: C901
+        if self.plat_name is None:
+            self.plat_name = get_platform()
+        else:
+            # plat-name only supported for windows (other platforms are
+            # supported via ./configure flags, if at all).  Avoid misleading
+            # other platforms.
+            if os.name != 'nt':
+                raise DistutilsOptionError(
+                    "--plat-name only supported on Windows (try "
+                    "using './configure --help' on your platform)"
+                )
+
+        plat_specifier = f".{self.plat_name}-{sys.implementation.cache_tag}"
+
+        # Python 3.13+ with --disable-gil shouldn't share build directories
+        if sysconfig.get_config_var('Py_GIL_DISABLED'):
+            plat_specifier += 't'
+
+        # Make it so Python 2.x and Python 2.x with --with-pydebug don't
+        # share the same build directories. Doing so confuses the build
+        # process for C modules
+        if hasattr(sys, 'gettotalrefcount'):
+            plat_specifier += '-pydebug'
+
+        # 'build_purelib' and 'build_platlib' just default to 'lib' and
+        # 'lib.' under the base build directory.  We only use one of
+        # them for a given distribution, though --
+        if self.build_purelib is None:
+            self.build_purelib = os.path.join(self.build_base, 'lib')
+        if self.build_platlib is None:
+            self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier)
+
+        # 'build_lib' is the actual directory that we will use for this
+        # particular module distribution -- if user didn't supply it, pick
+        # one of 'build_purelib' or 'build_platlib'.
+        if self.build_lib is None:
+            if self.distribution.has_ext_modules():
+                self.build_lib = self.build_platlib
+            else:
+                self.build_lib = self.build_purelib
+
+        # 'build_temp' -- temporary directory for compiler turds,
+        # "build/temp."
+        if self.build_temp is None:
+            self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier)
+        if self.build_scripts is None:
+            self.build_scripts = os.path.join(
+                self.build_base,
+                f'scripts-{sys.version_info.major}.{sys.version_info.minor}',
+            )
+
+        if self.executable is None and sys.executable:
+            self.executable = os.path.normpath(sys.executable)
+
+        if isinstance(self.parallel, str):
+            try:
+                self.parallel = int(self.parallel)
+            except ValueError:
+                raise DistutilsOptionError("parallel should be an integer")
+
+    def run(self) -> None:
+        # Run all relevant sub-commands.  This will be some subset of:
+        #  - build_py      - pure Python modules
+        #  - build_clib    - standalone C libraries
+        #  - build_ext     - Python extensions
+        #  - build_scripts - (Python) scripts
+        for cmd_name in self.get_sub_commands():
+            self.run_command(cmd_name)
+
+    # -- Predicates for the sub-command list ---------------------------
+
+    def has_pure_modules(self):
+        return self.distribution.has_pure_modules()
+
+    def has_c_libraries(self):
+        return self.distribution.has_c_libraries()
+
+    def has_ext_modules(self):
+        return self.distribution.has_ext_modules()
+
+    def has_scripts(self):
+        return self.distribution.has_scripts()
+
+    sub_commands = [
+        ('build_py', has_pure_modules),
+        ('build_clib', has_c_libraries),
+        ('build_ext', has_ext_modules),
+        ('build_scripts', has_scripts),
+    ]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_clib.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_clib.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b65b3d8ece0253e0c80cfea33160c7741a2435f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_clib.py
@@ -0,0 +1,201 @@
+"""distutils.command.build_clib
+
+Implements the Distutils 'build_clib' command, to build a C/C++ library
+that is included in the module distribution and needed by an extension
+module."""
+
+# XXX this module has *lots* of code ripped-off quite transparently from
+# build_ext.py -- not surprisingly really, as the work required to build
+# a static library from a collection of C source files is not really all
+# that different from what's required to build a shared object file from
+# a collection of C source files.  Nevertheless, I haven't done the
+# necessary refactoring to account for the overlap in code between the
+# two modules, mainly because a number of subtle details changed in the
+# cut 'n paste.  Sigh.
+from __future__ import annotations
+
+import os
+from collections.abc import Callable
+from distutils._log import log
+from typing import ClassVar
+
+from ..ccompiler import new_compiler, show_compilers
+from ..core import Command
+from ..errors import DistutilsSetupError
+from ..sysconfig import customize_compiler
+
+
+class build_clib(Command):
+    description = "build C/C++ libraries used by Python extensions"
+
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('build-clib=', 'b', "directory to build C/C++ libraries to"),
+        ('build-temp=', 't', "directory to put temporary build by-products"),
+        ('debug', 'g', "compile with debugging information"),
+        ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+        ('compiler=', 'c', "specify the compiler type"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['debug', 'force']
+
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
+        ('help-compiler', None, "list available compilers", show_compilers),
+    ]
+
+    def initialize_options(self):
+        self.build_clib = None
+        self.build_temp = None
+
+        # List of libraries to build
+        self.libraries = None
+
+        # Compilation options for all libraries
+        self.include_dirs = None
+        self.define = None
+        self.undef = None
+        self.debug = None
+        self.force = False
+        self.compiler = None
+
+    def finalize_options(self) -> None:
+        # This might be confusing: both build-clib and build-temp default
+        # to build-temp as defined by the "build" command.  This is because
+        # I think that C libraries are really just temporary build
+        # by-products, at least from the point of view of building Python
+        # extensions -- but I want to keep my options open.
+        self.set_undefined_options(
+            'build',
+            ('build_temp', 'build_clib'),
+            ('build_temp', 'build_temp'),
+            ('compiler', 'compiler'),
+            ('debug', 'debug'),
+            ('force', 'force'),
+        )
+
+        self.libraries = self.distribution.libraries
+        if self.libraries:
+            self.check_library_list(self.libraries)
+
+        if self.include_dirs is None:
+            self.include_dirs = self.distribution.include_dirs or []
+        if isinstance(self.include_dirs, str):
+            self.include_dirs = self.include_dirs.split(os.pathsep)
+
+        # XXX same as for build_ext -- what about 'self.define' and
+        # 'self.undef' ?
+
+    def run(self) -> None:
+        if not self.libraries:
+            return
+
+        self.compiler = new_compiler(
+            compiler=self.compiler, dry_run=self.dry_run, force=self.force
+        )
+        customize_compiler(self.compiler)
+
+        if self.include_dirs is not None:
+            self.compiler.set_include_dirs(self.include_dirs)
+        if self.define is not None:
+            # 'define' option is a list of (name,value) tuples
+            for name, value in self.define:
+                self.compiler.define_macro(name, value)
+        if self.undef is not None:
+            for macro in self.undef:
+                self.compiler.undefine_macro(macro)
+
+        self.build_libraries(self.libraries)
+
+    def check_library_list(self, libraries) -> None:
+        """Ensure that the list of libraries is valid.
+
+        `library` is presumably provided as a command option 'libraries'.
+        This method checks that it is a list of 2-tuples, where the tuples
+        are (library_name, build_info_dict).
+
+        Raise DistutilsSetupError if the structure is invalid anywhere;
+        just returns otherwise.
+        """
+        if not isinstance(libraries, list):
+            raise DistutilsSetupError("'libraries' option must be a list of tuples")
+
+        for lib in libraries:
+            if not isinstance(lib, tuple) and len(lib) != 2:
+                raise DistutilsSetupError("each element of 'libraries' must a 2-tuple")
+
+            name, build_info = lib
+
+            if not isinstance(name, str):
+                raise DistutilsSetupError(
+                    "first element of each tuple in 'libraries' "
+                    "must be a string (the library name)"
+                )
+
+            if '/' in name or (os.sep != '/' and os.sep in name):
+                raise DistutilsSetupError(
+                    f"bad library name '{lib[0]}': may not contain directory separators"
+                )
+
+            if not isinstance(build_info, dict):
+                raise DistutilsSetupError(
+                    "second element of each tuple in 'libraries' "
+                    "must be a dictionary (build info)"
+                )
+
+    def get_library_names(self):
+        # Assume the library list is valid -- 'check_library_list()' is
+        # called from 'finalize_options()', so it should be!
+        if not self.libraries:
+            return None
+
+        lib_names = []
+        for lib_name, _build_info in self.libraries:
+            lib_names.append(lib_name)
+        return lib_names
+
+    def get_source_files(self):
+        self.check_library_list(self.libraries)
+        filenames = []
+        for lib_name, build_info in self.libraries:
+            sources = build_info.get('sources')
+            if sources is None or not isinstance(sources, (list, tuple)):
+                raise DistutilsSetupError(
+                    f"in 'libraries' option (library '{lib_name}'), "
+                    "'sources' must be present and must be "
+                    "a list of source filenames"
+                )
+
+            filenames.extend(sources)
+        return filenames
+
+    def build_libraries(self, libraries) -> None:
+        for lib_name, build_info in libraries:
+            sources = build_info.get('sources')
+            if sources is None or not isinstance(sources, (list, tuple)):
+                raise DistutilsSetupError(
+                    f"in 'libraries' option (library '{lib_name}'), "
+                    "'sources' must be present and must be "
+                    "a list of source filenames"
+                )
+            sources = list(sources)
+
+            log.info("building '%s' library", lib_name)
+
+            # First, compile the source code to object files in the library
+            # directory.  (This should probably change to putting object
+            # files in a temporary build directory.)
+            macros = build_info.get('macros')
+            include_dirs = build_info.get('include_dirs')
+            objects = self.compiler.compile(
+                sources,
+                output_dir=self.build_temp,
+                macros=macros,
+                include_dirs=include_dirs,
+                debug=self.debug,
+            )
+
+            # Now "link" the object files together into a static library.
+            # (On Unix at least, this isn't really linking -- it just
+            # builds an archive.  Whatever.)
+            self.compiler.create_static_lib(
+                objects, lib_name, output_dir=self.build_clib, debug=self.debug
+            )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_ext.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_ext.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec45b4403e54d3f58459a412746bc86e4135a756
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_ext.py
@@ -0,0 +1,812 @@
+"""distutils.command.build_ext
+
+Implements the Distutils 'build_ext' command, for building extension
+modules (currently limited to C extensions, should accommodate C++
+extensions ASAP)."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import re
+import sys
+from collections.abc import Callable
+from distutils._log import log
+from site import USER_BASE
+from typing import ClassVar
+
+from .._modified import newer_group
+from ..ccompiler import new_compiler, show_compilers
+from ..core import Command
+from ..errors import (
+    CCompilerError,
+    CompileError,
+    DistutilsError,
+    DistutilsOptionError,
+    DistutilsPlatformError,
+    DistutilsSetupError,
+)
+from ..extension import Extension
+from ..sysconfig import customize_compiler, get_config_h_filename, get_python_version
+from ..util import get_platform, is_freethreaded, is_mingw
+
+# An extension name is just a dot-separated list of Python NAMEs (ie.
+# the same as a fully-qualified module name).
+extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
+
+
+class build_ext(Command):
+    description = "build C/C++ extensions (compile/link to build directory)"
+
+    # XXX thoughts on how to deal with complex command-line options like
+    # these, i.e. how to make it so fancy_getopt can suck them off the
+    # command line and make it look like setup.py defined the appropriate
+    # lists of tuples of what-have-you.
+    #   - each command needs a callback to process its command-line options
+    #   - Command.__init__() needs access to its share of the whole
+    #     command line (must ultimately come from
+    #     Distribution.parse_command_line())
+    #   - it then calls the current command class' option-parsing
+    #     callback to deal with weird options like -D, which have to
+    #     parse the option text and churn out some custom data
+    #     structure
+    #   - that data structure (in this case, a list of 2-tuples)
+    #     will then be present in the command object by the time
+    #     we get to finalize_options() (i.e. the constructor
+    #     takes care of both command-line and client options
+    #     in between initialize_options() and finalize_options())
+
+    sep_by = f" (separated by '{os.pathsep}')"
+    user_options = [
+        ('build-lib=', 'b', "directory for compiled extension modules"),
+        ('build-temp=', 't', "directory for temporary files (build by-products)"),
+        (
+            'plat-name=',
+            'p',
+            "platform name to cross-compile for, if supported "
+            f"[default: {get_platform()}]",
+        ),
+        (
+            'inplace',
+            'i',
+            "ignore build-lib and put compiled extensions into the source "
+            "directory alongside your pure Python modules",
+        ),
+        (
+            'include-dirs=',
+            'I',
+            "list of directories to search for header files" + sep_by,
+        ),
+        ('define=', 'D', "C preprocessor macros to define"),
+        ('undef=', 'U', "C preprocessor macros to undefine"),
+        ('libraries=', 'l', "external C libraries to link with"),
+        (
+            'library-dirs=',
+            'L',
+            "directories to search for external C libraries" + sep_by,
+        ),
+        ('rpath=', 'R', "directories to search for shared C libraries at runtime"),
+        ('link-objects=', 'O', "extra explicit link objects to include in the link"),
+        ('debug', 'g', "compile/link with debugging information"),
+        ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+        ('compiler=', 'c', "specify the compiler type"),
+        ('parallel=', 'j', "number of parallel build jobs"),
+        ('swig-cpp', None, "make SWIG create C++ files (default is C)"),
+        ('swig-opts=', None, "list of SWIG command line options"),
+        ('swig=', None, "path to the SWIG executable"),
+        ('user', None, "add user include, library and rpath"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = [
+        'inplace',
+        'debug',
+        'force',
+        'swig-cpp',
+        'user',
+    ]
+
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
+        ('help-compiler', None, "list available compilers", show_compilers),
+    ]
+
+    def initialize_options(self):
+        self.extensions = None
+        self.build_lib = None
+        self.plat_name = None
+        self.build_temp = None
+        self.inplace = False
+        self.package = None
+
+        self.include_dirs = None
+        self.define = None
+        self.undef = None
+        self.libraries = None
+        self.library_dirs = None
+        self.rpath = None
+        self.link_objects = None
+        self.debug = None
+        self.force = None
+        self.compiler = None
+        self.swig = None
+        self.swig_cpp = None
+        self.swig_opts = None
+        self.user = None
+        self.parallel = None
+
+    @staticmethod
+    def _python_lib_dir(sysconfig):
+        """
+        Resolve Python's library directory for building extensions
+        that rely on a shared Python library.
+
+        See python/cpython#44264 and python/cpython#48686
+        """
+        if not sysconfig.get_config_var('Py_ENABLE_SHARED'):
+            return
+
+        if sysconfig.python_build:
+            yield '.'
+            return
+
+        if sys.platform == 'zos':
+            # On z/OS, a user is not required to install Python to
+            # a predetermined path, but can use Python portably
+            installed_dir = sysconfig.get_config_var('base')
+            lib_dir = sysconfig.get_config_var('platlibdir')
+            yield os.path.join(installed_dir, lib_dir)
+        else:
+            # building third party extensions
+            yield sysconfig.get_config_var('LIBDIR')
+
+    def finalize_options(self) -> None:  # noqa: C901
+        from distutils import sysconfig
+
+        self.set_undefined_options(
+            'build',
+            ('build_lib', 'build_lib'),
+            ('build_temp', 'build_temp'),
+            ('compiler', 'compiler'),
+            ('debug', 'debug'),
+            ('force', 'force'),
+            ('parallel', 'parallel'),
+            ('plat_name', 'plat_name'),
+        )
+
+        if self.package is None:
+            self.package = self.distribution.ext_package
+
+        self.extensions = self.distribution.ext_modules
+
+        # Make sure Python's include directories (for Python.h, pyconfig.h,
+        # etc.) are in the include search path.
+        py_include = sysconfig.get_python_inc()
+        plat_py_include = sysconfig.get_python_inc(plat_specific=True)
+        if self.include_dirs is None:
+            self.include_dirs = self.distribution.include_dirs or []
+        if isinstance(self.include_dirs, str):
+            self.include_dirs = self.include_dirs.split(os.pathsep)
+
+        # If in a virtualenv, add its include directory
+        # Issue 16116
+        if sys.exec_prefix != sys.base_exec_prefix:
+            self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
+
+        # Put the Python "system" include dir at the end, so that
+        # any local include dirs take precedence.
+        self.include_dirs.extend(py_include.split(os.path.pathsep))
+        if plat_py_include != py_include:
+            self.include_dirs.extend(plat_py_include.split(os.path.pathsep))
+
+        self.ensure_string_list('libraries')
+        self.ensure_string_list('link_objects')
+
+        # Life is easier if we're not forever checking for None, so
+        # simplify these options to empty lists if unset
+        if self.libraries is None:
+            self.libraries = []
+        if self.library_dirs is None:
+            self.library_dirs = []
+        elif isinstance(self.library_dirs, str):
+            self.library_dirs = self.library_dirs.split(os.pathsep)
+
+        if self.rpath is None:
+            self.rpath = []
+        elif isinstance(self.rpath, str):
+            self.rpath = self.rpath.split(os.pathsep)
+
+        # for extensions under windows use different directories
+        # for Release and Debug builds.
+        # also Python's library directory must be appended to library_dirs
+        if os.name == 'nt' and not is_mingw():
+            # the 'libs' directory is for binary installs - we assume that
+            # must be the *native* platform.  But we don't really support
+            # cross-compiling via a binary install anyway, so we let it go.
+            self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
+            if sys.base_exec_prefix != sys.prefix:  # Issue 16116
+                self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
+            if self.debug:
+                self.build_temp = os.path.join(self.build_temp, "Debug")
+            else:
+                self.build_temp = os.path.join(self.build_temp, "Release")
+
+            # Append the source distribution include and library directories,
+            # this allows distutils on windows to work in the source tree
+            self.include_dirs.append(os.path.dirname(get_config_h_filename()))
+            self.library_dirs.append(sys.base_exec_prefix)
+
+            # Use the .lib files for the correct architecture
+            if self.plat_name == 'win32':
+                suffix = 'win32'
+            else:
+                # win-amd64
+                suffix = self.plat_name[4:]
+            new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
+            if suffix:
+                new_lib = os.path.join(new_lib, suffix)
+            self.library_dirs.append(new_lib)
+
+        # For extensions under Cygwin, Python's library directory must be
+        # appended to library_dirs
+        if sys.platform[:6] == 'cygwin':
+            if not sysconfig.python_build:
+                # building third party extensions
+                self.library_dirs.append(
+                    os.path.join(
+                        sys.prefix, "lib", "python" + get_python_version(), "config"
+                    )
+                )
+            else:
+                # building python standard extensions
+                self.library_dirs.append('.')
+
+        self.library_dirs.extend(self._python_lib_dir(sysconfig))
+
+        # The argument parsing will result in self.define being a string, but
+        # it has to be a list of 2-tuples.  All the preprocessor symbols
+        # specified by the 'define' option will be set to '1'.  Multiple
+        # symbols can be separated with commas.
+
+        if self.define:
+            defines = self.define.split(',')
+            self.define = [(symbol, '1') for symbol in defines]
+
+        # The option for macros to undefine is also a string from the
+        # option parsing, but has to be a list.  Multiple symbols can also
+        # be separated with commas here.
+        if self.undef:
+            self.undef = self.undef.split(',')
+
+        if self.swig_opts is None:
+            self.swig_opts = []
+        else:
+            self.swig_opts = self.swig_opts.split(' ')
+
+        # Finally add the user include and library directories if requested
+        if self.user:
+            user_include = os.path.join(USER_BASE, "include")
+            user_lib = os.path.join(USER_BASE, "lib")
+            if os.path.isdir(user_include):
+                self.include_dirs.append(user_include)
+            if os.path.isdir(user_lib):
+                self.library_dirs.append(user_lib)
+                self.rpath.append(user_lib)
+
+        if isinstance(self.parallel, str):
+            try:
+                self.parallel = int(self.parallel)
+            except ValueError:
+                raise DistutilsOptionError("parallel should be an integer")
+
+    def run(self) -> None:  # noqa: C901
+        # 'self.extensions', as supplied by setup.py, is a list of
+        # Extension instances.  See the documentation for Extension (in
+        # distutils.extension) for details.
+        #
+        # For backwards compatibility with Distutils 0.8.2 and earlier, we
+        # also allow the 'extensions' list to be a list of tuples:
+        #    (ext_name, build_info)
+        # where build_info is a dictionary containing everything that
+        # Extension instances do except the name, with a few things being
+        # differently named.  We convert these 2-tuples to Extension
+        # instances as needed.
+
+        if not self.extensions:
+            return
+
+        # If we were asked to build any C/C++ libraries, make sure that the
+        # directory where we put them is in the library search path for
+        # linking extensions.
+        if self.distribution.has_c_libraries():
+            build_clib = self.get_finalized_command('build_clib')
+            self.libraries.extend(build_clib.get_library_names() or [])
+            self.library_dirs.append(build_clib.build_clib)
+
+        # Setup the CCompiler object that we'll use to do all the
+        # compiling and linking
+        self.compiler = new_compiler(
+            compiler=self.compiler,
+            verbose=self.verbose,
+            dry_run=self.dry_run,
+            force=self.force,
+        )
+        customize_compiler(self.compiler)
+        # If we are cross-compiling, init the compiler now (if we are not
+        # cross-compiling, init would not hurt, but people may rely on
+        # late initialization of compiler even if they shouldn't...)
+        if os.name == 'nt' and self.plat_name != get_platform():
+            self.compiler.initialize(self.plat_name)
+
+        # The official Windows free threaded Python installer doesn't set
+        # Py_GIL_DISABLED because its pyconfig.h is shared with the
+        # default build, so define it here (pypa/setuptools#4662).
+        if os.name == 'nt' and is_freethreaded():
+            self.compiler.define_macro('Py_GIL_DISABLED', '1')
+
+        # And make sure that any compile/link-related options (which might
+        # come from the command-line or from the setup script) are set in
+        # that CCompiler object -- that way, they automatically apply to
+        # all compiling and linking done here.
+        if self.include_dirs is not None:
+            self.compiler.set_include_dirs(self.include_dirs)
+        if self.define is not None:
+            # 'define' option is a list of (name,value) tuples
+            for name, value in self.define:
+                self.compiler.define_macro(name, value)
+        if self.undef is not None:
+            for macro in self.undef:
+                self.compiler.undefine_macro(macro)
+        if self.libraries is not None:
+            self.compiler.set_libraries(self.libraries)
+        if self.library_dirs is not None:
+            self.compiler.set_library_dirs(self.library_dirs)
+        if self.rpath is not None:
+            self.compiler.set_runtime_library_dirs(self.rpath)
+        if self.link_objects is not None:
+            self.compiler.set_link_objects(self.link_objects)
+
+        # Now actually compile and link everything.
+        self.build_extensions()
+
+    def check_extensions_list(self, extensions) -> None:  # noqa: C901
+        """Ensure that the list of extensions (presumably provided as a
+        command option 'extensions') is valid, i.e. it is a list of
+        Extension objects.  We also support the old-style list of 2-tuples,
+        where the tuples are (ext_name, build_info), which are converted to
+        Extension instances here.
+
+        Raise DistutilsSetupError if the structure is invalid anywhere;
+        just returns otherwise.
+        """
+        if not isinstance(extensions, list):
+            raise DistutilsSetupError(
+                "'ext_modules' option must be a list of Extension instances"
+            )
+
+        for i, ext in enumerate(extensions):
+            if isinstance(ext, Extension):
+                continue  # OK! (assume type-checking done
+                # by Extension constructor)
+
+            if not isinstance(ext, tuple) or len(ext) != 2:
+                raise DistutilsSetupError(
+                    "each element of 'ext_modules' option must be an "
+                    "Extension instance or 2-tuple"
+                )
+
+            ext_name, build_info = ext
+
+            log.warning(
+                "old-style (ext_name, build_info) tuple found in "
+                "ext_modules for extension '%s' "
+                "-- please convert to Extension instance",
+                ext_name,
+            )
+
+            if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)):
+                raise DistutilsSetupError(
+                    "first element of each tuple in 'ext_modules' "
+                    "must be the extension name (a string)"
+                )
+
+            if not isinstance(build_info, dict):
+                raise DistutilsSetupError(
+                    "second element of each tuple in 'ext_modules' "
+                    "must be a dictionary (build info)"
+                )
+
+            # OK, the (ext_name, build_info) dict is type-safe: convert it
+            # to an Extension instance.
+            ext = Extension(ext_name, build_info['sources'])
+
+            # Easy stuff: one-to-one mapping from dict elements to
+            # instance attributes.
+            for key in (
+                'include_dirs',
+                'library_dirs',
+                'libraries',
+                'extra_objects',
+                'extra_compile_args',
+                'extra_link_args',
+            ):
+                val = build_info.get(key)
+                if val is not None:
+                    setattr(ext, key, val)
+
+            # Medium-easy stuff: same syntax/semantics, different names.
+            ext.runtime_library_dirs = build_info.get('rpath')
+            if 'def_file' in build_info:
+                log.warning("'def_file' element of build info dict no longer supported")
+
+            # Non-trivial stuff: 'macros' split into 'define_macros'
+            # and 'undef_macros'.
+            macros = build_info.get('macros')
+            if macros:
+                ext.define_macros = []
+                ext.undef_macros = []
+                for macro in macros:
+                    if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
+                        raise DistutilsSetupError(
+                            "'macros' element of build info dict must be 1- or 2-tuple"
+                        )
+                    if len(macro) == 1:
+                        ext.undef_macros.append(macro[0])
+                    elif len(macro) == 2:
+                        ext.define_macros.append(macro)
+
+            extensions[i] = ext
+
+    def get_source_files(self):
+        self.check_extensions_list(self.extensions)
+        filenames = []
+
+        # Wouldn't it be neat if we knew the names of header files too...
+        for ext in self.extensions:
+            filenames.extend(ext.sources)
+        return filenames
+
+    def get_outputs(self):
+        # Sanity check the 'extensions' list -- can't assume this is being
+        # done in the same run as a 'build_extensions()' call (in fact, we
+        # can probably assume that it *isn't*!).
+        self.check_extensions_list(self.extensions)
+
+        # And build the list of output (built) filenames.  Note that this
+        # ignores the 'inplace' flag, and assumes everything goes in the
+        # "build" tree.
+        return [self.get_ext_fullpath(ext.name) for ext in self.extensions]
+
+    def build_extensions(self) -> None:
+        # First, sanity-check the 'extensions' list
+        self.check_extensions_list(self.extensions)
+        if self.parallel:
+            self._build_extensions_parallel()
+        else:
+            self._build_extensions_serial()
+
+    def _build_extensions_parallel(self):
+        workers = self.parallel
+        if self.parallel is True:
+            workers = os.cpu_count()  # may return None
+        try:
+            from concurrent.futures import ThreadPoolExecutor
+        except ImportError:
+            workers = None
+
+        if workers is None:
+            self._build_extensions_serial()
+            return
+
+        with ThreadPoolExecutor(max_workers=workers) as executor:
+            futures = [
+                executor.submit(self.build_extension, ext) for ext in self.extensions
+            ]
+            for ext, fut in zip(self.extensions, futures):
+                with self._filter_build_errors(ext):
+                    fut.result()
+
+    def _build_extensions_serial(self):
+        for ext in self.extensions:
+            with self._filter_build_errors(ext):
+                self.build_extension(ext)
+
+    @contextlib.contextmanager
+    def _filter_build_errors(self, ext):
+        try:
+            yield
+        except (CCompilerError, DistutilsError, CompileError) as e:
+            if not ext.optional:
+                raise
+            self.warn(f'building extension "{ext.name}" failed: {e}')
+
+    def build_extension(self, ext) -> None:
+        sources = ext.sources
+        if sources is None or not isinstance(sources, (list, tuple)):
+            raise DistutilsSetupError(
+                f"in 'ext_modules' option (extension '{ext.name}'), "
+                "'sources' must be present and must be "
+                "a list of source filenames"
+            )
+        # sort to make the resulting .so file build reproducible
+        sources = sorted(sources)
+
+        ext_path = self.get_ext_fullpath(ext.name)
+        depends = sources + ext.depends
+        if not (self.force or newer_group(depends, ext_path, 'newer')):
+            log.debug("skipping '%s' extension (up-to-date)", ext.name)
+            return
+        else:
+            log.info("building '%s' extension", ext.name)
+
+        # First, scan the sources for SWIG definition files (.i), run
+        # SWIG on 'em to create .c files, and modify the sources list
+        # accordingly.
+        sources = self.swig_sources(sources, ext)
+
+        # Next, compile the source code to object files.
+
+        # XXX not honouring 'define_macros' or 'undef_macros' -- the
+        # CCompiler API needs to change to accommodate this, and I
+        # want to do one thing at a time!
+
+        # Two possible sources for extra compiler arguments:
+        #   - 'extra_compile_args' in Extension object
+        #   - CFLAGS environment variable (not particularly
+        #     elegant, but people seem to expect it and I
+        #     guess it's useful)
+        # The environment variable should take precedence, and
+        # any sensible compiler will give precedence to later
+        # command line args.  Hence we combine them in order:
+        extra_args = ext.extra_compile_args or []
+
+        macros = ext.define_macros[:]
+        for undef in ext.undef_macros:
+            macros.append((undef,))
+
+        objects = self.compiler.compile(
+            sources,
+            output_dir=self.build_temp,
+            macros=macros,
+            include_dirs=ext.include_dirs,
+            debug=self.debug,
+            extra_postargs=extra_args,
+            depends=ext.depends,
+        )
+
+        # XXX outdated variable, kept here in case third-part code
+        # needs it.
+        self._built_objects = objects[:]
+
+        # Now link the object files together into a "shared object" --
+        # of course, first we have to figure out all the other things
+        # that go into the mix.
+        if ext.extra_objects:
+            objects.extend(ext.extra_objects)
+        extra_args = ext.extra_link_args or []
+
+        # Detect target language, if not provided
+        language = ext.language or self.compiler.detect_language(sources)
+
+        self.compiler.link_shared_object(
+            objects,
+            ext_path,
+            libraries=self.get_libraries(ext),
+            library_dirs=ext.library_dirs,
+            runtime_library_dirs=ext.runtime_library_dirs,
+            extra_postargs=extra_args,
+            export_symbols=self.get_export_symbols(ext),
+            debug=self.debug,
+            build_temp=self.build_temp,
+            target_lang=language,
+        )
+
+    def swig_sources(self, sources, extension):
+        """Walk the list of source files in 'sources', looking for SWIG
+        interface (.i) files.  Run SWIG on all that are found, and
+        return a modified 'sources' list with SWIG source files replaced
+        by the generated C (or C++) files.
+        """
+        new_sources = []
+        swig_sources = []
+        swig_targets = {}
+
+        # XXX this drops generated C/C++ files into the source tree, which
+        # is fine for developers who want to distribute the generated
+        # source -- but there should be an option to put SWIG output in
+        # the temp dir.
+
+        if self.swig_cpp:
+            log.warning("--swig-cpp is deprecated - use --swig-opts=-c++")
+
+        if (
+            self.swig_cpp
+            or ('-c++' in self.swig_opts)
+            or ('-c++' in extension.swig_opts)
+        ):
+            target_ext = '.cpp'
+        else:
+            target_ext = '.c'
+
+        for source in sources:
+            (base, ext) = os.path.splitext(source)
+            if ext == ".i":  # SWIG interface file
+                new_sources.append(base + '_wrap' + target_ext)
+                swig_sources.append(source)
+                swig_targets[source] = new_sources[-1]
+            else:
+                new_sources.append(source)
+
+        if not swig_sources:
+            return new_sources
+
+        swig = self.swig or self.find_swig()
+        swig_cmd = [swig, "-python"]
+        swig_cmd.extend(self.swig_opts)
+        if self.swig_cpp:
+            swig_cmd.append("-c++")
+
+        # Do not override commandline arguments
+        if not self.swig_opts:
+            swig_cmd.extend(extension.swig_opts)
+
+        for source in swig_sources:
+            target = swig_targets[source]
+            log.info("swigging %s to %s", source, target)
+            self.spawn(swig_cmd + ["-o", target, source])
+
+        return new_sources
+
+    def find_swig(self):
+        """Return the name of the SWIG executable.  On Unix, this is
+        just "swig" -- it should be in the PATH.  Tries a bit harder on
+        Windows.
+        """
+        if os.name == "posix":
+            return "swig"
+        elif os.name == "nt":
+            # Look for SWIG in its standard installation directory on
+            # Windows (or so I presume!).  If we find it there, great;
+            # if not, act like Unix and assume it's in the PATH.
+            for vers in ("1.3", "1.2", "1.1"):
+                fn = os.path.join(f"c:\\swig{vers}", "swig.exe")
+                if os.path.isfile(fn):
+                    return fn
+            else:
+                return "swig.exe"
+        else:
+            raise DistutilsPlatformError(
+                f"I don't know how to find (much less run) SWIG on platform '{os.name}'"
+            )
+
+    # -- Name generators -----------------------------------------------
+    # (extension names, filenames, whatever)
+    def get_ext_fullpath(self, ext_name: str) -> str:
+        """Returns the path of the filename for a given extension.
+
+        The file is located in `build_lib` or directly in the package
+        (inplace option).
+        """
+        fullname = self.get_ext_fullname(ext_name)
+        modpath = fullname.split('.')
+        filename = self.get_ext_filename(modpath[-1])
+
+        if not self.inplace:
+            # no further work needed
+            # returning :
+            #   build_dir/package/path/filename
+            filename = os.path.join(*modpath[:-1] + [filename])
+            return os.path.join(self.build_lib, filename)
+
+        # the inplace option requires to find the package directory
+        # using the build_py command for that
+        package = '.'.join(modpath[0:-1])
+        build_py = self.get_finalized_command('build_py')
+        package_dir = os.path.abspath(build_py.get_package_dir(package))
+
+        # returning
+        #   package_dir/filename
+        return os.path.join(package_dir, filename)
+
+    def get_ext_fullname(self, ext_name: str) -> str:
+        """Returns the fullname of a given extension name.
+
+        Adds the `package.` prefix"""
+        if self.package is None:
+            return ext_name
+        else:
+            return self.package + '.' + ext_name
+
+    def get_ext_filename(self, ext_name: str) -> str:
+        r"""Convert the name of an extension (eg. "foo.bar") into the name
+        of the file from which it will be loaded (eg. "foo/bar.so", or
+        "foo\bar.pyd").
+        """
+        from ..sysconfig import get_config_var
+
+        ext_path = ext_name.split('.')
+        ext_suffix = get_config_var('EXT_SUFFIX')
+        return os.path.join(*ext_path) + ext_suffix
+
+    def get_export_symbols(self, ext: Extension) -> list[str]:
+        """Return the list of symbols that a shared extension has to
+        export.  This either uses 'ext.export_symbols' or, if it's not
+        provided, "PyInit_" + module_name.  Only relevant on Windows, where
+        the .pyd file (DLL) must export the module "PyInit_" function.
+        """
+        name = self._get_module_name_for_symbol(ext)
+        try:
+            # Unicode module name support as defined in PEP-489
+            # https://peps.python.org/pep-0489/#export-hook-name
+            name.encode('ascii')
+        except UnicodeEncodeError:
+            suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
+        else:
+            suffix = "_" + name
+
+        initfunc_name = "PyInit" + suffix
+        if initfunc_name not in ext.export_symbols:
+            ext.export_symbols.append(initfunc_name)
+        return ext.export_symbols
+
+    def _get_module_name_for_symbol(self, ext):
+        # Package name should be used for `__init__` modules
+        # https://github.com/python/cpython/issues/80074
+        # https://github.com/pypa/setuptools/issues/4826
+        parts = ext.name.split(".")
+        if parts[-1] == "__init__" and len(parts) >= 2:
+            return parts[-2]
+        return parts[-1]
+
+    def get_libraries(self, ext: Extension) -> list[str]:  # noqa: C901
+        """Return the list of libraries to link against when building a
+        shared extension.  On most platforms, this is just 'ext.libraries';
+        on Windows, we add the Python library (eg. python20.dll).
+        """
+        # The python library is always needed on Windows.  For MSVC, this
+        # is redundant, since the library is mentioned in a pragma in
+        # pyconfig.h that MSVC groks.  The other Windows compilers all seem
+        # to need it mentioned explicitly, though, so that's what we do.
+        # Append '_d' to the python import library on debug builds.
+        if sys.platform == "win32" and not is_mingw():
+            from .._msvccompiler import MSVCCompiler
+
+            if not isinstance(self.compiler, MSVCCompiler):
+                template = "python%d%d"
+                if self.debug:
+                    template = template + '_d'
+                pythonlib = template % (
+                    sys.hexversion >> 24,
+                    (sys.hexversion >> 16) & 0xFF,
+                )
+                # don't extend ext.libraries, it may be shared with other
+                # extensions, it is a reference to the original list
+                return ext.libraries + [pythonlib]
+        else:
+            # On Android only the main executable and LD_PRELOADs are considered
+            # to be RTLD_GLOBAL, all the dependencies of the main executable
+            # remain RTLD_LOCAL and so the shared libraries must be linked with
+            # libpython when python is built with a shared python library (issue
+            # bpo-21536).
+            # On Cygwin (and if required, other POSIX-like platforms based on
+            # Windows like MinGW) it is simply necessary that all symbols in
+            # shared libraries are resolved at link time.
+            from ..sysconfig import get_config_var
+
+            link_libpython = False
+            if get_config_var('Py_ENABLE_SHARED'):
+                # A native build on an Android device or on Cygwin
+                if hasattr(sys, 'getandroidapilevel'):
+                    link_libpython = True
+                elif sys.platform == 'cygwin' or is_mingw():
+                    link_libpython = True
+                elif '_PYTHON_HOST_PLATFORM' in os.environ:
+                    # We are cross-compiling for one of the relevant platforms
+                    if get_config_var('ANDROID_API_LEVEL') != 0:
+                        link_libpython = True
+                    elif get_config_var('MACHDEP') == 'cygwin':
+                        link_libpython = True
+
+            if link_libpython:
+                ldversion = get_config_var('LDVERSION')
+                return ext.libraries + ['python' + ldversion]
+
+        return ext.libraries
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_py.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..a20b076fe7cca9140e05b1cf171b62155995f36e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_py.py
@@ -0,0 +1,407 @@
+"""distutils.command.build_py
+
+Implements the Distutils 'build_py' command."""
+
+import glob
+import importlib.util
+import os
+import sys
+from distutils._log import log
+from typing import ClassVar
+
+from ..core import Command
+from ..errors import DistutilsFileError, DistutilsOptionError
+from ..util import convert_path
+
+
+class build_py(Command):
+    description = "\"build\" pure Python modules (copy to build directory)"
+
+    user_options = [
+        ('build-lib=', 'd', "directory to \"build\" (copy) to"),
+        ('compile', 'c', "compile .py to .pyc"),
+        ('no-compile', None, "don't compile .py files [default]"),
+        (
+            'optimize=',
+            'O',
+            "also compile with optimization: -O1 for \"python -O\", "
+            "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+        ),
+        ('force', 'f', "forcibly build everything (ignore file timestamps)"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['compile', 'force']
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
+
+    def initialize_options(self):
+        self.build_lib = None
+        self.py_modules = None
+        self.package = None
+        self.package_data = None
+        self.package_dir = None
+        self.compile = False
+        self.optimize = 0
+        self.force = None
+
+    def finalize_options(self) -> None:
+        self.set_undefined_options(
+            'build', ('build_lib', 'build_lib'), ('force', 'force')
+        )
+
+        # Get the distribution options that are aliases for build_py
+        # options -- list of packages and list of modules.
+        self.packages = self.distribution.packages
+        self.py_modules = self.distribution.py_modules
+        self.package_data = self.distribution.package_data
+        self.package_dir = {}
+        if self.distribution.package_dir:
+            for name, path in self.distribution.package_dir.items():
+                self.package_dir[name] = convert_path(path)
+        self.data_files = self.get_data_files()
+
+        # Ick, copied straight from install_lib.py (fancy_getopt needs a
+        # type system!  Hell, *everything* needs a type system!!!)
+        if not isinstance(self.optimize, int):
+            try:
+                self.optimize = int(self.optimize)
+                assert 0 <= self.optimize <= 2
+            except (ValueError, AssertionError):
+                raise DistutilsOptionError("optimize must be 0, 1, or 2")
+
+    def run(self) -> None:
+        # XXX copy_file by default preserves atime and mtime.  IMHO this is
+        # the right thing to do, but perhaps it should be an option -- in
+        # particular, a site administrator might want installed files to
+        # reflect the time of installation rather than the last
+        # modification time before the installed release.
+
+        # XXX copy_file by default preserves mode, which appears to be the
+        # wrong thing to do: if a file is read-only in the working
+        # directory, we want it to be installed read/write so that the next
+        # installation of the same module distribution can overwrite it
+        # without problems.  (This might be a Unix-specific issue.)  Thus
+        # we turn off 'preserve_mode' when copying to the build directory,
+        # since the build directory is supposed to be exactly what the
+        # installation will look like (ie. we preserve mode when
+        # installing).
+
+        # Two options control which modules will be installed: 'packages'
+        # and 'py_modules'.  The former lets us work with whole packages, not
+        # specifying individual modules at all; the latter is for
+        # specifying modules one-at-a-time.
+
+        if self.py_modules:
+            self.build_modules()
+        if self.packages:
+            self.build_packages()
+            self.build_package_data()
+
+        self.byte_compile(self.get_outputs(include_bytecode=False))
+
+    def get_data_files(self):
+        """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
+        data = []
+        if not self.packages:
+            return data
+        for package in self.packages:
+            # Locate package source directory
+            src_dir = self.get_package_dir(package)
+
+            # Compute package build directory
+            build_dir = os.path.join(*([self.build_lib] + package.split('.')))
+
+            # Length of path to strip from found files
+            plen = 0
+            if src_dir:
+                plen = len(src_dir) + 1
+
+            # Strip directory from globbed filenames
+            filenames = [file[plen:] for file in self.find_data_files(package, src_dir)]
+            data.append((package, src_dir, build_dir, filenames))
+        return data
+
+    def find_data_files(self, package, src_dir):
+        """Return filenames for package's data files in 'src_dir'"""
+        globs = self.package_data.get('', []) + self.package_data.get(package, [])
+        files = []
+        for pattern in globs:
+            # Each pattern has to be converted to a platform-specific path
+            filelist = glob.glob(
+                os.path.join(glob.escape(src_dir), convert_path(pattern))
+            )
+            # Files that match more than one pattern are only added once
+            files.extend([
+                fn for fn in filelist if fn not in files and os.path.isfile(fn)
+            ])
+        return files
+
+    def build_package_data(self) -> None:
+        """Copy data files into build directory"""
+        for _package, src_dir, build_dir, filenames in self.data_files:
+            for filename in filenames:
+                target = os.path.join(build_dir, filename)
+                self.mkpath(os.path.dirname(target))
+                self.copy_file(
+                    os.path.join(src_dir, filename), target, preserve_mode=False
+                )
+
+    def get_package_dir(self, package):
+        """Return the directory, relative to the top of the source
+        distribution, where package 'package' should be found
+        (at least according to the 'package_dir' option, if any)."""
+        path = package.split('.')
+
+        if not self.package_dir:
+            if path:
+                return os.path.join(*path)
+            else:
+                return ''
+        else:
+            tail = []
+            while path:
+                try:
+                    pdir = self.package_dir['.'.join(path)]
+                except KeyError:
+                    tail.insert(0, path[-1])
+                    del path[-1]
+                else:
+                    tail.insert(0, pdir)
+                    return os.path.join(*tail)
+            else:
+                # Oops, got all the way through 'path' without finding a
+                # match in package_dir.  If package_dir defines a directory
+                # for the root (nameless) package, then fallback on it;
+                # otherwise, we might as well have not consulted
+                # package_dir at all, as we just use the directory implied
+                # by 'tail' (which should be the same as the original value
+                # of 'path' at this point).
+                pdir = self.package_dir.get('')
+                if pdir is not None:
+                    tail.insert(0, pdir)
+
+                if tail:
+                    return os.path.join(*tail)
+                else:
+                    return ''
+
+    def check_package(self, package, package_dir):
+        # Empty dir name means current directory, which we can probably
+        # assume exists.  Also, os.path.exists and isdir don't know about
+        # my "empty string means current dir" convention, so we have to
+        # circumvent them.
+        if package_dir != "":
+            if not os.path.exists(package_dir):
+                raise DistutilsFileError(
+                    f"package directory '{package_dir}' does not exist"
+                )
+            if not os.path.isdir(package_dir):
+                raise DistutilsFileError(
+                    f"supposed package directory '{package_dir}' exists, "
+                    "but is not a directory"
+                )
+
+        # Directories without __init__.py are namespace packages (PEP 420).
+        if package:
+            init_py = os.path.join(package_dir, "__init__.py")
+            if os.path.isfile(init_py):
+                return init_py
+
+        # Either not in a package at all (__init__.py not expected), or
+        # __init__.py doesn't exist -- so don't return the filename.
+        return None
+
+    def check_module(self, module, module_file):
+        if not os.path.isfile(module_file):
+            log.warning("file %s (for module %s) not found", module_file, module)
+            return False
+        else:
+            return True
+
+    def find_package_modules(self, package, package_dir):
+        self.check_package(package, package_dir)
+        module_files = glob.glob(os.path.join(glob.escape(package_dir), "*.py"))
+        modules = []
+        setup_script = os.path.abspath(self.distribution.script_name)
+
+        for f in module_files:
+            abs_f = os.path.abspath(f)
+            if abs_f != setup_script:
+                module = os.path.splitext(os.path.basename(f))[0]
+                modules.append((package, module, f))
+            else:
+                self.debug_print(f"excluding {setup_script}")
+        return modules
+
+    def find_modules(self):
+        """Finds individually-specified Python modules, ie. those listed by
+        module name in 'self.py_modules'.  Returns a list of tuples (package,
+        module_base, filename): 'package' is a tuple of the path through
+        package-space to the module; 'module_base' is the bare (no
+        packages, no dots) module name, and 'filename' is the path to the
+        ".py" file (relative to the distribution root) that implements the
+        module.
+        """
+        # Map package names to tuples of useful info about the package:
+        #    (package_dir, checked)
+        # package_dir - the directory where we'll find source files for
+        #   this package
+        # checked - true if we have checked that the package directory
+        #   is valid (exists, contains __init__.py, ... ?)
+        packages = {}
+
+        # List of (package, module, filename) tuples to return
+        modules = []
+
+        # We treat modules-in-packages almost the same as toplevel modules,
+        # just the "package" for a toplevel is empty (either an empty
+        # string or empty list, depending on context).  Differences:
+        #   - don't check for __init__.py in directory for empty package
+        for module in self.py_modules:
+            path = module.split('.')
+            package = '.'.join(path[0:-1])
+            module_base = path[-1]
+
+            try:
+                (package_dir, checked) = packages[package]
+            except KeyError:
+                package_dir = self.get_package_dir(package)
+                checked = False
+
+            if not checked:
+                init_py = self.check_package(package, package_dir)
+                packages[package] = (package_dir, 1)
+                if init_py:
+                    modules.append((package, "__init__", init_py))
+
+            # XXX perhaps we should also check for just .pyc files
+            # (so greedy closed-source bastards can distribute Python
+            # modules too)
+            module_file = os.path.join(package_dir, module_base + ".py")
+            if not self.check_module(module, module_file):
+                continue
+
+            modules.append((package, module_base, module_file))
+
+        return modules
+
+    def find_all_modules(self):
+        """Compute the list of all modules that will be built, whether
+        they are specified one-module-at-a-time ('self.py_modules') or
+        by whole packages ('self.packages').  Return a list of tuples
+        (package, module, module_file), just like 'find_modules()' and
+        'find_package_modules()' do."""
+        modules = []
+        if self.py_modules:
+            modules.extend(self.find_modules())
+        if self.packages:
+            for package in self.packages:
+                package_dir = self.get_package_dir(package)
+                m = self.find_package_modules(package, package_dir)
+                modules.extend(m)
+        return modules
+
+    def get_source_files(self):
+        return [module[-1] for module in self.find_all_modules()]
+
+    def get_module_outfile(self, build_dir, package, module):
+        outfile_path = [build_dir] + list(package) + [module + ".py"]
+        return os.path.join(*outfile_path)
+
+    def get_outputs(self, include_bytecode: bool = True) -> list[str]:
+        modules = self.find_all_modules()
+        outputs = []
+        for package, module, _module_file in modules:
+            package = package.split('.')
+            filename = self.get_module_outfile(self.build_lib, package, module)
+            outputs.append(filename)
+            if include_bytecode:
+                if self.compile:
+                    outputs.append(
+                        importlib.util.cache_from_source(filename, optimization='')
+                    )
+                if self.optimize > 0:
+                    outputs.append(
+                        importlib.util.cache_from_source(
+                            filename, optimization=self.optimize
+                        )
+                    )
+
+        outputs += [
+            os.path.join(build_dir, filename)
+            for package, src_dir, build_dir, filenames in self.data_files
+            for filename in filenames
+        ]
+
+        return outputs
+
+    def build_module(self, module, module_file, package):
+        if isinstance(package, str):
+            package = package.split('.')
+        elif not isinstance(package, (list, tuple)):
+            raise TypeError(
+                "'package' must be a string (dot-separated), list, or tuple"
+            )
+
+        # Now put the module source file into the "build" area -- this is
+        # easy, we just copy it somewhere under self.build_lib (the build
+        # directory for Python source).
+        outfile = self.get_module_outfile(self.build_lib, package, module)
+        dir = os.path.dirname(outfile)
+        self.mkpath(dir)
+        return self.copy_file(module_file, outfile, preserve_mode=False)
+
+    def build_modules(self) -> None:
+        modules = self.find_modules()
+        for package, module, module_file in modules:
+            # Now "build" the module -- ie. copy the source file to
+            # self.build_lib (the build directory for Python source).
+            # (Actually, it gets copied to the directory for this package
+            # under self.build_lib.)
+            self.build_module(module, module_file, package)
+
+    def build_packages(self) -> None:
+        for package in self.packages:
+            # Get list of (package, module, module_file) tuples based on
+            # scanning the package directory.  'package' is only included
+            # in the tuple so that 'find_modules()' and
+            # 'find_package_tuples()' have a consistent interface; it's
+            # ignored here (apart from a sanity check).  Also, 'module' is
+            # the *unqualified* module name (ie. no dots, no package -- we
+            # already know its package!), and 'module_file' is the path to
+            # the .py file, relative to the current directory
+            # (ie. including 'package_dir').
+            package_dir = self.get_package_dir(package)
+            modules = self.find_package_modules(package, package_dir)
+
+            # Now loop over the modules we found, "building" each one (just
+            # copy it to self.build_lib).
+            for package_, module, module_file in modules:
+                assert package == package_
+                self.build_module(module, module_file, package)
+
+    def byte_compile(self, files) -> None:
+        if sys.dont_write_bytecode:
+            self.warn('byte-compiling is disabled, skipping.')
+            return
+
+        from ..util import byte_compile
+
+        prefix = self.build_lib
+        if prefix[-1] != os.sep:
+            prefix = prefix + os.sep
+
+        # XXX this code is essentially the same as the 'byte_compile()
+        # method of the "install_lib" command, except for the determination
+        # of the 'prefix' string.  Hmmm.
+        if self.compile:
+            byte_compile(
+                files, optimize=0, force=self.force, prefix=prefix, dry_run=self.dry_run
+            )
+        if self.optimize > 0:
+            byte_compile(
+                files,
+                optimize=self.optimize,
+                force=self.force,
+                prefix=prefix,
+                dry_run=self.dry_run,
+            )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_scripts.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_scripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..b86ee6e6ba6a4613f552f6d2f19b8c5157391d8d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/build_scripts.py
@@ -0,0 +1,160 @@
+"""distutils.command.build_scripts
+
+Implements the Distutils 'build_scripts' command."""
+
+import os
+import re
+import tokenize
+from distutils._log import log
+from stat import ST_MODE
+from typing import ClassVar
+
+from .._modified import newer
+from ..core import Command
+from ..util import convert_path
+
+shebang_pattern = re.compile('^#!.*python[0-9.]*([ \t].*)?$')
+"""
+Pattern matching a Python interpreter indicated in first line of a script.
+"""
+
+# for Setuptools compatibility
+first_line_re = shebang_pattern
+
+
+class build_scripts(Command):
+    description = "\"build\" scripts (copy and fixup #! line)"
+
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('build-dir=', 'd', "directory to \"build\" (copy) to"),
+        ('force', 'f', "forcibly build everything (ignore file timestamps"),
+        ('executable=', 'e', "specify final destination interpreter path"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['force']
+
+    def initialize_options(self):
+        self.build_dir = None
+        self.scripts = None
+        self.force = None
+        self.executable = None
+
+    def finalize_options(self):
+        self.set_undefined_options(
+            'build',
+            ('build_scripts', 'build_dir'),
+            ('force', 'force'),
+            ('executable', 'executable'),
+        )
+        self.scripts = self.distribution.scripts
+
+    def get_source_files(self):
+        return self.scripts
+
+    def run(self):
+        if not self.scripts:
+            return
+        self.copy_scripts()
+
+    def copy_scripts(self):
+        """
+        Copy each script listed in ``self.scripts``.
+
+        If a script is marked as a Python script (first line matches
+        'shebang_pattern', i.e. starts with ``#!`` and contains
+        "python"), then adjust in the copy the first line to refer to
+        the current Python interpreter.
+        """
+        self.mkpath(self.build_dir)
+        outfiles = []
+        updated_files = []
+        for script in self.scripts:
+            self._copy_script(script, outfiles, updated_files)
+
+        self._change_modes(outfiles)
+
+        return outfiles, updated_files
+
+    def _copy_script(self, script, outfiles, updated_files):
+        shebang_match = None
+        script = convert_path(script)
+        outfile = os.path.join(self.build_dir, os.path.basename(script))
+        outfiles.append(outfile)
+
+        if not self.force and not newer(script, outfile):
+            log.debug("not copying %s (up-to-date)", script)
+            return
+
+        # Always open the file, but ignore failures in dry-run mode
+        # in order to attempt to copy directly.
+        try:
+            f = tokenize.open(script)
+        except OSError:
+            if not self.dry_run:
+                raise
+            f = None
+        else:
+            first_line = f.readline()
+            if not first_line:
+                self.warn(f"{script} is an empty file (skipping)")
+                return
+
+            shebang_match = shebang_pattern.match(first_line)
+
+        updated_files.append(outfile)
+        if shebang_match:
+            log.info("copying and adjusting %s -> %s", script, self.build_dir)
+            if not self.dry_run:
+                post_interp = shebang_match.group(1) or ''
+                shebang = "#!" + self.executable + post_interp + "\n"
+                self._validate_shebang(shebang, f.encoding)
+                with open(outfile, "w", encoding=f.encoding) as outf:
+                    outf.write(shebang)
+                    outf.writelines(f.readlines())
+            if f:
+                f.close()
+        else:
+            if f:
+                f.close()
+            self.copy_file(script, outfile)
+
+    def _change_modes(self, outfiles):
+        if os.name != 'posix':
+            return
+
+        for file in outfiles:
+            self._change_mode(file)
+
+    def _change_mode(self, file):
+        if self.dry_run:
+            log.info("changing mode of %s", file)
+            return
+
+        oldmode = os.stat(file)[ST_MODE] & 0o7777
+        newmode = (oldmode | 0o555) & 0o7777
+        if newmode != oldmode:
+            log.info("changing mode of %s from %o to %o", file, oldmode, newmode)
+            os.chmod(file, newmode)
+
+    @staticmethod
+    def _validate_shebang(shebang, encoding):
+        # Python parser starts to read a script using UTF-8 until
+        # it gets a #coding:xxx cookie. The shebang has to be the
+        # first line of a file, the #coding:xxx cookie cannot be
+        # written before. So the shebang has to be encodable to
+        # UTF-8.
+        try:
+            shebang.encode('utf-8')
+        except UnicodeEncodeError:
+            raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")
+
+        # If the script is encoded to a custom encoding (use a
+        # #coding:xxx cookie), the shebang has to be encodable to
+        # the script encoding too.
+        try:
+            shebang.encode(encoding)
+        except UnicodeEncodeError:
+            raise ValueError(
+                f"The shebang ({shebang!r}) is not encodable "
+                f"to the script encoding ({encoding})"
+            )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/check.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/check.py
new file mode 100644
index 0000000000000000000000000000000000000000..58a823dd3904cf105ed432e458a45d94948fbb4c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/check.py
@@ -0,0 +1,152 @@
+"""distutils.command.check
+
+Implements the Distutils 'check' command.
+"""
+
+import contextlib
+from typing import ClassVar
+
+from ..core import Command
+from ..errors import DistutilsSetupError
+
+with contextlib.suppress(ImportError):
+    import docutils.frontend
+    import docutils.nodes
+    import docutils.parsers.rst
+    import docutils.utils
+
+    class SilentReporter(docutils.utils.Reporter):
+        def __init__(
+            self,
+            source,
+            report_level,
+            halt_level,
+            stream=None,
+            debug=False,
+            encoding='ascii',
+            error_handler='replace',
+        ):
+            self.messages = []
+            super().__init__(
+                source, report_level, halt_level, stream, debug, encoding, error_handler
+            )
+
+        def system_message(self, level, message, *children, **kwargs):
+            self.messages.append((level, message, children, kwargs))
+            return docutils.nodes.system_message(
+                message, *children, level=level, type=self.levels[level], **kwargs
+            )
+
+
+class check(Command):
+    """This command checks the meta-data of the package."""
+
+    description = "perform some checks on the package"
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('metadata', 'm', 'Verify meta-data'),
+        (
+            'restructuredtext',
+            'r',
+            'Checks if long string meta-data syntax are reStructuredText-compliant',
+        ),
+        ('strict', 's', 'Will exit with an error if a check fails'),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['metadata', 'restructuredtext', 'strict']
+
+    def initialize_options(self):
+        """Sets default values for options."""
+        self.restructuredtext = False
+        self.metadata = 1
+        self.strict = False
+        self._warnings = 0
+
+    def finalize_options(self):
+        pass
+
+    def warn(self, msg):
+        """Counts the number of warnings that occurs."""
+        self._warnings += 1
+        return Command.warn(self, msg)
+
+    def run(self):
+        """Runs the command."""
+        # perform the various tests
+        if self.metadata:
+            self.check_metadata()
+        if self.restructuredtext:
+            if 'docutils' in globals():
+                try:
+                    self.check_restructuredtext()
+                except TypeError as exc:
+                    raise DistutilsSetupError(str(exc))
+            elif self.strict:
+                raise DistutilsSetupError('The docutils package is needed.')
+
+        # let's raise an error in strict mode, if we have at least
+        # one warning
+        if self.strict and self._warnings > 0:
+            raise DistutilsSetupError('Please correct your package.')
+
+    def check_metadata(self):
+        """Ensures that all required elements of meta-data are supplied.
+
+        Required fields:
+            name, version
+
+        Warns if any are missing.
+        """
+        metadata = self.distribution.metadata
+
+        missing = [
+            attr for attr in ('name', 'version') if not getattr(metadata, attr, None)
+        ]
+
+        if missing:
+            self.warn("missing required meta-data: {}".format(', '.join(missing)))
+
+    def check_restructuredtext(self):
+        """Checks if the long string fields are reST-compliant."""
+        data = self.distribution.get_long_description()
+        for warning in self._check_rst_data(data):
+            line = warning[-1].get('line')
+            if line is None:
+                warning = warning[1]
+            else:
+                warning = f'{warning[1]} (line {line})'
+            self.warn(warning)
+
+    def _check_rst_data(self, data):
+        """Returns warnings when the provided data doesn't compile."""
+        # the include and csv_table directives need this to be a path
+        source_path = self.distribution.script_name or 'setup.py'
+        parser = docutils.parsers.rst.Parser()
+        settings = docutils.frontend.OptionParser(
+            components=(docutils.parsers.rst.Parser,)
+        ).get_default_values()
+        settings.tab_width = 4
+        settings.pep_references = None
+        settings.rfc_references = None
+        reporter = SilentReporter(
+            source_path,
+            settings.report_level,
+            settings.halt_level,
+            stream=settings.warning_stream,
+            debug=settings.debug,
+            encoding=settings.error_encoding,
+            error_handler=settings.error_encoding_error_handler,
+        )
+
+        document = docutils.nodes.document(settings, reporter, source=source_path)
+        document.note_source(source_path, -1)
+        try:
+            parser.parse(data, document)
+        except (AttributeError, TypeError) as e:
+            reporter.messages.append((
+                -1,
+                f'Could not finish the parsing: {e}.',
+                '',
+                {},
+            ))
+
+        return reporter.messages
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/clean.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/clean.py
new file mode 100644
index 0000000000000000000000000000000000000000..23427aba21132ec16122ec17b54794203b02baa5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/clean.py
@@ -0,0 +1,77 @@
+"""distutils.command.clean
+
+Implements the Distutils 'clean' command."""
+
+# contributed by Bastian Kleineidam , added 2000-03-18
+
+import os
+from distutils._log import log
+from typing import ClassVar
+
+from ..core import Command
+from ..dir_util import remove_tree
+
+
+class clean(Command):
+    description = "clean up temporary files from 'build' command"
+    user_options = [
+        ('build-base=', 'b', "base build directory [default: 'build.build-base']"),
+        (
+            'build-lib=',
+            None,
+            "build directory for all modules [default: 'build.build-lib']",
+        ),
+        ('build-temp=', 't', "temporary build directory [default: 'build.build-temp']"),
+        (
+            'build-scripts=',
+            None,
+            "build directory for scripts [default: 'build.build-scripts']",
+        ),
+        ('bdist-base=', None, "temporary directory for built distributions"),
+        ('all', 'a', "remove all build output, not just temporary by-products"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['all']
+
+    def initialize_options(self):
+        self.build_base = None
+        self.build_lib = None
+        self.build_temp = None
+        self.build_scripts = None
+        self.bdist_base = None
+        self.all = None
+
+    def finalize_options(self):
+        self.set_undefined_options(
+            'build',
+            ('build_base', 'build_base'),
+            ('build_lib', 'build_lib'),
+            ('build_scripts', 'build_scripts'),
+            ('build_temp', 'build_temp'),
+        )
+        self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
+
+    def run(self):
+        # remove the build/temp. directory (unless it's already
+        # gone)
+        if os.path.exists(self.build_temp):
+            remove_tree(self.build_temp, dry_run=self.dry_run)
+        else:
+            log.debug("'%s' does not exist -- can't clean it", self.build_temp)
+
+        if self.all:
+            # remove build directories
+            for directory in (self.build_lib, self.bdist_base, self.build_scripts):
+                if os.path.exists(directory):
+                    remove_tree(directory, dry_run=self.dry_run)
+                else:
+                    log.warning("'%s' does not exist -- can't clean it", directory)
+
+        # just for the heck of it, try to remove the base build directory:
+        # we might have emptied it right now, but if not we don't care
+        if not self.dry_run:
+            try:
+                os.rmdir(self.build_base)
+                log.info("removing '%s'", self.build_base)
+            except OSError:
+                pass
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/config.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..c825765c873f04e85b8c38869f0b3e5e416a2dad
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/config.py
@@ -0,0 +1,358 @@
+"""distutils.command.config
+
+Implements the Distutils 'config' command, a (mostly) empty command class
+that exists mainly to be sub-classed by specific module distributions and
+applications.  The idea is that while every "config" command is different,
+at least they're all named the same, and users always see "config" in the
+list of standard commands.  Also, this is a good place to put common
+configure-like tasks: "try to compile this C code", or "figure out where
+this header file lives".
+"""
+
+from __future__ import annotations
+
+import os
+import pathlib
+import re
+from collections.abc import Sequence
+from distutils._log import log
+
+from ..ccompiler import CCompiler, CompileError, LinkError, new_compiler
+from ..core import Command
+from ..errors import DistutilsExecError
+from ..sysconfig import customize_compiler
+
+LANG_EXT = {"c": ".c", "c++": ".cxx"}
+
+
+class config(Command):
+    description = "prepare to build"
+
+    user_options = [
+        ('compiler=', None, "specify the compiler type"),
+        ('cc=', None, "specify the compiler executable"),
+        ('include-dirs=', 'I', "list of directories to search for header files"),
+        ('define=', 'D', "C preprocessor macros to define"),
+        ('undef=', 'U', "C preprocessor macros to undefine"),
+        ('libraries=', 'l', "external C libraries to link with"),
+        ('library-dirs=', 'L', "directories to search for external C libraries"),
+        ('noisy', None, "show every action (compile, link, run, ...) taken"),
+        (
+            'dump-source',
+            None,
+            "dump generated source files before attempting to compile them",
+        ),
+    ]
+
+    # The three standard command methods: since the "config" command
+    # does nothing by default, these are empty.
+
+    def initialize_options(self):
+        self.compiler = None
+        self.cc = None
+        self.include_dirs = None
+        self.libraries = None
+        self.library_dirs = None
+
+        # maximal output for now
+        self.noisy = 1
+        self.dump_source = 1
+
+        # list of temporary files generated along-the-way that we have
+        # to clean at some point
+        self.temp_files = []
+
+    def finalize_options(self):
+        if self.include_dirs is None:
+            self.include_dirs = self.distribution.include_dirs or []
+        elif isinstance(self.include_dirs, str):
+            self.include_dirs = self.include_dirs.split(os.pathsep)
+
+        if self.libraries is None:
+            self.libraries = []
+        elif isinstance(self.libraries, str):
+            self.libraries = [self.libraries]
+
+        if self.library_dirs is None:
+            self.library_dirs = []
+        elif isinstance(self.library_dirs, str):
+            self.library_dirs = self.library_dirs.split(os.pathsep)
+
+    def run(self):
+        pass
+
+    # Utility methods for actual "config" commands.  The interfaces are
+    # loosely based on Autoconf macros of similar names.  Sub-classes
+    # may use these freely.
+
+    def _check_compiler(self):
+        """Check that 'self.compiler' really is a CCompiler object;
+        if not, make it one.
+        """
+        if not isinstance(self.compiler, CCompiler):
+            self.compiler = new_compiler(
+                compiler=self.compiler, dry_run=self.dry_run, force=True
+            )
+            customize_compiler(self.compiler)
+            if self.include_dirs:
+                self.compiler.set_include_dirs(self.include_dirs)
+            if self.libraries:
+                self.compiler.set_libraries(self.libraries)
+            if self.library_dirs:
+                self.compiler.set_library_dirs(self.library_dirs)
+
+    def _gen_temp_sourcefile(self, body, headers, lang):
+        filename = "_configtest" + LANG_EXT[lang]
+        with open(filename, "w", encoding='utf-8') as file:
+            if headers:
+                for header in headers:
+                    file.write(f"#include <{header}>\n")
+                file.write("\n")
+            file.write(body)
+            if body[-1] != "\n":
+                file.write("\n")
+        return filename
+
+    def _preprocess(self, body, headers, include_dirs, lang):
+        src = self._gen_temp_sourcefile(body, headers, lang)
+        out = "_configtest.i"
+        self.temp_files.extend([src, out])
+        self.compiler.preprocess(src, out, include_dirs=include_dirs)
+        return (src, out)
+
+    def _compile(self, body, headers, include_dirs, lang):
+        src = self._gen_temp_sourcefile(body, headers, lang)
+        if self.dump_source:
+            dump_file(src, f"compiling '{src}':")
+        (obj,) = self.compiler.object_filenames([src])
+        self.temp_files.extend([src, obj])
+        self.compiler.compile([src], include_dirs=include_dirs)
+        return (src, obj)
+
+    def _link(self, body, headers, include_dirs, libraries, library_dirs, lang):
+        (src, obj) = self._compile(body, headers, include_dirs, lang)
+        prog = os.path.splitext(os.path.basename(src))[0]
+        self.compiler.link_executable(
+            [obj],
+            prog,
+            libraries=libraries,
+            library_dirs=library_dirs,
+            target_lang=lang,
+        )
+
+        if self.compiler.exe_extension is not None:
+            prog = prog + self.compiler.exe_extension
+        self.temp_files.append(prog)
+
+        return (src, obj, prog)
+
+    def _clean(self, *filenames):
+        if not filenames:
+            filenames = self.temp_files
+            self.temp_files = []
+        log.info("removing: %s", ' '.join(filenames))
+        for filename in filenames:
+            try:
+                os.remove(filename)
+            except OSError:
+                pass
+
+    # XXX these ignore the dry-run flag: what to do, what to do? even if
+    # you want a dry-run build, you still need some sort of configuration
+    # info.  My inclination is to make it up to the real config command to
+    # consult 'dry_run', and assume a default (minimal) configuration if
+    # true.  The problem with trying to do it here is that you'd have to
+    # return either true or false from all the 'try' methods, neither of
+    # which is correct.
+
+    # XXX need access to the header search path and maybe default macros.
+
+    def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
+        """Construct a source file from 'body' (a string containing lines
+        of C/C++ code) and 'headers' (a list of header files to include)
+        and run it through the preprocessor.  Return true if the
+        preprocessor succeeded, false if there were any errors.
+        ('body' probably isn't of much use, but what the heck.)
+        """
+        self._check_compiler()
+        ok = True
+        try:
+            self._preprocess(body, headers, include_dirs, lang)
+        except CompileError:
+            ok = False
+
+        self._clean()
+        return ok
+
+    def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="c"):
+        """Construct a source file (just like 'try_cpp()'), run it through
+        the preprocessor, and return true if any line of the output matches
+        'pattern'.  'pattern' should either be a compiled regex object or a
+        string containing a regex.  If both 'body' and 'headers' are None,
+        preprocesses an empty file -- which can be useful to determine the
+        symbols the preprocessor and compiler set by default.
+        """
+        self._check_compiler()
+        src, out = self._preprocess(body, headers, include_dirs, lang)
+
+        if isinstance(pattern, str):
+            pattern = re.compile(pattern)
+
+        with open(out, encoding='utf-8') as file:
+            match = any(pattern.search(line) for line in file)
+
+        self._clean()
+        return match
+
+    def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
+        """Try to compile a source file built from 'body' and 'headers'.
+        Return true on success, false otherwise.
+        """
+        self._check_compiler()
+        try:
+            self._compile(body, headers, include_dirs, lang)
+            ok = True
+        except CompileError:
+            ok = False
+
+        log.info(ok and "success!" or "failure.")
+        self._clean()
+        return ok
+
+    def try_link(
+        self,
+        body,
+        headers=None,
+        include_dirs=None,
+        libraries=None,
+        library_dirs=None,
+        lang="c",
+    ):
+        """Try to compile and link a source file, built from 'body' and
+        'headers', to executable form.  Return true on success, false
+        otherwise.
+        """
+        self._check_compiler()
+        try:
+            self._link(body, headers, include_dirs, libraries, library_dirs, lang)
+            ok = True
+        except (CompileError, LinkError):
+            ok = False
+
+        log.info(ok and "success!" or "failure.")
+        self._clean()
+        return ok
+
+    def try_run(
+        self,
+        body,
+        headers=None,
+        include_dirs=None,
+        libraries=None,
+        library_dirs=None,
+        lang="c",
+    ):
+        """Try to compile, link to an executable, and run a program
+        built from 'body' and 'headers'.  Return true on success, false
+        otherwise.
+        """
+        self._check_compiler()
+        try:
+            src, obj, exe = self._link(
+                body, headers, include_dirs, libraries, library_dirs, lang
+            )
+            self.spawn([exe])
+            ok = True
+        except (CompileError, LinkError, DistutilsExecError):
+            ok = False
+
+        log.info(ok and "success!" or "failure.")
+        self._clean()
+        return ok
+
+    # -- High-level methods --------------------------------------------
+    # (these are the ones that are actually likely to be useful
+    # when implementing a real-world config command!)
+
+    def check_func(
+        self,
+        func,
+        headers=None,
+        include_dirs=None,
+        libraries=None,
+        library_dirs=None,
+        decl=False,
+        call=False,
+    ):
+        """Determine if function 'func' is available by constructing a
+        source file that refers to 'func', and compiles and links it.
+        If everything succeeds, returns true; otherwise returns false.
+
+        The constructed source file starts out by including the header
+        files listed in 'headers'.  If 'decl' is true, it then declares
+        'func' (as "int func()"); you probably shouldn't supply 'headers'
+        and set 'decl' true in the same call, or you might get errors about
+        a conflicting declarations for 'func'.  Finally, the constructed
+        'main()' function either references 'func' or (if 'call' is true)
+        calls it.  'libraries' and 'library_dirs' are used when
+        linking.
+        """
+        self._check_compiler()
+        body = []
+        if decl:
+            body.append(f"int {func} ();")
+        body.append("int main () {")
+        if call:
+            body.append(f"  {func}();")
+        else:
+            body.append(f"  {func};")
+        body.append("}")
+        body = "\n".join(body) + "\n"
+
+        return self.try_link(body, headers, include_dirs, libraries, library_dirs)
+
+    def check_lib(
+        self,
+        library,
+        library_dirs=None,
+        headers=None,
+        include_dirs=None,
+        other_libraries: Sequence[str] = [],
+    ):
+        """Determine if 'library' is available to be linked against,
+        without actually checking that any particular symbols are provided
+        by it.  'headers' will be used in constructing the source file to
+        be compiled, but the only effect of this is to check if all the
+        header files listed are available.  Any libraries listed in
+        'other_libraries' will be included in the link, in case 'library'
+        has symbols that depend on other libraries.
+        """
+        self._check_compiler()
+        return self.try_link(
+            "int main (void) { }",
+            headers,
+            include_dirs,
+            [library] + list(other_libraries),
+            library_dirs,
+        )
+
+    def check_header(self, header, include_dirs=None, library_dirs=None, lang="c"):
+        """Determine if the system header file named by 'header_file'
+        exists and can be found by the preprocessor; return true if so,
+        false otherwise.
+        """
+        return self.try_cpp(
+            body="/* No body */", headers=[header], include_dirs=include_dirs
+        )
+
+
+def dump_file(filename, head=None):
+    """Dumps a file content into log.info.
+
+    If head is not None, will be dumped before the file content.
+    """
+    if head is None:
+        log.info('%s', filename)
+    else:
+        log.info(head)
+    log.info(pathlib.Path(filename).read_text(encoding='utf-8'))
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc17e56a8070b26f0e3d09c82250e006f1aed826
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install.py
@@ -0,0 +1,805 @@
+"""distutils.command.install
+
+Implements the Distutils 'install' command."""
+
+from __future__ import annotations
+
+import collections
+import contextlib
+import itertools
+import os
+import sys
+import sysconfig
+from distutils._log import log
+from site import USER_BASE, USER_SITE
+from typing import ClassVar
+
+from ..core import Command
+from ..debug import DEBUG
+from ..errors import DistutilsOptionError, DistutilsPlatformError
+from ..file_util import write_file
+from ..sysconfig import get_config_vars
+from ..util import change_root, convert_path, get_platform, subst_vars
+from . import _framework_compat as fw
+
+HAS_USER_SITE = True
+
+WINDOWS_SCHEME = {
+    'purelib': '{base}/Lib/site-packages',
+    'platlib': '{base}/Lib/site-packages',
+    'headers': '{base}/Include/{dist_name}',
+    'scripts': '{base}/Scripts',
+    'data': '{base}',
+}
+
+INSTALL_SCHEMES = {
+    'posix_prefix': {
+        'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
+        'platlib': '{platbase}/{platlibdir}/{implementation_lower}'
+        '{py_version_short}/site-packages',
+        'headers': '{base}/include/{implementation_lower}'
+        '{py_version_short}{abiflags}/{dist_name}',
+        'scripts': '{base}/bin',
+        'data': '{base}',
+    },
+    'posix_home': {
+        'purelib': '{base}/lib/{implementation_lower}',
+        'platlib': '{base}/{platlibdir}/{implementation_lower}',
+        'headers': '{base}/include/{implementation_lower}/{dist_name}',
+        'scripts': '{base}/bin',
+        'data': '{base}',
+    },
+    'nt': WINDOWS_SCHEME,
+    'pypy': {
+        'purelib': '{base}/site-packages',
+        'platlib': '{base}/site-packages',
+        'headers': '{base}/include/{dist_name}',
+        'scripts': '{base}/bin',
+        'data': '{base}',
+    },
+    'pypy_nt': {
+        'purelib': '{base}/site-packages',
+        'platlib': '{base}/site-packages',
+        'headers': '{base}/include/{dist_name}',
+        'scripts': '{base}/Scripts',
+        'data': '{base}',
+    },
+}
+
+# user site schemes
+if HAS_USER_SITE:
+    INSTALL_SCHEMES['nt_user'] = {
+        'purelib': '{usersite}',
+        'platlib': '{usersite}',
+        'headers': '{userbase}/{implementation}{py_version_nodot_plat}'
+        '/Include/{dist_name}',
+        'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
+        'data': '{userbase}',
+    }
+
+    INSTALL_SCHEMES['posix_user'] = {
+        'purelib': '{usersite}',
+        'platlib': '{usersite}',
+        'headers': '{userbase}/include/{implementation_lower}'
+        '{py_version_short}{abiflags}/{dist_name}',
+        'scripts': '{userbase}/bin',
+        'data': '{userbase}',
+    }
+
+
+INSTALL_SCHEMES.update(fw.schemes)
+
+
+# The keys to an installation scheme; if any new types of files are to be
+# installed, be sure to add an entry to every installation scheme above,
+# and to SCHEME_KEYS here.
+SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')
+
+
+def _load_sysconfig_schemes():
+    with contextlib.suppress(AttributeError):
+        return {
+            scheme: sysconfig.get_paths(scheme, expand=False)
+            for scheme in sysconfig.get_scheme_names()
+        }
+
+
+def _load_schemes():
+    """
+    Extend default schemes with schemes from sysconfig.
+    """
+
+    sysconfig_schemes = _load_sysconfig_schemes() or {}
+
+    return {
+        scheme: {
+            **INSTALL_SCHEMES.get(scheme, {}),
+            **sysconfig_schemes.get(scheme, {}),
+        }
+        for scheme in set(itertools.chain(INSTALL_SCHEMES, sysconfig_schemes))
+    }
+
+
+def _get_implementation():
+    if hasattr(sys, 'pypy_version_info'):
+        return 'PyPy'
+    else:
+        return 'Python'
+
+
+def _select_scheme(ob, name):
+    scheme = _inject_headers(name, _load_scheme(_resolve_scheme(name)))
+    vars(ob).update(_remove_set(ob, _scheme_attrs(scheme)))
+
+
+def _remove_set(ob, attrs):
+    """
+    Include only attrs that are None in ob.
+    """
+    return {key: value for key, value in attrs.items() if getattr(ob, key) is None}
+
+
+def _resolve_scheme(name):
+    os_name, sep, key = name.partition('_')
+    try:
+        resolved = sysconfig.get_preferred_scheme(key)
+    except Exception:
+        resolved = fw.scheme(name)
+    return resolved
+
+
+def _load_scheme(name):
+    return _load_schemes()[name]
+
+
+def _inject_headers(name, scheme):
+    """
+    Given a scheme name and the resolved scheme,
+    if the scheme does not include headers, resolve
+    the fallback scheme for the name and use headers
+    from it. pypa/distutils#88
+    """
+    # Bypass the preferred scheme, which may not
+    # have defined headers.
+    fallback = _load_scheme(name)
+    scheme.setdefault('headers', fallback['headers'])
+    return scheme
+
+
+def _scheme_attrs(scheme):
+    """Resolve install directories by applying the install schemes."""
+    return {f'install_{key}': scheme[key] for key in SCHEME_KEYS}
+
+
+class install(Command):
+    description = "install everything from build directory"
+
+    user_options = [
+        # Select installation scheme and set base director(y|ies)
+        ('prefix=', None, "installation prefix"),
+        ('exec-prefix=', None, "(Unix only) prefix for platform-specific files"),
+        ('home=', None, "(Unix only) home directory to install under"),
+        # Or, just set the base director(y|ies)
+        (
+            'install-base=',
+            None,
+            "base installation directory (instead of --prefix or --home)",
+        ),
+        (
+            'install-platbase=',
+            None,
+            "base installation directory for platform-specific files (instead of --exec-prefix or --home)",
+        ),
+        ('root=', None, "install everything relative to this alternate root directory"),
+        # Or, explicitly set the installation scheme
+        (
+            'install-purelib=',
+            None,
+            "installation directory for pure Python module distributions",
+        ),
+        (
+            'install-platlib=',
+            None,
+            "installation directory for non-pure module distributions",
+        ),
+        (
+            'install-lib=',
+            None,
+            "installation directory for all module distributions (overrides --install-purelib and --install-platlib)",
+        ),
+        ('install-headers=', None, "installation directory for C/C++ headers"),
+        ('install-scripts=', None, "installation directory for Python scripts"),
+        ('install-data=', None, "installation directory for data files"),
+        # Byte-compilation options -- see install_lib.py for details, as
+        # these are duplicated from there (but only install_lib does
+        # anything with them).
+        ('compile', 'c', "compile .py to .pyc [default]"),
+        ('no-compile', None, "don't compile .py files"),
+        (
+            'optimize=',
+            'O',
+            "also compile with optimization: -O1 for \"python -O\", "
+            "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+        ),
+        # Miscellaneous control options
+        ('force', 'f', "force installation (overwrite any existing files)"),
+        ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
+        # Where to install documentation (eventually!)
+        # ('doc-format=', None, "format of documentation to generate"),
+        # ('install-man=', None, "directory for Unix man pages"),
+        # ('install-html=', None, "directory for HTML documentation"),
+        # ('install-info=', None, "directory for GNU info files"),
+        ('record=', None, "filename in which to record list of installed files"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['compile', 'force', 'skip-build']
+
+    if HAS_USER_SITE:
+        user_options.append((
+            'user',
+            None,
+            f"install in user site-package '{USER_SITE}'",
+        ))
+        boolean_options.append('user')
+
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
+
+    def initialize_options(self) -> None:
+        """Initializes options."""
+        # High-level options: these select both an installation base
+        # and scheme.
+        self.prefix: str | None = None
+        self.exec_prefix: str | None = None
+        self.home: str | None = None
+        self.user = False
+
+        # These select only the installation base; it's up to the user to
+        # specify the installation scheme (currently, that means supplying
+        # the --install-{platlib,purelib,scripts,data} options).
+        self.install_base = None
+        self.install_platbase = None
+        self.root: str | None = None
+
+        # These options are the actual installation directories; if not
+        # supplied by the user, they are filled in using the installation
+        # scheme implied by prefix/exec-prefix/home and the contents of
+        # that installation scheme.
+        self.install_purelib = None  # for pure module distributions
+        self.install_platlib = None  # non-pure (dists w/ extensions)
+        self.install_headers = None  # for C/C++ headers
+        self.install_lib: str | None = None  # set to either purelib or platlib
+        self.install_scripts = None
+        self.install_data = None
+        self.install_userbase = USER_BASE
+        self.install_usersite = USER_SITE
+
+        self.compile = None
+        self.optimize = None
+
+        # Deprecated
+        # These two are for putting non-packagized distributions into their
+        # own directory and creating a .pth file if it makes sense.
+        # 'extra_path' comes from the setup file; 'install_path_file' can
+        # be turned off if it makes no sense to install a .pth file.  (But
+        # better to install it uselessly than to guess wrong and not
+        # install it when it's necessary and would be used!)  Currently,
+        # 'install_path_file' is always true unless some outsider meddles
+        # with it.
+        self.extra_path = None
+        self.install_path_file = True
+
+        # 'force' forces installation, even if target files are not
+        # out-of-date.  'skip_build' skips running the "build" command,
+        # handy if you know it's not necessary.  'warn_dir' (which is *not*
+        # a user option, it's just there so the bdist_* commands can turn
+        # it off) determines whether we warn about installing to a
+        # directory not in sys.path.
+        self.force = False
+        self.skip_build = False
+        self.warn_dir = True
+
+        # These are only here as a conduit from the 'build' command to the
+        # 'install_*' commands that do the real work.  ('build_base' isn't
+        # actually used anywhere, but it might be useful in future.)  They
+        # are not user options, because if the user told the install
+        # command where the build directory is, that wouldn't affect the
+        # build command.
+        self.build_base = None
+        self.build_lib = None
+
+        # Not defined yet because we don't know anything about
+        # documentation yet.
+        # self.install_man = None
+        # self.install_html = None
+        # self.install_info = None
+
+        self.record = None
+
+    # -- Option finalizing methods -------------------------------------
+    # (This is rather more involved than for most commands,
+    # because this is where the policy for installing third-
+    # party Python modules on various platforms given a wide
+    # array of user input is decided.  Yes, it's quite complex!)
+
+    def finalize_options(self) -> None:  # noqa: C901
+        """Finalizes options."""
+        # This method (and its helpers, like 'finalize_unix()',
+        # 'finalize_other()', and 'select_scheme()') is where the default
+        # installation directories for modules, extension modules, and
+        # anything else we care to install from a Python module
+        # distribution.  Thus, this code makes a pretty important policy
+        # statement about how third-party stuff is added to a Python
+        # installation!  Note that the actual work of installation is done
+        # by the relatively simple 'install_*' commands; they just take
+        # their orders from the installation directory options determined
+        # here.
+
+        # Check for errors/inconsistencies in the options; first, stuff
+        # that's wrong on any platform.
+
+        if (self.prefix or self.exec_prefix or self.home) and (
+            self.install_base or self.install_platbase
+        ):
+            raise DistutilsOptionError(
+                "must supply either prefix/exec-prefix/home or install-base/install-platbase -- not both"
+            )
+
+        if self.home and (self.prefix or self.exec_prefix):
+            raise DistutilsOptionError(
+                "must supply either home or prefix/exec-prefix -- not both"
+            )
+
+        if self.user and (
+            self.prefix
+            or self.exec_prefix
+            or self.home
+            or self.install_base
+            or self.install_platbase
+        ):
+            raise DistutilsOptionError(
+                "can't combine user with prefix, "
+                "exec_prefix/home, or install_(plat)base"
+            )
+
+        # Next, stuff that's wrong (or dubious) only on certain platforms.
+        if os.name != "posix":
+            if self.exec_prefix:
+                self.warn("exec-prefix option ignored on this platform")
+                self.exec_prefix = None
+
+        # Now the interesting logic -- so interesting that we farm it out
+        # to other methods.  The goal of these methods is to set the final
+        # values for the install_{lib,scripts,data,...}  options, using as
+        # input a heady brew of prefix, exec_prefix, home, install_base,
+        # install_platbase, user-supplied versions of
+        # install_{purelib,platlib,lib,scripts,data,...}, and the
+        # install schemes.  Phew!
+
+        self.dump_dirs("pre-finalize_{unix,other}")
+
+        if os.name == 'posix':
+            self.finalize_unix()
+        else:
+            self.finalize_other()
+
+        self.dump_dirs("post-finalize_{unix,other}()")
+
+        # Expand configuration variables, tilde, etc. in self.install_base
+        # and self.install_platbase -- that way, we can use $base or
+        # $platbase in the other installation directories and not worry
+        # about needing recursive variable expansion (shudder).
+
+        py_version = sys.version.split()[0]
+        (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
+        try:
+            abiflags = sys.abiflags
+        except AttributeError:
+            # sys.abiflags may not be defined on all platforms.
+            abiflags = ''
+        local_vars = {
+            'dist_name': self.distribution.get_name(),
+            'dist_version': self.distribution.get_version(),
+            'dist_fullname': self.distribution.get_fullname(),
+            'py_version': py_version,
+            'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',
+            'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
+            'sys_prefix': prefix,
+            'prefix': prefix,
+            'sys_exec_prefix': exec_prefix,
+            'exec_prefix': exec_prefix,
+            'abiflags': abiflags,
+            'platlibdir': getattr(sys, 'platlibdir', 'lib'),
+            'implementation_lower': _get_implementation().lower(),
+            'implementation': _get_implementation(),
+        }
+
+        # vars for compatibility on older Pythons
+        compat_vars = dict(
+            # Python 3.9 and earlier
+            py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''),
+        )
+
+        if HAS_USER_SITE:
+            local_vars['userbase'] = self.install_userbase
+            local_vars['usersite'] = self.install_usersite
+
+        self.config_vars = collections.ChainMap(
+            local_vars,
+            sysconfig.get_config_vars(),
+            compat_vars,
+            fw.vars(),
+        )
+
+        self.expand_basedirs()
+
+        self.dump_dirs("post-expand_basedirs()")
+
+        # Now define config vars for the base directories so we can expand
+        # everything else.
+        local_vars['base'] = self.install_base
+        local_vars['platbase'] = self.install_platbase
+
+        if DEBUG:
+            from pprint import pprint
+
+            print("config vars:")
+            pprint(dict(self.config_vars))
+
+        # Expand "~" and configuration variables in the installation
+        # directories.
+        self.expand_dirs()
+
+        self.dump_dirs("post-expand_dirs()")
+
+        # Create directories in the home dir:
+        if self.user:
+            self.create_home_path()
+
+        # Pick the actual directory to install all modules to: either
+        # install_purelib or install_platlib, depending on whether this
+        # module distribution is pure or not.  Of course, if the user
+        # already specified install_lib, use their selection.
+        if self.install_lib is None:
+            if self.distribution.has_ext_modules():  # has extensions: non-pure
+                self.install_lib = self.install_platlib
+            else:
+                self.install_lib = self.install_purelib
+
+        # Convert directories from Unix /-separated syntax to the local
+        # convention.
+        self.convert_paths(
+            'lib',
+            'purelib',
+            'platlib',
+            'scripts',
+            'data',
+            'headers',
+            'userbase',
+            'usersite',
+        )
+
+        # Deprecated
+        # Well, we're not actually fully completely finalized yet: we still
+        # have to deal with 'extra_path', which is the hack for allowing
+        # non-packagized module distributions (hello, Numerical Python!) to
+        # get their own directories.
+        self.handle_extra_path()
+        self.install_libbase = self.install_lib  # needed for .pth file
+        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
+
+        # If a new root directory was supplied, make all the installation
+        # dirs relative to it.
+        if self.root is not None:
+            self.change_roots(
+                'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers'
+            )
+
+        self.dump_dirs("after prepending root")
+
+        # Find out the build directories, ie. where to install from.
+        self.set_undefined_options(
+            'build', ('build_base', 'build_base'), ('build_lib', 'build_lib')
+        )
+
+        # Punt on doc directories for now -- after all, we're punting on
+        # documentation completely!
+
+    def dump_dirs(self, msg) -> None:
+        """Dumps the list of user options."""
+        if not DEBUG:
+            return
+        from ..fancy_getopt import longopt_xlate
+
+        log.debug(msg + ":")
+        for opt in self.user_options:
+            opt_name = opt[0]
+            if opt_name[-1] == "=":
+                opt_name = opt_name[0:-1]
+            if opt_name in self.negative_opt:
+                opt_name = self.negative_opt[opt_name]
+                opt_name = opt_name.translate(longopt_xlate)
+                val = not getattr(self, opt_name)
+            else:
+                opt_name = opt_name.translate(longopt_xlate)
+                val = getattr(self, opt_name)
+            log.debug("  %s: %s", opt_name, val)
+
+    def finalize_unix(self) -> None:
+        """Finalizes options for posix platforms."""
+        if self.install_base is not None or self.install_platbase is not None:
+            incomplete_scheme = (
+                (
+                    self.install_lib is None
+                    and self.install_purelib is None
+                    and self.install_platlib is None
+                )
+                or self.install_headers is None
+                or self.install_scripts is None
+                or self.install_data is None
+            )
+            if incomplete_scheme:
+                raise DistutilsOptionError(
+                    "install-base or install-platbase supplied, but "
+                    "installation scheme is incomplete"
+                )
+            return
+
+        if self.user:
+            if self.install_userbase is None:
+                raise DistutilsPlatformError("User base directory is not specified")
+            self.install_base = self.install_platbase = self.install_userbase
+            self.select_scheme("posix_user")
+        elif self.home is not None:
+            self.install_base = self.install_platbase = self.home
+            self.select_scheme("posix_home")
+        else:
+            if self.prefix is None:
+                if self.exec_prefix is not None:
+                    raise DistutilsOptionError(
+                        "must not supply exec-prefix without prefix"
+                    )
+
+                # Allow Fedora to add components to the prefix
+                _prefix_addition = getattr(sysconfig, '_prefix_addition', "")
+
+                self.prefix = os.path.normpath(sys.prefix) + _prefix_addition
+                self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition
+
+            else:
+                if self.exec_prefix is None:
+                    self.exec_prefix = self.prefix
+
+            self.install_base = self.prefix
+            self.install_platbase = self.exec_prefix
+            self.select_scheme("posix_prefix")
+
+    def finalize_other(self) -> None:
+        """Finalizes options for non-posix platforms"""
+        if self.user:
+            if self.install_userbase is None:
+                raise DistutilsPlatformError("User base directory is not specified")
+            self.install_base = self.install_platbase = self.install_userbase
+            self.select_scheme(os.name + "_user")
+        elif self.home is not None:
+            self.install_base = self.install_platbase = self.home
+            self.select_scheme("posix_home")
+        else:
+            if self.prefix is None:
+                self.prefix = os.path.normpath(sys.prefix)
+
+            self.install_base = self.install_platbase = self.prefix
+            try:
+                self.select_scheme(os.name)
+            except KeyError:
+                raise DistutilsPlatformError(
+                    f"I don't know how to install stuff on '{os.name}'"
+                )
+
+    def select_scheme(self, name) -> None:
+        _select_scheme(self, name)
+
+    def _expand_attrs(self, attrs):
+        for attr in attrs:
+            val = getattr(self, attr)
+            if val is not None:
+                if os.name in ('posix', 'nt'):
+                    val = os.path.expanduser(val)
+                val = subst_vars(val, self.config_vars)
+                setattr(self, attr, val)
+
+    def expand_basedirs(self) -> None:
+        """Calls `os.path.expanduser` on install_base, install_platbase and
+        root."""
+        self._expand_attrs(['install_base', 'install_platbase', 'root'])
+
+    def expand_dirs(self) -> None:
+        """Calls `os.path.expanduser` on install dirs."""
+        self._expand_attrs([
+            'install_purelib',
+            'install_platlib',
+            'install_lib',
+            'install_headers',
+            'install_scripts',
+            'install_data',
+        ])
+
+    def convert_paths(self, *names) -> None:
+        """Call `convert_path` over `names`."""
+        for name in names:
+            attr = "install_" + name
+            setattr(self, attr, convert_path(getattr(self, attr)))
+
+    def handle_extra_path(self) -> None:
+        """Set `path_file` and `extra_dirs` using `extra_path`."""
+        if self.extra_path is None:
+            self.extra_path = self.distribution.extra_path
+
+        if self.extra_path is not None:
+            log.warning(
+                "Distribution option extra_path is deprecated. "
+                "See issue27919 for details."
+            )
+            if isinstance(self.extra_path, str):
+                self.extra_path = self.extra_path.split(',')
+
+            if len(self.extra_path) == 1:
+                path_file = extra_dirs = self.extra_path[0]
+            elif len(self.extra_path) == 2:
+                path_file, extra_dirs = self.extra_path
+            else:
+                raise DistutilsOptionError(
+                    "'extra_path' option must be a list, tuple, or "
+                    "comma-separated string with 1 or 2 elements"
+                )
+
+            # convert to local form in case Unix notation used (as it
+            # should be in setup scripts)
+            extra_dirs = convert_path(extra_dirs)
+        else:
+            path_file = None
+            extra_dirs = ''
+
+        # XXX should we warn if path_file and not extra_dirs? (in which
+        # case the path file would be harmless but pointless)
+        self.path_file = path_file
+        self.extra_dirs = extra_dirs
+
+    def change_roots(self, *names) -> None:
+        """Change the install directories pointed by name using root."""
+        for name in names:
+            attr = "install_" + name
+            setattr(self, attr, change_root(self.root, getattr(self, attr)))
+
+    def create_home_path(self) -> None:
+        """Create directories under ~."""
+        if not self.user:
+            return
+        home = convert_path(os.path.expanduser("~"))
+        for path in self.config_vars.values():
+            if str(path).startswith(home) and not os.path.isdir(path):
+                self.debug_print(f"os.makedirs('{path}', 0o700)")
+                os.makedirs(path, 0o700)
+
+    # -- Command execution methods -------------------------------------
+
+    def run(self):
+        """Runs the command."""
+        # Obviously have to build before we can install
+        if not self.skip_build:
+            self.run_command('build')
+            # If we built for any other platform, we can't install.
+            build_plat = self.distribution.get_command_obj('build').plat_name
+            # check warn_dir - it is a clue that the 'install' is happening
+            # internally, and not to sys.path, so we don't check the platform
+            # matches what we are running.
+            if self.warn_dir and build_plat != get_platform():
+                raise DistutilsPlatformError("Can't install when cross-compiling")
+
+        # Run all sub-commands (at least those that need to be run)
+        for cmd_name in self.get_sub_commands():
+            self.run_command(cmd_name)
+
+        if self.path_file:
+            self.create_path_file()
+
+        # write list of installed files, if requested.
+        if self.record:
+            outputs = self.get_outputs()
+            if self.root:  # strip any package prefix
+                root_len = len(self.root)
+                for counter in range(len(outputs)):
+                    outputs[counter] = outputs[counter][root_len:]
+            self.execute(
+                write_file,
+                (self.record, outputs),
+                f"writing list of installed files to '{self.record}'",
+            )
+
+        sys_path = map(os.path.normpath, sys.path)
+        sys_path = map(os.path.normcase, sys_path)
+        install_lib = os.path.normcase(os.path.normpath(self.install_lib))
+        if (
+            self.warn_dir
+            and not (self.path_file and self.install_path_file)
+            and install_lib not in sys_path
+        ):
+            log.debug(
+                (
+                    "modules installed to '%s', which is not in "
+                    "Python's module search path (sys.path) -- "
+                    "you'll have to change the search path yourself"
+                ),
+                self.install_lib,
+            )
+
+    def create_path_file(self):
+        """Creates the .pth file"""
+        filename = os.path.join(self.install_libbase, self.path_file + ".pth")
+        if self.install_path_file:
+            self.execute(
+                write_file, (filename, [self.extra_dirs]), f"creating {filename}"
+            )
+        else:
+            self.warn(f"path file '{filename}' not created")
+
+    # -- Reporting methods ---------------------------------------------
+
+    def get_outputs(self):
+        """Assembles the outputs of all the sub-commands."""
+        outputs = []
+        for cmd_name in self.get_sub_commands():
+            cmd = self.get_finalized_command(cmd_name)
+            # Add the contents of cmd.get_outputs(), ensuring
+            # that outputs doesn't contain duplicate entries
+            for filename in cmd.get_outputs():
+                if filename not in outputs:
+                    outputs.append(filename)
+
+        if self.path_file and self.install_path_file:
+            outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth"))
+
+        return outputs
+
+    def get_inputs(self):
+        """Returns the inputs of all the sub-commands"""
+        # XXX gee, this looks familiar ;-(
+        inputs = []
+        for cmd_name in self.get_sub_commands():
+            cmd = self.get_finalized_command(cmd_name)
+            inputs.extend(cmd.get_inputs())
+
+        return inputs
+
+    # -- Predicates for sub-command list -------------------------------
+
+    def has_lib(self):
+        """Returns true if the current distribution has any Python
+        modules to install."""
+        return (
+            self.distribution.has_pure_modules() or self.distribution.has_ext_modules()
+        )
+
+    def has_headers(self):
+        """Returns true if the current distribution has any headers to
+        install."""
+        return self.distribution.has_headers()
+
+    def has_scripts(self):
+        """Returns true if the current distribution has any scripts to.
+        install."""
+        return self.distribution.has_scripts()
+
+    def has_data(self):
+        """Returns true if the current distribution has any data to.
+        install."""
+        return self.distribution.has_data_files()
+
+    # 'sub_commands': a list of commands this command might have to run to
+    # get its work done.  See cmd.py for more info.
+    sub_commands = [
+        ('install_lib', has_lib),
+        ('install_headers', has_headers),
+        ('install_scripts', has_scripts),
+        ('install_data', has_data),
+        ('install_egg_info', lambda self: True),
+    ]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_data.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ad186e8ec61b92967ea1c12cdca51d00e82dd15
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_data.py
@@ -0,0 +1,94 @@
+"""distutils.command.install_data
+
+Implements the Distutils 'install_data' command, for installing
+platform-independent data files."""
+
+# contributed by Bastian Kleineidam
+
+from __future__ import annotations
+
+import functools
+import os
+from collections.abc import Iterable
+from typing import ClassVar
+
+from ..core import Command
+from ..util import change_root, convert_path
+
+
+class install_data(Command):
+    description = "install data files"
+
+    user_options = [
+        (
+            'install-dir=',
+            'd',
+            "base directory for installing data files [default: installation base dir]",
+        ),
+        ('root=', None, "install everything relative to this alternate root directory"),
+        ('force', 'f', "force installation (overwrite existing files)"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['force']
+
+    def initialize_options(self):
+        self.install_dir = None
+        self.outfiles = []
+        self.root = None
+        self.force = False
+        self.data_files = self.distribution.data_files
+        self.warn_dir = True
+
+    def finalize_options(self) -> None:
+        self.set_undefined_options(
+            'install',
+            ('install_data', 'install_dir'),
+            ('root', 'root'),
+            ('force', 'force'),
+        )
+
+    def run(self) -> None:
+        self.mkpath(self.install_dir)
+        for f in self.data_files:
+            self._copy(f)
+
+    @functools.singledispatchmethod
+    def _copy(self, f: tuple[str | os.PathLike, Iterable[str | os.PathLike]]):
+        # it's a tuple with path to install to and a list of files
+        dir = convert_path(f[0])
+        if not os.path.isabs(dir):
+            dir = os.path.join(self.install_dir, dir)
+        elif self.root:
+            dir = change_root(self.root, dir)
+        self.mkpath(dir)
+
+        if f[1] == []:
+            # If there are no files listed, the user must be
+            # trying to create an empty directory, so add the
+            # directory to the list of output files.
+            self.outfiles.append(dir)
+        else:
+            # Copy files, adding them to the list of output files.
+            for data in f[1]:
+                data = convert_path(data)
+                (out, _) = self.copy_file(data, dir)
+                self.outfiles.append(out)
+
+    @_copy.register(str)
+    @_copy.register(os.PathLike)
+    def _(self, f: str | os.PathLike):
+        # it's a simple file, so copy it
+        f = convert_path(f)
+        if self.warn_dir:
+            self.warn(
+                "setup script did not provide a directory for "
+                f"'{f}' -- installing right in '{self.install_dir}'"
+            )
+        (out, _) = self.copy_file(f, self.install_dir)
+        self.outfiles.append(out)
+
+    def get_inputs(self):
+        return self.data_files or []
+
+    def get_outputs(self):
+        return self.outfiles
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_egg_info.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_egg_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..230e94ab46f0c87f58428b456e9d2fe98eca27a4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_egg_info.py
@@ -0,0 +1,91 @@
+"""
+distutils.command.install_egg_info
+
+Implements the Distutils 'install_egg_info' command, for installing
+a package's PKG-INFO metadata.
+"""
+
+import os
+import re
+import sys
+from typing import ClassVar
+
+from .. import dir_util
+from .._log import log
+from ..cmd import Command
+
+
+class install_egg_info(Command):
+    """Install an .egg-info file for the package"""
+
+    description = "Install package's PKG-INFO metadata as an .egg-info file"
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('install-dir=', 'd', "directory to install to"),
+    ]
+
+    def initialize_options(self):
+        self.install_dir = None
+
+    @property
+    def basename(self):
+        """
+        Allow basename to be overridden by child class.
+        Ref pypa/distutils#2.
+        """
+        name = to_filename(safe_name(self.distribution.get_name()))
+        version = to_filename(safe_version(self.distribution.get_version()))
+        return f"{name}-{version}-py{sys.version_info.major}.{sys.version_info.minor}.egg-info"
+
+    def finalize_options(self):
+        self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
+        self.target = os.path.join(self.install_dir, self.basename)
+        self.outputs = [self.target]
+
+    def run(self):
+        target = self.target
+        if os.path.isdir(target) and not os.path.islink(target):
+            dir_util.remove_tree(target, dry_run=self.dry_run)
+        elif os.path.exists(target):
+            self.execute(os.unlink, (self.target,), "Removing " + target)
+        elif not os.path.isdir(self.install_dir):
+            self.execute(
+                os.makedirs, (self.install_dir,), "Creating " + self.install_dir
+            )
+        log.info("Writing %s", target)
+        if not self.dry_run:
+            with open(target, 'w', encoding='UTF-8') as f:
+                self.distribution.metadata.write_pkg_file(f)
+
+    def get_outputs(self):
+        return self.outputs
+
+
+# The following routines are taken from setuptools' pkg_resources module and
+# can be replaced by importing them from pkg_resources once it is included
+# in the stdlib.
+
+
+def safe_name(name):
+    """Convert an arbitrary string to a standard distribution name
+
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub('[^A-Za-z0-9.]+', '-', name)
+
+
+def safe_version(version):
+    """Convert an arbitrary string to a standard version string
+
+    Spaces become dots, and all other non-alphanumeric characters become
+    dashes, with runs of multiple dashes condensed to a single dash.
+    """
+    version = version.replace(' ', '.')
+    return re.sub('[^A-Za-z0-9.]+', '-', version)
+
+
+def to_filename(name):
+    """Convert a project or version name to its filename-escaped form
+
+    Any '-' characters are currently replaced with '_'.
+    """
+    return name.replace('-', '_')
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_headers.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_headers.py
new file mode 100644
index 0000000000000000000000000000000000000000..97af1371efcc73423e9b91d7b3ced684ff936377
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_headers.py
@@ -0,0 +1,46 @@
+"""distutils.command.install_headers
+
+Implements the Distutils 'install_headers' command, to install C/C++ header
+files to the Python include directory."""
+
+from typing import ClassVar
+
+from ..core import Command
+
+
+# XXX force is never used
+class install_headers(Command):
+    description = "install C/C++ header files"
+
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ('install-dir=', 'd', "directory to install header files to"),
+        ('force', 'f', "force installation (overwrite existing files)"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['force']
+
+    def initialize_options(self):
+        self.install_dir = None
+        self.force = False
+        self.outfiles = []
+
+    def finalize_options(self):
+        self.set_undefined_options(
+            'install', ('install_headers', 'install_dir'), ('force', 'force')
+        )
+
+    def run(self):
+        headers = self.distribution.headers
+        if not headers:
+            return
+
+        self.mkpath(self.install_dir)
+        for header in headers:
+            (out, _) = self.copy_file(header, self.install_dir)
+            self.outfiles.append(out)
+
+    def get_inputs(self):
+        return self.distribution.headers or []
+
+    def get_outputs(self):
+        return self.outfiles
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_lib.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..2aababf8004d4636f039dd0609457387a0346ca0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_lib.py
@@ -0,0 +1,238 @@
+"""distutils.command.install_lib
+
+Implements the Distutils 'install_lib' command
+(install all Python modules)."""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+from typing import Any, ClassVar
+
+from ..core import Command
+from ..errors import DistutilsOptionError
+
+# Extension for Python source files.
+PYTHON_SOURCE_EXTENSION = ".py"
+
+
+class install_lib(Command):
+    description = "install all Python modules (extensions and pure Python)"
+
+    # The byte-compilation options are a tad confusing.  Here are the
+    # possible scenarios:
+    #   1) no compilation at all (--no-compile --no-optimize)
+    #   2) compile .pyc only (--compile --no-optimize; default)
+    #   3) compile .pyc and "opt-1" .pyc (--compile --optimize)
+    #   4) compile "opt-1" .pyc only (--no-compile --optimize)
+    #   5) compile .pyc and "opt-2" .pyc (--compile --optimize-more)
+    #   6) compile "opt-2" .pyc only (--no-compile --optimize-more)
+    #
+    # The UI for this is two options, 'compile' and 'optimize'.
+    # 'compile' is strictly boolean, and only decides whether to
+    # generate .pyc files.  'optimize' is three-way (0, 1, or 2), and
+    # decides both whether to generate .pyc files and what level of
+    # optimization to use.
+
+    user_options = [
+        ('install-dir=', 'd', "directory to install to"),
+        ('build-dir=', 'b', "build directory (where to install from)"),
+        ('force', 'f', "force installation (overwrite existing files)"),
+        ('compile', 'c', "compile .py to .pyc [default]"),
+        ('no-compile', None, "don't compile .py files"),
+        (
+            'optimize=',
+            'O',
+            "also compile with optimization: -O1 for \"python -O\", "
+            "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
+        ),
+        ('skip-build', None, "skip the build steps"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['force', 'compile', 'skip-build']
+    negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
+
+    def initialize_options(self):
+        # let the 'install' command dictate our installation directory
+        self.install_dir = None
+        self.build_dir = None
+        self.force = False
+        self.compile = None
+        self.optimize = None
+        self.skip_build = None
+
+    def finalize_options(self) -> None:
+        # Get all the information we need to install pure Python modules
+        # from the umbrella 'install' command -- build (source) directory,
+        # install (target) directory, and whether to compile .py files.
+        self.set_undefined_options(
+            'install',
+            ('build_lib', 'build_dir'),
+            ('install_lib', 'install_dir'),
+            ('force', 'force'),
+            ('compile', 'compile'),
+            ('optimize', 'optimize'),
+            ('skip_build', 'skip_build'),
+        )
+
+        if self.compile is None:
+            self.compile = True
+        if self.optimize is None:
+            self.optimize = False
+
+        if not isinstance(self.optimize, int):
+            try:
+                self.optimize = int(self.optimize)
+            except ValueError:
+                pass
+            if self.optimize not in (0, 1, 2):
+                raise DistutilsOptionError("optimize must be 0, 1, or 2")
+
+    def run(self) -> None:
+        # Make sure we have built everything we need first
+        self.build()
+
+        # Install everything: simply dump the entire contents of the build
+        # directory to the installation directory (that's the beauty of
+        # having a build directory!)
+        outfiles = self.install()
+
+        # (Optionally) compile .py to .pyc
+        if outfiles is not None and self.distribution.has_pure_modules():
+            self.byte_compile(outfiles)
+
+    # -- Top-level worker functions ------------------------------------
+    # (called from 'run()')
+
+    def build(self) -> None:
+        if not self.skip_build:
+            if self.distribution.has_pure_modules():
+                self.run_command('build_py')
+            if self.distribution.has_ext_modules():
+                self.run_command('build_ext')
+
+    # Any: https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#the-any-trick
+    def install(self) -> list[str] | Any:
+        if os.path.isdir(self.build_dir):
+            outfiles = self.copy_tree(self.build_dir, self.install_dir)
+        else:
+            self.warn(
+                f"'{self.build_dir}' does not exist -- no Python modules to install"
+            )
+            return
+        return outfiles
+
+    def byte_compile(self, files) -> None:
+        if sys.dont_write_bytecode:
+            self.warn('byte-compiling is disabled, skipping.')
+            return
+
+        from ..util import byte_compile
+
+        # Get the "--root" directory supplied to the "install" command,
+        # and use it as a prefix to strip off the purported filename
+        # encoded in bytecode files.  This is far from complete, but it
+        # should at least generate usable bytecode in RPM distributions.
+        install_root = self.get_finalized_command('install').root
+
+        if self.compile:
+            byte_compile(
+                files,
+                optimize=0,
+                force=self.force,
+                prefix=install_root,
+                dry_run=self.dry_run,
+            )
+        if self.optimize > 0:
+            byte_compile(
+                files,
+                optimize=self.optimize,
+                force=self.force,
+                prefix=install_root,
+                verbose=self.verbose,
+                dry_run=self.dry_run,
+            )
+
+    # -- Utility methods -----------------------------------------------
+
+    def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
+        if not has_any:
+            return []
+
+        build_cmd = self.get_finalized_command(build_cmd)
+        build_files = build_cmd.get_outputs()
+        build_dir = getattr(build_cmd, cmd_option)
+
+        prefix_len = len(build_dir) + len(os.sep)
+        outputs = [os.path.join(output_dir, file[prefix_len:]) for file in build_files]
+
+        return outputs
+
+    def _bytecode_filenames(self, py_filenames):
+        bytecode_files = []
+        for py_file in py_filenames:
+            # Since build_py handles package data installation, the
+            # list of outputs can contain more than just .py files.
+            # Make sure we only report bytecode for the .py files.
+            ext = os.path.splitext(os.path.normcase(py_file))[1]
+            if ext != PYTHON_SOURCE_EXTENSION:
+                continue
+            if self.compile:
+                bytecode_files.append(
+                    importlib.util.cache_from_source(py_file, optimization='')
+                )
+            if self.optimize > 0:
+                bytecode_files.append(
+                    importlib.util.cache_from_source(
+                        py_file, optimization=self.optimize
+                    )
+                )
+
+        return bytecode_files
+
+    # -- External interface --------------------------------------------
+    # (called by outsiders)
+
+    def get_outputs(self):
+        """Return the list of files that would be installed if this command
+        were actually run.  Not affected by the "dry-run" flag or whether
+        modules have actually been built yet.
+        """
+        pure_outputs = self._mutate_outputs(
+            self.distribution.has_pure_modules(),
+            'build_py',
+            'build_lib',
+            self.install_dir,
+        )
+        if self.compile:
+            bytecode_outputs = self._bytecode_filenames(pure_outputs)
+        else:
+            bytecode_outputs = []
+
+        ext_outputs = self._mutate_outputs(
+            self.distribution.has_ext_modules(),
+            'build_ext',
+            'build_lib',
+            self.install_dir,
+        )
+
+        return pure_outputs + bytecode_outputs + ext_outputs
+
+    def get_inputs(self):
+        """Get the list of files that are input to this command, ie. the
+        files that get installed as they are named in the build tree.
+        The files in this list correspond one-to-one to the output
+        filenames returned by 'get_outputs()'.
+        """
+        inputs = []
+
+        if self.distribution.has_pure_modules():
+            build_py = self.get_finalized_command('build_py')
+            inputs.extend(build_py.get_outputs())
+
+        if self.distribution.has_ext_modules():
+            build_ext = self.get_finalized_command('build_ext')
+            inputs.extend(build_ext.get_outputs())
+
+        return inputs
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_scripts.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_scripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e8694111ee29bd82a33218e1c7f2a9ecbd3a4e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/install_scripts.py
@@ -0,0 +1,62 @@
+"""distutils.command.install_scripts
+
+Implements the Distutils 'install_scripts' command, for installing
+Python scripts."""
+
+# contributed by Bastian Kleineidam
+
+import os
+from distutils._log import log
+from stat import ST_MODE
+from typing import ClassVar
+
+from ..core import Command
+
+
+class install_scripts(Command):
+    description = "install scripts (Python or otherwise)"
+
+    user_options = [
+        ('install-dir=', 'd', "directory to install scripts to"),
+        ('build-dir=', 'b', "build directory (where to install from)"),
+        ('force', 'f', "force installation (overwrite existing files)"),
+        ('skip-build', None, "skip the build steps"),
+    ]
+
+    boolean_options: ClassVar[list[str]] = ['force', 'skip-build']
+
+    def initialize_options(self):
+        self.install_dir = None
+        self.force = False
+        self.build_dir = None
+        self.skip_build = None
+
+    def finalize_options(self) -> None:
+        self.set_undefined_options('build', ('build_scripts', 'build_dir'))
+        self.set_undefined_options(
+            'install',
+            ('install_scripts', 'install_dir'),
+            ('force', 'force'),
+            ('skip_build', 'skip_build'),
+        )
+
+    def run(self) -> None:
+        if not self.skip_build:
+            self.run_command('build_scripts')
+        self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
+        if os.name == 'posix':
+            # Set the executable bits (owner, group, and world) on
+            # all the scripts we just installed.
+            for file in self.get_outputs():
+                if self.dry_run:
+                    log.info("changing mode of %s", file)
+                else:
+                    mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
+                    log.info("changing mode of %s to %o", file, mode)
+                    os.chmod(file, mode)
+
+    def get_inputs(self):
+        return self.distribution.scripts or []
+
+    def get_outputs(self):
+        return self.outfiles or []
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/command/sdist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/command/sdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3bf0c326aa04c00e8da0e82e8c74afa488be055
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/command/sdist.py
@@ -0,0 +1,521 @@
+"""distutils.command.sdist
+
+Implements the Distutils 'sdist' command (create a source distribution)."""
+
+from __future__ import annotations
+
+import os
+import sys
+from collections.abc import Callable
+from distutils import archive_util, dir_util, file_util
+from distutils._log import log
+from glob import glob
+from itertools import filterfalse
+from typing import ClassVar
+
+from ..core import Command
+from ..errors import DistutilsOptionError, DistutilsTemplateError
+from ..filelist import FileList
+from ..text_file import TextFile
+from ..util import convert_path
+
+
+def show_formats():
+    """Print all possible values for the 'formats' option (used by
+    the "--help-formats" command-line option).
+    """
+    from ..archive_util import ARCHIVE_FORMATS
+    from ..fancy_getopt import FancyGetopt
+
+    formats = sorted(
+        ("formats=" + format, None, ARCHIVE_FORMATS[format][2])
+        for format in ARCHIVE_FORMATS.keys()
+    )
+    FancyGetopt(formats).print_help("List of available source distribution formats:")
+
+
+class sdist(Command):
+    description = "create a source distribution (tarball, zip file, etc.)"
+
+    def checking_metadata(self) -> bool:
+        """Callable used for the check sub-command.
+
+        Placed here so user_options can view it"""
+        return self.metadata_check
+
+    user_options = [
+        ('template=', 't', "name of manifest template file [default: MANIFEST.in]"),
+        ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
+        (
+            'use-defaults',
+            None,
+            "include the default file set in the manifest "
+            "[default; disable with --no-defaults]",
+        ),
+        ('no-defaults', None, "don't include the default file set"),
+        (
+            'prune',
+            None,
+            "specifically exclude files/directories that should not be "
+            "distributed (build tree, RCS/CVS dirs, etc.) "
+            "[default; disable with --no-prune]",
+        ),
+        ('no-prune', None, "don't automatically exclude anything"),
+        (
+            'manifest-only',
+            'o',
+            "just regenerate the manifest and then stop (implies --force-manifest)",
+        ),
+        (
+            'force-manifest',
+            'f',
+            "forcibly regenerate the manifest and carry on as usual. "
+            "Deprecated: now the manifest is always regenerated.",
+        ),
+        ('formats=', None, "formats for source distribution (comma-separated list)"),
+        (
+            'keep-temp',
+            'k',
+            "keep the distribution tree around after creating " + "archive file(s)",
+        ),
+        (
+            'dist-dir=',
+            'd',
+            "directory to put the source distribution archive(s) in [default: dist]",
+        ),
+        (
+            'metadata-check',
+            None,
+            "Ensure that all required elements of meta-data "
+            "are supplied. Warn if any missing. [default]",
+        ),
+        (
+            'owner=',
+            'u',
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            'group=',
+            'g',
+            "Group name used when creating a tar file [default: current group]",
+        ),
+    ]
+
+    boolean_options: ClassVar[list[str]] = [
+        'use-defaults',
+        'prune',
+        'manifest-only',
+        'force-manifest',
+        'keep-temp',
+        'metadata-check',
+    ]
+
+    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
+        ('help-formats', None, "list available distribution formats", show_formats),
+    ]
+
+    negative_opt: ClassVar[dict[str, str]] = {
+        'no-defaults': 'use-defaults',
+        'no-prune': 'prune',
+    }
+
+    sub_commands = [('check', checking_metadata)]
+
+    READMES: ClassVar[tuple[str, ...]] = ('README', 'README.txt', 'README.rst')
+
+    def initialize_options(self):
+        # 'template' and 'manifest' are, respectively, the names of
+        # the manifest template and manifest file.
+        self.template = None
+        self.manifest = None
+
+        # 'use_defaults': if true, we will include the default file set
+        # in the manifest
+        self.use_defaults = True
+        self.prune = True
+
+        self.manifest_only = False
+        self.force_manifest = False
+
+        self.formats = ['gztar']
+        self.keep_temp = False
+        self.dist_dir = None
+
+        self.archive_files = None
+        self.metadata_check = True
+        self.owner = None
+        self.group = None
+
+    def finalize_options(self) -> None:
+        if self.manifest is None:
+            self.manifest = "MANIFEST"
+        if self.template is None:
+            self.template = "MANIFEST.in"
+
+        self.ensure_string_list('formats')
+
+        bad_format = archive_util.check_archive_formats(self.formats)
+        if bad_format:
+            raise DistutilsOptionError(f"unknown archive format '{bad_format}'")
+
+        if self.dist_dir is None:
+            self.dist_dir = "dist"
+
+    def run(self) -> None:
+        # 'filelist' contains the list of files that will make up the
+        # manifest
+        self.filelist = FileList()
+
+        # Run sub commands
+        for cmd_name in self.get_sub_commands():
+            self.run_command(cmd_name)
+
+        # Do whatever it takes to get the list of files to process
+        # (process the manifest template, read an existing manifest,
+        # whatever).  File list is accumulated in 'self.filelist'.
+        self.get_file_list()
+
+        # If user just wanted us to regenerate the manifest, stop now.
+        if self.manifest_only:
+            return
+
+        # Otherwise, go ahead and create the source distribution tarball,
+        # or zipfile, or whatever.
+        self.make_distribution()
+
+    def get_file_list(self) -> None:
+        """Figure out the list of files to include in the source
+        distribution, and put it in 'self.filelist'.  This might involve
+        reading the manifest template (and writing the manifest), or just
+        reading the manifest, or just using the default file set -- it all
+        depends on the user's options.
+        """
+        # new behavior when using a template:
+        # the file list is recalculated every time because
+        # even if MANIFEST.in or setup.py are not changed
+        # the user might have added some files in the tree that
+        # need to be included.
+        #
+        #  This makes --force the default and only behavior with templates.
+        template_exists = os.path.isfile(self.template)
+        if not template_exists and self._manifest_is_not_generated():
+            self.read_manifest()
+            self.filelist.sort()
+            self.filelist.remove_duplicates()
+            return
+
+        if not template_exists:
+            self.warn(
+                ("manifest template '%s' does not exist " + "(using default file list)")
+                % self.template
+            )
+        self.filelist.findall()
+
+        if self.use_defaults:
+            self.add_defaults()
+
+        if template_exists:
+            self.read_template()
+
+        if self.prune:
+            self.prune_file_list()
+
+        self.filelist.sort()
+        self.filelist.remove_duplicates()
+        self.write_manifest()
+
+    def add_defaults(self) -> None:
+        """Add all the default files to self.filelist:
+          - README or README.txt
+          - setup.py
+          - tests/test*.py and test/test*.py
+          - all pure Python modules mentioned in setup script
+          - all files pointed by package_data (build_py)
+          - all files defined in data_files.
+          - all files defined as scripts.
+          - all C sources listed as part of extensions or C libraries
+            in the setup script (doesn't catch C headers!)
+        Warns if (README or README.txt) or setup.py are missing; everything
+        else is optional.
+        """
+        self._add_defaults_standards()
+        self._add_defaults_optional()
+        self._add_defaults_python()
+        self._add_defaults_data_files()
+        self._add_defaults_ext()
+        self._add_defaults_c_libs()
+        self._add_defaults_scripts()
+
+    @staticmethod
+    def _cs_path_exists(fspath):
+        """
+        Case-sensitive path existence check
+
+        >>> sdist._cs_path_exists(__file__)
+        True
+        >>> sdist._cs_path_exists(__file__.upper())
+        False
+        """
+        if not os.path.exists(fspath):
+            return False
+        # make absolute so we always have a directory
+        abspath = os.path.abspath(fspath)
+        directory, filename = os.path.split(abspath)
+        return filename in os.listdir(directory)
+
+    def _add_defaults_standards(self):
+        standards = [self.READMES, self.distribution.script_name]
+        for fn in standards:
+            if isinstance(fn, tuple):
+                alts = fn
+                got_it = False
+                for fn in alts:
+                    if self._cs_path_exists(fn):
+                        got_it = True
+                        self.filelist.append(fn)
+                        break
+
+                if not got_it:
+                    self.warn(
+                        "standard file not found: should have one of " + ', '.join(alts)
+                    )
+            else:
+                if self._cs_path_exists(fn):
+                    self.filelist.append(fn)
+                else:
+                    self.warn(f"standard file '{fn}' not found")
+
+    def _add_defaults_optional(self):
+        optional = ['tests/test*.py', 'test/test*.py', 'setup.cfg']
+        for pattern in optional:
+            files = filter(os.path.isfile, glob(pattern))
+            self.filelist.extend(files)
+
+    def _add_defaults_python(self):
+        # build_py is used to get:
+        #  - python modules
+        #  - files defined in package_data
+        build_py = self.get_finalized_command('build_py')
+
+        # getting python files
+        if self.distribution.has_pure_modules():
+            self.filelist.extend(build_py.get_source_files())
+
+        # getting package_data files
+        # (computed in build_py.data_files by build_py.finalize_options)
+        for _pkg, src_dir, _build_dir, filenames in build_py.data_files:
+            for filename in filenames:
+                self.filelist.append(os.path.join(src_dir, filename))
+
+    def _add_defaults_data_files(self):
+        # getting distribution.data_files
+        if self.distribution.has_data_files():
+            for item in self.distribution.data_files:
+                if isinstance(item, str):
+                    # plain file
+                    item = convert_path(item)
+                    if os.path.isfile(item):
+                        self.filelist.append(item)
+                else:
+                    # a (dirname, filenames) tuple
+                    dirname, filenames = item
+                    for f in filenames:
+                        f = convert_path(f)
+                        if os.path.isfile(f):
+                            self.filelist.append(f)
+
+    def _add_defaults_ext(self):
+        if self.distribution.has_ext_modules():
+            build_ext = self.get_finalized_command('build_ext')
+            self.filelist.extend(build_ext.get_source_files())
+
+    def _add_defaults_c_libs(self):
+        if self.distribution.has_c_libraries():
+            build_clib = self.get_finalized_command('build_clib')
+            self.filelist.extend(build_clib.get_source_files())
+
+    def _add_defaults_scripts(self):
+        if self.distribution.has_scripts():
+            build_scripts = self.get_finalized_command('build_scripts')
+            self.filelist.extend(build_scripts.get_source_files())
+
+    def read_template(self) -> None:
+        """Read and parse manifest template file named by self.template.
+
+        (usually "MANIFEST.in") The parsing and processing is done by
+        'self.filelist', which updates itself accordingly.
+        """
+        log.info("reading manifest template '%s'", self.template)
+        template = TextFile(
+            self.template,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            lstrip_ws=True,
+            rstrip_ws=True,
+            collapse_join=True,
+        )
+
+        try:
+            while True:
+                line = template.readline()
+                if line is None:  # end of file
+                    break
+
+                try:
+                    self.filelist.process_template_line(line)
+                # the call above can raise a DistutilsTemplateError for
+                # malformed lines, or a ValueError from the lower-level
+                # convert_path function
+                except (DistutilsTemplateError, ValueError) as msg:
+                    self.warn(
+                        f"{template.filename}, line {int(template.current_line)}: {msg}"
+                    )
+        finally:
+            template.close()
+
+    def prune_file_list(self) -> None:
+        """Prune off branches that might slip into the file list as created
+        by 'read_template()', but really don't belong there:
+          * the build tree (typically "build")
+          * the release tree itself (only an issue if we ran "sdist"
+            previously with --keep-temp, or it aborted)
+          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
+        """
+        build = self.get_finalized_command('build')
+        base_dir = self.distribution.get_fullname()
+
+        self.filelist.exclude_pattern(None, prefix=os.fspath(build.build_base))
+        self.filelist.exclude_pattern(None, prefix=base_dir)
+
+        if sys.platform == 'win32':
+            seps = r'/|\\'
+        else:
+            seps = '/'
+
+        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs']
+        vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps)
+        self.filelist.exclude_pattern(vcs_ptrn, is_regex=True)
+
+    def write_manifest(self) -> None:
+        """Write the file list in 'self.filelist' (presumably as filled in
+        by 'add_defaults()' and 'read_template()') to the manifest file
+        named by 'self.manifest'.
+        """
+        if self._manifest_is_not_generated():
+            log.info(
+                f"not writing to manually maintained manifest file '{self.manifest}'"
+            )
+            return
+
+        content = self.filelist.files[:]
+        content.insert(0, '# file GENERATED by distutils, do NOT edit')
+        self.execute(
+            file_util.write_file,
+            (self.manifest, content),
+            f"writing manifest file '{self.manifest}'",
+        )
+
+    def _manifest_is_not_generated(self):
+        # check for special comment used in 3.1.3 and higher
+        if not os.path.isfile(self.manifest):
+            return False
+
+        with open(self.manifest, encoding='utf-8') as fp:
+            first_line = next(fp)
+        return first_line != '# file GENERATED by distutils, do NOT edit\n'
+
+    def read_manifest(self) -> None:
+        """Read the manifest file (named by 'self.manifest') and use it to
+        fill in 'self.filelist', the list of files to include in the source
+        distribution.
+        """
+        log.info("reading manifest file '%s'", self.manifest)
+        with open(self.manifest, encoding='utf-8') as lines:
+            self.filelist.extend(
+                # ignore comments and blank lines
+                filter(None, filterfalse(is_comment, map(str.strip, lines)))
+            )
+
+    def make_release_tree(self, base_dir, files) -> None:
+        """Create the directory tree that will become the source
+        distribution archive.  All directories implied by the filenames in
+        'files' are created under 'base_dir', and then we hard link or copy
+        (if hard linking is unavailable) those files into place.
+        Essentially, this duplicates the developer's source tree, but in a
+        directory named after the distribution, containing only the files
+        to be distributed.
+        """
+        # Create all the directories under 'base_dir' necessary to
+        # put 'files' there; the 'mkpath()' is just so we don't die
+        # if the manifest happens to be empty.
+        self.mkpath(base_dir)
+        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
+
+        # And walk over the list of files, either making a hard link (if
+        # os.link exists) to each one that doesn't already exist in its
+        # corresponding location under 'base_dir', or copying each file
+        # that's out-of-date in 'base_dir'.  (Usually, all files will be
+        # out-of-date, because by default we blow away 'base_dir' when
+        # we're done making the distribution archives.)
+
+        if hasattr(os, 'link'):  # can make hard links on this system
+            link = 'hard'
+            msg = f"making hard links in {base_dir}..."
+        else:  # nope, have to copy
+            link = None
+            msg = f"copying files to {base_dir}..."
+
+        if not files:
+            log.warning("no files to distribute -- empty manifest?")
+        else:
+            log.info(msg)
+        for file in files:
+            if not os.path.isfile(file):
+                log.warning("'%s' not a regular file -- skipping", file)
+            else:
+                dest = os.path.join(base_dir, file)
+                self.copy_file(file, dest, link=link)
+
+        self.distribution.metadata.write_pkg_info(base_dir)
+
+    def make_distribution(self) -> None:
+        """Create the source distribution(s).  First, we create the release
+        tree with 'make_release_tree()'; then, we create all required
+        archive files (according to 'self.formats') from the release tree.
+        Finally, we clean up by blowing away the release tree (unless
+        'self.keep_temp' is true).  The list of archive files created is
+        stored so it can be retrieved later by 'get_archive_files()'.
+        """
+        # Don't warn about missing meta-data here -- should be (and is!)
+        # done elsewhere.
+        base_dir = self.distribution.get_fullname()
+        base_name = os.path.join(self.dist_dir, base_dir)
+
+        self.make_release_tree(base_dir, self.filelist.files)
+        archive_files = []  # remember names of files we create
+        # tar archive must be created last to avoid overwrite and remove
+        if 'tar' in self.formats:
+            self.formats.append(self.formats.pop(self.formats.index('tar')))
+
+        for fmt in self.formats:
+            file = self.make_archive(
+                base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group
+            )
+            archive_files.append(file)
+            self.distribution.dist_files.append(('sdist', '', file))
+
+        self.archive_files = archive_files
+
+        if not self.keep_temp:
+            dir_util.remove_tree(base_dir, dry_run=self.dry_run)
+
+    def get_archive_files(self):
+        """Return the list of archive files created when the command
+        was run, or None if the command hasn't run yet.
+        """
+        return self.archive_files
+
+
+def is_comment(line: str) -> bool:
+    return line.startswith('#')
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c43729b09ea5e5bf9d8c0708e63c69b5114a279
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/__init__.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import TypeVar
+
+_IterableT = TypeVar("_IterableT", bound="Iterable[str]")
+
+
+def consolidate_linker_args(args: _IterableT) -> _IterableT | str:
+    """
+    Ensure the return value is a string for backward compatibility.
+
+    Retain until at least 2025-04-31. See pypa/distutils#246
+    """
+
+    if not all(arg.startswith('-Wl,') for arg in args):
+        return args
+    return '-Wl,' + ','.join(arg.removeprefix('-Wl,') for arg in args)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compat/numpy.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..73eca7acb103b7c7ca8e7a9f7f2d772a64aa344b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/numpy.py
@@ -0,0 +1,2 @@
+# required for older numpy versions on Pythons prior to 3.12; see pypa/setuptools#4876
+from ..compilers.C.base import _default_compilers, compiler_class  # noqa: F401
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compat/py39.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b436d76586cbcf38164548f3fc849ce1a3ff600
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compat/py39.py
@@ -0,0 +1,66 @@
+import functools
+import itertools
+import platform
+import sys
+
+
+def add_ext_suffix_39(vars):
+    """
+    Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130
+    """
+    import _imp
+
+    ext_suffix = _imp.extension_suffixes()[0]
+    vars.update(
+        EXT_SUFFIX=ext_suffix,
+        # sysconfig sets SO to match EXT_SUFFIX, so maintain
+        # that expectation.
+        # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673
+        SO=ext_suffix,
+    )
+
+
+needs_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows'
+add_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None
+
+
+# from more_itertools
+class UnequalIterablesError(ValueError):
+    def __init__(self, details=None):
+        msg = 'Iterables have different lengths'
+        if details is not None:
+            msg += (': index 0 has length {}; index {} has length {}').format(*details)
+
+        super().__init__(msg)
+
+
+# from more_itertools
+def _zip_equal_generator(iterables):
+    _marker = object()
+    for combo in itertools.zip_longest(*iterables, fillvalue=_marker):
+        for val in combo:
+            if val is _marker:
+                raise UnequalIterablesError()
+        yield combo
+
+
+# from more_itertools
+def _zip_equal(*iterables):
+    # Check whether the iterables are all the same size.
+    try:
+        first_size = len(iterables[0])
+        for i, it in enumerate(iterables[1:], 1):
+            size = len(it)
+            if size != first_size:
+                raise UnequalIterablesError(details=(first_size, i, size))
+        # All sizes are equal, we can use the built-in zip.
+        return zip(*iterables)
+    # If any one of the iterables didn't have a length, start reading
+    # them until one runs out.
+    except TypeError:
+        return _zip_equal_generator(iterables)
+
+
+zip_strict = (
+    _zip_equal if sys.version_info < (3, 10) else functools.partial(zip, strict=True)
+)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/base.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5efd2a39d6a8cd7a722b7aefc3de4f1def4e4788
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/base.py
@@ -0,0 +1,1394 @@
+"""distutils.ccompiler
+
+Contains Compiler, an abstract base class that defines the interface
+for the Distutils compiler abstraction model."""
+
+from __future__ import annotations
+
+import os
+import pathlib
+import re
+import sys
+import warnings
+from collections.abc import Callable, Iterable, MutableSequence, Sequence
+from typing import (
+    TYPE_CHECKING,
+    ClassVar,
+    Literal,
+    TypeVar,
+    Union,
+    overload,
+)
+
+from more_itertools import always_iterable
+
+from ..._log import log
+from ..._modified import newer_group
+from ...dir_util import mkpath
+from ...errors import (
+    DistutilsModuleError,
+    DistutilsPlatformError,
+)
+from ...file_util import move_file
+from ...spawn import spawn
+from ...util import execute, is_mingw, split_quoted
+from .errors import (
+    CompileError,
+    LinkError,
+    UnknownFileType,
+)
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeAlias, TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
+
+_Macro: TypeAlias = Union[tuple[str], tuple[str, Union[str, None]]]
+_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
+_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
+
+
+class Compiler:
+    """Abstract base class to define the interface that must be implemented
+    by real compiler classes.  Also has some utility methods used by
+    several compiler classes.
+
+    The basic idea behind a compiler abstraction class is that each
+    instance can be used for all the compile/link steps in building a
+    single project.  Thus, attributes common to all of those compile and
+    link steps -- include directories, macros to define, libraries to link
+    against, etc. -- are attributes of the compiler instance.  To allow for
+    variability in how individual files are treated, most of those
+    attributes may be varied on a per-compilation or per-link basis.
+    """
+
+    # 'compiler_type' is a class attribute that identifies this class.  It
+    # keeps code that wants to know what kind of compiler it's dealing with
+    # from having to import all possible compiler classes just to do an
+    # 'isinstance'.  In concrete CCompiler subclasses, 'compiler_type'
+    # should really, really be one of the keys of the 'compiler_class'
+    # dictionary (see below -- used by the 'new_compiler()' factory
+    # function) -- authors of new compiler interface classes are
+    # responsible for updating 'compiler_class'!
+    compiler_type: ClassVar[str] = None  # type: ignore[assignment]
+
+    # XXX things not handled by this compiler abstraction model:
+    #   * client can't provide additional options for a compiler,
+    #     e.g. warning, optimization, debugging flags.  Perhaps this
+    #     should be the domain of concrete compiler abstraction classes
+    #     (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
+    #     class should have methods for the common ones.
+    #   * can't completely override the include or library searchg
+    #     path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
+    #     I'm not sure how widely supported this is even by Unix
+    #     compilers, much less on other platforms.  And I'm even less
+    #     sure how useful it is; maybe for cross-compiling, but
+    #     support for that is a ways off.  (And anyways, cross
+    #     compilers probably have a dedicated binary with the
+    #     right paths compiled in.  I hope.)
+    #   * can't do really freaky things with the library list/library
+    #     dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
+    #     different versions of libfoo.a in different locations.  I
+    #     think this is useless without the ability to null out the
+    #     library search path anyways.
+
+    executables: ClassVar[dict]
+
+    # Subclasses that rely on the standard filename generation methods
+    # implemented below should override these; see the comment near
+    # those methods ('object_filenames()' et. al.) for details:
+    src_extensions: ClassVar[list[str] | None] = None
+    obj_extension: ClassVar[str | None] = None
+    static_lib_extension: ClassVar[str | None] = None
+    shared_lib_extension: ClassVar[str | None] = None
+    static_lib_format: ClassVar[str | None] = None  # format string
+    shared_lib_format: ClassVar[str | None] = None  # prob. same as static_lib_format
+    exe_extension: ClassVar[str | None] = None
+
+    # Default language settings. language_map is used to detect a source
+    # file or Extension target language, checking source filenames.
+    # language_order is used to detect the language precedence, when deciding
+    # what language to use when mixing source types. For example, if some
+    # extension has two files with ".c" extension, and one with ".cpp", it
+    # is still linked as c++.
+    language_map: ClassVar[dict[str, str]] = {
+        ".c": "c",
+        ".cc": "c++",
+        ".cpp": "c++",
+        ".cxx": "c++",
+        ".m": "objc",
+    }
+    language_order: ClassVar[list[str]] = ["c++", "objc", "c"]
+
+    include_dirs: list[str] = []
+    """
+    include dirs specific to this compiler class
+    """
+
+    library_dirs: list[str] = []
+    """
+    library dirs specific to this compiler class
+    """
+
+    def __init__(
+        self, verbose: bool = False, dry_run: bool = False, force: bool = False
+    ) -> None:
+        self.dry_run = dry_run
+        self.force = force
+        self.verbose = verbose
+
+        # 'output_dir': a common output directory for object, library,
+        # shared object, and shared library files
+        self.output_dir: str | None = None
+
+        # 'macros': a list of macro definitions (or undefinitions).  A
+        # macro definition is a 2-tuple (name, value), where the value is
+        # either a string or None (no explicit value).  A macro
+        # undefinition is a 1-tuple (name,).
+        self.macros: list[_Macro] = []
+
+        # 'include_dirs': a list of directories to search for include files
+        self.include_dirs = []
+
+        # 'libraries': a list of libraries to include in any link
+        # (library names, not filenames: eg. "foo" not "libfoo.a")
+        self.libraries: list[str] = []
+
+        # 'library_dirs': a list of directories to search for libraries
+        self.library_dirs = []
+
+        # 'runtime_library_dirs': a list of directories to search for
+        # shared libraries/objects at runtime
+        self.runtime_library_dirs: list[str] = []
+
+        # 'objects': a list of object files (or similar, such as explicitly
+        # named library files) to include on any link
+        self.objects: list[str] = []
+
+        for key in self.executables.keys():
+            self.set_executable(key, self.executables[key])
+
+    def set_executables(self, **kwargs: str) -> None:
+        """Define the executables (and options for them) that will be run
+        to perform the various stages of compilation.  The exact set of
+        executables that may be specified here depends on the compiler
+        class (via the 'executables' class attribute), but most will have:
+          compiler      the C/C++ compiler
+          linker_so     linker used to create shared objects and libraries
+          linker_exe    linker used to create binary executables
+          archiver      static library creator
+
+        On platforms with a command-line (Unix, DOS/Windows), each of these
+        is a string that will be split into executable name and (optional)
+        list of arguments.  (Splitting the string is done similarly to how
+        Unix shells operate: words are delimited by spaces, but quotes and
+        backslashes can override this.  See
+        'distutils.util.split_quoted()'.)
+        """
+
+        # Note that some CCompiler implementation classes will define class
+        # attributes 'cpp', 'cc', etc. with hard-coded executable names;
+        # this is appropriate when a compiler class is for exactly one
+        # compiler/OS combination (eg. MSVCCompiler).  Other compiler
+        # classes (UnixCCompiler, in particular) are driven by information
+        # discovered at run-time, since there are many different ways to do
+        # basically the same things with Unix C compilers.
+
+        for key in kwargs:
+            if key not in self.executables:
+                raise ValueError(
+                    f"unknown executable '{key}' for class {self.__class__.__name__}"
+                )
+            self.set_executable(key, kwargs[key])
+
+    def set_executable(self, key, value):
+        if isinstance(value, str):
+            setattr(self, key, split_quoted(value))
+        else:
+            setattr(self, key, value)
+
+    def _find_macro(self, name):
+        i = 0
+        for defn in self.macros:
+            if defn[0] == name:
+                return i
+            i += 1
+        return None
+
+    def _check_macro_definitions(self, definitions):
+        """Ensure that every element of 'definitions' is valid."""
+        for defn in definitions:
+            self._check_macro_definition(*defn)
+
+    def _check_macro_definition(self, defn):
+        """
+        Raise a TypeError if defn is not valid.
+
+        A valid definition is either a (name, value) 2-tuple or a (name,) tuple.
+        """
+        if not isinstance(defn, tuple) or not self._is_valid_macro(*defn):
+            raise TypeError(
+                f"invalid macro definition '{defn}': "
+                "must be tuple (string,), (string, string), or (string, None)"
+            )
+
+    @staticmethod
+    def _is_valid_macro(name, value=None):
+        """
+        A valid macro is a ``name : str`` and a ``value : str | None``.
+
+        >>> Compiler._is_valid_macro('foo', None)
+        True
+        """
+        return isinstance(name, str) and isinstance(value, (str, type(None)))
+
+    # -- Bookkeeping methods -------------------------------------------
+
+    def define_macro(self, name: str, value: str | None = None) -> None:
+        """Define a preprocessor macro for all compilations driven by this
+        compiler object.  The optional parameter 'value' should be a
+        string; if it is not supplied, then the macro will be defined
+        without an explicit value and the exact outcome depends on the
+        compiler used (XXX true? does ANSI say anything about this?)
+        """
+        # Delete from the list of macro definitions/undefinitions if
+        # already there (so that this one will take precedence).
+        i = self._find_macro(name)
+        if i is not None:
+            del self.macros[i]
+
+        self.macros.append((name, value))
+
+    def undefine_macro(self, name: str) -> None:
+        """Undefine a preprocessor macro for all compilations driven by
+        this compiler object.  If the same macro is defined by
+        'define_macro()' and undefined by 'undefine_macro()' the last call
+        takes precedence (including multiple redefinitions or
+        undefinitions).  If the macro is redefined/undefined on a
+        per-compilation basis (ie. in the call to 'compile()'), then that
+        takes precedence.
+        """
+        # Delete from the list of macro definitions/undefinitions if
+        # already there (so that this one will take precedence).
+        i = self._find_macro(name)
+        if i is not None:
+            del self.macros[i]
+
+        undefn = (name,)
+        self.macros.append(undefn)
+
+    def add_include_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        header files.  The compiler is instructed to search directories in
+        the order in which they are supplied by successive calls to
+        'add_include_dir()'.
+        """
+        self.include_dirs.append(dir)
+
+    def set_include_dirs(self, dirs: list[str]) -> None:
+        """Set the list of directories that will be searched to 'dirs' (a
+        list of strings).  Overrides any preceding calls to
+        'add_include_dir()'; subsequence calls to 'add_include_dir()' add
+        to the list passed to 'set_include_dirs()'.  This does not affect
+        any list of standard include directories that the compiler may
+        search by default.
+        """
+        self.include_dirs = dirs[:]
+
+    def add_library(self, libname: str) -> None:
+        """Add 'libname' to the list of libraries that will be included in
+        all links driven by this compiler object.  Note that 'libname'
+        should *not* be the name of a file containing a library, but the
+        name of the library itself: the actual filename will be inferred by
+        the linker, the compiler, or the compiler class (depending on the
+        platform).
+
+        The linker will be instructed to link against libraries in the
+        order they were supplied to 'add_library()' and/or
+        'set_libraries()'.  It is perfectly valid to duplicate library
+        names; the linker will be instructed to link against libraries as
+        many times as they are mentioned.
+        """
+        self.libraries.append(libname)
+
+    def set_libraries(self, libnames: list[str]) -> None:
+        """Set the list of libraries to be included in all links driven by
+        this compiler object to 'libnames' (a list of strings).  This does
+        not affect any standard system libraries that the linker may
+        include by default.
+        """
+        self.libraries = libnames[:]
+
+    def add_library_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        libraries specified to 'add_library()' and 'set_libraries()'.  The
+        linker will be instructed to search for libraries in the order they
+        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
+        """
+        self.library_dirs.append(dir)
+
+    def set_library_dirs(self, dirs: list[str]) -> None:
+        """Set the list of library search directories to 'dirs' (a list of
+        strings).  This does not affect any standard library search path
+        that the linker may search by default.
+        """
+        self.library_dirs = dirs[:]
+
+    def add_runtime_library_dir(self, dir: str) -> None:
+        """Add 'dir' to the list of directories that will be searched for
+        shared libraries at runtime.
+        """
+        self.runtime_library_dirs.append(dir)
+
+    def set_runtime_library_dirs(self, dirs: list[str]) -> None:
+        """Set the list of directories to search for shared libraries at
+        runtime to 'dirs' (a list of strings).  This does not affect any
+        standard search path that the runtime linker may search by
+        default.
+        """
+        self.runtime_library_dirs = dirs[:]
+
+    def add_link_object(self, object: str) -> None:
+        """Add 'object' to the list of object files (or analogues, such as
+        explicitly named library files or the output of "resource
+        compilers") to be included in every link driven by this compiler
+        object.
+        """
+        self.objects.append(object)
+
+    def set_link_objects(self, objects: list[str]) -> None:
+        """Set the list of object files (or analogues) to be included in
+        every link to 'objects'.  This does not affect any standard object
+        files that the linker may include by default (such as system
+        libraries).
+        """
+        self.objects = objects[:]
+
+    # -- Private utility methods --------------------------------------
+    # (here for the convenience of subclasses)
+
+    # Helper method to prep compiler in subclass compile() methods
+
+    def _setup_compile(
+        self,
+        outdir: str | None,
+        macros: list[_Macro] | None,
+        incdirs: list[str] | tuple[str, ...] | None,
+        sources,
+        depends,
+        extra,
+    ):
+        """Process arguments and decide which source files to compile."""
+        outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)
+
+        if extra is None:
+            extra = []
+
+        # Get the list of expected output (object) files
+        objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir)
+        assert len(objects) == len(sources)
+
+        pp_opts = gen_preprocess_options(macros, incdirs)
+
+        build = {}
+        for i in range(len(sources)):
+            src = sources[i]
+            obj = objects[i]
+            ext = os.path.splitext(src)[1]
+            self.mkpath(os.path.dirname(obj))
+            build[obj] = (src, ext)
+
+        return macros, objects, extra, pp_opts, build
+
+    def _get_cc_args(self, pp_opts, debug, before):
+        # works for unixccompiler, cygwinccompiler
+        cc_args = pp_opts + ['-c']
+        if debug:
+            cc_args[:0] = ['-g']
+        if before:
+            cc_args[:0] = before
+        return cc_args
+
+    def _fix_compile_args(
+        self,
+        output_dir: str | None,
+        macros: list[_Macro] | None,
+        include_dirs: list[str] | tuple[str, ...] | None,
+    ) -> tuple[str, list[_Macro], list[str]]:
+        """Typecheck and fix-up some of the arguments to the 'compile()'
+        method, and return fixed-up values.  Specifically: if 'output_dir'
+        is None, replaces it with 'self.output_dir'; ensures that 'macros'
+        is a list, and augments it with 'self.macros'; ensures that
+        'include_dirs' is a list, and augments it with 'self.include_dirs'.
+        Guarantees that the returned values are of the correct type,
+        i.e. for 'output_dir' either string or None, and for 'macros' and
+        'include_dirs' either list or None.
+        """
+        if output_dir is None:
+            output_dir = self.output_dir
+        elif not isinstance(output_dir, str):
+            raise TypeError("'output_dir' must be a string or None")
+
+        if macros is None:
+            macros = list(self.macros)
+        elif isinstance(macros, list):
+            macros = macros + (self.macros or [])
+        else:
+            raise TypeError("'macros' (if supplied) must be a list of tuples")
+
+        if include_dirs is None:
+            include_dirs = list(self.include_dirs)
+        elif isinstance(include_dirs, (list, tuple)):
+            include_dirs = list(include_dirs) + (self.include_dirs or [])
+        else:
+            raise TypeError("'include_dirs' (if supplied) must be a list of strings")
+
+        # add include dirs for class
+        include_dirs += self.__class__.include_dirs
+
+        return output_dir, macros, include_dirs
+
+    def _prep_compile(self, sources, output_dir, depends=None):
+        """Decide which source files must be recompiled.
+
+        Determine the list of object files corresponding to 'sources',
+        and figure out which ones really need to be recompiled.
+        Return a list of all object files and a dictionary telling
+        which source files can be skipped.
+        """
+        # Get the list of expected output (object) files
+        objects = self.object_filenames(sources, output_dir=output_dir)
+        assert len(objects) == len(sources)
+
+        # Return an empty dict for the "which source files can be skipped"
+        # return value to preserve API compatibility.
+        return objects, {}
+
+    def _fix_object_args(
+        self, objects: list[str] | tuple[str, ...], output_dir: str | None
+    ) -> tuple[list[str], str]:
+        """Typecheck and fix up some arguments supplied to various methods.
+        Specifically: ensure that 'objects' is a list; if output_dir is
+        None, replace with self.output_dir.  Return fixed versions of
+        'objects' and 'output_dir'.
+        """
+        if not isinstance(objects, (list, tuple)):
+            raise TypeError("'objects' must be a list or tuple of strings")
+        objects = list(objects)
+
+        if output_dir is None:
+            output_dir = self.output_dir
+        elif not isinstance(output_dir, str):
+            raise TypeError("'output_dir' must be a string or None")
+
+        return (objects, output_dir)
+
+    def _fix_lib_args(
+        self,
+        libraries: list[str] | tuple[str, ...] | None,
+        library_dirs: list[str] | tuple[str, ...] | None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None,
+    ) -> tuple[list[str], list[str], list[str]]:
+        """Typecheck and fix up some of the arguments supplied to the
+        'link_*' methods.  Specifically: ensure that all arguments are
+        lists, and augment them with their permanent versions
+        (eg. 'self.libraries' augments 'libraries').  Return a tuple with
+        fixed versions of all arguments.
+        """
+        if libraries is None:
+            libraries = list(self.libraries)
+        elif isinstance(libraries, (list, tuple)):
+            libraries = list(libraries) + (self.libraries or [])
+        else:
+            raise TypeError("'libraries' (if supplied) must be a list of strings")
+
+        if library_dirs is None:
+            library_dirs = list(self.library_dirs)
+        elif isinstance(library_dirs, (list, tuple)):
+            library_dirs = list(library_dirs) + (self.library_dirs or [])
+        else:
+            raise TypeError("'library_dirs' (if supplied) must be a list of strings")
+
+        # add library dirs for class
+        library_dirs += self.__class__.library_dirs
+
+        if runtime_library_dirs is None:
+            runtime_library_dirs = list(self.runtime_library_dirs)
+        elif isinstance(runtime_library_dirs, (list, tuple)):
+            runtime_library_dirs = list(runtime_library_dirs) + (
+                self.runtime_library_dirs or []
+            )
+        else:
+            raise TypeError(
+                "'runtime_library_dirs' (if supplied) must be a list of strings"
+            )
+
+        return (libraries, library_dirs, runtime_library_dirs)
+
+    def _need_link(self, objects, output_file):
+        """Return true if we need to relink the files listed in 'objects'
+        to recreate 'output_file'.
+        """
+        if self.force:
+            return True
+        else:
+            if self.dry_run:
+                newer = newer_group(objects, output_file, missing='newer')
+            else:
+                newer = newer_group(objects, output_file)
+            return newer
+
+    def detect_language(self, sources: str | list[str]) -> str | None:
+        """Detect the language of a given file, or list of files. Uses
+        language_map, and language_order to do the job.
+        """
+        if not isinstance(sources, list):
+            sources = [sources]
+        lang = None
+        index = len(self.language_order)
+        for source in sources:
+            base, ext = os.path.splitext(source)
+            extlang = self.language_map.get(ext)
+            try:
+                extindex = self.language_order.index(extlang)
+                if extindex < index:
+                    lang = extlang
+                    index = extindex
+            except ValueError:
+                pass
+        return lang
+
+    # -- Worker methods ------------------------------------------------
+    # (must be implemented by subclasses)
+
+    def preprocess(
+        self,
+        source: str | os.PathLike[str],
+        output_file: str | os.PathLike[str] | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+    ):
+        """Preprocess a single C/C++ source file, named in 'source'.
+        Output will be written to file named 'output_file', or stdout if
+        'output_file' not supplied.  'macros' is a list of macro
+        definitions as for 'compile()', which will augment the macros set
+        with 'define_macro()' and 'undefine_macro()'.  'include_dirs' is a
+        list of directory names that will be added to the default list.
+
+        Raises PreprocessError on failure.
+        """
+        pass
+
+    def compile(
+        self,
+        sources: Sequence[str | os.PathLike[str]],
+        output_dir: str | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        depends: list[str] | tuple[str, ...] | None = None,
+    ) -> list[str]:
+        """Compile one or more source files.
+
+        'sources' must be a list of filenames, most likely C/C++
+        files, but in reality anything that can be handled by a
+        particular compiler and compiler class (eg. MSVCCompiler can
+        handle resource files in 'sources').  Return a list of object
+        filenames, one per source filename in 'sources'.  Depending on
+        the implementation, not all source files will necessarily be
+        compiled, but all corresponding object filenames will be
+        returned.
+
+        If 'output_dir' is given, object files will be put under it, while
+        retaining their original path component.  That is, "foo/bar.c"
+        normally compiles to "foo/bar.o" (for a Unix implementation); if
+        'output_dir' is "build", then it would compile to
+        "build/foo/bar.o".
+
+        'macros', if given, must be a list of macro definitions.  A macro
+        definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
+        The former defines a macro; if the value is None, the macro is
+        defined without an explicit value.  The 1-tuple case undefines a
+        macro.  Later definitions/redefinitions/ undefinitions take
+        precedence.
+
+        'include_dirs', if given, must be a list of strings, the
+        directories to add to the default include file search path for this
+        compilation only.
+
+        'debug' is a boolean; if true, the compiler will be instructed to
+        output debug symbols in (or alongside) the object file(s).
+
+        'extra_preargs' and 'extra_postargs' are implementation- dependent.
+        On platforms that have the notion of a command-line (e.g. Unix,
+        DOS/Windows), they are most likely lists of strings: extra
+        command-line arguments to prepend/append to the compiler command
+        line.  On other platforms, consult the implementation class
+        documentation.  In any event, they are intended as an escape hatch
+        for those occasions when the abstract compiler framework doesn't
+        cut the mustard.
+
+        'depends', if given, is a list of filenames that all targets
+        depend on.  If a source file is older than any file in
+        depends, then the source file will be recompiled.  This
+        supports dependency tracking, but only at a coarse
+        granularity.
+
+        Raises CompileError on failure.
+        """
+        # A concrete compiler class can either override this method
+        # entirely or implement _compile().
+        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
+            output_dir, macros, include_dirs, sources, depends, extra_postargs
+        )
+        cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
+
+        for obj in objects:
+            try:
+                src, ext = build[obj]
+            except KeyError:
+                continue
+            self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
+
+        # Return *all* object filenames, not just the ones we just built.
+        return objects
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        """Compile 'src' to product 'obj'."""
+        # A concrete compiler class that does not override compile()
+        # should implement _compile().
+        pass
+
+    def create_static_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        debug: bool = False,
+        target_lang: str | None = None,
+    ) -> None:
+        """Link a bunch of stuff together to create a static library file.
+        The "bunch of stuff" consists of the list of object files supplied
+        as 'objects', the extra object files supplied to
+        'add_link_object()' and/or 'set_link_objects()', the libraries
+        supplied to 'add_library()' and/or 'set_libraries()', and the
+        libraries supplied as 'libraries' (if any).
+
+        'output_libname' should be a library name, not a filename; the
+        filename will be inferred from the library name.  'output_dir' is
+        the directory where the library file will be put.
+
+        'debug' is a boolean; if true, debugging information will be
+        included in the library (note that on most platforms, it is the
+        compile step where this matters: the 'debug' flag is included here
+        just for consistency).
+
+        'target_lang' is the target language for which the given objects
+        are being compiled. This allows specific linkage time treatment of
+        certain languages.
+
+        Raises LibError on failure.
+        """
+        pass
+
+    # values for target_desc parameter in link()
+    SHARED_OBJECT = "shared_object"
+    SHARED_LIBRARY = "shared_library"
+    EXECUTABLE = "executable"
+
+    def link(
+        self,
+        target_desc: str,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        """Link a bunch of stuff together to create an executable or
+        shared library file.
+
+        The "bunch of stuff" consists of the list of object files supplied
+        as 'objects'.  'output_filename' should be a filename.  If
+        'output_dir' is supplied, 'output_filename' is relative to it
+        (i.e. 'output_filename' can provide directory components if
+        needed).
+
+        'libraries' is a list of libraries to link against.  These are
+        library names, not filenames, since they're translated into
+        filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
+        on Unix and "foo.lib" on DOS/Windows).  However, they can include a
+        directory component, which means the linker will look in that
+        specific directory rather than searching all the normal locations.
+
+        'library_dirs', if supplied, should be a list of directories to
+        search for libraries that were specified as bare library names
+        (ie. no directory component).  These are on top of the system
+        default and those supplied to 'add_library_dir()' and/or
+        'set_library_dirs()'.  'runtime_library_dirs' is a list of
+        directories that will be embedded into the shared library and used
+        to search for other shared libraries that *it* depends on at
+        run-time.  (This may only be relevant on Unix.)
+
+        'export_symbols' is a list of symbols that the shared library will
+        export.  (This appears to be relevant only on Windows.)
+
+        'debug' is as for 'compile()' and 'create_static_lib()', with the
+        slight distinction that it actually matters on most platforms (as
+        opposed to 'create_static_lib()', which includes a 'debug' flag
+        mostly for form's sake).
+
+        'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
+        of course that they supply command-line arguments for the
+        particular linker being used).
+
+        'target_lang' is the target language for which the given objects
+        are being compiled. This allows specific linkage time treatment of
+        certain languages.
+
+        Raises LinkError on failure.
+        """
+        raise NotImplementedError
+
+    # Old 'link_*()' methods, rewritten to use the new 'link()' method.
+
+    def link_shared_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.SHARED_LIBRARY,
+            objects,
+            self.library_filename(output_libname, lib_type='shared'),
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def link_shared_object(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.SHARED_OBJECT,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def link_executable(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_progname: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: list[str] | None = None,
+        target_lang: str | None = None,
+    ):
+        self.link(
+            Compiler.EXECUTABLE,
+            objects,
+            self.executable_filename(output_progname),
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            None,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            None,
+            target_lang,
+        )
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function; there is
+    # no appropriate default implementation so subclasses should
+    # implement all of these.
+
+    def library_dir_option(self, dir: str) -> str:
+        """Return the compiler option to add 'dir' to the list of
+        directories searched for libraries.
+        """
+        raise NotImplementedError
+
+    def runtime_library_dir_option(self, dir: str) -> str:
+        """Return the compiler option to add 'dir' to the list of
+        directories searched for runtime libraries.
+        """
+        raise NotImplementedError
+
+    def library_option(self, lib: str) -> str:
+        """Return the compiler option to add 'lib' to the list of libraries
+        linked into the shared library or executable.
+        """
+        raise NotImplementedError
+
+    def has_function(  # noqa: C901
+        self,
+        funcname: str,
+        includes: Iterable[str] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        libraries: list[str] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+    ) -> bool:
+        """Return a boolean indicating whether funcname is provided as
+        a symbol on the current platform.  The optional arguments can
+        be used to augment the compilation environment.
+
+        The libraries argument is a list of flags to be passed to the
+        linker to make additional symbol definitions available for
+        linking.
+
+        The includes and include_dirs arguments are deprecated.
+        Usually, supplying include files with function declarations
+        will cause function detection to fail even in cases where the
+        symbol is available for linking.
+
+        """
+        # this can't be included at module scope because it tries to
+        # import math which might not be available at that point - maybe
+        # the necessary logic should just be inlined?
+        import tempfile
+
+        if includes is None:
+            includes = []
+        else:
+            warnings.warn("includes is deprecated", DeprecationWarning)
+        if include_dirs is None:
+            include_dirs = []
+        else:
+            warnings.warn("include_dirs is deprecated", DeprecationWarning)
+        if libraries is None:
+            libraries = []
+        if library_dirs is None:
+            library_dirs = []
+        fd, fname = tempfile.mkstemp(".c", funcname, text=True)
+        with os.fdopen(fd, "w", encoding='utf-8') as f:
+            for incl in includes:
+                f.write(f"""#include "{incl}"\n""")
+            if not includes:
+                # Use "char func(void);" as the prototype to follow
+                # what autoconf does.  This prototype does not match
+                # any well-known function the compiler might recognize
+                # as a builtin, so this ends up as a true link test.
+                # Without a fake prototype, the test would need to
+                # know the exact argument types, and the has_function
+                # interface does not provide that level of information.
+                f.write(
+                    f"""\
+#ifdef __cplusplus
+extern "C"
+#endif
+char {funcname}(void);
+"""
+                )
+            f.write(
+                f"""\
+int main (int argc, char **argv) {{
+    {funcname}();
+    return 0;
+}}
+"""
+            )
+
+        try:
+            objects = self.compile([fname], include_dirs=include_dirs)
+        except CompileError:
+            return False
+        finally:
+            os.remove(fname)
+
+        try:
+            self.link_executable(
+                objects, "a.out", libraries=libraries, library_dirs=library_dirs
+            )
+        except (LinkError, TypeError):
+            return False
+        else:
+            os.remove(
+                self.executable_filename("a.out", output_dir=self.output_dir or '')
+            )
+        finally:
+            for fn in objects:
+                os.remove(fn)
+        return True
+
+    def find_library_file(
+        self, dirs: Iterable[str], lib: str, debug: bool = False
+    ) -> str | None:
+        """Search the specified list of directories for a static or shared
+        library file 'lib' and return the full path to that file.  If
+        'debug' true, look for a debugging version (if that makes sense on
+        the current platform).  Return None if 'lib' wasn't found in any of
+        the specified directories.
+        """
+        raise NotImplementedError
+
+    # -- Filename generation methods -----------------------------------
+
+    # The default implementation of the filename generating methods are
+    # prejudiced towards the Unix/DOS/Windows view of the world:
+    #   * object files are named by replacing the source file extension
+    #     (eg. .c/.cpp -> .o/.obj)
+    #   * library files (shared or static) are named by plugging the
+    #     library name and extension into a format string, eg.
+    #     "lib%s.%s" % (lib_name, ".a") for Unix static libraries
+    #   * executables are named by appending an extension (possibly
+    #     empty) to the program name: eg. progname + ".exe" for
+    #     Windows
+    #
+    # To reduce redundant code, these methods expect to find
+    # several attributes in the current object (presumably defined
+    # as class attributes):
+    #   * src_extensions -
+    #     list of C/C++ source file extensions, eg. ['.c', '.cpp']
+    #   * obj_extension -
+    #     object file extension, eg. '.o' or '.obj'
+    #   * static_lib_extension -
+    #     extension for static library files, eg. '.a' or '.lib'
+    #   * shared_lib_extension -
+    #     extension for shared library/object files, eg. '.so', '.dll'
+    #   * static_lib_format -
+    #     format string for generating static library filenames,
+    #     eg. 'lib%s.%s' or '%s.%s'
+    #   * shared_lib_format
+    #     format string for generating shared library filenames
+    #     (probably same as static_lib_format, since the extension
+    #     is one of the intended parameters to the format string)
+    #   * exe_extension -
+    #     extension for executable files, eg. '' or '.exe'
+
+    def object_filenames(
+        self,
+        source_filenames: Iterable[str | os.PathLike[str]],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] | None = '',
+    ) -> list[str]:
+        if output_dir is None:
+            output_dir = ''
+        return list(
+            self._make_out_path(output_dir, strip_dir, src_name)
+            for src_name in source_filenames
+        )
+
+    @property
+    def out_extensions(self):
+        return dict.fromkeys(self.src_extensions, self.obj_extension)
+
+    def _make_out_path(self, output_dir, strip_dir, src_name):
+        return self._make_out_path_exts(
+            output_dir, strip_dir, src_name, self.out_extensions
+        )
+
+    @classmethod
+    def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions):
+        r"""
+        >>> exts = {'.c': '.o'}
+        >>> Compiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/')
+        './foo/bar.o'
+        >>> Compiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/')
+        './bar.o'
+        """
+        src = pathlib.PurePath(src_name)
+        # Ensure base is relative to honor output_dir (python/cpython#37775).
+        base = cls._make_relative(src)
+        try:
+            new_ext = extensions[src.suffix]
+        except LookupError:
+            raise UnknownFileType(f"unknown file type '{src.suffix}' (from '{src}')")
+        if strip_dir:
+            base = pathlib.PurePath(base.name)
+        return os.path.join(output_dir, base.with_suffix(new_ext))
+
+    @staticmethod
+    def _make_relative(base: pathlib.Path):
+        return base.relative_to(base.anchor)
+
+    @overload
+    def shared_object_filename(
+        self,
+        basename: str,
+        strip_dir: Literal[False] = False,
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    @overload
+    def shared_object_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: Literal[True],
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    def shared_object_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = '',
+    ) -> str:
+        assert output_dir is not None
+        if strip_dir:
+            basename = os.path.basename(basename)
+        return os.path.join(output_dir, basename + self.shared_lib_extension)
+
+    @overload
+    def executable_filename(
+        self,
+        basename: str,
+        strip_dir: Literal[False] = False,
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    @overload
+    def executable_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: Literal[True],
+        output_dir: str | os.PathLike[str] = "",
+    ) -> str: ...
+    def executable_filename(
+        self,
+        basename: str | os.PathLike[str],
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = '',
+    ) -> str:
+        assert output_dir is not None
+        if strip_dir:
+            basename = os.path.basename(basename)
+        return os.path.join(output_dir, basename + (self.exe_extension or ''))
+
+    def library_filename(
+        self,
+        libname: str,
+        lib_type: str = "static",
+        strip_dir: bool = False,
+        output_dir: str | os.PathLike[str] = "",  # or 'shared'
+    ):
+        assert output_dir is not None
+        expected = '"static", "shared", "dylib", "xcode_stub"'
+        if lib_type not in eval(expected):
+            raise ValueError(f"'lib_type' must be {expected}")
+        fmt = getattr(self, lib_type + "_lib_format")
+        ext = getattr(self, lib_type + "_lib_extension")
+
+        dir, base = os.path.split(libname)
+        filename = fmt % (base, ext)
+        if strip_dir:
+            dir = ''
+
+        return os.path.join(output_dir, dir, filename)
+
+    # -- Utility methods -----------------------------------------------
+
+    def announce(self, msg: object, level: int = 1) -> None:
+        log.debug(msg)
+
+    def debug_print(self, msg: object) -> None:
+        from distutils.debug import DEBUG
+
+        if DEBUG:
+            print(msg)
+
+    def warn(self, msg: object) -> None:
+        sys.stderr.write(f"warning: {msg}\n")
+
+    def execute(
+        self,
+        func: Callable[[Unpack[_Ts]], object],
+        args: tuple[Unpack[_Ts]],
+        msg: object = None,
+        level: int = 1,
+    ) -> None:
+        execute(func, args, msg, self.dry_run)
+
+    def spawn(
+        self, cmd: MutableSequence[bytes | str | os.PathLike[str]], **kwargs
+    ) -> None:
+        spawn(cmd, dry_run=self.dry_run, **kwargs)
+
+    @overload
+    def move_file(
+        self, src: str | os.PathLike[str], dst: _StrPathT
+    ) -> _StrPathT | str: ...
+    @overload
+    def move_file(
+        self, src: bytes | os.PathLike[bytes], dst: _BytesPathT
+    ) -> _BytesPathT | bytes: ...
+    def move_file(
+        self,
+        src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+        dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
+    ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
+        return move_file(src, dst, dry_run=self.dry_run)
+
+    def mkpath(self, name, mode=0o777):
+        mkpath(name, mode, dry_run=self.dry_run)
+
+
+# Map a sys.platform/os.name ('posix', 'nt') to the default compiler
+# type for that platform. Keys are interpreted as re match
+# patterns. Order is important; platform mappings are preferred over
+# OS names.
+_default_compilers = (
+    # Platform string mappings
+    # on a cygwin built python we can use gcc like an ordinary UNIXish
+    # compiler
+    ('cygwin.*', 'unix'),
+    ('zos', 'zos'),
+    # OS name mappings
+    ('posix', 'unix'),
+    ('nt', 'msvc'),
+)
+
+
+def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str:
+    """Determine the default compiler to use for the given platform.
+
+    osname should be one of the standard Python OS names (i.e. the
+    ones returned by os.name) and platform the common value
+    returned by sys.platform for the platform in question.
+
+    The default values are os.name and sys.platform in case the
+    parameters are not given.
+    """
+    if osname is None:
+        osname = os.name
+    if platform is None:
+        platform = sys.platform
+    # Mingw is a special case where sys.platform is 'win32' but we
+    # want to use the 'mingw32' compiler, so check it first
+    if is_mingw():
+        return 'mingw32'
+    for pattern, compiler in _default_compilers:
+        if (
+            re.match(pattern, platform) is not None
+            or re.match(pattern, osname) is not None
+        ):
+            return compiler
+    # Default to Unix compiler
+    return 'unix'
+
+
+# Map compiler types to (module_name, class_name) pairs -- ie. where to
+# find the code that implements an interface to this compiler.  (The module
+# is assumed to be in the 'distutils' package.)
+compiler_class = {
+    'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
+    'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
+    'cygwin': (
+        'cygwinccompiler',
+        'CygwinCCompiler',
+        "Cygwin port of GNU C Compiler for Win32",
+    ),
+    'mingw32': (
+        'cygwinccompiler',
+        'Mingw32CCompiler',
+        "Mingw32 port of GNU C Compiler for Win32",
+    ),
+    'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
+    'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'),
+}
+
+
+def show_compilers() -> None:
+    """Print list of available compilers (used by the "--help-compiler"
+    options to "build", "build_ext", "build_clib").
+    """
+    # XXX this "knows" that the compiler option it's describing is
+    # "--compiler", which just happens to be the case for the three
+    # commands that use it.
+    from distutils.fancy_getopt import FancyGetopt
+
+    compilers = sorted(
+        ("compiler=" + compiler, None, compiler_class[compiler][2])
+        for compiler in compiler_class.keys()
+    )
+    pretty_printer = FancyGetopt(compilers)
+    pretty_printer.print_help("List of available compilers:")
+
+
+def new_compiler(
+    plat: str | None = None,
+    compiler: str | None = None,
+    verbose: bool = False,
+    dry_run: bool = False,
+    force: bool = False,
+) -> Compiler:
+    """Generate an instance of some CCompiler subclass for the supplied
+    platform/compiler combination.  'plat' defaults to 'os.name'
+    (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
+    for that platform.  Currently only 'posix' and 'nt' are supported, and
+    the default compilers are "traditional Unix interface" (UnixCCompiler
+    class) and Visual C++ (MSVCCompiler class).  Note that it's perfectly
+    possible to ask for a Unix compiler object under Windows, and a
+    Microsoft compiler object under Unix -- if you supply a value for
+    'compiler', 'plat' is ignored.
+    """
+    if plat is None:
+        plat = os.name
+
+    try:
+        if compiler is None:
+            compiler = get_default_compiler(plat)
+
+        (module_name, class_name, long_description) = compiler_class[compiler]
+    except KeyError:
+        msg = f"don't know how to compile C/C++ code on platform '{plat}'"
+        if compiler is not None:
+            msg = msg + f" with '{compiler}' compiler"
+        raise DistutilsPlatformError(msg)
+
+    try:
+        module_name = "distutils." + module_name
+        __import__(module_name)
+        module = sys.modules[module_name]
+        klass = vars(module)[class_name]
+    except ImportError:
+        raise DistutilsModuleError(
+            f"can't compile C/C++ code: unable to load module '{module_name}'"
+        )
+    except KeyError:
+        raise DistutilsModuleError(
+            f"can't compile C/C++ code: unable to find class '{class_name}' "
+            f"in module '{module_name}'"
+        )
+
+    # XXX The None is necessary to preserve backwards compatibility
+    # with classes that expect verbose to be the first positional
+    # argument.
+    return klass(None, dry_run, force)
+
+
+def gen_preprocess_options(
+    macros: Iterable[_Macro], include_dirs: Iterable[str]
+) -> list[str]:
+    """Generate C pre-processor options (-D, -U, -I) as used by at least
+    two types of compilers: the typical Unix compiler and Visual C++.
+    'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
+    means undefine (-U) macro 'name', and (name,value) means define (-D)
+    macro 'name' to 'value'.  'include_dirs' is just a list of directory
+    names to be added to the header file search path (-I).  Returns a list
+    of command-line options suitable for either Unix compilers or Visual
+    C++.
+    """
+    # XXX it would be nice (mainly aesthetic, and so we don't generate
+    # stupid-looking command lines) to go over 'macros' and eliminate
+    # redundant definitions/undefinitions (ie. ensure that only the
+    # latest mention of a particular macro winds up on the command
+    # line).  I don't think it's essential, though, since most (all?)
+    # Unix C compilers only pay attention to the latest -D or -U
+    # mention of a macro on their command line.  Similar situation for
+    # 'include_dirs'.  I'm punting on both for now.  Anyways, weeding out
+    # redundancies like this should probably be the province of
+    # CCompiler, since the data structures used are inherited from it
+    # and therefore common to all CCompiler classes.
+    pp_opts = []
+    for macro in macros:
+        if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
+            raise TypeError(
+                f"bad macro definition '{macro}': "
+                "each element of 'macros' list must be a 1- or 2-tuple"
+            )
+
+        if len(macro) == 1:  # undefine this macro
+            pp_opts.append(f"-U{macro[0]}")
+        elif len(macro) == 2:
+            if macro[1] is None:  # define with no explicit value
+                pp_opts.append(f"-D{macro[0]}")
+            else:
+                # XXX *don't* need to be clever about quoting the
+                # macro value here, because we're going to avoid the
+                # shell at all costs when we spawn the command!
+                pp_opts.append("-D{}={}".format(*macro))
+
+    pp_opts.extend(f"-I{dir}" for dir in include_dirs)
+    return pp_opts
+
+
+def gen_lib_options(
+    compiler: Compiler,
+    library_dirs: Iterable[str],
+    runtime_library_dirs: Iterable[str],
+    libraries: Iterable[str],
+) -> list[str]:
+    """Generate linker options for searching library directories and
+    linking with specific libraries.  'libraries' and 'library_dirs' are,
+    respectively, lists of library names (not filenames!) and search
+    directories.  Returns a list of command-line options suitable for use
+    with some compiler (depending on the two format strings passed in).
+    """
+    lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs]
+
+    for dir in runtime_library_dirs:
+        lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir)))
+
+    # XXX it's important that we *not* remove redundant library mentions!
+    # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
+    # resolve all symbols.  I just hope we never have to say "-lfoo obj.o
+    # -lbar" to get things to work -- that's certainly a possibility, but a
+    # pretty nasty way to arrange your C code.
+
+    for lib in libraries:
+        (lib_dir, lib_name) = os.path.split(lib)
+        if lib_dir:
+            lib_file = compiler.find_library_file([lib_dir], lib_name)
+            if lib_file:
+                lib_opts.append(lib_file)
+            else:
+                compiler.warn(
+                    f"no library file corresponding to '{lib}' found (skipping)"
+                )
+        else:
+            lib_opts.append(compiler.library_option(lib))
+    return lib_opts
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/cygwin.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/cygwin.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfabbb306e7e44ed120d35f083304e65d7cecf83
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/cygwin.py
@@ -0,0 +1,340 @@
+"""distutils.cygwinccompiler
+
+Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
+handles the Cygwin port of the GNU C compiler to Windows.  It also contains
+the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
+cygwin in no-cygwin mode).
+"""
+
+import copy
+import os
+import pathlib
+import shlex
+import sys
+import warnings
+from subprocess import check_output
+
+from ...errors import (
+    DistutilsExecError,
+    DistutilsPlatformError,
+)
+from ...file_util import write_file
+from ...sysconfig import get_config_vars
+from ...version import LooseVersion, suppress_known_deprecation
+from . import unix
+from .errors import (
+    CompileError,
+    Error,
+)
+
+
+def get_msvcr():
+    """No longer needed, but kept for backward compatibility."""
+    return []
+
+
+_runtime_library_dirs_msg = (
+    "Unable to set runtime library search path on Windows, "
+    "usually indicated by `runtime_library_dirs` parameter to Extension"
+)
+
+
+class Compiler(unix.Compiler):
+    """Handles the Cygwin port of the GNU C compiler to Windows."""
+
+    compiler_type = 'cygwin'
+    obj_extension = ".o"
+    static_lib_extension = ".a"
+    shared_lib_extension = ".dll.a"
+    dylib_lib_extension = ".dll"
+    static_lib_format = "lib%s%s"
+    shared_lib_format = "lib%s%s"
+    dylib_lib_format = "cyg%s%s"
+    exe_extension = ".exe"
+
+    def __init__(self, verbose=False, dry_run=False, force=False):
+        super().__init__(verbose, dry_run, force)
+
+        status, details = check_config_h()
+        self.debug_print(f"Python's GCC status: {status} (details: {details})")
+        if status is not CONFIG_H_OK:
+            self.warn(
+                "Python's pyconfig.h doesn't seem to support your compiler. "
+                f"Reason: {details}. "
+                "Compiling may fail because of undefined preprocessor macros."
+            )
+
+        self.cc, self.cxx = get_config_vars('CC', 'CXX')
+
+        # Override 'CC' and 'CXX' environment variables for
+        # building using MINGW compiler for MSVC python.
+        self.cc = os.environ.get('CC', self.cc or 'gcc')
+        self.cxx = os.environ.get('CXX', self.cxx or 'g++')
+
+        self.linker_dll = self.cc
+        self.linker_dll_cxx = self.cxx
+        shared_option = "-shared"
+
+        self.set_executables(
+            compiler=f'{self.cc} -mcygwin -O -Wall',
+            compiler_so=f'{self.cc} -mcygwin -mdll -O -Wall',
+            compiler_cxx=f'{self.cxx} -mcygwin -O -Wall',
+            compiler_so_cxx=f'{self.cxx} -mcygwin -mdll -O -Wall',
+            linker_exe=f'{self.cc} -mcygwin',
+            linker_so=f'{self.linker_dll} -mcygwin {shared_option}',
+            linker_exe_cxx=f'{self.cxx} -mcygwin',
+            linker_so_cxx=f'{self.linker_dll_cxx} -mcygwin {shared_option}',
+        )
+
+        self.dll_libraries = get_msvcr()
+
+    @property
+    def gcc_version(self):
+        # Older numpy depended on this existing to check for ancient
+        # gcc versions. This doesn't make much sense with clang etc so
+        # just hardcode to something recent.
+        # https://github.com/numpy/numpy/pull/20333
+        warnings.warn(
+            "gcc_version attribute of CygwinCCompiler is deprecated. "
+            "Instead of returning actual gcc version a fixed value 11.2.0 is returned.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        with suppress_known_deprecation():
+            return LooseVersion("11.2.0")
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        """Compiles the source by spawning GCC and windres if needed."""
+        if ext in ('.rc', '.res'):
+            # gcc needs '.res' and '.rc' compiled to object files !!!
+            try:
+                self.spawn(["windres", "-i", src, "-o", obj])
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+        else:  # for other files use the C-compiler
+            try:
+                if self.detect_language(src) == 'c++':
+                    self.spawn(
+                        self.compiler_so_cxx
+                        + cc_args
+                        + [src, '-o', obj]
+                        + extra_postargs
+                    )
+                else:
+                    self.spawn(
+                        self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
+                    )
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+
+    def link(
+        self,
+        target_desc,
+        objects,
+        output_filename,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        """Link the objects."""
+        # use separate copies, so we can modify the lists
+        extra_preargs = copy.copy(extra_preargs or [])
+        libraries = copy.copy(libraries or [])
+        objects = copy.copy(objects or [])
+
+        if runtime_library_dirs:
+            self.warn(_runtime_library_dirs_msg)
+
+        # Additional libraries
+        libraries.extend(self.dll_libraries)
+
+        # handle export symbols by creating a def-file
+        # with executables this only works with gcc/ld as linker
+        if (export_symbols is not None) and (
+            target_desc != self.EXECUTABLE or self.linker_dll == "gcc"
+        ):
+            # (The linker doesn't do anything if output is up-to-date.
+            # So it would probably better to check if we really need this,
+            # but for this we had to insert some unchanged parts of
+            # UnixCCompiler, and this is not what we want.)
+
+            # we want to put some files in the same directory as the
+            # object files are, build_temp doesn't help much
+            # where are the object files
+            temp_dir = os.path.dirname(objects[0])
+            # name of dll to give the helper files the same base name
+            (dll_name, dll_extension) = os.path.splitext(
+                os.path.basename(output_filename)
+            )
+
+            # generate the filenames for these files
+            def_file = os.path.join(temp_dir, dll_name + ".def")
+
+            # Generate .def file
+            contents = [f"LIBRARY {os.path.basename(output_filename)}", "EXPORTS"]
+            contents.extend(export_symbols)
+            self.execute(write_file, (def_file, contents), f"writing {def_file}")
+
+            # next add options for def-file
+
+            # for gcc/ld the def-file is specified as any object files
+            objects.append(def_file)
+
+        # end: if ((export_symbols is not None) and
+        #        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
+
+        # who wants symbols and a many times larger output file
+        # should explicitly switch the debug mode on
+        # otherwise we let ld strip the output file
+        # (On my machine: 10KiB < stripped_file < ??100KiB
+        #   unstripped_file = stripped_file + XXX KiB
+        #  ( XXX=254 for a typical python extension))
+        if not debug:
+            extra_preargs.append("-s")
+
+        super().link(
+            target_desc,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            None,  # export_symbols, we do this in our def-file
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
+
+    def runtime_library_dir_option(self, dir):
+        # cygwin doesn't support rpath. While in theory we could error
+        # out like MSVC does, code might expect it to work like on Unix, so
+        # just warn and hope for the best.
+        self.warn(_runtime_library_dirs_msg)
+        return []
+
+    # -- Miscellaneous methods -----------------------------------------
+
+    def _make_out_path(self, output_dir, strip_dir, src_name):
+        # use normcase to make sure '.rc' is really '.rc' and not '.RC'
+        norm_src_name = os.path.normcase(src_name)
+        return super()._make_out_path(output_dir, strip_dir, norm_src_name)
+
+    @property
+    def out_extensions(self):
+        """
+        Add support for rc and res files.
+        """
+        return {
+            **super().out_extensions,
+            **{ext: ext + self.obj_extension for ext in ('.res', '.rc')},
+        }
+
+
+# the same as cygwin plus some additional parameters
+class MinGW32Compiler(Compiler):
+    """Handles the Mingw32 port of the GNU C compiler to Windows."""
+
+    compiler_type = 'mingw32'
+
+    def __init__(self, verbose=False, dry_run=False, force=False):
+        super().__init__(verbose, dry_run, force)
+
+        shared_option = "-shared"
+
+        if is_cygwincc(self.cc):
+            raise Error('Cygwin gcc cannot be used with --compiler=mingw32')
+
+        self.set_executables(
+            compiler=f'{self.cc} -O -Wall',
+            compiler_so=f'{self.cc} -shared -O -Wall',
+            compiler_so_cxx=f'{self.cxx} -shared -O -Wall',
+            compiler_cxx=f'{self.cxx} -O -Wall',
+            linker_exe=f'{self.cc}',
+            linker_so=f'{self.linker_dll} {shared_option}',
+            linker_exe_cxx=f'{self.cxx}',
+            linker_so_cxx=f'{self.linker_dll_cxx} {shared_option}',
+        )
+
+    def runtime_library_dir_option(self, dir):
+        raise DistutilsPlatformError(_runtime_library_dirs_msg)
+
+
+# Because these compilers aren't configured in Python's pyconfig.h file by
+# default, we should at least warn the user if he is using an unmodified
+# version.
+
+CONFIG_H_OK = "ok"
+CONFIG_H_NOTOK = "not ok"
+CONFIG_H_UNCERTAIN = "uncertain"
+
+
+def check_config_h():
+    """Check if the current Python installation appears amenable to building
+    extensions with GCC.
+
+    Returns a tuple (status, details), where 'status' is one of the following
+    constants:
+
+    - CONFIG_H_OK: all is well, go ahead and compile
+    - CONFIG_H_NOTOK: doesn't look good
+    - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
+
+    'details' is a human-readable string explaining the situation.
+
+    Note there are two ways to conclude "OK": either 'sys.version' contains
+    the string "GCC" (implying that this Python was built with GCC), or the
+    installed "pyconfig.h" contains the string "__GNUC__".
+    """
+
+    # XXX since this function also checks sys.version, it's not strictly a
+    # "pyconfig.h" check -- should probably be renamed...
+
+    from distutils import sysconfig
+
+    # if sys.version contains GCC then python was compiled with GCC, and the
+    # pyconfig.h file should be OK
+    if "GCC" in sys.version:
+        return CONFIG_H_OK, "sys.version mentions 'GCC'"
+
+    # Clang would also work
+    if "Clang" in sys.version:
+        return CONFIG_H_OK, "sys.version mentions 'Clang'"
+
+    # let's see if __GNUC__ is mentioned in python.h
+    fn = sysconfig.get_config_h_filename()
+    try:
+        config_h = pathlib.Path(fn).read_text(encoding='utf-8')
+    except OSError as exc:
+        return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}")
+    else:
+        substring = '__GNUC__'
+        if substring in config_h:
+            code = CONFIG_H_OK
+            mention_inflected = 'mentions'
+        else:
+            code = CONFIG_H_NOTOK
+            mention_inflected = 'does not mention'
+        return code, f"{fn!r} {mention_inflected} {substring!r}"
+
+
+def is_cygwincc(cc):
+    """Try to determine if the compiler that would be used is from cygwin."""
+    out_string = check_output(shlex.split(cc) + ['-dumpmachine'])
+    return out_string.strip().endswith(b'cygwin')
+
+
+get_versions = None
+"""
+A stand-in for the previous get_versions() function to prevent failures
+when monkeypatched. See pypa/setuptools#2969.
+"""
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/errors.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..01328592b2dad80f4d16c55cd9db9829b3c650f1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/errors.py
@@ -0,0 +1,24 @@
+class Error(Exception):
+    """Some compile/link operation failed."""
+
+
+class PreprocessError(Error):
+    """Failure to preprocess one or more C/C++ files."""
+
+
+class CompileError(Error):
+    """Failure to compile one or more C/C++ source files."""
+
+
+class LibError(Error):
+    """Failure to create a static library from one or more C/C++ object
+    files."""
+
+
+class LinkError(Error):
+    """Failure to link one or more C/C++ object files into an executable
+    or shared library file."""
+
+
+class UnknownFileType(Error):
+    """Attempt to process an unknown file type."""
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/msvc.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/msvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..6db062a9e714d0a95e1550d387abbffe5950547f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/msvc.py
@@ -0,0 +1,614 @@
+"""distutils._msvccompiler
+
+Contains MSVCCompiler, an implementation of the abstract CCompiler class
+for Microsoft Visual Studio 2015.
+
+This module requires VS 2015 or later.
+"""
+
+# Written by Perry Stoll
+# hacked by Robin Becker and Thomas Heller to do a better job of
+#   finding DevStudio (through the registry)
+# ported to VS 2005 and VS 2008 by Christian Heimes
+# ported to VS 2015 by Steve Dower
+from __future__ import annotations
+
+import contextlib
+import os
+import subprocess
+import unittest.mock as mock
+import warnings
+from collections.abc import Iterable
+
+with contextlib.suppress(ImportError):
+    import winreg
+
+from itertools import count
+
+from ..._log import log
+from ...errors import (
+    DistutilsExecError,
+    DistutilsPlatformError,
+)
+from ...util import get_host_platform, get_platform
+from . import base
+from .base import gen_lib_options
+from .errors import (
+    CompileError,
+    LibError,
+    LinkError,
+)
+
+
+def _find_vc2015():
+    try:
+        key = winreg.OpenKeyEx(
+            winreg.HKEY_LOCAL_MACHINE,
+            r"Software\Microsoft\VisualStudio\SxS\VC7",
+            access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
+        )
+    except OSError:
+        log.debug("Visual C++ is not registered")
+        return None, None
+
+    best_version = 0
+    best_dir = None
+    with key:
+        for i in count():
+            try:
+                v, vc_dir, vt = winreg.EnumValue(key, i)
+            except OSError:
+                break
+            if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
+                try:
+                    version = int(float(v))
+                except (ValueError, TypeError):
+                    continue
+                if version >= 14 and version > best_version:
+                    best_version, best_dir = version, vc_dir
+    return best_version, best_dir
+
+
+def _find_vc2017():
+    """Returns "15, path" based on the result of invoking vswhere.exe
+    If no install is found, returns "None, None"
+
+    The version is returned to avoid unnecessarily changing the function
+    result. It may be ignored when the path is not None.
+
+    If vswhere.exe is not available, by definition, VS 2017 is not
+    installed.
+    """
+    root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
+    if not root:
+        return None, None
+
+    variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64'
+    suitable_components = (
+        f"Microsoft.VisualStudio.Component.VC.Tools.{variant}",
+        "Microsoft.VisualStudio.Workload.WDExpress",
+    )
+
+    for component in suitable_components:
+        # Workaround for `-requiresAny` (only available on VS 2017 > 15.6)
+        with contextlib.suppress(
+            subprocess.CalledProcessError, OSError, UnicodeDecodeError
+        ):
+            path = (
+                subprocess.check_output([
+                    os.path.join(
+                        root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
+                    ),
+                    "-latest",
+                    "-prerelease",
+                    "-requires",
+                    component,
+                    "-property",
+                    "installationPath",
+                    "-products",
+                    "*",
+                ])
+                .decode(encoding="mbcs", errors="strict")
+                .strip()
+            )
+
+            path = os.path.join(path, "VC", "Auxiliary", "Build")
+            if os.path.isdir(path):
+                return 15, path
+
+    return None, None  # no suitable component found
+
+
+PLAT_SPEC_TO_RUNTIME = {
+    'x86': 'x86',
+    'x86_amd64': 'x64',
+    'x86_arm': 'arm',
+    'x86_arm64': 'arm64',
+}
+
+
+def _find_vcvarsall(plat_spec):
+    # bpo-38597: Removed vcruntime return value
+    _, best_dir = _find_vc2017()
+
+    if not best_dir:
+        best_version, best_dir = _find_vc2015()
+
+    if not best_dir:
+        log.debug("No suitable Visual C++ version found")
+        return None, None
+
+    vcvarsall = os.path.join(best_dir, "vcvarsall.bat")
+    if not os.path.isfile(vcvarsall):
+        log.debug("%s cannot be found", vcvarsall)
+        return None, None
+
+    return vcvarsall, None
+
+
+def _get_vc_env(plat_spec):
+    if os.getenv("DISTUTILS_USE_SDK"):
+        return {key.lower(): value for key, value in os.environ.items()}
+
+    vcvarsall, _ = _find_vcvarsall(plat_spec)
+    if not vcvarsall:
+        raise DistutilsPlatformError(
+            'Microsoft Visual C++ 14.0 or greater is required. '
+            'Get it with "Microsoft C++ Build Tools": '
+            'https://visualstudio.microsoft.com/visual-cpp-build-tools/'
+        )
+
+    try:
+        out = subprocess.check_output(
+            f'cmd /u /c "{vcvarsall}" {plat_spec} && set',
+            stderr=subprocess.STDOUT,
+        ).decode('utf-16le', errors='replace')
+    except subprocess.CalledProcessError as exc:
+        log.error(exc.output)
+        raise DistutilsPlatformError(f"Error executing {exc.cmd}")
+
+    env = {
+        key.lower(): value
+        for key, _, value in (line.partition('=') for line in out.splitlines())
+        if key and value
+    }
+
+    return env
+
+
+def _find_exe(exe, paths=None):
+    """Return path to an MSVC executable program.
+
+    Tries to find the program in several places: first, one of the
+    MSVC program search paths from the registry; next, the directories
+    in the PATH environment variable.  If any of those work, return an
+    absolute path that is known to exist.  If none of them work, just
+    return the original program name, 'exe'.
+    """
+    if not paths:
+        paths = os.getenv('path').split(os.pathsep)
+    for p in paths:
+        fn = os.path.join(os.path.abspath(p), exe)
+        if os.path.isfile(fn):
+            return fn
+    return exe
+
+
+_vcvars_names = {
+    'win32': 'x86',
+    'win-amd64': 'amd64',
+    'win-arm32': 'arm',
+    'win-arm64': 'arm64',
+}
+
+
+def _get_vcvars_spec(host_platform, platform):
+    """
+    Given a host platform and platform, determine the spec for vcvarsall.
+
+    Uses the native MSVC host if the host platform would need expensive
+    emulation for x86.
+
+    >>> _get_vcvars_spec('win-arm64', 'win32')
+    'arm64_x86'
+    >>> _get_vcvars_spec('win-arm64', 'win-amd64')
+    'arm64_amd64'
+
+    Otherwise, always cross-compile from x86 to work with the
+    lighter-weight MSVC installs that do not include native 64-bit tools.
+
+    >>> _get_vcvars_spec('win32', 'win32')
+    'x86'
+    >>> _get_vcvars_spec('win-arm32', 'win-arm32')
+    'x86_arm'
+    >>> _get_vcvars_spec('win-amd64', 'win-arm64')
+    'x86_arm64'
+    """
+    if host_platform != 'win-arm64':
+        host_platform = 'win32'
+    vc_hp = _vcvars_names[host_platform]
+    vc_plat = _vcvars_names[platform]
+    return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}'
+
+
+class Compiler(base.Compiler):
+    """Concrete class that implements an interface to Microsoft Visual C++,
+    as defined by the CCompiler abstract class."""
+
+    compiler_type = 'msvc'
+
+    # Just set this so CCompiler's constructor doesn't barf.  We currently
+    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
+    # as it really isn't necessary for this sort of single-compiler class.
+    # Would be nice to have a consistent interface with UnixCCompiler,
+    # though, so it's worth thinking about.
+    executables = {}
+
+    # Private class data (need to distinguish C from C++ source for compiler)
+    _c_extensions = ['.c']
+    _cpp_extensions = ['.cc', '.cpp', '.cxx']
+    _rc_extensions = ['.rc']
+    _mc_extensions = ['.mc']
+
+    # Needed for the filename generation methods provided by the
+    # base class, CCompiler.
+    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
+    res_extension = '.res'
+    obj_extension = '.obj'
+    static_lib_extension = '.lib'
+    shared_lib_extension = '.dll'
+    static_lib_format = shared_lib_format = '%s%s'
+    exe_extension = '.exe'
+
+    def __init__(self, verbose=False, dry_run=False, force=False) -> None:
+        super().__init__(verbose, dry_run, force)
+        # target platform (.plat_name is consistent with 'bdist')
+        self.plat_name = None
+        self.initialized = False
+
+    @classmethod
+    def _configure(cls, vc_env):
+        """
+        Set class-level include/lib dirs.
+        """
+        cls.include_dirs = cls._parse_path(vc_env.get('include', ''))
+        cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))
+
+    @staticmethod
+    def _parse_path(val):
+        return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]
+
+    def initialize(self, plat_name: str | None = None) -> None:
+        # multi-init means we would need to check platform same each time...
+        assert not self.initialized, "don't init multiple times"
+        if plat_name is None:
+            plat_name = get_platform()
+        # sanity check for platforms to prevent obscure errors later.
+        if plat_name not in _vcvars_names:
+            raise DistutilsPlatformError(
+                f"--plat-name must be one of {tuple(_vcvars_names)}"
+            )
+
+        plat_spec = _get_vcvars_spec(get_host_platform(), plat_name)
+
+        vc_env = _get_vc_env(plat_spec)
+        if not vc_env:
+            raise DistutilsPlatformError(
+                "Unable to find a compatible Visual Studio installation."
+            )
+        self._configure(vc_env)
+
+        self._paths = vc_env.get('path', '')
+        paths = self._paths.split(os.pathsep)
+        self.cc = _find_exe("cl.exe", paths)
+        self.linker = _find_exe("link.exe", paths)
+        self.lib = _find_exe("lib.exe", paths)
+        self.rc = _find_exe("rc.exe", paths)  # resource compiler
+        self.mc = _find_exe("mc.exe", paths)  # message compiler
+        self.mt = _find_exe("mt.exe", paths)  # message compiler
+
+        self.preprocess_options = None
+        # bpo-38597: Always compile with dynamic linking
+        # Future releases of Python 3.x will include all past
+        # versions of vcruntime*.dll for compatibility.
+        self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
+
+        self.compile_options_debug = [
+            '/nologo',
+            '/Od',
+            '/MDd',
+            '/Zi',
+            '/W3',
+            '/D_DEBUG',
+        ]
+
+        ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
+
+        ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
+
+        self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
+        self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
+        self.ldflags_shared = [
+            *ldflags,
+            '/DLL',
+            '/MANIFEST:EMBED,ID=2',
+            '/MANIFESTUAC:NO',
+        ]
+        self.ldflags_shared_debug = [
+            *ldflags_debug,
+            '/DLL',
+            '/MANIFEST:EMBED,ID=2',
+            '/MANIFESTUAC:NO',
+        ]
+        self.ldflags_static = [*ldflags]
+        self.ldflags_static_debug = [*ldflags_debug]
+
+        self._ldflags = {
+            (base.Compiler.EXECUTABLE, None): self.ldflags_exe,
+            (base.Compiler.EXECUTABLE, False): self.ldflags_exe,
+            (base.Compiler.EXECUTABLE, True): self.ldflags_exe_debug,
+            (base.Compiler.SHARED_OBJECT, None): self.ldflags_shared,
+            (base.Compiler.SHARED_OBJECT, False): self.ldflags_shared,
+            (base.Compiler.SHARED_OBJECT, True): self.ldflags_shared_debug,
+            (base.Compiler.SHARED_LIBRARY, None): self.ldflags_static,
+            (base.Compiler.SHARED_LIBRARY, False): self.ldflags_static,
+            (base.Compiler.SHARED_LIBRARY, True): self.ldflags_static_debug,
+        }
+
+        self.initialized = True
+
+    # -- Worker methods ------------------------------------------------
+
+    @property
+    def out_extensions(self) -> dict[str, str]:
+        return {
+            **super().out_extensions,
+            **{
+                ext: self.res_extension
+                for ext in self._rc_extensions + self._mc_extensions
+            },
+        }
+
+    def compile(  # noqa: C901
+        self,
+        sources,
+        output_dir=None,
+        macros=None,
+        include_dirs=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        depends=None,
+    ):
+        if not self.initialized:
+            self.initialize()
+        compile_info = self._setup_compile(
+            output_dir, macros, include_dirs, sources, depends, extra_postargs
+        )
+        macros, objects, extra_postargs, pp_opts, build = compile_info
+
+        compile_opts = extra_preargs or []
+        compile_opts.append('/c')
+        if debug:
+            compile_opts.extend(self.compile_options_debug)
+        else:
+            compile_opts.extend(self.compile_options)
+
+        add_cpp_opts = False
+
+        for obj in objects:
+            try:
+                src, ext = build[obj]
+            except KeyError:
+                continue
+            if debug:
+                # pass the full pathname to MSVC in debug mode,
+                # this allows the debugger to find the source file
+                # without asking the user to browse for it
+                src = os.path.abspath(src)
+
+            if ext in self._c_extensions:
+                input_opt = f"/Tc{src}"
+            elif ext in self._cpp_extensions:
+                input_opt = f"/Tp{src}"
+                add_cpp_opts = True
+            elif ext in self._rc_extensions:
+                # compile .RC to .RES file
+                input_opt = src
+                output_opt = "/fo" + obj
+                try:
+                    self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
+                except DistutilsExecError as msg:
+                    raise CompileError(msg)
+                continue
+            elif ext in self._mc_extensions:
+                # Compile .MC to .RC file to .RES file.
+                #   * '-h dir' specifies the directory for the
+                #     generated include file
+                #   * '-r dir' specifies the target directory of the
+                #     generated RC file and the binary message resource
+                #     it includes
+                #
+                # For now (since there are no options to change this),
+                # we use the source-directory for the include file and
+                # the build directory for the RC file and message
+                # resources. This works at least for win32all.
+                h_dir = os.path.dirname(src)
+                rc_dir = os.path.dirname(obj)
+                try:
+                    # first compile .MC to .RC and .H file
+                    self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
+                    base, _ = os.path.splitext(os.path.basename(src))
+                    rc_file = os.path.join(rc_dir, base + '.rc')
+                    # then compile .RC to .RES file
+                    self.spawn([self.rc, "/fo" + obj, rc_file])
+
+                except DistutilsExecError as msg:
+                    raise CompileError(msg)
+                continue
+            else:
+                # how to handle this file?
+                raise CompileError(f"Don't know how to compile {src} to {obj}")
+
+            args = [self.cc] + compile_opts + pp_opts
+            if add_cpp_opts:
+                args.append('/EHsc')
+            args.extend((input_opt, "/Fo" + obj))
+            args.extend(extra_postargs)
+
+            try:
+                self.spawn(args)
+            except DistutilsExecError as msg:
+                raise CompileError(msg)
+
+        return objects
+
+    def create_static_lib(
+        self,
+        objects: list[str] | tuple[str, ...],
+        output_libname: str,
+        output_dir: str | None = None,
+        debug: bool = False,
+        target_lang: str | None = None,
+    ) -> None:
+        if not self.initialized:
+            self.initialize()
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        output_filename = self.library_filename(output_libname, output_dir=output_dir)
+
+        if self._need_link(objects, output_filename):
+            lib_args = objects + ['/OUT:' + output_filename]
+            if debug:
+                pass  # XXX what goes here?
+            try:
+                log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
+                self.spawn([self.lib] + lib_args)
+            except DistutilsExecError as msg:
+                raise LibError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def link(
+        self,
+        target_desc: str,
+        objects: list[str] | tuple[str, ...],
+        output_filename: str,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols: Iterable[str] | None = None,
+        debug: bool = False,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+        build_temp: str | os.PathLike[str] | None = None,
+        target_lang: str | None = None,
+    ) -> None:
+        if not self.initialized:
+            self.initialize()
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
+        libraries, library_dirs, runtime_library_dirs = fixed_args
+
+        if runtime_library_dirs:
+            self.warn(
+                "I don't know what to do with 'runtime_library_dirs': "
+                + str(runtime_library_dirs)
+            )
+
+        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
+        if output_dir is not None:
+            output_filename = os.path.join(output_dir, output_filename)
+
+        if self._need_link(objects, output_filename):
+            ldflags = self._ldflags[target_desc, debug]
+
+            export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
+
+            ld_args = (
+                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
+            )
+
+            # The MSVC linker generates .lib and .exp files, which cannot be
+            # suppressed by any linker switches. The .lib files may even be
+            # needed! Make sure they are generated in the temporary build
+            # directory. Since they have different names for debug and release
+            # builds, they can go into the same directory.
+            build_temp = os.path.dirname(objects[0])
+            if export_symbols is not None:
+                (dll_name, dll_ext) = os.path.splitext(
+                    os.path.basename(output_filename)
+                )
+                implib_file = os.path.join(build_temp, self.library_filename(dll_name))
+                ld_args.append('/IMPLIB:' + implib_file)
+
+            if extra_preargs:
+                ld_args[:0] = extra_preargs
+            if extra_postargs:
+                ld_args.extend(extra_postargs)
+
+            output_dir = os.path.dirname(os.path.abspath(output_filename))
+            self.mkpath(output_dir)
+            try:
+                log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
+                self.spawn([self.linker] + ld_args)
+            except DistutilsExecError as msg:
+                raise LinkError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def spawn(self, cmd):
+        env = dict(os.environ, PATH=self._paths)
+        with self._fallback_spawn(cmd, env) as fallback:
+            return super().spawn(cmd, env=env)
+        return fallback.value
+
+    @contextlib.contextmanager
+    def _fallback_spawn(self, cmd, env):
+        """
+        Discovered in pypa/distutils#15, some tools monkeypatch the compiler,
+        so the 'env' kwarg causes a TypeError. Detect this condition and
+        restore the legacy, unsafe behavior.
+        """
+        bag = type('Bag', (), {})()
+        try:
+            yield bag
+        except TypeError as exc:
+            if "unexpected keyword argument 'env'" not in str(exc):
+                raise
+        else:
+            return
+        warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
+        with mock.patch.dict('os.environ', env):
+            bag.value = super().spawn(cmd)
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function, in
+    # ccompiler.py.
+
+    def library_dir_option(self, dir):
+        return "/LIBPATH:" + dir
+
+    def runtime_library_dir_option(self, dir):
+        raise DistutilsPlatformError(
+            "don't know how to set runtime library search path for MSVC"
+        )
+
+    def library_option(self, lib):
+        return self.library_filename(lib)
+
+    def find_library_file(self, dirs, lib, debug=False):
+        # Prefer a debugging library if found (and requested), but deal
+        # with it if we don't have one.
+        if debug:
+            try_names = [lib + "_d", lib]
+        else:
+            try_names = [lib]
+        for dir in dirs:
+            for name in try_names:
+                libfile = os.path.join(dir, self.library_filename(name))
+                if os.path.isfile(libfile):
+                    return libfile
+        else:
+            # Oops, didn't find it in *any* of 'dirs'
+            return None
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..a762e2b649d7977ef42f4d35854eab26bd54e9e7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py
@@ -0,0 +1,83 @@
+import platform
+import sysconfig
+import textwrap
+
+import pytest
+
+from .. import base
+
+pytestmark = pytest.mark.usefixtures('suppress_path_mangle')
+
+
+@pytest.fixture
+def c_file(tmp_path):
+    c_file = tmp_path / 'foo.c'
+    gen_headers = ('Python.h',)
+    is_windows = platform.system() == "Windows"
+    plat_headers = ('windows.h',) * is_windows
+    all_headers = gen_headers + plat_headers
+    headers = '\n'.join(f'#include <{header}>\n' for header in all_headers)
+    payload = (
+        textwrap.dedent(
+            """
+        #headers
+        void PyInit_foo(void) {}
+        """
+        )
+        .lstrip()
+        .replace('#headers', headers)
+    )
+    c_file.write_text(payload, encoding='utf-8')
+    return c_file
+
+
+def test_set_include_dirs(c_file):
+    """
+    Extensions should build even if set_include_dirs is invoked.
+    In particular, compiler-specific paths should not be overridden.
+    """
+    compiler = base.new_compiler()
+    python = sysconfig.get_paths()['include']
+    compiler.set_include_dirs([python])
+    compiler.compile([c_file])
+
+    # do it again, setting include dirs after any initialization
+    compiler.set_include_dirs([python])
+    compiler.compile([c_file])
+
+
+def test_has_function_prototype():
+    # Issue https://github.com/pypa/setuptools/issues/3648
+    # Test prototype-generating behavior.
+
+    compiler = base.new_compiler()
+
+    # Every C implementation should have these.
+    assert compiler.has_function('abort')
+    assert compiler.has_function('exit')
+    with pytest.deprecated_call(match='includes is deprecated'):
+        # abort() is a valid expression with the  prototype.
+        assert compiler.has_function('abort', includes=['stdlib.h'])
+    with pytest.deprecated_call(match='includes is deprecated'):
+        # But exit() is not valid with the actual prototype in scope.
+        assert not compiler.has_function('exit', includes=['stdlib.h'])
+    # And setuptools_does_not_exist is not declared or defined at all.
+    assert not compiler.has_function('setuptools_does_not_exist')
+    with pytest.deprecated_call(match='includes is deprecated'):
+        assert not compiler.has_function(
+            'setuptools_does_not_exist', includes=['stdio.h']
+        )
+
+
+def test_include_dirs_after_multiple_compile_calls(c_file):
+    """
+    Calling compile multiple times should not change the include dirs
+    (regression test for setuptools issue #3591).
+    """
+    compiler = base.new_compiler()
+    python = sysconfig.get_paths()['include']
+    compiler.set_include_dirs([python])
+    compiler.compile([c_file])
+    assert compiler.include_dirs == [python]
+    compiler.compile([c_file])
+    assert compiler.include_dirs == [python]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py
new file mode 100644
index 0000000000000000000000000000000000000000..9adf6b8ebf165b4fe92a52d8a14aed21aebba539
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py
@@ -0,0 +1,76 @@
+"""Tests for distutils.cygwinccompiler."""
+
+import os
+import sys
+from distutils import sysconfig
+from distutils.tests import support
+
+import pytest
+
+from .. import cygwin
+
+
+@pytest.fixture(autouse=True)
+def stuff(request, monkeypatch, distutils_managed_tempdir):
+    self = request.instance
+    self.python_h = os.path.join(self.mkdtemp(), 'python.h')
+    monkeypatch.setattr(sysconfig, 'get_config_h_filename', self._get_config_h_filename)
+    monkeypatch.setattr(sys, 'version', sys.version)
+
+
+class TestCygwinCCompiler(support.TempdirManager):
+    def _get_config_h_filename(self):
+        return self.python_h
+
+    @pytest.mark.skipif('sys.platform != "cygwin"')
+    @pytest.mark.skipif('not os.path.exists("/usr/lib/libbash.dll.a")')
+    def test_find_library_file(self):
+        from distutils.cygwinccompiler import CygwinCCompiler
+
+        compiler = CygwinCCompiler()
+        link_name = "bash"
+        linkable_file = compiler.find_library_file(["/usr/lib"], link_name)
+        assert linkable_file is not None
+        assert os.path.exists(linkable_file)
+        assert linkable_file == f"/usr/lib/lib{link_name:s}.dll.a"
+
+    @pytest.mark.skipif('sys.platform != "cygwin"')
+    def test_runtime_library_dir_option(self):
+        from distutils.cygwinccompiler import CygwinCCompiler
+
+        compiler = CygwinCCompiler()
+        assert compiler.runtime_library_dir_option('/foo') == []
+
+    def test_check_config_h(self):
+        # check_config_h looks for "GCC" in sys.version first
+        # returns CONFIG_H_OK if found
+        sys.version = (
+            '2.6.1 (r261:67515, Dec  6 2008, 16:42:21) \n[GCC '
+            '4.0.1 (Apple Computer, Inc. build 5370)]'
+        )
+
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK
+
+        # then it tries to see if it can find "__GNUC__" in pyconfig.h
+        sys.version = 'something without the *CC word'
+
+        # if the file doesn't exist it returns  CONFIG_H_UNCERTAIN
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_UNCERTAIN
+
+        # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK
+        self.write_file(self.python_h, 'xxx')
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_NOTOK
+
+        # and CONFIG_H_OK if __GNUC__ is found
+        self.write_file(self.python_h, 'xxx __GNUC__ xxx')
+        assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK
+
+    def test_get_msvcr(self):
+        assert cygwin.get_msvcr() == []
+
+    @pytest.mark.skipif('sys.platform != "cygwin"')
+    def test_dll_libraries_not_none(self):
+        from distutils.cygwinccompiler import CygwinCCompiler
+
+        compiler = CygwinCCompiler()
+        assert compiler.dll_libraries is not None
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc45687a917808edbf692ced18b0c99183d21e2d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py
@@ -0,0 +1,48 @@
+from distutils import sysconfig
+from distutils.errors import DistutilsPlatformError
+from distutils.util import is_mingw, split_quoted
+
+import pytest
+
+from .. import cygwin, errors
+
+
+class TestMinGW32Compiler:
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_compiler_type(self):
+        compiler = cygwin.MinGW32Compiler()
+        assert compiler.compiler_type == 'mingw32'
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_set_executables(self, monkeypatch):
+        monkeypatch.setenv('CC', 'cc')
+        monkeypatch.setenv('CXX', 'c++')
+
+        compiler = cygwin.MinGW32Compiler()
+
+        assert compiler.compiler == split_quoted('cc -O -Wall')
+        assert compiler.compiler_so == split_quoted('cc -shared -O -Wall')
+        assert compiler.compiler_cxx == split_quoted('c++ -O -Wall')
+        assert compiler.linker_exe == split_quoted('cc')
+        assert compiler.linker_so == split_quoted('cc -shared')
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_runtime_library_dir_option(self):
+        compiler = cygwin.MinGW32Compiler()
+        with pytest.raises(DistutilsPlatformError):
+            compiler.runtime_library_dir_option('/usr/lib')
+
+    @pytest.mark.skipif(not is_mingw(), reason='not on mingw')
+    def test_cygwincc_error(self, monkeypatch):
+        monkeypatch.setattr(cygwin, 'is_cygwincc', lambda _: True)
+
+        with pytest.raises(errors.Error):
+            cygwin.MinGW32Compiler()
+
+    @pytest.mark.skipif('sys.platform == "cygwin"')
+    def test_customize_compiler_with_msvc_python(self):
+        # In case we have an MSVC Python build, but still want to use
+        # MinGW32Compiler, then customize_compiler() shouldn't fail at least.
+        # https://github.com/pypa/setuptools/issues/4456
+        compiler = cygwin.MinGW32Compiler()
+        sysconfig.customize_compiler(compiler)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..eca831996adcb07f05560581fe4285cdb29392d3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py
@@ -0,0 +1,136 @@
+import os
+import sys
+import sysconfig
+import threading
+import unittest.mock as mock
+from distutils.errors import DistutilsPlatformError
+from distutils.tests import support
+from distutils.util import get_platform
+
+import pytest
+
+from .. import msvc
+
+needs_winreg = pytest.mark.skipif('not hasattr(msvc, "winreg")')
+
+
+class Testmsvccompiler(support.TempdirManager):
+    def test_no_compiler(self, monkeypatch):
+        # makes sure query_vcvarsall raises
+        # a DistutilsPlatformError if the compiler
+        # is not found
+        def _find_vcvarsall(plat_spec):
+            return None, None
+
+        monkeypatch.setattr(msvc, '_find_vcvarsall', _find_vcvarsall)
+
+        with pytest.raises(DistutilsPlatformError):
+            msvc._get_vc_env(
+                'wont find this version',
+            )
+
+    @pytest.mark.skipif(
+        not sysconfig.get_platform().startswith("win"),
+        reason="Only run test for non-mingw Windows platforms",
+    )
+    @pytest.mark.parametrize(
+        "plat_name, expected",
+        [
+            ("win-arm64", "win-arm64"),
+            ("win-amd64", "win-amd64"),
+            (None, get_platform()),
+        ],
+    )
+    def test_cross_platform_compilation_paths(self, monkeypatch, plat_name, expected):
+        """
+        Ensure a specified target platform is passed to _get_vcvars_spec.
+        """
+        compiler = msvc.Compiler()
+
+        def _get_vcvars_spec(host_platform, platform):
+            assert platform == expected
+
+        monkeypatch.setattr(msvc, '_get_vcvars_spec', _get_vcvars_spec)
+        compiler.initialize(plat_name)
+
+    @needs_winreg
+    def test_get_vc_env_unicode(self):
+        test_var = 'ṰḖṤṪ┅ṼẨṜ'
+        test_value = '₃⁴₅'
+
+        # Ensure we don't early exit from _get_vc_env
+        old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None)
+        os.environ[test_var] = test_value
+        try:
+            env = msvc._get_vc_env('x86')
+            assert test_var.lower() in env
+            assert test_value == env[test_var.lower()]
+        finally:
+            os.environ.pop(test_var)
+            if old_distutils_use_sdk:
+                os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk
+
+    @needs_winreg
+    @pytest.mark.parametrize('ver', (2015, 2017))
+    def test_get_vc(self, ver):
+        # This function cannot be mocked, so pass if VC is found
+        # and skip otherwise.
+        lookup = getattr(msvc, f'_find_vc{ver}')
+        expected_version = {2015: 14, 2017: 15}[ver]
+        version, path = lookup()
+        if not version:
+            pytest.skip(f"VS {ver} is not installed")
+        assert version >= expected_version
+        assert os.path.isdir(path)
+
+
+class CheckThread(threading.Thread):
+    exc_info = None
+
+    def run(self):
+        try:
+            super().run()
+        except Exception:
+            self.exc_info = sys.exc_info()
+
+    def __bool__(self):
+        return not self.exc_info
+
+
+class TestSpawn:
+    def test_concurrent_safe(self):
+        """
+        Concurrent calls to spawn should have consistent results.
+        """
+        compiler = msvc.Compiler()
+        compiler._paths = "expected"
+        inner_cmd = 'import os; assert os.environ["PATH"] == "expected"'
+        command = [sys.executable, '-c', inner_cmd]
+
+        threads = [
+            CheckThread(target=compiler.spawn, args=[command]) for n in range(100)
+        ]
+        for thread in threads:
+            thread.start()
+        for thread in threads:
+            thread.join()
+        assert all(threads)
+
+    def test_concurrent_safe_fallback(self):
+        """
+        If CCompiler.spawn has been monkey-patched without support
+        for an env, it should still execute.
+        """
+        from distutils import ccompiler
+
+        compiler = msvc.Compiler()
+        compiler._paths = "expected"
+
+        def CCompiler_spawn(self, cmd):
+            "A spawn without an env argument."
+            assert os.environ["PATH"] == "expected"
+
+        with mock.patch.object(ccompiler.CCompiler, 'spawn', CCompiler_spawn):
+            compiler.spawn(["n/a"])
+
+        assert os.environ.get("PATH") != "expected"
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..35b6b0e050c654bd9eff711ec3b94bea9adff2af
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py
@@ -0,0 +1,413 @@
+"""Tests for distutils.unixccompiler."""
+
+import os
+import sys
+import unittest.mock as mock
+from distutils import sysconfig
+from distutils.compat import consolidate_linker_args
+from distutils.errors import DistutilsPlatformError
+from distutils.tests import support
+from distutils.tests.compat.py39 import EnvironmentVarGuard
+from distutils.util import _clear_cached_macosx_ver
+
+import pytest
+
+from .. import unix
+
+
+@pytest.fixture(autouse=True)
+def save_values(monkeypatch):
+    monkeypatch.setattr(sys, 'platform', sys.platform)
+    monkeypatch.setattr(sysconfig, 'get_config_var', sysconfig.get_config_var)
+    monkeypatch.setattr(sysconfig, 'get_config_vars', sysconfig.get_config_vars)
+
+
+@pytest.fixture(autouse=True)
+def compiler_wrapper(request):
+    class CompilerWrapper(unix.Compiler):
+        def rpath_foo(self):
+            return self.runtime_library_dir_option('/foo')
+
+    request.instance.cc = CompilerWrapper()
+
+
+class TestUnixCCompiler(support.TempdirManager):
+    @pytest.mark.skipif('platform.system == "Windows"')
+    def test_runtime_libdir_option(self):  # noqa: C901
+        # Issue #5900; GitHub Issue #37
+        #
+        # Ensure RUNPATH is added to extension modules with RPATH if
+        # GNU ld is used
+
+        # darwin
+        sys.platform = 'darwin'
+        darwin_ver_var = 'MACOSX_DEPLOYMENT_TARGET'
+        darwin_rpath_flag = '-Wl,-rpath,/foo'
+        darwin_lib_flag = '-L/foo'
+
+        # (macOS version from syscfg, macOS version from env var) -> flag
+        # Version value of None generates two tests: as None and as empty string
+        # Expected flag value of None means an mismatch exception is expected
+        darwin_test_cases = [
+            ((None, None), darwin_lib_flag),
+            ((None, '11'), darwin_rpath_flag),
+            (('10', None), darwin_lib_flag),
+            (('10.3', None), darwin_lib_flag),
+            (('10.3.1', None), darwin_lib_flag),
+            (('10.5', None), darwin_rpath_flag),
+            (('10.5.1', None), darwin_rpath_flag),
+            (('10.3', '10.3'), darwin_lib_flag),
+            (('10.3', '10.5'), darwin_rpath_flag),
+            (('10.5', '10.3'), darwin_lib_flag),
+            (('10.5', '11'), darwin_rpath_flag),
+            (('10.4', '10'), None),
+        ]
+
+        def make_darwin_gcv(syscfg_macosx_ver):
+            def gcv(var):
+                if var == darwin_ver_var:
+                    return syscfg_macosx_ver
+                return "xxx"
+
+            return gcv
+
+        def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag):
+            env = os.environ
+            msg = f"macOS version = (sysconfig={syscfg_macosx_ver!r}, env={env_macosx_ver!r})"
+
+            # Save
+            old_gcv = sysconfig.get_config_var
+            old_env_macosx_ver = env.get(darwin_ver_var)
+
+            # Setup environment
+            _clear_cached_macosx_ver()
+            sysconfig.get_config_var = make_darwin_gcv(syscfg_macosx_ver)
+            if env_macosx_ver is not None:
+                env[darwin_ver_var] = env_macosx_ver
+            elif darwin_ver_var in env:
+                env.pop(darwin_ver_var)
+
+            # Run the test
+            if expected_flag is not None:
+                assert self.cc.rpath_foo() == expected_flag, msg
+            else:
+                with pytest.raises(
+                    DistutilsPlatformError, match=darwin_ver_var + r' mismatch'
+                ):
+                    self.cc.rpath_foo()
+
+            # Restore
+            if old_env_macosx_ver is not None:
+                env[darwin_ver_var] = old_env_macosx_ver
+            elif darwin_ver_var in env:
+                env.pop(darwin_ver_var)
+            sysconfig.get_config_var = old_gcv
+            _clear_cached_macosx_ver()
+
+        for macosx_vers, expected_flag in darwin_test_cases:
+            syscfg_macosx_ver, env_macosx_ver = macosx_vers
+            do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag)
+            # Bonus test cases with None interpreted as empty string
+            if syscfg_macosx_ver is None:
+                do_darwin_test("", env_macosx_ver, expected_flag)
+            if env_macosx_ver is None:
+                do_darwin_test(syscfg_macosx_ver, "", expected_flag)
+            if syscfg_macosx_ver is None and env_macosx_ver is None:
+                do_darwin_test("", "", expected_flag)
+
+        old_gcv = sysconfig.get_config_var
+
+        # hp-ux
+        sys.platform = 'hp-ux'
+
+        def gcv(v):
+            return 'xxx'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == ['+s', '-L/foo']
+
+        def gcv(v):
+            return 'gcc'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo']
+
+        def gcv(v):
+            return 'g++'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo']
+
+        sysconfig.get_config_var = old_gcv
+
+        # GCC GNULD
+        sys.platform = 'bar'
+
+        def gcv(v):
+            if v == 'CC':
+                return 'gcc'
+            elif v == 'GNULD':
+                return 'yes'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
+
+        def gcv(v):
+            if v == 'CC':
+                return 'gcc -pthread -B /bar'
+            elif v == 'GNULD':
+                return 'yes'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
+
+        # GCC non-GNULD
+        sys.platform = 'bar'
+
+        def gcv(v):
+            if v == 'CC':
+                return 'gcc'
+            elif v == 'GNULD':
+                return 'no'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == '-Wl,-R/foo'
+
+        # GCC GNULD with fully qualified configuration prefix
+        # see #7617
+        sys.platform = 'bar'
+
+        def gcv(v):
+            if v == 'CC':
+                return 'x86_64-pc-linux-gnu-gcc-4.4.2'
+            elif v == 'GNULD':
+                return 'yes'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
+
+        # non-GCC GNULD
+        sys.platform = 'bar'
+
+        def gcv(v):
+            if v == 'CC':
+                return 'cc'
+            elif v == 'GNULD':
+                return 'yes'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == consolidate_linker_args([
+            '-Wl,--enable-new-dtags',
+            '-Wl,-rpath,/foo',
+        ])
+
+        # non-GCC non-GNULD
+        sys.platform = 'bar'
+
+        def gcv(v):
+            if v == 'CC':
+                return 'cc'
+            elif v == 'GNULD':
+                return 'no'
+
+        sysconfig.get_config_var = gcv
+        assert self.cc.rpath_foo() == '-Wl,-R/foo'
+
+    @pytest.mark.skipif('platform.system == "Windows"')
+    def test_cc_overrides_ldshared(self):
+        # Issue #18080:
+        # ensure that setting CC env variable also changes default linker
+        def gcv(v):
+            if v == 'LDSHARED':
+                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
+            return 'gcc-4.2'
+
+        def gcvs(*args, _orig=sysconfig.get_config_vars):
+            if args:
+                return list(map(sysconfig.get_config_var, args))
+            return _orig()
+
+        sysconfig.get_config_var = gcv
+        sysconfig.get_config_vars = gcvs
+        with EnvironmentVarGuard() as env:
+            env['CC'] = 'my_cc'
+            del env['LDSHARED']
+            sysconfig.customize_compiler(self.cc)
+        assert self.cc.linker_so[0] == 'my_cc'
+
+    @pytest.mark.skipif('platform.system == "Windows"')
+    def test_cxx_commands_used_are_correct(self):
+        def gcv(v):
+            if v == 'LDSHARED':
+                return 'ccache gcc-4.2 -bundle -undefined dynamic_lookup'
+            elif v == 'LDCXXSHARED':
+                return 'ccache g++-4.2 -bundle -undefined dynamic_lookup'
+            elif v == 'CXX':
+                return 'ccache g++-4.2'
+            elif v == 'CC':
+                return 'ccache gcc-4.2'
+            return ''
+
+        def gcvs(*args, _orig=sysconfig.get_config_vars):
+            if args:
+                return list(map(sysconfig.get_config_var, args))
+            return _orig()  # pragma: no cover
+
+        sysconfig.get_config_var = gcv
+        sysconfig.get_config_vars = gcvs
+        with (
+            mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
+            mock.patch.object(self.cc, '_need_link', return_value=True),
+            mock.patch.object(self.cc, 'mkpath', return_value=None),
+            EnvironmentVarGuard() as env,
+        ):
+            # override environment overrides in case they're specified by CI
+            del env['CXX']
+            del env['LDCXXSHARED']
+
+            sysconfig.customize_compiler(self.cc)
+            assert self.cc.linker_so_cxx[0:2] == ['ccache', 'g++-4.2']
+            assert self.cc.linker_exe_cxx[0:2] == ['ccache', 'g++-4.2']
+            self.cc.link(None, [], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['ccache', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
+            assert call_args[:5] == expected
+
+            self.cc.link_executable([], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['ccache', 'g++-4.2', '-o', self.cc.executable_filename('a.out')]
+            assert call_args[:4] == expected
+
+            env['LDCXXSHARED'] = 'wrapper g++-4.2 -bundle -undefined dynamic_lookup'
+            env['CXX'] = 'wrapper g++-4.2'
+            sysconfig.customize_compiler(self.cc)
+            assert self.cc.linker_so_cxx[0:2] == ['wrapper', 'g++-4.2']
+            assert self.cc.linker_exe_cxx[0:2] == ['wrapper', 'g++-4.2']
+            self.cc.link(None, [], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['wrapper', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
+            assert call_args[:5] == expected
+
+            self.cc.link_executable([], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = [
+                'wrapper',
+                'g++-4.2',
+                '-o',
+                self.cc.executable_filename('a.out'),
+            ]
+            assert call_args[:4] == expected
+
+    @pytest.mark.skipif('platform.system == "Windows"')
+    @pytest.mark.usefixtures('disable_macos_customization')
+    def test_cc_overrides_ldshared_for_cxx_correctly(self):
+        """
+        Ensure that setting CC env variable also changes default linker
+        correctly when building C++ extensions.
+
+        pypa/distutils#126
+        """
+
+        def gcv(v):
+            if v == 'LDSHARED':
+                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
+            elif v == 'LDCXXSHARED':
+                return 'g++-4.2 -bundle -undefined dynamic_lookup '
+            elif v == 'CXX':
+                return 'g++-4.2'
+            elif v == 'CC':
+                return 'gcc-4.2'
+            return ''
+
+        def gcvs(*args, _orig=sysconfig.get_config_vars):
+            if args:
+                return list(map(sysconfig.get_config_var, args))
+            return _orig()
+
+        sysconfig.get_config_var = gcv
+        sysconfig.get_config_vars = gcvs
+        with (
+            mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
+            mock.patch.object(self.cc, '_need_link', return_value=True),
+            mock.patch.object(self.cc, 'mkpath', return_value=None),
+            EnvironmentVarGuard() as env,
+        ):
+            env['CC'] = 'ccache my_cc'
+            env['CXX'] = 'my_cxx'
+            del env['LDSHARED']
+            sysconfig.customize_compiler(self.cc)
+            assert self.cc.linker_so[0:2] == ['ccache', 'my_cc']
+            self.cc.link(None, [], 'a.out', target_lang='c++')
+            call_args = mock_spawn.call_args[0][0]
+            expected = ['my_cxx', '-bundle', '-undefined', 'dynamic_lookup']
+            assert call_args[:4] == expected
+
+    @pytest.mark.skipif('platform.system == "Windows"')
+    def test_explicit_ldshared(self):
+        # Issue #18080:
+        # ensure that setting CC env variable does not change
+        #   explicit LDSHARED setting for linker
+        def gcv(v):
+            if v == 'LDSHARED':
+                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
+            return 'gcc-4.2'
+
+        def gcvs(*args, _orig=sysconfig.get_config_vars):
+            if args:
+                return list(map(sysconfig.get_config_var, args))
+            return _orig()
+
+        sysconfig.get_config_var = gcv
+        sysconfig.get_config_vars = gcvs
+        with EnvironmentVarGuard() as env:
+            env['CC'] = 'my_cc'
+            env['LDSHARED'] = 'my_ld -bundle -dynamic'
+            sysconfig.customize_compiler(self.cc)
+        assert self.cc.linker_so[0] == 'my_ld'
+
+    def test_has_function(self):
+        # Issue https://github.com/pypa/distutils/issues/64:
+        # ensure that setting output_dir does not raise
+        # FileNotFoundError: [Errno 2] No such file or directory: 'a.out'
+        self.cc.output_dir = 'scratch'
+        os.chdir(self.mkdtemp())
+        self.cc.has_function('abort')
+
+    def test_find_library_file(self, monkeypatch):
+        compiler = unix.Compiler()
+        compiler._library_root = lambda dir: dir
+        monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)
+
+        libname = 'libabc.dylib' if sys.platform != 'cygwin' else 'cygabc.dll'
+        dirs = ('/foo/bar/missing', '/foo/bar/existing')
+        assert (
+            compiler.find_library_file(dirs, 'abc').replace('\\', '/')
+            == f'/foo/bar/existing/{libname}'
+        )
+        assert (
+            compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
+            == f'/foo/bar/existing/{libname}'
+        )
+
+        monkeypatch.setattr(
+            os.path,
+            'exists',
+            lambda d: 'existing' in d and '.a' in d and '.dll.a' not in d,
+        )
+        assert (
+            compiler.find_library_file(dirs, 'abc').replace('\\', '/')
+            == '/foo/bar/existing/libabc.a'
+        )
+        assert (
+            compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
+            == '/foo/bar/existing/libabc.a'
+        )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/unix.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..1231b32d20fc0524ea50f6a70d7e017211c69e9b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/unix.py
@@ -0,0 +1,422 @@
+"""distutils.unixccompiler
+
+Contains the UnixCCompiler class, a subclass of CCompiler that handles
+the "typical" Unix-style command-line C compiler:
+  * macros defined with -Dname[=value]
+  * macros undefined with -Uname
+  * include search directories specified with -Idir
+  * libraries specified with -lllib
+  * library search directories specified with -Ldir
+  * compile handled by 'cc' (or similar) executable with -c option:
+    compiles .c to .o
+  * link static library handled by 'ar' command (possibly with 'ranlib')
+  * link shared library handled by 'cc -shared'
+"""
+
+from __future__ import annotations
+
+import itertools
+import os
+import re
+import shlex
+import sys
+from collections.abc import Iterable
+
+from ... import sysconfig
+from ..._log import log
+from ..._macos_compat import compiler_fixup
+from ..._modified import newer
+from ...compat import consolidate_linker_args
+from ...errors import DistutilsExecError
+from . import base
+from .base import _Macro, gen_lib_options, gen_preprocess_options
+from .errors import (
+    CompileError,
+    LibError,
+    LinkError,
+)
+
+# XXX Things not currently handled:
+#   * optimization/debug/warning flags; we just use whatever's in Python's
+#     Makefile and live with it.  Is this adequate?  If not, we might
+#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
+#     SunCCompiler, and I suspect down that road lies madness.
+#   * even if we don't know a warning flag from an optimization flag,
+#     we need some way for outsiders to feed preprocessor/compiler/linker
+#     flags in to us -- eg. a sysadmin might want to mandate certain flags
+#     via a site config file, or a user might want to set something for
+#     compiling this module distribution only via the setup.py command
+#     line, whatever.  As long as these options come from something on the
+#     current system, they can be as system-dependent as they like, and we
+#     should just happily stuff them into the preprocessor/compiler/linker
+#     options and carry on.
+
+
+def _split_env(cmd):
+    """
+    For macOS, split command into 'env' portion (if any)
+    and the rest of the linker command.
+
+    >>> _split_env(['a', 'b', 'c'])
+    ([], ['a', 'b', 'c'])
+    >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
+    (['/usr/bin/env', 'A=3'], ['gcc'])
+    """
+    pivot = 0
+    if os.path.basename(cmd[0]) == "env":
+        pivot = 1
+        while '=' in cmd[pivot]:
+            pivot += 1
+    return cmd[:pivot], cmd[pivot:]
+
+
+def _split_aix(cmd):
+    """
+    AIX platforms prefix the compiler with the ld_so_aix
+    script, so split that from the linker command.
+
+    >>> _split_aix(['a', 'b', 'c'])
+    ([], ['a', 'b', 'c'])
+    >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
+    (['/bin/foo/ld_so_aix'], ['gcc'])
+    """
+    pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
+    return cmd[:pivot], cmd[pivot:]
+
+
+def _linker_params(linker_cmd, compiler_cmd):
+    """
+    The linker command usually begins with the compiler
+    command (possibly multiple elements), followed by zero or more
+    params for shared library building.
+
+    If the LDSHARED env variable overrides the linker command,
+    however, the commands may not match.
+
+    Return the best guess of the linker parameters by stripping
+    the linker command. If the compiler command does not
+    match the linker command, assume the linker command is
+    just the first element.
+
+    >>> _linker_params('gcc foo bar'.split(), ['gcc'])
+    ['foo', 'bar']
+    >>> _linker_params('gcc foo bar'.split(), ['other'])
+    ['foo', 'bar']
+    >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
+    ['foo', 'bar']
+    >>> _linker_params(['gcc'], ['gcc'])
+    []
+    """
+    c_len = len(compiler_cmd)
+    pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
+    return linker_cmd[pivot:]
+
+
+class Compiler(base.Compiler):
+    compiler_type = 'unix'
+
+    # These are used by CCompiler in two places: the constructor sets
+    # instance attributes 'preprocessor', 'compiler', etc. from them, and
+    # 'set_executable()' allows any of these to be set.  The defaults here
+    # are pretty generic; they will probably have to be set by an outsider
+    # (eg. using information discovered by the sysconfig about building
+    # Python extensions).
+    executables = {
+        'preprocessor': None,
+        'compiler': ["cc"],
+        'compiler_so': ["cc"],
+        'compiler_cxx': ["c++"],
+        'compiler_so_cxx': ["c++"],
+        'linker_so': ["cc", "-shared"],
+        'linker_so_cxx': ["c++", "-shared"],
+        'linker_exe': ["cc"],
+        'linker_exe_cxx': ["c++", "-shared"],
+        'archiver': ["ar", "-cr"],
+        'ranlib': None,
+    }
+
+    if sys.platform[:6] == "darwin":
+        executables['ranlib'] = ["ranlib"]
+
+    # Needed for the filename generation methods provided by the base
+    # class, CCompiler.  NB. whoever instantiates/uses a particular
+    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
+    # reasonable common default here, but it's not necessarily used on all
+    # Unices!
+
+    src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
+    obj_extension = ".o"
+    static_lib_extension = ".a"
+    shared_lib_extension = ".so"
+    dylib_lib_extension = ".dylib"
+    xcode_stub_lib_extension = ".tbd"
+    static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
+    xcode_stub_lib_format = dylib_lib_format
+    if sys.platform == "cygwin":
+        exe_extension = ".exe"
+        shared_lib_extension = ".dll.a"
+        dylib_lib_extension = ".dll"
+        dylib_lib_format = "cyg%s%s"
+
+    def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
+        """Remove standard library path from rpath"""
+        libraries, library_dirs, runtime_library_dirs = super()._fix_lib_args(
+            libraries, library_dirs, runtime_library_dirs
+        )
+        libdir = sysconfig.get_config_var('LIBDIR')
+        if (
+            runtime_library_dirs
+            and libdir.startswith("/usr/lib")
+            and (libdir in runtime_library_dirs)
+        ):
+            runtime_library_dirs.remove(libdir)
+        return libraries, library_dirs, runtime_library_dirs
+
+    def preprocess(
+        self,
+        source: str | os.PathLike[str],
+        output_file: str | os.PathLike[str] | None = None,
+        macros: list[_Macro] | None = None,
+        include_dirs: list[str] | tuple[str, ...] | None = None,
+        extra_preargs: list[str] | None = None,
+        extra_postargs: Iterable[str] | None = None,
+    ):
+        fixed_args = self._fix_compile_args(None, macros, include_dirs)
+        ignore, macros, include_dirs = fixed_args
+        pp_opts = gen_preprocess_options(macros, include_dirs)
+        pp_args = self.preprocessor + pp_opts
+        if output_file:
+            pp_args.extend(['-o', output_file])
+        if extra_preargs:
+            pp_args[:0] = extra_preargs
+        if extra_postargs:
+            pp_args.extend(extra_postargs)
+        pp_args.append(source)
+
+        # reasons to preprocess:
+        # - force is indicated
+        # - output is directed to stdout
+        # - source file is newer than the target
+        preprocess = self.force or output_file is None or newer(source, output_file)
+        if not preprocess:
+            return
+
+        if output_file:
+            self.mkpath(os.path.dirname(output_file))
+
+        try:
+            self.spawn(pp_args)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
+        compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs)
+        try:
+            if self.detect_language(src) == 'c++':
+                self.spawn(
+                    compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs
+                )
+            else:
+                self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def create_static_lib(
+        self, objects, output_libname, output_dir=None, debug=False, target_lang=None
+    ):
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+
+        output_filename = self.library_filename(output_libname, output_dir=output_dir)
+
+        if self._need_link(objects, output_filename):
+            self.mkpath(os.path.dirname(output_filename))
+            self.spawn(self.archiver + [output_filename] + objects + self.objects)
+
+            # Not many Unices required ranlib anymore -- SunOS 4.x is, I
+            # think the only major Unix that does.  Maybe we need some
+            # platform intelligence here to skip ranlib if it's not
+            # needed -- or maybe Python's configure script took care of
+            # it for us, hence the check for leading colon.
+            if self.ranlib:
+                try:
+                    self.spawn(self.ranlib + [output_filename])
+                except DistutilsExecError as msg:
+                    raise LibError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    def link(
+        self,
+        target_desc,
+        objects: list[str] | tuple[str, ...],
+        output_filename,
+        output_dir: str | None = None,
+        libraries: list[str] | tuple[str, ...] | None = None,
+        library_dirs: list[str] | tuple[str, ...] | None = None,
+        runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        objects, output_dir = self._fix_object_args(objects, output_dir)
+        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
+        libraries, library_dirs, runtime_library_dirs = fixed_args
+
+        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
+        if not isinstance(output_dir, (str, type(None))):
+            raise TypeError("'output_dir' must be a string or None")
+        if output_dir is not None:
+            output_filename = os.path.join(output_dir, output_filename)
+
+        if self._need_link(objects, output_filename):
+            ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
+            if debug:
+                ld_args[:0] = ['-g']
+            if extra_preargs:
+                ld_args[:0] = extra_preargs
+            if extra_postargs:
+                ld_args.extend(extra_postargs)
+            self.mkpath(os.path.dirname(output_filename))
+            try:
+                # Select a linker based on context: linker_exe when
+                # building an executable or linker_so (with shared options)
+                # when building a shared library.
+                building_exe = target_desc == base.Compiler.EXECUTABLE
+                target_cxx = target_lang == "c++"
+                linker = (
+                    (self.linker_exe_cxx if target_cxx else self.linker_exe)
+                    if building_exe
+                    else (self.linker_so_cxx if target_cxx else self.linker_so)
+                )[:]
+
+                if target_cxx and self.compiler_cxx:
+                    env, linker_ne = _split_env(linker)
+                    aix, linker_na = _split_aix(linker_ne)
+                    _, compiler_cxx_ne = _split_env(self.compiler_cxx)
+                    _, linker_exe_ne = _split_env(self.linker_exe_cxx)
+
+                    params = _linker_params(linker_na, linker_exe_ne)
+                    linker = env + aix + compiler_cxx_ne + params
+
+                linker = compiler_fixup(linker, ld_args)
+
+                self.spawn(linker + ld_args)
+            except DistutilsExecError as msg:
+                raise LinkError(msg)
+        else:
+            log.debug("skipping %s (up-to-date)", output_filename)
+
+    # -- Miscellaneous methods -----------------------------------------
+    # These are all used by the 'gen_lib_options() function, in
+    # ccompiler.py.
+
+    def library_dir_option(self, dir):
+        return "-L" + dir
+
+    def _is_gcc(self):
+        cc_var = sysconfig.get_config_var("CC")
+        compiler = os.path.basename(shlex.split(cc_var)[0])
+        return "gcc" in compiler or "g++" in compiler
+
+    def runtime_library_dir_option(self, dir: str) -> str | list[str]:  # type: ignore[override] # Fixed in pypa/distutils#339
+        # XXX Hackish, at the very least.  See Python bug #445902:
+        # https://bugs.python.org/issue445902
+        # Linkers on different platforms need different options to
+        # specify that directories need to be added to the list of
+        # directories searched for dependencies when a dynamic library
+        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to
+        # be told to pass the -R option through to the linker, whereas
+        # other compilers and gcc on other systems just know this.
+        # Other compilers may need something slightly different.  At
+        # this time, there's no way to determine this information from
+        # the configuration data stored in the Python installation, so
+        # we use this hack.
+        if sys.platform[:6] == "darwin":
+            from distutils.util import get_macosx_target_ver, split_version
+
+            macosx_target_ver = get_macosx_target_ver()
+            if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
+                return "-Wl,-rpath," + dir
+            else:  # no support for -rpath on earlier macOS versions
+                return "-L" + dir
+        elif sys.platform[:7] == "freebsd":
+            return "-Wl,-rpath=" + dir
+        elif sys.platform[:5] == "hp-ux":
+            return [
+                "-Wl,+s" if self._is_gcc() else "+s",
+                "-L" + dir,
+            ]
+
+        # For all compilers, `-Wl` is the presumed way to pass a
+        # compiler option to the linker
+        if sysconfig.get_config_var("GNULD") == "yes":
+            return consolidate_linker_args([
+                # Force RUNPATH instead of RPATH
+                "-Wl,--enable-new-dtags",
+                "-Wl,-rpath," + dir,
+            ])
+        else:
+            return "-Wl,-R" + dir
+
+    def library_option(self, lib):
+        return "-l" + lib
+
+    @staticmethod
+    def _library_root(dir):
+        """
+        macOS users can specify an alternate SDK using'-isysroot'.
+        Calculate the SDK root if it is specified.
+
+        Note that, as of Xcode 7, Apple SDKs may contain textual stub
+        libraries with .tbd extensions rather than the normal .dylib
+        shared libraries installed in /.  The Apple compiler tool
+        chain handles this transparently but it can cause problems
+        for programs that are being built with an SDK and searching
+        for specific libraries.  Callers of find_library_file need to
+        keep in mind that the base filename of the returned SDK library
+        file might have a different extension from that of the library
+        file installed on the running system, for example:
+          /Applications/Xcode.app/Contents/Developer/Platforms/
+              MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
+              usr/lib/libedit.tbd
+        vs
+          /usr/lib/libedit.dylib
+        """
+        cflags = sysconfig.get_config_var('CFLAGS')
+        match = re.search(r'-isysroot\s*(\S+)', cflags)
+
+        apply_root = (
+            sys.platform == 'darwin'
+            and match
+            and (
+                dir.startswith('/System/')
+                or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
+            )
+        )
+
+        return os.path.join(match.group(1), dir[1:]) if apply_root else dir
+
+    def find_library_file(self, dirs, lib, debug=False):
+        """
+        Second-guess the linker with not much hard
+        data to go on: GCC seems to prefer the shared library, so
+        assume that *all* Unix C compilers do,
+        ignoring even GCC's "-static" option.
+        """
+        lib_names = (
+            self.library_filename(lib, lib_type=type)
+            for type in 'dylib xcode_stub shared static'.split()
+        )
+
+        roots = map(self._library_root, dirs)
+
+        searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names))
+
+        found = filter(os.path.exists, searched)
+
+        # Return None if it could not be found in any dir.
+        return next(found, None)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/zos.py b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/zos.py
new file mode 100644
index 0000000000000000000000000000000000000000..82d017fc90db55b8f7b2517ba6c8a8fd2082cb5e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/compilers/C/zos.py
@@ -0,0 +1,230 @@
+"""distutils.zosccompiler
+
+Contains the selection of the c & c++ compilers on z/OS. There are several
+different c compilers on z/OS, all of them are optional, so the correct
+one needs to be chosen based on the users input. This is compatible with
+the following compilers:
+
+IBM C/C++ For Open Enterprise Languages on z/OS 2.0
+IBM Open XL C/C++ 1.1 for z/OS
+IBM XL C/C++ V2.4.1 for z/OS 2.4 and 2.5
+IBM z/OS XL C/C++
+"""
+
+import os
+
+from ... import sysconfig
+from ...errors import DistutilsExecError
+from . import unix
+from .errors import CompileError
+
+_cc_args = {
+    'ibm-openxl': [
+        '-m64',
+        '-fvisibility=default',
+        '-fzos-le-char-mode=ascii',
+        '-fno-short-enums',
+    ],
+    'ibm-xlclang': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+    ],
+    'ibm-xlc': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+        '-qlanglvl=extc99',
+    ],
+}
+
+_cxx_args = {
+    'ibm-openxl': [
+        '-m64',
+        '-fvisibility=default',
+        '-fzos-le-char-mode=ascii',
+        '-fno-short-enums',
+    ],
+    'ibm-xlclang': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+    ],
+    'ibm-xlc': [
+        '-q64',
+        '-qexportall',
+        '-qascii',
+        '-qstrict',
+        '-qnocsect',
+        '-Wa,asa,goff',
+        '-Wa,xplink',
+        '-qgonumber',
+        '-qenum=int',
+        '-Wc,DLL',
+        '-qlanglvl=extended0x',
+    ],
+}
+
+_asm_args = {
+    'ibm-openxl': ['-fasm', '-fno-integrated-as', '-Wa,--ASA', '-Wa,--GOFF'],
+    'ibm-xlclang': [],
+    'ibm-xlc': [],
+}
+
+_ld_args = {
+    'ibm-openxl': [],
+    'ibm-xlclang': ['-Wl,dll', '-q64'],
+    'ibm-xlc': ['-Wl,dll', '-q64'],
+}
+
+
+# Python on z/OS is built with no compiler specific options in it's CFLAGS.
+# But each compiler requires it's own specific options to build successfully,
+# though some of the options are common between them
+class Compiler(unix.Compiler):
+    src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s']
+    _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C']
+    _asm_extensions = ['.s']
+
+    def _get_zos_compiler_name(self):
+        zos_compiler_names = [
+            os.path.basename(binary)
+            for envvar in ('CC', 'CXX', 'LDSHARED')
+            if (binary := os.environ.get(envvar, None))
+        ]
+        if len(zos_compiler_names) == 0:
+            return 'ibm-openxl'
+
+        zos_compilers = {}
+        for compiler in (
+            'ibm-clang',
+            'ibm-clang64',
+            'ibm-clang++',
+            'ibm-clang++64',
+            'clang',
+            'clang++',
+            'clang-14',
+        ):
+            zos_compilers[compiler] = 'ibm-openxl'
+
+        for compiler in ('xlclang', 'xlclang++', 'njsc', 'njsc++'):
+            zos_compilers[compiler] = 'ibm-xlclang'
+
+        for compiler in ('xlc', 'xlC', 'xlc++'):
+            zos_compilers[compiler] = 'ibm-xlc'
+
+        return zos_compilers.get(zos_compiler_names[0], 'ibm-openxl')
+
+    def __init__(self, verbose=False, dry_run=False, force=False):
+        super().__init__(verbose, dry_run, force)
+        self.zos_compiler = self._get_zos_compiler_name()
+        sysconfig.customize_compiler(self)
+
+    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
+        local_args = []
+        if ext in self._cpp_extensions:
+            compiler = self.compiler_cxx
+            local_args.extend(_cxx_args[self.zos_compiler])
+        elif ext in self._asm_extensions:
+            compiler = self.compiler_so
+            local_args.extend(_cc_args[self.zos_compiler])
+            local_args.extend(_asm_args[self.zos_compiler])
+        else:
+            compiler = self.compiler_so
+            local_args.extend(_cc_args[self.zos_compiler])
+        local_args.extend(cc_args)
+
+        try:
+            self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs)
+        except DistutilsExecError as msg:
+            raise CompileError(msg)
+
+    def runtime_library_dir_option(self, dir):
+        return '-L' + dir
+
+    def link(
+        self,
+        target_desc,
+        objects,
+        output_filename,
+        output_dir=None,
+        libraries=None,
+        library_dirs=None,
+        runtime_library_dirs=None,
+        export_symbols=None,
+        debug=False,
+        extra_preargs=None,
+        extra_postargs=None,
+        build_temp=None,
+        target_lang=None,
+    ):
+        # For a built module to use functions from cpython, it needs to use Pythons
+        # side deck file. The side deck is located beside the libpython3.xx.so
+        ldversion = sysconfig.get_config_var('LDVERSION')
+        if sysconfig.python_build:
+            side_deck_path = os.path.join(
+                sysconfig.get_config_var('abs_builddir'),
+                f'libpython{ldversion}.x',
+            )
+        else:
+            side_deck_path = os.path.join(
+                sysconfig.get_config_var('installed_base'),
+                sysconfig.get_config_var('platlibdir'),
+                f'libpython{ldversion}.x',
+            )
+
+        if os.path.exists(side_deck_path):
+            if extra_postargs:
+                extra_postargs.append(side_deck_path)
+            else:
+                extra_postargs = [side_deck_path]
+
+        # Check and replace libraries included side deck files
+        if runtime_library_dirs:
+            for dir in runtime_library_dirs:
+                for library in libraries[:]:
+                    library_side_deck = os.path.join(dir, f'{library}.x')
+                    if os.path.exists(library_side_deck):
+                        libraries.remove(library)
+                        extra_postargs.append(library_side_deck)
+                        break
+
+        # Any required ld args for the given compiler
+        extra_postargs.extend(_ld_args[self.zos_compiler])
+
+        super().link(
+            target_desc,
+            objects,
+            output_filename,
+            output_dir,
+            libraries,
+            library_dirs,
+            runtime_library_dirs,
+            export_symbols,
+            debug,
+            extra_preargs,
+            extra_postargs,
+            build_temp,
+            target_lang,
+        )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/core.py b/python_embeded/Lib/site-packages/setuptools/_distutils/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd62546bdd9d35dcc46e0b46a46b0c61a43fd0ba
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/core.py
@@ -0,0 +1,289 @@
+"""distutils.core
+
+The only module that needs to be imported to use the Distutils; provides
+the 'setup' function (which is to be called from the setup script).  Also
+indirectly provides the Distribution and Command classes, although they are
+really defined in distutils.dist and distutils.cmd.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import tokenize
+from collections.abc import Iterable
+
+from .cmd import Command
+from .debug import DEBUG
+
+# Mainly import these so setup scripts can "from distutils.core import" them.
+from .dist import Distribution
+from .errors import (
+    CCompilerError,
+    DistutilsArgError,
+    DistutilsError,
+    DistutilsSetupError,
+)
+from .extension import Extension
+
+__all__ = ['Distribution', 'Command', 'Extension', 'setup']
+
+# This is a barebones help message generated displayed when the user
+# runs the setup script with no arguments at all.  More useful help
+# is generated with various --help options: global help, list commands,
+# and per-command help.
+USAGE = """\
+usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
+   or: %(script)s --help [cmd1 cmd2 ...]
+   or: %(script)s --help-commands
+   or: %(script)s cmd --help
+"""
+
+
+def gen_usage(script_name):
+    script = os.path.basename(script_name)
+    return USAGE % locals()
+
+
+# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
+_setup_stop_after = None
+_setup_distribution = None
+
+# Legal keyword arguments for the setup() function
+setup_keywords = (
+    'distclass',
+    'script_name',
+    'script_args',
+    'options',
+    'name',
+    'version',
+    'author',
+    'author_email',
+    'maintainer',
+    'maintainer_email',
+    'url',
+    'license',
+    'description',
+    'long_description',
+    'keywords',
+    'platforms',
+    'classifiers',
+    'download_url',
+    'requires',
+    'provides',
+    'obsoletes',
+)
+
+# Legal keyword arguments for the Extension constructor
+extension_keywords = (
+    'name',
+    'sources',
+    'include_dirs',
+    'define_macros',
+    'undef_macros',
+    'library_dirs',
+    'libraries',
+    'runtime_library_dirs',
+    'extra_objects',
+    'extra_compile_args',
+    'extra_link_args',
+    'swig_opts',
+    'export_symbols',
+    'depends',
+    'language',
+)
+
+
+def setup(**attrs):  # noqa: C901
+    """The gateway to the Distutils: do everything your setup script needs
+    to do, in a highly flexible and user-driven way.  Briefly: create a
+    Distribution instance; find and parse config files; parse the command
+    line; run each Distutils command found there, customized by the options
+    supplied to 'setup()' (as keyword arguments), in config files, and on
+    the command line.
+
+    The Distribution instance might be an instance of a class supplied via
+    the 'distclass' keyword argument to 'setup'; if no such class is
+    supplied, then the Distribution class (in dist.py) is instantiated.
+    All other arguments to 'setup' (except for 'cmdclass') are used to set
+    attributes of the Distribution instance.
+
+    The 'cmdclass' argument, if supplied, is a dictionary mapping command
+    names to command classes.  Each command encountered on the command line
+    will be turned into a command class, which is in turn instantiated; any
+    class found in 'cmdclass' is used in place of the default, which is
+    (for command 'foo_bar') class 'foo_bar' in module
+    'distutils.command.foo_bar'.  The command class must provide a
+    'user_options' attribute which is a list of option specifiers for
+    'distutils.fancy_getopt'.  Any command-line options between the current
+    and the next command are used to set attributes of the current command
+    object.
+
+    When the entire command-line has been successfully parsed, calls the
+    'run()' method on each command object in turn.  This method will be
+    driven entirely by the Distribution object (which each command object
+    has a reference to, thanks to its constructor), and the
+    command-specific options that became attributes of each command
+    object.
+    """
+
+    global _setup_stop_after, _setup_distribution
+
+    # Determine the distribution class -- either caller-supplied or
+    # our Distribution (see below).
+    klass = attrs.get('distclass')
+    if klass:
+        attrs.pop('distclass')
+    else:
+        klass = Distribution
+
+    if 'script_name' not in attrs:
+        attrs['script_name'] = os.path.basename(sys.argv[0])
+    if 'script_args' not in attrs:
+        attrs['script_args'] = sys.argv[1:]
+
+    # Create the Distribution instance, using the remaining arguments
+    # (ie. everything except distclass) to initialize it
+    try:
+        _setup_distribution = dist = klass(attrs)
+    except DistutilsSetupError as msg:
+        if 'name' not in attrs:
+            raise SystemExit(f"error in setup command: {msg}")
+        else:
+            raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg))
+
+    if _setup_stop_after == "init":
+        return dist
+
+    # Find and parse the config file(s): they will override options from
+    # the setup script, but be overridden by the command line.
+    dist.parse_config_files()
+
+    if DEBUG:
+        print("options (after parsing config files):")
+        dist.dump_option_dicts()
+
+    if _setup_stop_after == "config":
+        return dist
+
+    # Parse the command line and override config files; any
+    # command-line errors are the end user's fault, so turn them into
+    # SystemExit to suppress tracebacks.
+    try:
+        ok = dist.parse_command_line()
+    except DistutilsArgError as msg:
+        raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}")
+
+    if DEBUG:
+        print("options (after parsing command line):")
+        dist.dump_option_dicts()
+
+    if _setup_stop_after == "commandline":
+        return dist
+
+    # And finally, run all the commands found on the command line.
+    if ok:
+        return run_commands(dist)
+
+    return dist
+
+
+# setup ()
+
+
+def run_commands(dist):
+    """Given a Distribution object run all the commands,
+    raising ``SystemExit`` errors in the case of failure.
+
+    This function assumes that either ``sys.argv`` or ``dist.script_args``
+    is already set accordingly.
+    """
+    try:
+        dist.run_commands()
+    except KeyboardInterrupt:
+        raise SystemExit("interrupted")
+    except OSError as exc:
+        if DEBUG:
+            sys.stderr.write(f"error: {exc}\n")
+            raise
+        else:
+            raise SystemExit(f"error: {exc}")
+
+    except (DistutilsError, CCompilerError) as msg:
+        if DEBUG:
+            raise
+        else:
+            raise SystemExit("error: " + str(msg))
+
+    return dist
+
+
+def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"):
+    """Run a setup script in a somewhat controlled environment, and
+    return the Distribution instance that drives things.  This is useful
+    if you need to find out the distribution meta-data (passed as
+    keyword args from 'script' to 'setup()', or the contents of the
+    config files or command-line.
+
+    'script_name' is a file that will be read and run with 'exec()';
+    'sys.argv[0]' will be replaced with 'script' for the duration of the
+    call.  'script_args' is a list of strings; if supplied,
+    'sys.argv[1:]' will be replaced by 'script_args' for the duration of
+    the call.
+
+    'stop_after' tells 'setup()' when to stop processing; possible
+    values:
+      init
+        stop after the Distribution instance has been created and
+        populated with the keyword arguments to 'setup()'
+      config
+        stop after config files have been parsed (and their data
+        stored in the Distribution instance)
+      commandline
+        stop after the command-line ('sys.argv[1:]' or 'script_args')
+        have been parsed (and the data stored in the Distribution)
+      run [default]
+        stop after all commands have been run (the same as if 'setup()'
+        had been called in the usual way
+
+    Returns the Distribution instance, which provides all information
+    used to drive the Distutils.
+    """
+    if stop_after not in ('init', 'config', 'commandline', 'run'):
+        raise ValueError(f"invalid value for 'stop_after': {stop_after!r}")
+
+    global _setup_stop_after, _setup_distribution
+    _setup_stop_after = stop_after
+
+    save_argv = sys.argv.copy()
+    g = {'__file__': script_name, '__name__': '__main__'}
+    try:
+        try:
+            sys.argv[0] = script_name
+            if script_args is not None:
+                sys.argv[1:] = script_args
+            # tokenize.open supports automatic encoding detection
+            with tokenize.open(script_name) as f:
+                code = f.read().replace(r'\r\n', r'\n')
+                exec(code, g)
+        finally:
+            sys.argv = save_argv
+            _setup_stop_after = None
+    except SystemExit:
+        # Hmm, should we do something if exiting with a non-zero code
+        # (ie. error)?
+        pass
+
+    if _setup_distribution is None:
+        raise RuntimeError(
+            "'distutils.core.setup()' was never called -- "
+            f"perhaps '{script_name}' is not a Distutils setup script?"
+        )
+
+    # I wonder if the setup script's namespace -- g and l -- would be of
+    # any interest to callers?
+    # print "_setup_distribution:", _setup_distribution
+    return _setup_distribution
+
+
+# run_setup ()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/cygwinccompiler.py b/python_embeded/Lib/site-packages/setuptools/_distutils/cygwinccompiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..de89e3cd8402c9b7048c9e456ff67601934f972b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/cygwinccompiler.py
@@ -0,0 +1,31 @@
+from .compilers.C import cygwin
+from .compilers.C.cygwin import (
+    CONFIG_H_NOTOK,
+    CONFIG_H_OK,
+    CONFIG_H_UNCERTAIN,
+    check_config_h,
+    get_msvcr,
+    is_cygwincc,
+)
+
+__all__ = [
+    'CONFIG_H_NOTOK',
+    'CONFIG_H_OK',
+    'CONFIG_H_UNCERTAIN',
+    'CygwinCCompiler',
+    'Mingw32CCompiler',
+    'check_config_h',
+    'get_msvcr',
+    'is_cygwincc',
+]
+
+
+CygwinCCompiler = cygwin.Compiler
+Mingw32CCompiler = cygwin.MinGW32Compiler
+
+
+get_versions = None
+"""
+A stand-in for the previous get_versions() function to prevent failures
+when monkeypatched. See pypa/setuptools#2969.
+"""
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/debug.py b/python_embeded/Lib/site-packages/setuptools/_distutils/debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..daf1660f0d821143e388d37532a39ddfd2ca0347
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/debug.py
@@ -0,0 +1,5 @@
+import os
+
+# If DISTUTILS_DEBUG is anything other than the empty string, we run in
+# debug mode.
+DEBUG = os.environ.get('DISTUTILS_DEBUG')
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/dep_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/dep_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..09a8a2e126c8bb009dbbe61c5c4bd5e358744996
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/dep_util.py
@@ -0,0 +1,14 @@
+import warnings
+
+from . import _modified
+
+
+def __getattr__(name):
+    if name not in ['newer', 'newer_group', 'newer_pairwise']:
+        raise AttributeError(name)
+    warnings.warn(
+        "dep_util is Deprecated. Use functions from setuptools instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    return getattr(_modified, name)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/dir_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/dir_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9782602cfe78d4033fb43846965347de8ad9cdf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/dir_util.py
@@ -0,0 +1,244 @@
+"""distutils.dir_util
+
+Utility functions for manipulating directories and directory trees."""
+
+import functools
+import itertools
+import os
+import pathlib
+
+from . import file_util
+from ._log import log
+from .errors import DistutilsFileError, DistutilsInternalError
+
+
+class SkipRepeatAbsolutePaths(set):
+    """
+    Cache for mkpath.
+
+    In addition to cheapening redundant calls, eliminates redundant
+    "creating /foo/bar/baz" messages in dry-run mode.
+    """
+
+    def __init__(self):
+        SkipRepeatAbsolutePaths.instance = self
+
+    @classmethod
+    def clear(cls):
+        super(cls, cls.instance).clear()
+
+    def wrap(self, func):
+        @functools.wraps(func)
+        def wrapper(path, *args, **kwargs):
+            if path.absolute() in self:
+                return
+            result = func(path, *args, **kwargs)
+            self.add(path.absolute())
+            return result
+
+        return wrapper
+
+
+# Python 3.8 compatibility
+wrapper = SkipRepeatAbsolutePaths().wrap
+
+
+@functools.singledispatch
+@wrapper
+def mkpath(name: pathlib.Path, mode=0o777, verbose=True, dry_run=False) -> None:
+    """Create a directory and any missing ancestor directories.
+
+    If the directory already exists (or if 'name' is the empty string, which
+    means the current directory, which of course exists), then do nothing.
+    Raise DistutilsFileError if unable to create some directory along the way
+    (eg. some sub-path exists, but is a file rather than a directory).
+    If 'verbose' is true, log the directory created.
+    """
+    if verbose and not name.is_dir():
+        log.info("creating %s", name)
+
+    try:
+        dry_run or name.mkdir(mode=mode, parents=True, exist_ok=True)
+    except OSError as exc:
+        raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}")
+
+
+@mkpath.register
+def _(name: str, *args, **kwargs):
+    return mkpath(pathlib.Path(name), *args, **kwargs)
+
+
+@mkpath.register
+def _(name: None, *args, **kwargs):
+    """
+    Detect a common bug -- name is None.
+    """
+    raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")
+
+
+def create_tree(base_dir, files, mode=0o777, verbose=True, dry_run=False):
+    """Create all the empty directories under 'base_dir' needed to put 'files'
+    there.
+
+    'base_dir' is just the name of a directory which doesn't necessarily
+    exist yet; 'files' is a list of filenames to be interpreted relative to
+    'base_dir'.  'base_dir' + the directory portion of every file in 'files'
+    will be created if it doesn't already exist.  'mode', 'verbose' and
+    'dry_run' flags are as for 'mkpath()'.
+    """
+    # First get the list of directories to create
+    need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files)
+
+    # Now create them
+    for dir in sorted(need_dir):
+        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
+
+
+def copy_tree(
+    src,
+    dst,
+    preserve_mode=True,
+    preserve_times=True,
+    preserve_symlinks=False,
+    update=False,
+    verbose=True,
+    dry_run=False,
+):
+    """Copy an entire directory tree 'src' to a new location 'dst'.
+
+    Both 'src' and 'dst' must be directory names.  If 'src' is not a
+    directory, raise DistutilsFileError.  If 'dst' does not exist, it is
+    created with 'mkpath()'.  The end result of the copy is that every
+    file in 'src' is copied to 'dst', and directories under 'src' are
+    recursively copied to 'dst'.  Return the list of files that were
+    copied or might have been copied, using their output name.  The
+    return value is unaffected by 'update' or 'dry_run': it is simply
+    the list of all files under 'src', with the names changed to be
+    under 'dst'.
+
+    'preserve_mode' and 'preserve_times' are the same as for
+    'copy_file'; note that they only apply to regular files, not to
+    directories.  If 'preserve_symlinks' is true, symlinks will be
+    copied as symlinks (on platforms that support them!); otherwise
+    (the default), the destination of the symlink will be copied.
+    'update' and 'verbose' are the same as for 'copy_file'.
+    """
+    if not dry_run and not os.path.isdir(src):
+        raise DistutilsFileError(f"cannot copy tree '{src}': not a directory")
+    try:
+        names = os.listdir(src)
+    except OSError as e:
+        if dry_run:
+            names = []
+        else:
+            raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
+
+    if not dry_run:
+        mkpath(dst, verbose=verbose)
+
+    copy_one = functools.partial(
+        _copy_one,
+        src=src,
+        dst=dst,
+        preserve_symlinks=preserve_symlinks,
+        verbose=verbose,
+        dry_run=dry_run,
+        preserve_mode=preserve_mode,
+        preserve_times=preserve_times,
+        update=update,
+    )
+    return list(itertools.chain.from_iterable(map(copy_one, names)))
+
+
+def _copy_one(
+    name,
+    *,
+    src,
+    dst,
+    preserve_symlinks,
+    verbose,
+    dry_run,
+    preserve_mode,
+    preserve_times,
+    update,
+):
+    src_name = os.path.join(src, name)
+    dst_name = os.path.join(dst, name)
+
+    if name.startswith('.nfs'):
+        # skip NFS rename files
+        return
+
+    if preserve_symlinks and os.path.islink(src_name):
+        link_dest = os.readlink(src_name)
+        if verbose >= 1:
+            log.info("linking %s -> %s", dst_name, link_dest)
+        if not dry_run:
+            os.symlink(link_dest, dst_name)
+        yield dst_name
+
+    elif os.path.isdir(src_name):
+        yield from copy_tree(
+            src_name,
+            dst_name,
+            preserve_mode,
+            preserve_times,
+            preserve_symlinks,
+            update,
+            verbose=verbose,
+            dry_run=dry_run,
+        )
+    else:
+        file_util.copy_file(
+            src_name,
+            dst_name,
+            preserve_mode,
+            preserve_times,
+            update,
+            verbose=verbose,
+            dry_run=dry_run,
+        )
+        yield dst_name
+
+
+def _build_cmdtuple(path, cmdtuples):
+    """Helper for remove_tree()."""
+    for f in os.listdir(path):
+        real_f = os.path.join(path, f)
+        if os.path.isdir(real_f) and not os.path.islink(real_f):
+            _build_cmdtuple(real_f, cmdtuples)
+        else:
+            cmdtuples.append((os.remove, real_f))
+    cmdtuples.append((os.rmdir, path))
+
+
+def remove_tree(directory, verbose=True, dry_run=False):
+    """Recursively remove an entire directory tree.
+
+    Any errors are ignored (apart from being reported to stdout if 'verbose'
+    is true).
+    """
+    if verbose >= 1:
+        log.info("removing '%s' (and everything under it)", directory)
+    if dry_run:
+        return
+    cmdtuples = []
+    _build_cmdtuple(directory, cmdtuples)
+    for cmd in cmdtuples:
+        try:
+            cmd[0](cmd[1])
+            # Clear the cache
+            SkipRepeatAbsolutePaths.clear()
+        except OSError as exc:
+            log.warning("error removing %s: %s", directory, exc)
+
+
+def ensure_relative(path):
+    """Take the full path 'path', and make it a relative path.
+
+    This is useful to make 'path' the second argument to os.path.join().
+    """
+    drive, path = os.path.splitdrive(path)
+    if path[0:1] == os.sep:
+        path = drive + path[1:]
+    return path
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/dist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..37b788df92549877684c2311ed1c71634f14dcd2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/dist.py
@@ -0,0 +1,1386 @@
+"""distutils.dist
+
+Provides the Distribution class, which represents the module distribution
+being built/installed/distributed.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import pathlib
+import re
+import sys
+import warnings
+from collections.abc import Iterable, MutableMapping
+from email import message_from_file
+from typing import (
+    IO,
+    TYPE_CHECKING,
+    Any,
+    ClassVar,
+    Literal,
+    TypeVar,
+    Union,
+    overload,
+)
+
+from packaging.utils import canonicalize_name, canonicalize_version
+
+from ._log import log
+from .debug import DEBUG
+from .errors import (
+    DistutilsArgError,
+    DistutilsClassError,
+    DistutilsModuleError,
+    DistutilsOptionError,
+)
+from .fancy_getopt import FancyGetopt, translate_longopt
+from .util import check_environ, rfc822_escape, strtobool
+
+if TYPE_CHECKING:
+    from _typeshed import SupportsWrite
+    from typing_extensions import TypeAlias
+
+    # type-only import because of mutual dependence between these modules
+    from .cmd import Command
+
+_CommandT = TypeVar("_CommandT", bound="Command")
+_OptionsList: TypeAlias = list[
+    Union[tuple[str, Union[str, None], str, int], tuple[str, Union[str, None], str]]
+]
+
+
+# Regex to define acceptable Distutils command names.  This is not *quite*
+# the same as a Python NAME -- I don't allow leading underscores.  The fact
+# that they're very similar is no coincidence; the default naming scheme is
+# to look for a Python module named after the command.
+command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
+
+
+def _ensure_list(value: str | Iterable[str], fieldname) -> str | list[str]:
+    if isinstance(value, str):
+        # a string containing comma separated values is okay.  It will
+        # be converted to a list by Distribution.finalize_options().
+        pass
+    elif not isinstance(value, list):
+        # passing a tuple or an iterator perhaps, warn and convert
+        typename = type(value).__name__
+        msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"
+        msg = msg.format(**locals())
+        log.warning(msg)
+        value = list(value)
+    return value
+
+
+class Distribution:
+    """The core of the Distutils.  Most of the work hiding behind 'setup'
+    is really done within a Distribution instance, which farms the work out
+    to the Distutils commands specified on the command line.
+
+    Setup scripts will almost never instantiate Distribution directly,
+    unless the 'setup()' function is totally inadequate to their needs.
+    However, it is conceivable that a setup script might wish to subclass
+    Distribution for some specialized purpose, and then pass the subclass
+    to 'setup()' as the 'distclass' keyword argument.  If so, it is
+    necessary to respect the expectations that 'setup' has of Distribution.
+    See the code for 'setup()', in core.py, for details.
+    """
+
+    # 'global_options' describes the command-line options that may be
+    # supplied to the setup script prior to any actual commands.
+    # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
+    # these global options.  This list should be kept to a bare minimum,
+    # since every global option is also valid as a command option -- and we
+    # don't want to pollute the commands with too many options that they
+    # have minimal control over.
+    # The fourth entry for verbose means that it can be repeated.
+    global_options: ClassVar[_OptionsList] = [
+        ('verbose', 'v', "run verbosely (default)", 1),
+        ('quiet', 'q', "run quietly (turns verbosity off)"),
+        ('dry-run', 'n', "don't actually do anything"),
+        ('help', 'h', "show detailed help message"),
+        ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
+    ]
+
+    # 'common_usage' is a short (2-3 line) string describing the common
+    # usage of the setup script.
+    common_usage: ClassVar[str] = """\
+Common commands: (see '--help-commands' for more)
+
+  setup.py build      will build the package underneath 'build/'
+  setup.py install    will install the package
+"""
+
+    # options that are not propagated to the commands
+    display_options: ClassVar[_OptionsList] = [
+        ('help-commands', None, "list all available commands"),
+        ('name', None, "print package name"),
+        ('version', 'V', "print package version"),
+        ('fullname', None, "print -"),
+        ('author', None, "print the author's name"),
+        ('author-email', None, "print the author's email address"),
+        ('maintainer', None, "print the maintainer's name"),
+        ('maintainer-email', None, "print the maintainer's email address"),
+        ('contact', None, "print the maintainer's name if known, else the author's"),
+        (
+            'contact-email',
+            None,
+            "print the maintainer's email address if known, else the author's",
+        ),
+        ('url', None, "print the URL for this package"),
+        ('license', None, "print the license of the package"),
+        ('licence', None, "alias for --license"),
+        ('description', None, "print the package description"),
+        ('long-description', None, "print the long package description"),
+        ('platforms', None, "print the list of platforms"),
+        ('classifiers', None, "print the list of classifiers"),
+        ('keywords', None, "print the list of keywords"),
+        ('provides', None, "print the list of packages/modules provided"),
+        ('requires', None, "print the list of packages/modules required"),
+        ('obsoletes', None, "print the list of packages/modules made obsolete"),
+    ]
+    display_option_names: ClassVar[list[str]] = [
+        translate_longopt(x[0]) for x in display_options
+    ]
+
+    # negative options are options that exclude other options
+    negative_opt: ClassVar[dict[str, str]] = {'quiet': 'verbose'}
+
+    # -- Creation/initialization methods -------------------------------
+
+    # Can't Unpack a TypedDict with optional properties, so using Any instead
+    def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:  # noqa: C901
+        """Construct a new Distribution instance: initialize all the
+        attributes of a Distribution, and then use 'attrs' (a dictionary
+        mapping attribute names to values) to assign some of those
+        attributes their "real" values.  (Any attributes not mentioned in
+        'attrs' will be assigned to some null value: 0, None, an empty list
+        or dictionary, etc.)  Most importantly, initialize the
+        'command_obj' attribute to the empty dictionary; this will be
+        filled in with real command objects by 'parse_command_line()'.
+        """
+
+        # Default values for our command-line options
+        self.verbose = True
+        self.dry_run = False
+        self.help = False
+        for attr in self.display_option_names:
+            setattr(self, attr, False)
+
+        # Store the distribution meta-data (name, version, author, and so
+        # forth) in a separate object -- we're getting to have enough
+        # information here (and enough command-line options) that it's
+        # worth it.  Also delegate 'get_XXX()' methods to the 'metadata'
+        # object in a sneaky and underhanded (but efficient!) way.
+        self.metadata = DistributionMetadata()
+        for basename in self.metadata._METHOD_BASENAMES:
+            method_name = "get_" + basename
+            setattr(self, method_name, getattr(self.metadata, method_name))
+
+        # 'cmdclass' maps command names to class objects, so we
+        # can 1) quickly figure out which class to instantiate when
+        # we need to create a new command object, and 2) have a way
+        # for the setup script to override command classes
+        self.cmdclass: dict[str, type[Command]] = {}
+
+        # 'command_packages' is a list of packages in which commands
+        # are searched for.  The factory for command 'foo' is expected
+        # to be named 'foo' in the module 'foo' in one of the packages
+        # named here.  This list is searched from the left; an error
+        # is raised if no named package provides the command being
+        # searched for.  (Always access using get_command_packages().)
+        self.command_packages: str | list[str] | None = None
+
+        # 'script_name' and 'script_args' are usually set to sys.argv[0]
+        # and sys.argv[1:], but they can be overridden when the caller is
+        # not necessarily a setup script run from the command-line.
+        self.script_name: str | os.PathLike[str] | None = None
+        self.script_args: list[str] | None = None
+
+        # 'command_options' is where we store command options between
+        # parsing them (from config files, the command-line, etc.) and when
+        # they are actually needed -- ie. when the command in question is
+        # instantiated.  It is a dictionary of dictionaries of 2-tuples:
+        #   command_options = { command_name : { option : (source, value) } }
+        self.command_options: dict[str, dict[str, tuple[str, str]]] = {}
+
+        # 'dist_files' is the list of (command, pyversion, file) that
+        # have been created by any dist commands run so far. This is
+        # filled regardless of whether the run is dry or not. pyversion
+        # gives sysconfig.get_python_version() if the dist file is
+        # specific to a Python version, 'any' if it is good for all
+        # Python versions on the target platform, and '' for a source
+        # file. pyversion should not be used to specify minimum or
+        # maximum required Python versions; use the metainfo for that
+        # instead.
+        self.dist_files: list[tuple[str, str, str]] = []
+
+        # These options are really the business of various commands, rather
+        # than of the Distribution itself.  We provide aliases for them in
+        # Distribution as a convenience to the developer.
+        self.packages = None
+        self.package_data: dict[str, list[str]] = {}
+        self.package_dir = None
+        self.py_modules = None
+        self.libraries = None
+        self.headers = None
+        self.ext_modules = None
+        self.ext_package = None
+        self.include_dirs = None
+        self.extra_path = None
+        self.scripts = None
+        self.data_files = None
+        self.password = ''
+
+        # And now initialize bookkeeping stuff that can't be supplied by
+        # the caller at all.  'command_obj' maps command names to
+        # Command instances -- that's how we enforce that every command
+        # class is a singleton.
+        self.command_obj: dict[str, Command] = {}
+
+        # 'have_run' maps command names to boolean values; it keeps track
+        # of whether we have actually run a particular command, to make it
+        # cheap to "run" a command whenever we think we might need to -- if
+        # it's already been done, no need for expensive filesystem
+        # operations, we just check the 'have_run' dictionary and carry on.
+        # It's only safe to query 'have_run' for a command class that has
+        # been instantiated -- a false value will be inserted when the
+        # command object is created, and replaced with a true value when
+        # the command is successfully run.  Thus it's probably best to use
+        # '.get()' rather than a straight lookup.
+        self.have_run: dict[str, bool] = {}
+
+        # Now we'll use the attrs dictionary (ultimately, keyword args from
+        # the setup script) to possibly override any or all of these
+        # distribution options.
+
+        if attrs:
+            # Pull out the set of command options and work on them
+            # specifically.  Note that this order guarantees that aliased
+            # command options will override any supplied redundantly
+            # through the general options dictionary.
+            options = attrs.get('options')
+            if options is not None:
+                del attrs['options']
+                for command, cmd_options in options.items():
+                    opt_dict = self.get_option_dict(command)
+                    for opt, val in cmd_options.items():
+                        opt_dict[opt] = ("setup script", val)
+
+            if 'licence' in attrs:
+                attrs['license'] = attrs['licence']
+                del attrs['licence']
+                msg = "'licence' distribution option is deprecated; use 'license'"
+                warnings.warn(msg)
+
+            # Now work on the rest of the attributes.  Any attribute that's
+            # not already defined is invalid!
+            for key, val in attrs.items():
+                if hasattr(self.metadata, "set_" + key):
+                    getattr(self.metadata, "set_" + key)(val)
+                elif hasattr(self.metadata, key):
+                    setattr(self.metadata, key, val)
+                elif hasattr(self, key):
+                    setattr(self, key, val)
+                else:
+                    msg = f"Unknown distribution option: {key!r}"
+                    warnings.warn(msg)
+
+        # no-user-cfg is handled before other command line args
+        # because other args override the config files, and this
+        # one is needed before we can load the config files.
+        # If attrs['script_args'] wasn't passed, assume false.
+        #
+        # This also make sure we just look at the global options
+        self.want_user_cfg = True
+
+        if self.script_args is not None:
+            # Coerce any possible iterable from attrs into a list
+            self.script_args = list(self.script_args)
+            for arg in self.script_args:
+                if not arg.startswith('-'):
+                    break
+                if arg == '--no-user-cfg':
+                    self.want_user_cfg = False
+                    break
+
+        self.finalize_options()
+
+    def get_option_dict(self, command):
+        """Get the option dictionary for a given command.  If that
+        command's option dictionary hasn't been created yet, then create it
+        and return the new dictionary; otherwise, return the existing
+        option dictionary.
+        """
+        dict = self.command_options.get(command)
+        if dict is None:
+            dict = self.command_options[command] = {}
+        return dict
+
+    def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None:
+        from pprint import pformat
+
+        if commands is None:  # dump all command option dicts
+            commands = sorted(self.command_options.keys())
+
+        if header is not None:
+            self.announce(indent + header)
+            indent = indent + "  "
+
+        if not commands:
+            self.announce(indent + "no commands known yet")
+            return
+
+        for cmd_name in commands:
+            opt_dict = self.command_options.get(cmd_name)
+            if opt_dict is None:
+                self.announce(indent + f"no option dict for '{cmd_name}' command")
+            else:
+                self.announce(indent + f"option dict for '{cmd_name}' command:")
+                out = pformat(opt_dict)
+                for line in out.split('\n'):
+                    self.announce(indent + "  " + line)
+
+    # -- Config file finding/parsing methods ---------------------------
+
+    def find_config_files(self):
+        """Find as many configuration files as should be processed for this
+        platform, and return a list of filenames in the order in which they
+        should be parsed.  The filenames returned are guaranteed to exist
+        (modulo nasty race conditions).
+
+        There are multiple possible config files:
+        - distutils.cfg in the Distutils installation directory (i.e.
+          where the top-level Distutils __inst__.py file lives)
+        - a file in the user's home directory named .pydistutils.cfg
+          on Unix and pydistutils.cfg on Windows/Mac; may be disabled
+          with the ``--no-user-cfg`` option
+        - setup.cfg in the current directory
+        - a file named by an environment variable
+        """
+        check_environ()
+        files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
+
+        if DEBUG:
+            self.announce("using config files: {}".format(', '.join(files)))
+
+        return files
+
+    def _gen_paths(self):
+        # The system-wide Distutils config file
+        sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent
+        yield sys_dir / "distutils.cfg"
+
+        # The per-user config file
+        prefix = '.' * (os.name == 'posix')
+        filename = prefix + 'pydistutils.cfg'
+        if self.want_user_cfg:
+            with contextlib.suppress(RuntimeError):
+                yield pathlib.Path('~').expanduser() / filename
+
+        # All platforms support local setup.cfg
+        yield pathlib.Path('setup.cfg')
+
+        # Additional config indicated in the environment
+        with contextlib.suppress(TypeError):
+            yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG"))
+
+    def parse_config_files(self, filenames=None):  # noqa: C901
+        from configparser import ConfigParser
+
+        # Ignore install directory options if we have a venv
+        if sys.prefix != sys.base_prefix:
+            ignore_options = [
+                'install-base',
+                'install-platbase',
+                'install-lib',
+                'install-platlib',
+                'install-purelib',
+                'install-headers',
+                'install-scripts',
+                'install-data',
+                'prefix',
+                'exec-prefix',
+                'home',
+                'user',
+                'root',
+            ]
+        else:
+            ignore_options = []
+
+        ignore_options = frozenset(ignore_options)
+
+        if filenames is None:
+            filenames = self.find_config_files()
+
+        if DEBUG:
+            self.announce("Distribution.parse_config_files():")
+
+        parser = ConfigParser()
+        for filename in filenames:
+            if DEBUG:
+                self.announce(f"  reading {filename}")
+            parser.read(filename, encoding='utf-8')
+            for section in parser.sections():
+                options = parser.options(section)
+                opt_dict = self.get_option_dict(section)
+
+                for opt in options:
+                    if opt != '__name__' and opt not in ignore_options:
+                        val = parser.get(section, opt)
+                        opt = opt.replace('-', '_')
+                        opt_dict[opt] = (filename, val)
+
+            # Make the ConfigParser forget everything (so we retain
+            # the original filenames that options come from)
+            parser.__init__()
+
+        # If there was a "global" section in the config file, use it
+        # to set Distribution options.
+
+        if 'global' in self.command_options:
+            for opt, (_src, val) in self.command_options['global'].items():
+                alias = self.negative_opt.get(opt)
+                try:
+                    if alias:
+                        setattr(self, alias, not strtobool(val))
+                    elif opt in ('verbose', 'dry_run'):  # ugh!
+                        setattr(self, opt, strtobool(val))
+                    else:
+                        setattr(self, opt, val)
+                except ValueError as msg:
+                    raise DistutilsOptionError(msg)
+
+    # -- Command-line parsing methods ----------------------------------
+
+    def parse_command_line(self):
+        """Parse the setup script's command line, taken from the
+        'script_args' instance attribute (which defaults to 'sys.argv[1:]'
+        -- see 'setup()' in core.py).  This list is first processed for
+        "global options" -- options that set attributes of the Distribution
+        instance.  Then, it is alternately scanned for Distutils commands
+        and options for that command.  Each new command terminates the
+        options for the previous command.  The allowed options for a
+        command are determined by the 'user_options' attribute of the
+        command class -- thus, we have to be able to load command classes
+        in order to parse the command line.  Any error in that 'options'
+        attribute raises DistutilsGetoptError; any error on the
+        command-line raises DistutilsArgError.  If no Distutils commands
+        were found on the command line, raises DistutilsArgError.  Return
+        true if command-line was successfully parsed and we should carry
+        on with executing commands; false if no errors but we shouldn't
+        execute commands (currently, this only happens if user asks for
+        help).
+        """
+        #
+        # We now have enough information to show the Macintosh dialog
+        # that allows the user to interactively specify the "command line".
+        #
+        toplevel_options = self._get_toplevel_options()
+
+        # We have to parse the command line a bit at a time -- global
+        # options, then the first command, then its options, and so on --
+        # because each command will be handled by a different class, and
+        # the options that are valid for a particular class aren't known
+        # until we have loaded the command class, which doesn't happen
+        # until we know what the command is.
+
+        self.commands = []
+        parser = FancyGetopt(toplevel_options + self.display_options)
+        parser.set_negative_aliases(self.negative_opt)
+        parser.set_aliases({'licence': 'license'})
+        args = parser.getopt(args=self.script_args, object=self)
+        option_order = parser.get_option_order()
+        logging.getLogger().setLevel(logging.WARN - 10 * self.verbose)
+
+        # for display options we return immediately
+        if self.handle_display_options(option_order):
+            return
+        while args:
+            args = self._parse_command_opts(parser, args)
+            if args is None:  # user asked for help (and got it)
+                return
+
+        # Handle the cases of --help as a "global" option, ie.
+        # "setup.py --help" and "setup.py --help command ...".  For the
+        # former, we show global options (--verbose, --dry-run, etc.)
+        # and display-only options (--name, --version, etc.); for the
+        # latter, we omit the display-only options and show help for
+        # each command listed on the command line.
+        if self.help:
+            self._show_help(
+                parser, display_options=len(self.commands) == 0, commands=self.commands
+            )
+            return
+
+        # Oops, no commands found -- an end-user error
+        if not self.commands:
+            raise DistutilsArgError("no commands supplied")
+
+        # All is well: return true
+        return True
+
+    def _get_toplevel_options(self):
+        """Return the non-display options recognized at the top level.
+
+        This includes options that are recognized *only* at the top
+        level as well as options recognized for commands.
+        """
+        return self.global_options + [
+            (
+                "command-packages=",
+                None,
+                "list of packages that provide distutils commands",
+            ),
+        ]
+
+    def _parse_command_opts(self, parser, args):  # noqa: C901
+        """Parse the command-line options for a single command.
+        'parser' must be a FancyGetopt instance; 'args' must be the list
+        of arguments, starting with the current command (whose options
+        we are about to parse).  Returns a new version of 'args' with
+        the next command at the front of the list; will be the empty
+        list if there are no more commands on the command line.  Returns
+        None if the user asked for help on this command.
+        """
+        # late import because of mutual dependence between these modules
+        from distutils.cmd import Command
+
+        # Pull the current command from the head of the command line
+        command = args[0]
+        if not command_re.match(command):
+            raise SystemExit(f"invalid command name '{command}'")
+        self.commands.append(command)
+
+        # Dig up the command class that implements this command, so we
+        # 1) know that it's a valid command, and 2) know which options
+        # it takes.
+        try:
+            cmd_class = self.get_command_class(command)
+        except DistutilsModuleError as msg:
+            raise DistutilsArgError(msg)
+
+        # Require that the command class be derived from Command -- want
+        # to be sure that the basic "command" interface is implemented.
+        if not issubclass(cmd_class, Command):
+            raise DistutilsClassError(
+                f"command class {cmd_class} must subclass Command"
+            )
+
+        # Also make sure that the command object provides a list of its
+        # known options.
+        if not (
+            hasattr(cmd_class, 'user_options')
+            and isinstance(cmd_class.user_options, list)
+        ):
+            msg = (
+                "command class %s must provide "
+                "'user_options' attribute (a list of tuples)"
+            )
+            raise DistutilsClassError(msg % cmd_class)
+
+        # If the command class has a list of negative alias options,
+        # merge it in with the global negative aliases.
+        negative_opt = self.negative_opt
+        if hasattr(cmd_class, 'negative_opt'):
+            negative_opt = negative_opt.copy()
+            negative_opt.update(cmd_class.negative_opt)
+
+        # Check for help_options in command class.  They have a different
+        # format (tuple of four) so we need to preprocess them here.
+        if hasattr(cmd_class, 'help_options') and isinstance(
+            cmd_class.help_options, list
+        ):
+            help_options = fix_help_options(cmd_class.help_options)
+        else:
+            help_options = []
+
+        # All commands support the global options too, just by adding
+        # in 'global_options'.
+        parser.set_option_table(
+            self.global_options + cmd_class.user_options + help_options
+        )
+        parser.set_negative_aliases(negative_opt)
+        (args, opts) = parser.getopt(args[1:])
+        if hasattr(opts, 'help') and opts.help:
+            self._show_help(parser, display_options=False, commands=[cmd_class])
+            return
+
+        if hasattr(cmd_class, 'help_options') and isinstance(
+            cmd_class.help_options, list
+        ):
+            help_option_found = 0
+            for help_option, _short, _desc, func in cmd_class.help_options:
+                if hasattr(opts, parser.get_attr_name(help_option)):
+                    help_option_found = 1
+                    if callable(func):
+                        func()
+                    else:
+                        raise DistutilsClassError(
+                            f"invalid help function {func!r} for help option '{help_option}': "
+                            "must be a callable object (function, etc.)"
+                        )
+
+            if help_option_found:
+                return
+
+        # Put the options from the command-line into their official
+        # holding pen, the 'command_options' dictionary.
+        opt_dict = self.get_option_dict(command)
+        for name, value in vars(opts).items():
+            opt_dict[name] = ("command line", value)
+
+        return args
+
+    def finalize_options(self) -> None:
+        """Set final values for all the options on the Distribution
+        instance, analogous to the .finalize_options() method of Command
+        objects.
+        """
+        for attr in ('keywords', 'platforms'):
+            value = getattr(self.metadata, attr)
+            if value is None:
+                continue
+            if isinstance(value, str):
+                value = [elm.strip() for elm in value.split(',')]
+                setattr(self.metadata, attr, value)
+
+    def _show_help(
+        self, parser, global_options=True, display_options=True, commands: Iterable = ()
+    ):
+        """Show help for the setup script command-line in the form of
+        several lists of command-line options.  'parser' should be a
+        FancyGetopt instance; do not expect it to be returned in the
+        same state, as its option table will be reset to make it
+        generate the correct help text.
+
+        If 'global_options' is true, lists the global options:
+        --verbose, --dry-run, etc.  If 'display_options' is true, lists
+        the "display-only" options: --name, --version, etc.  Finally,
+        lists per-command help for every command name or command class
+        in 'commands'.
+        """
+        # late import because of mutual dependence between these modules
+        from distutils.cmd import Command
+        from distutils.core import gen_usage
+
+        if global_options:
+            if display_options:
+                options = self._get_toplevel_options()
+            else:
+                options = self.global_options
+            parser.set_option_table(options)
+            parser.print_help(self.common_usage + "\nGlobal options:")
+            print()
+
+        if display_options:
+            parser.set_option_table(self.display_options)
+            parser.print_help(
+                "Information display options (just display information, ignore any commands)"
+            )
+            print()
+
+        for command in commands:
+            if isinstance(command, type) and issubclass(command, Command):
+                klass = command
+            else:
+                klass = self.get_command_class(command)
+            if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
+                parser.set_option_table(
+                    klass.user_options + fix_help_options(klass.help_options)
+                )
+            else:
+                parser.set_option_table(klass.user_options)
+            parser.print_help(f"Options for '{klass.__name__}' command:")
+            print()
+
+        print(gen_usage(self.script_name))
+
+    def handle_display_options(self, option_order):
+        """If there were any non-global "display-only" options
+        (--help-commands or the metadata display options) on the command
+        line, display the requested info and return true; else return
+        false.
+        """
+        from distutils.core import gen_usage
+
+        # User just wants a list of commands -- we'll print it out and stop
+        # processing now (ie. if they ran "setup --help-commands foo bar",
+        # we ignore "foo bar").
+        if self.help_commands:
+            self.print_commands()
+            print()
+            print(gen_usage(self.script_name))
+            return 1
+
+        # If user supplied any of the "display metadata" options, then
+        # display that metadata in the order in which the user supplied the
+        # metadata options.
+        any_display_options = 0
+        is_display_option = set()
+        for option in self.display_options:
+            is_display_option.add(option[0])
+
+        for opt, val in option_order:
+            if val and opt in is_display_option:
+                opt = translate_longopt(opt)
+                value = getattr(self.metadata, "get_" + opt)()
+                if opt in ('keywords', 'platforms'):
+                    print(','.join(value))
+                elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
+                    print('\n'.join(value))
+                else:
+                    print(value)
+                any_display_options = 1
+
+        return any_display_options
+
+    def print_command_list(self, commands, header, max_length) -> None:
+        """Print a subset of the list of all commands -- used by
+        'print_commands()'.
+        """
+        print(header + ":")
+
+        for cmd in commands:
+            klass = self.cmdclass.get(cmd)
+            if not klass:
+                klass = self.get_command_class(cmd)
+            try:
+                description = klass.description
+            except AttributeError:
+                description = "(no description available)"
+
+            print(f"  {cmd:<{max_length}}  {description}")
+
+    def print_commands(self) -> None:
+        """Print out a help message listing all available commands with a
+        description of each.  The list is divided into "standard commands"
+        (listed in distutils.command.__all__) and "extra commands"
+        (mentioned in self.cmdclass, but not a standard command).  The
+        descriptions come from the command class attribute
+        'description'.
+        """
+        import distutils.command
+
+        std_commands = distutils.command.__all__
+        is_std = set(std_commands)
+
+        extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
+
+        max_length = 0
+        for cmd in std_commands + extra_commands:
+            if len(cmd) > max_length:
+                max_length = len(cmd)
+
+        self.print_command_list(std_commands, "Standard commands", max_length)
+        if extra_commands:
+            print()
+            self.print_command_list(extra_commands, "Extra commands", max_length)
+
+    def get_command_list(self):
+        """Get a list of (command, description) tuples.
+        The list is divided into "standard commands" (listed in
+        distutils.command.__all__) and "extra commands" (mentioned in
+        self.cmdclass, but not a standard command).  The descriptions come
+        from the command class attribute 'description'.
+        """
+        # Currently this is only used on Mac OS, for the Mac-only GUI
+        # Distutils interface (by Jack Jansen)
+        import distutils.command
+
+        std_commands = distutils.command.__all__
+        is_std = set(std_commands)
+
+        extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
+
+        rv = []
+        for cmd in std_commands + extra_commands:
+            klass = self.cmdclass.get(cmd)
+            if not klass:
+                klass = self.get_command_class(cmd)
+            try:
+                description = klass.description
+            except AttributeError:
+                description = "(no description available)"
+            rv.append((cmd, description))
+        return rv
+
+    # -- Command class/object methods ----------------------------------
+
+    def get_command_packages(self):
+        """Return a list of packages from which commands are loaded."""
+        pkgs = self.command_packages
+        if not isinstance(pkgs, list):
+            if pkgs is None:
+                pkgs = ''
+            pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
+            if "distutils.command" not in pkgs:
+                pkgs.insert(0, "distutils.command")
+            self.command_packages = pkgs
+        return pkgs
+
+    def get_command_class(self, command: str) -> type[Command]:
+        """Return the class that implements the Distutils command named by
+        'command'.  First we check the 'cmdclass' dictionary; if the
+        command is mentioned there, we fetch the class object from the
+        dictionary and return it.  Otherwise we load the command module
+        ("distutils.command." + command) and fetch the command class from
+        the module.  The loaded class is also stored in 'cmdclass'
+        to speed future calls to 'get_command_class()'.
+
+        Raises DistutilsModuleError if the expected module could not be
+        found, or if that module does not define the expected class.
+        """
+        klass = self.cmdclass.get(command)
+        if klass:
+            return klass
+
+        for pkgname in self.get_command_packages():
+            module_name = f"{pkgname}.{command}"
+            klass_name = command
+
+            try:
+                __import__(module_name)
+                module = sys.modules[module_name]
+            except ImportError:
+                continue
+
+            try:
+                klass = getattr(module, klass_name)
+            except AttributeError:
+                raise DistutilsModuleError(
+                    f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')"
+                )
+
+            self.cmdclass[command] = klass
+            return klass
+
+        raise DistutilsModuleError(f"invalid command '{command}'")
+
+    @overload
+    def get_command_obj(
+        self, command: str, create: Literal[True] = True
+    ) -> Command: ...
+    @overload
+    def get_command_obj(
+        self, command: str, create: Literal[False]
+    ) -> Command | None: ...
+    def get_command_obj(self, command: str, create: bool = True) -> Command | None:
+        """Return the command object for 'command'.  Normally this object
+        is cached on a previous call to 'get_command_obj()'; if no command
+        object for 'command' is in the cache, then we either create and
+        return it (if 'create' is true) or return None.
+        """
+        cmd_obj = self.command_obj.get(command)
+        if not cmd_obj and create:
+            if DEBUG:
+                self.announce(
+                    "Distribution.get_command_obj(): "
+                    f"creating '{command}' command object"
+                )
+
+            klass = self.get_command_class(command)
+            cmd_obj = self.command_obj[command] = klass(self)
+            self.have_run[command] = False
+
+            # Set any options that were supplied in config files
+            # or on the command line.  (NB. support for error
+            # reporting is lame here: any errors aren't reported
+            # until 'finalize_options()' is called, which means
+            # we won't report the source of the error.)
+            options = self.command_options.get(command)
+            if options:
+                self._set_command_options(cmd_obj, options)
+
+        return cmd_obj
+
+    def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901
+        """Set the options for 'command_obj' from 'option_dict'.  Basically
+        this means copying elements of a dictionary ('option_dict') to
+        attributes of an instance ('command').
+
+        'command_obj' must be a Command instance.  If 'option_dict' is not
+        supplied, uses the standard option dictionary for this command
+        (from 'self.command_options').
+        """
+        command_name = command_obj.get_command_name()
+        if option_dict is None:
+            option_dict = self.get_option_dict(command_name)
+
+        if DEBUG:
+            self.announce(f"  setting options for '{command_name}' command:")
+        for option, (source, value) in option_dict.items():
+            if DEBUG:
+                self.announce(f"    {option} = {value} (from {source})")
+            try:
+                bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
+            except AttributeError:
+                bool_opts = []
+            try:
+                neg_opt = command_obj.negative_opt
+            except AttributeError:
+                neg_opt = {}
+
+            try:
+                is_string = isinstance(value, str)
+                if option in neg_opt and is_string:
+                    setattr(command_obj, neg_opt[option], not strtobool(value))
+                elif option in bool_opts and is_string:
+                    setattr(command_obj, option, strtobool(value))
+                elif hasattr(command_obj, option):
+                    setattr(command_obj, option, value)
+                else:
+                    raise DistutilsOptionError(
+                        f"error in {source}: command '{command_name}' has no such option '{option}'"
+                    )
+            except ValueError as msg:
+                raise DistutilsOptionError(msg)
+
+    @overload
+    def reinitialize_command(
+        self, command: str, reinit_subcommands: bool = False
+    ) -> Command: ...
+    @overload
+    def reinitialize_command(
+        self, command: _CommandT, reinit_subcommands: bool = False
+    ) -> _CommandT: ...
+    def reinitialize_command(
+        self, command: str | Command, reinit_subcommands=False
+    ) -> Command:
+        """Reinitializes a command to the state it was in when first
+        returned by 'get_command_obj()': ie., initialized but not yet
+        finalized.  This provides the opportunity to sneak option
+        values in programmatically, overriding or supplementing
+        user-supplied values from the config files and command line.
+        You'll have to re-finalize the command object (by calling
+        'finalize_options()' or 'ensure_finalized()') before using it for
+        real.
+
+        'command' should be a command name (string) or command object.  If
+        'reinit_subcommands' is true, also reinitializes the command's
+        sub-commands, as declared by the 'sub_commands' class attribute (if
+        it has one).  See the "install" command for an example.  Only
+        reinitializes the sub-commands that actually matter, ie. those
+        whose test predicates return true.
+
+        Returns the reinitialized command object.
+        """
+        from distutils.cmd import Command
+
+        if not isinstance(command, Command):
+            command_name = command
+            command = self.get_command_obj(command_name)
+        else:
+            command_name = command.get_command_name()
+
+        if not command.finalized:
+            return command
+        command.initialize_options()
+        command.finalized = False
+        self.have_run[command_name] = False
+        self._set_command_options(command)
+
+        if reinit_subcommands:
+            for sub in command.get_sub_commands():
+                self.reinitialize_command(sub, reinit_subcommands)
+
+        return command
+
+    # -- Methods that operate on the Distribution ----------------------
+
+    def announce(self, msg, level: int = logging.INFO) -> None:
+        log.log(level, msg)
+
+    def run_commands(self) -> None:
+        """Run each command that was seen on the setup script command line.
+        Uses the list of commands found and cache of command objects
+        created by 'get_command_obj()'.
+        """
+        for cmd in self.commands:
+            self.run_command(cmd)
+
+    # -- Methods that operate on its Commands --------------------------
+
+    def run_command(self, command: str) -> None:
+        """Do whatever it takes to run a command (including nothing at all,
+        if the command has already been run).  Specifically: if we have
+        already created and run the command named by 'command', return
+        silently without doing anything.  If the command named by 'command'
+        doesn't even have a command object yet, create one.  Then invoke
+        'run()' on that command object (or an existing one).
+        """
+        # Already been here, done that? then return silently.
+        if self.have_run.get(command):
+            return
+
+        log.info("running %s", command)
+        cmd_obj = self.get_command_obj(command)
+        cmd_obj.ensure_finalized()
+        cmd_obj.run()
+        self.have_run[command] = True
+
+    # -- Distribution query methods ------------------------------------
+
+    def has_pure_modules(self) -> bool:
+        return len(self.packages or self.py_modules or []) > 0
+
+    def has_ext_modules(self) -> bool:
+        return self.ext_modules and len(self.ext_modules) > 0
+
+    def has_c_libraries(self) -> bool:
+        return self.libraries and len(self.libraries) > 0
+
+    def has_modules(self) -> bool:
+        return self.has_pure_modules() or self.has_ext_modules()
+
+    def has_headers(self) -> bool:
+        return self.headers and len(self.headers) > 0
+
+    def has_scripts(self) -> bool:
+        return self.scripts and len(self.scripts) > 0
+
+    def has_data_files(self) -> bool:
+        return self.data_files and len(self.data_files) > 0
+
+    def is_pure(self) -> bool:
+        return (
+            self.has_pure_modules()
+            and not self.has_ext_modules()
+            and not self.has_c_libraries()
+        )
+
+    # -- Metadata query methods ----------------------------------------
+
+    # If you're looking for 'get_name()', 'get_version()', and so forth,
+    # they are defined in a sneaky way: the constructor binds self.get_XXX
+    # to self.metadata.get_XXX.  The actual code is in the
+    # DistributionMetadata class, below.
+    if TYPE_CHECKING:
+        # Unfortunately this means we need to specify them manually or not expose statically
+        def _(self) -> None:
+            self.get_name = self.metadata.get_name
+            self.get_version = self.metadata.get_version
+            self.get_fullname = self.metadata.get_fullname
+            self.get_author = self.metadata.get_author
+            self.get_author_email = self.metadata.get_author_email
+            self.get_maintainer = self.metadata.get_maintainer
+            self.get_maintainer_email = self.metadata.get_maintainer_email
+            self.get_contact = self.metadata.get_contact
+            self.get_contact_email = self.metadata.get_contact_email
+            self.get_url = self.metadata.get_url
+            self.get_license = self.metadata.get_license
+            self.get_licence = self.metadata.get_licence
+            self.get_description = self.metadata.get_description
+            self.get_long_description = self.metadata.get_long_description
+            self.get_keywords = self.metadata.get_keywords
+            self.get_platforms = self.metadata.get_platforms
+            self.get_classifiers = self.metadata.get_classifiers
+            self.get_download_url = self.metadata.get_download_url
+            self.get_requires = self.metadata.get_requires
+            self.get_provides = self.metadata.get_provides
+            self.get_obsoletes = self.metadata.get_obsoletes
+
+        # Default attributes generated in __init__ from self.display_option_names
+        help_commands: bool
+        name: str | Literal[False]
+        version: str | Literal[False]
+        fullname: str | Literal[False]
+        author: str | Literal[False]
+        author_email: str | Literal[False]
+        maintainer: str | Literal[False]
+        maintainer_email: str | Literal[False]
+        contact: str | Literal[False]
+        contact_email: str | Literal[False]
+        url: str | Literal[False]
+        license: str | Literal[False]
+        licence: str | Literal[False]
+        description: str | Literal[False]
+        long_description: str | Literal[False]
+        platforms: str | list[str] | Literal[False]
+        classifiers: str | list[str] | Literal[False]
+        keywords: str | list[str] | Literal[False]
+        provides: list[str] | Literal[False]
+        requires: list[str] | Literal[False]
+        obsoletes: list[str] | Literal[False]
+
+
+class DistributionMetadata:
+    """Dummy class to hold the distribution meta-data: name, version,
+    author, and so forth.
+    """
+
+    _METHOD_BASENAMES = (
+        "name",
+        "version",
+        "author",
+        "author_email",
+        "maintainer",
+        "maintainer_email",
+        "url",
+        "license",
+        "description",
+        "long_description",
+        "keywords",
+        "platforms",
+        "fullname",
+        "contact",
+        "contact_email",
+        "classifiers",
+        "download_url",
+        # PEP 314
+        "provides",
+        "requires",
+        "obsoletes",
+    )
+
+    def __init__(
+        self, path: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None
+    ) -> None:
+        if path is not None:
+            self.read_pkg_file(open(path))
+        else:
+            self.name: str | None = None
+            self.version: str | None = None
+            self.author: str | None = None
+            self.author_email: str | None = None
+            self.maintainer: str | None = None
+            self.maintainer_email: str | None = None
+            self.url: str | None = None
+            self.license: str | None = None
+            self.description: str | None = None
+            self.long_description: str | None = None
+            self.keywords: str | list[str] | None = None
+            self.platforms: str | list[str] | None = None
+            self.classifiers: str | list[str] | None = None
+            self.download_url: str | None = None
+            # PEP 314
+            self.provides: str | list[str] | None = None
+            self.requires: str | list[str] | None = None
+            self.obsoletes: str | list[str] | None = None
+
+    def read_pkg_file(self, file: IO[str]) -> None:
+        """Reads the metadata values from a file object."""
+        msg = message_from_file(file)
+
+        def _read_field(name: str) -> str | None:
+            value = msg[name]
+            if value and value != "UNKNOWN":
+                return value
+            return None
+
+        def _read_list(name):
+            values = msg.get_all(name, None)
+            if values == []:
+                return None
+            return values
+
+        metadata_version = msg['metadata-version']
+        self.name = _read_field('name')
+        self.version = _read_field('version')
+        self.description = _read_field('summary')
+        # we are filling author only.
+        self.author = _read_field('author')
+        self.maintainer = None
+        self.author_email = _read_field('author-email')
+        self.maintainer_email = None
+        self.url = _read_field('home-page')
+        self.license = _read_field('license')
+
+        if 'download-url' in msg:
+            self.download_url = _read_field('download-url')
+        else:
+            self.download_url = None
+
+        self.long_description = _read_field('description')
+        self.description = _read_field('summary')
+
+        if 'keywords' in msg:
+            self.keywords = _read_field('keywords').split(',')
+
+        self.platforms = _read_list('platform')
+        self.classifiers = _read_list('classifier')
+
+        # PEP 314 - these fields only exist in 1.1
+        if metadata_version == '1.1':
+            self.requires = _read_list('requires')
+            self.provides = _read_list('provides')
+            self.obsoletes = _read_list('obsoletes')
+        else:
+            self.requires = None
+            self.provides = None
+            self.obsoletes = None
+
+    def write_pkg_info(self, base_dir: str | os.PathLike[str]) -> None:
+        """Write the PKG-INFO file into the release tree."""
+        with open(
+            os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
+        ) as pkg_info:
+            self.write_pkg_file(pkg_info)
+
+    def write_pkg_file(self, file: SupportsWrite[str]) -> None:
+        """Write the PKG-INFO format data to a file object."""
+        version = '1.0'
+        if (
+            self.provides
+            or self.requires
+            or self.obsoletes
+            or self.classifiers
+            or self.download_url
+        ):
+            version = '1.1'
+
+        # required fields
+        file.write(f'Metadata-Version: {version}\n')
+        file.write(f'Name: {self.get_name()}\n')
+        file.write(f'Version: {self.get_version()}\n')
+
+        def maybe_write(header, val):
+            if val:
+                file.write(f"{header}: {val}\n")
+
+        # optional fields
+        maybe_write("Summary", self.get_description())
+        maybe_write("Home-page", self.get_url())
+        maybe_write("Author", self.get_contact())
+        maybe_write("Author-email", self.get_contact_email())
+        maybe_write("License", self.get_license())
+        maybe_write("Download-URL", self.download_url)
+        maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
+        maybe_write("Keywords", ",".join(self.get_keywords()))
+
+        self._write_list(file, 'Platform', self.get_platforms())
+        self._write_list(file, 'Classifier', self.get_classifiers())
+
+        # PEP 314
+        self._write_list(file, 'Requires', self.get_requires())
+        self._write_list(file, 'Provides', self.get_provides())
+        self._write_list(file, 'Obsoletes', self.get_obsoletes())
+
+    def _write_list(self, file, name, values):
+        values = values or []
+        for value in values:
+            file.write(f'{name}: {value}\n')
+
+    # -- Metadata query methods ----------------------------------------
+
+    def get_name(self) -> str:
+        return self.name or "UNKNOWN"
+
+    def get_version(self) -> str:
+        return self.version or "0.0.0"
+
+    def get_fullname(self) -> str:
+        return self._fullname(self.get_name(), self.get_version())
+
+    @staticmethod
+    def _fullname(name: str, version: str) -> str:
+        """
+        >>> DistributionMetadata._fullname('setup.tools', '1.0-2')
+        'setup_tools-1.0.post2'
+        >>> DistributionMetadata._fullname('setup-tools', '1.2post2')
+        'setup_tools-1.2.post2'
+        >>> DistributionMetadata._fullname('setup-tools', '1.0-r2')
+        'setup_tools-1.0.post2'
+        >>> DistributionMetadata._fullname('setup.tools', '1.0.post')
+        'setup_tools-1.0.post0'
+        >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1')
+        'setup_tools-1.0+ubuntu.1'
+        """
+        return "{}-{}".format(
+            canonicalize_name(name).replace('-', '_'),
+            canonicalize_version(version, strip_trailing_zero=False),
+        )
+
+    def get_author(self) -> str | None:
+        return self.author
+
+    def get_author_email(self) -> str | None:
+        return self.author_email
+
+    def get_maintainer(self) -> str | None:
+        return self.maintainer
+
+    def get_maintainer_email(self) -> str | None:
+        return self.maintainer_email
+
+    def get_contact(self) -> str | None:
+        return self.maintainer or self.author
+
+    def get_contact_email(self) -> str | None:
+        return self.maintainer_email or self.author_email
+
+    def get_url(self) -> str | None:
+        return self.url
+
+    def get_license(self) -> str | None:
+        return self.license
+
+    get_licence = get_license
+
+    def get_description(self) -> str | None:
+        return self.description
+
+    def get_long_description(self) -> str | None:
+        return self.long_description
+
+    def get_keywords(self) -> str | list[str]:
+        return self.keywords or []
+
+    def set_keywords(self, value: str | Iterable[str]) -> None:
+        self.keywords = _ensure_list(value, 'keywords')
+
+    def get_platforms(self) -> str | list[str] | None:
+        return self.platforms
+
+    def set_platforms(self, value: str | Iterable[str]) -> None:
+        self.platforms = _ensure_list(value, 'platforms')
+
+    def get_classifiers(self) -> str | list[str]:
+        return self.classifiers or []
+
+    def set_classifiers(self, value: str | Iterable[str]) -> None:
+        self.classifiers = _ensure_list(value, 'classifiers')
+
+    def get_download_url(self) -> str | None:
+        return self.download_url
+
+    # PEP 314
+    def get_requires(self) -> str | list[str]:
+        return self.requires or []
+
+    def set_requires(self, value: Iterable[str]) -> None:
+        import distutils.versionpredicate
+
+        for v in value:
+            distutils.versionpredicate.VersionPredicate(v)
+        self.requires = list(value)
+
+    def get_provides(self) -> str | list[str]:
+        return self.provides or []
+
+    def set_provides(self, value: Iterable[str]) -> None:
+        value = [v.strip() for v in value]
+        for v in value:
+            import distutils.versionpredicate
+
+            distutils.versionpredicate.split_provision(v)
+        self.provides = value
+
+    def get_obsoletes(self) -> str | list[str]:
+        return self.obsoletes or []
+
+    def set_obsoletes(self, value: Iterable[str]) -> None:
+        import distutils.versionpredicate
+
+        for v in value:
+            distutils.versionpredicate.VersionPredicate(v)
+        self.obsoletes = list(value)
+
+
+def fix_help_options(options):
+    """Convert a 4-tuple 'help_options' list as found in various command
+    classes to the 3-tuple form required by FancyGetopt.
+    """
+    return [opt[0:3] for opt in options]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/errors.py b/python_embeded/Lib/site-packages/setuptools/_distutils/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..409d21faa2caeb8a53fed10e4266f7cccc764d23
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/errors.py
@@ -0,0 +1,108 @@
+"""
+Exceptions used by the Distutils modules.
+
+Distutils modules may raise these or standard exceptions,
+including :exc:`SystemExit`.
+"""
+
+# compiler exceptions aliased for compatibility
+from .compilers.C.errors import CompileError as CompileError
+from .compilers.C.errors import Error as _Error
+from .compilers.C.errors import LibError as LibError
+from .compilers.C.errors import LinkError as LinkError
+from .compilers.C.errors import PreprocessError as PreprocessError
+from .compilers.C.errors import UnknownFileType as _UnknownFileType
+
+CCompilerError = _Error
+UnknownFileError = _UnknownFileType
+
+
+class DistutilsError(Exception):
+    """The root of all Distutils evil."""
+
+    pass
+
+
+class DistutilsModuleError(DistutilsError):
+    """Unable to load an expected module, or to find an expected class
+    within some module (in particular, command modules and classes)."""
+
+    pass
+
+
+class DistutilsClassError(DistutilsError):
+    """Some command class (or possibly distribution class, if anyone
+    feels a need to subclass Distribution) is found not to be holding
+    up its end of the bargain, ie. implementing some part of the
+    "command "interface."""
+
+    pass
+
+
+class DistutilsGetoptError(DistutilsError):
+    """The option table provided to 'fancy_getopt()' is bogus."""
+
+    pass
+
+
+class DistutilsArgError(DistutilsError):
+    """Raised by fancy_getopt in response to getopt.error -- ie. an
+    error in the command line usage."""
+
+    pass
+
+
+class DistutilsFileError(DistutilsError):
+    """Any problems in the filesystem: expected file not found, etc.
+    Typically this is for problems that we detect before OSError
+    could be raised."""
+
+    pass
+
+
+class DistutilsOptionError(DistutilsError):
+    """Syntactic/semantic errors in command options, such as use of
+    mutually conflicting options, or inconsistent options,
+    badly-spelled values, etc.  No distinction is made between option
+    values originating in the setup script, the command line, config
+    files, or what-have-you -- but if we *know* something originated in
+    the setup script, we'll raise DistutilsSetupError instead."""
+
+    pass
+
+
+class DistutilsSetupError(DistutilsError):
+    """For errors that can be definitely blamed on the setup script,
+    such as invalid keyword arguments to 'setup()'."""
+
+    pass
+
+
+class DistutilsPlatformError(DistutilsError):
+    """We don't know how to do something on the current platform (but
+    we do know how to do it on some platform) -- eg. trying to compile
+    C files on a platform not supported by a CCompiler subclass."""
+
+    pass
+
+
+class DistutilsExecError(DistutilsError):
+    """Any problems executing an external program (such as the C
+    compiler, when compiling C files)."""
+
+    pass
+
+
+class DistutilsInternalError(DistutilsError):
+    """Internal inconsistencies or impossibilities (obviously, this
+    should never be seen if the code is working!)."""
+
+    pass
+
+
+class DistutilsTemplateError(DistutilsError):
+    """Syntax error in a file list template."""
+
+
+class DistutilsByteCompileError(DistutilsError):
+    """Byte compile error."""
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/extension.py b/python_embeded/Lib/site-packages/setuptools/_distutils/extension.py
new file mode 100644
index 0000000000000000000000000000000000000000..f51411266e4047275280d883b75e7103af21faef
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/extension.py
@@ -0,0 +1,258 @@
+"""distutils.extension
+
+Provides the Extension class, used to describe C/C++ extension
+modules in setup scripts."""
+
+from __future__ import annotations
+
+import os
+import warnings
+from collections.abc import Iterable
+
+# This class is really only used by the "build_ext" command, so it might
+# make sense to put it in distutils.command.build_ext.  However, that
+# module is already big enough, and I want to make this class a bit more
+# complex to simplify some common cases ("foo" module in "foo.c") and do
+# better error-checking ("foo.c" actually exists).
+#
+# Also, putting this in build_ext.py means every setup script would have to
+# import that large-ish module (indirectly, through distutils.core) in
+# order to do anything.
+
+
+class Extension:
+    """Just a collection of attributes that describes an extension
+    module and everything needed to build it (hopefully in a portable
+    way, but there are hooks that let you be as unportable as you need).
+
+    Instance attributes:
+      name : string
+        the full name of the extension, including any packages -- ie.
+        *not* a filename or pathname, but Python dotted name
+      sources : Iterable[string | os.PathLike]
+        iterable of source filenames (except strings, which could be misinterpreted
+        as a single filename), relative to the distribution root (where the setup
+        script lives), in Unix form (slash-separated) for portability. Can be any
+        non-string iterable (list, tuple, set, etc.) containing strings or
+        PathLike objects. Source files may be C, C++, SWIG (.i), platform-specific
+        resource files, or whatever else is recognized by the "build_ext" command
+        as source for a Python extension.
+      include_dirs : [string]
+        list of directories to search for C/C++ header files (in Unix
+        form for portability)
+      define_macros : [(name : string, value : string|None)]
+        list of macros to define; each macro is defined using a 2-tuple,
+        where 'value' is either the string to define it to or None to
+        define it without a particular value (equivalent of "#define
+        FOO" in source or -DFOO on Unix C compiler command line)
+      undef_macros : [string]
+        list of macros to undefine explicitly
+      library_dirs : [string]
+        list of directories to search for C/C++ libraries at link time
+      libraries : [string]
+        list of library names (not filenames or paths) to link against
+      runtime_library_dirs : [string]
+        list of directories to search for C/C++ libraries at run time
+        (for shared extensions, this is when the extension is loaded)
+      extra_objects : [string]
+        list of extra files to link with (eg. object files not implied
+        by 'sources', static library that must be explicitly specified,
+        binary resource files, etc.)
+      extra_compile_args : [string]
+        any extra platform- and compiler-specific information to use
+        when compiling the source files in 'sources'.  For platforms and
+        compilers where "command line" makes sense, this is typically a
+        list of command-line arguments, but for other platforms it could
+        be anything.
+      extra_link_args : [string]
+        any extra platform- and compiler-specific information to use
+        when linking object files together to create the extension (or
+        to create a new static Python interpreter).  Similar
+        interpretation as for 'extra_compile_args'.
+      export_symbols : [string]
+        list of symbols to be exported from a shared extension.  Not
+        used on all platforms, and not generally necessary for Python
+        extensions, which typically export exactly one symbol: "init" +
+        extension_name.
+      swig_opts : [string]
+        any extra options to pass to SWIG if a source file has the .i
+        extension.
+      depends : [string]
+        list of files that the extension depends on
+      language : string
+        extension language (i.e. "c", "c++", "objc"). Will be detected
+        from the source extensions if not provided.
+      optional : boolean
+        specifies that a build failure in the extension should not abort the
+        build process, but simply not install the failing extension.
+    """
+
+    # When adding arguments to this constructor, be sure to update
+    # setup_keywords in core.py.
+    def __init__(
+        self,
+        name: str,
+        sources: Iterable[str | os.PathLike[str]],
+        include_dirs: list[str] | None = None,
+        define_macros: list[tuple[str, str | None]] | None = None,
+        undef_macros: list[str] | None = None,
+        library_dirs: list[str] | None = None,
+        libraries: list[str] | None = None,
+        runtime_library_dirs: list[str] | None = None,
+        extra_objects: list[str] | None = None,
+        extra_compile_args: list[str] | None = None,
+        extra_link_args: list[str] | None = None,
+        export_symbols: list[str] | None = None,
+        swig_opts: list[str] | None = None,
+        depends: list[str] | None = None,
+        language: str | None = None,
+        optional: bool | None = None,
+        **kw,  # To catch unknown keywords
+    ):
+        if not isinstance(name, str):
+            raise TypeError("'name' must be a string")
+
+        # handle the string case first; since strings are iterable, disallow them
+        if isinstance(sources, str):
+            raise TypeError(
+                "'sources' must be an iterable of strings or PathLike objects, not a string"
+            )
+
+        # now we check if it's iterable and contains valid types
+        try:
+            self.sources = list(map(os.fspath, sources))
+        except TypeError:
+            raise TypeError(
+                "'sources' must be an iterable of strings or PathLike objects"
+            )
+
+        self.name = name
+        self.include_dirs = include_dirs or []
+        self.define_macros = define_macros or []
+        self.undef_macros = undef_macros or []
+        self.library_dirs = library_dirs or []
+        self.libraries = libraries or []
+        self.runtime_library_dirs = runtime_library_dirs or []
+        self.extra_objects = extra_objects or []
+        self.extra_compile_args = extra_compile_args or []
+        self.extra_link_args = extra_link_args or []
+        self.export_symbols = export_symbols or []
+        self.swig_opts = swig_opts or []
+        self.depends = depends or []
+        self.language = language
+        self.optional = optional
+
+        # If there are unknown keyword options, warn about them
+        if len(kw) > 0:
+            options = [repr(option) for option in kw]
+            options = ', '.join(sorted(options))
+            msg = f"Unknown Extension options: {options}"
+            warnings.warn(msg)
+
+    def __repr__(self):
+        return f'<{self.__class__.__module__}.{self.__class__.__qualname__}({self.name!r}) at {id(self):#x}>'
+
+
+def read_setup_file(filename):  # noqa: C901
+    """Reads a Setup file and returns Extension instances."""
+    from distutils.sysconfig import _variable_rx, expand_makefile_vars, parse_makefile
+    from distutils.text_file import TextFile
+    from distutils.util import split_quoted
+
+    # First pass over the file to gather "VAR = VALUE" assignments.
+    vars = parse_makefile(filename)
+
+    # Second pass to gobble up the real content: lines of the form
+    #    ... [ ...] [ ...] [ ...]
+    file = TextFile(
+        filename,
+        strip_comments=True,
+        skip_blanks=True,
+        join_lines=True,
+        lstrip_ws=True,
+        rstrip_ws=True,
+    )
+    try:
+        extensions = []
+
+        while True:
+            line = file.readline()
+            if line is None:  # eof
+                break
+            if _variable_rx.match(line):  # VAR=VALUE, handled in first pass
+                continue
+
+            if line[0] == line[-1] == "*":
+                file.warn(f"'{line}' lines not handled yet")
+                continue
+
+            line = expand_makefile_vars(line, vars)
+            words = split_quoted(line)
+
+            # NB. this parses a slightly different syntax than the old
+            # makesetup script: here, there must be exactly one extension per
+            # line, and it must be the first word of the line.  I have no idea
+            # why the old syntax supported multiple extensions per line, as
+            # they all wind up being the same.
+
+            module = words[0]
+            ext = Extension(module, [])
+            append_next_word = None
+
+            for word in words[1:]:
+                if append_next_word is not None:
+                    append_next_word.append(word)
+                    append_next_word = None
+                    continue
+
+                suffix = os.path.splitext(word)[1]
+                switch = word[0:2]
+                value = word[2:]
+
+                if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
+                    # hmm, should we do something about C vs. C++ sources?
+                    # or leave it up to the CCompiler implementation to
+                    # worry about?
+                    ext.sources.append(word)
+                elif switch == "-I":
+                    ext.include_dirs.append(value)
+                elif switch == "-D":
+                    equals = value.find("=")
+                    if equals == -1:  # bare "-DFOO" -- no value
+                        ext.define_macros.append((value, None))
+                    else:  # "-DFOO=blah"
+                        ext.define_macros.append((value[0:equals], value[equals + 2 :]))
+                elif switch == "-U":
+                    ext.undef_macros.append(value)
+                elif switch == "-C":  # only here 'cause makesetup has it!
+                    ext.extra_compile_args.append(word)
+                elif switch == "-l":
+                    ext.libraries.append(value)
+                elif switch == "-L":
+                    ext.library_dirs.append(value)
+                elif switch == "-R":
+                    ext.runtime_library_dirs.append(value)
+                elif word == "-rpath":
+                    append_next_word = ext.runtime_library_dirs
+                elif word == "-Xlinker":
+                    append_next_word = ext.extra_link_args
+                elif word == "-Xcompiler":
+                    append_next_word = ext.extra_compile_args
+                elif switch == "-u":
+                    ext.extra_link_args.append(word)
+                    if not value:
+                        append_next_word = ext.extra_link_args
+                elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
+                    # NB. a really faithful emulation of makesetup would
+                    # append a .o file to extra_objects only if it
+                    # had a slash in it; otherwise, it would s/.o/.c/
+                    # and append it to sources.  Hmmmm.
+                    ext.extra_objects.append(word)
+                else:
+                    file.warn(f"unrecognized argument '{word}'")
+
+            extensions.append(ext)
+    finally:
+        file.close()
+
+    return extensions
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/fancy_getopt.py b/python_embeded/Lib/site-packages/setuptools/_distutils/fancy_getopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a1d3a05da544b98ff84d03ecbee1185b2eb45f7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/fancy_getopt.py
@@ -0,0 +1,471 @@
+"""distutils.fancy_getopt
+
+Wrapper around the standard getopt module that provides the following
+additional features:
+  * short and long options are tied together
+  * options have help strings, so fancy_getopt could potentially
+    create a complete usage summary
+  * options set attributes of a passed-in object
+"""
+
+from __future__ import annotations
+
+import getopt
+import re
+import string
+import sys
+from collections.abc import Sequence
+from typing import Any
+
+from .errors import DistutilsArgError, DistutilsGetoptError
+
+# Much like command_re in distutils.core, this is close to but not quite
+# the same as a Python NAME -- except, in the spirit of most GNU
+# utilities, we use '-' in place of '_'.  (The spirit of LISP lives on!)
+# The similarities to NAME are again not a coincidence...
+longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
+longopt_re = re.compile(rf'^{longopt_pat}$')
+
+# For recognizing "negative alias" options, eg. "quiet=!verbose"
+neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")
+
+# This is used to translate long options to legitimate Python identifiers
+# (for use as attributes of some object).
+longopt_xlate = str.maketrans('-', '_')
+
+
+class FancyGetopt:
+    """Wrapper around the standard 'getopt()' module that provides some
+    handy extra functionality:
+      * short and long options are tied together
+      * options have help strings, and help text can be assembled
+        from them
+      * options set attributes of a passed-in object
+      * boolean options can have "negative aliases" -- eg. if
+        --quiet is the "negative alias" of --verbose, then "--quiet"
+        on the command line sets 'verbose' to false
+    """
+
+    def __init__(self, option_table=None):
+        # The option table is (currently) a list of tuples.  The
+        # tuples may have 3 or four values:
+        #   (long_option, short_option, help_string [, repeatable])
+        # if an option takes an argument, its long_option should have '='
+        # appended; short_option should just be a single character, no ':'
+        # in any case.  If a long_option doesn't have a corresponding
+        # short_option, short_option should be None.  All option tuples
+        # must have long options.
+        self.option_table = option_table
+
+        # 'option_index' maps long option names to entries in the option
+        # table (ie. those 3-tuples).
+        self.option_index = {}
+        if self.option_table:
+            self._build_index()
+
+        # 'alias' records (duh) alias options; {'foo': 'bar'} means
+        # --foo is an alias for --bar
+        self.alias = {}
+
+        # 'negative_alias' keeps track of options that are the boolean
+        # opposite of some other option
+        self.negative_alias = {}
+
+        # These keep track of the information in the option table.  We
+        # don't actually populate these structures until we're ready to
+        # parse the command-line, since the 'option_table' passed in here
+        # isn't necessarily the final word.
+        self.short_opts = []
+        self.long_opts = []
+        self.short2long = {}
+        self.attr_name = {}
+        self.takes_arg = {}
+
+        # And 'option_order' is filled up in 'getopt()'; it records the
+        # original order of options (and their values) on the command-line,
+        # but expands short options, converts aliases, etc.
+        self.option_order = []
+
+    def _build_index(self):
+        self.option_index.clear()
+        for option in self.option_table:
+            self.option_index[option[0]] = option
+
+    def set_option_table(self, option_table):
+        self.option_table = option_table
+        self._build_index()
+
+    def add_option(self, long_option, short_option=None, help_string=None):
+        if long_option in self.option_index:
+            raise DistutilsGetoptError(
+                f"option conflict: already an option '{long_option}'"
+            )
+        else:
+            option = (long_option, short_option, help_string)
+            self.option_table.append(option)
+            self.option_index[long_option] = option
+
+    def has_option(self, long_option):
+        """Return true if the option table for this parser has an
+        option with long name 'long_option'."""
+        return long_option in self.option_index
+
+    def get_attr_name(self, long_option):
+        """Translate long option name 'long_option' to the form it
+        has as an attribute of some object: ie., translate hyphens
+        to underscores."""
+        return long_option.translate(longopt_xlate)
+
+    def _check_alias_dict(self, aliases, what):
+        assert isinstance(aliases, dict)
+        for alias, opt in aliases.items():
+            if alias not in self.option_index:
+                raise DistutilsGetoptError(
+                    f"invalid {what} '{alias}': option '{alias}' not defined"
+                )
+            if opt not in self.option_index:
+                raise DistutilsGetoptError(
+                    f"invalid {what} '{alias}': aliased option '{opt}' not defined"
+                )
+
+    def set_aliases(self, alias):
+        """Set the aliases for this option parser."""
+        self._check_alias_dict(alias, "alias")
+        self.alias = alias
+
+    def set_negative_aliases(self, negative_alias):
+        """Set the negative aliases for this option parser.
+        'negative_alias' should be a dictionary mapping option names to
+        option names, both the key and value must already be defined
+        in the option table."""
+        self._check_alias_dict(negative_alias, "negative alias")
+        self.negative_alias = negative_alias
+
+    def _grok_option_table(self):  # noqa: C901
+        """Populate the various data structures that keep tabs on the
+        option table.  Called by 'getopt()' before it can do anything
+        worthwhile.
+        """
+        self.long_opts = []
+        self.short_opts = []
+        self.short2long.clear()
+        self.repeat = {}
+
+        for option in self.option_table:
+            if len(option) == 3:
+                long, short, help = option
+                repeat = 0
+            elif len(option) == 4:
+                long, short, help, repeat = option
+            else:
+                # the option table is part of the code, so simply
+                # assert that it is correct
+                raise ValueError(f"invalid option tuple: {option!r}")
+
+            # Type- and value-check the option names
+            if not isinstance(long, str) or len(long) < 2:
+                raise DistutilsGetoptError(
+                    f"invalid long option '{long}': must be a string of length >= 2"
+                )
+
+            if not ((short is None) or (isinstance(short, str) and len(short) == 1)):
+                raise DistutilsGetoptError(
+                    f"invalid short option '{short}': must a single character or None"
+                )
+
+            self.repeat[long] = repeat
+            self.long_opts.append(long)
+
+            if long[-1] == '=':  # option takes an argument?
+                if short:
+                    short = short + ':'
+                long = long[0:-1]
+                self.takes_arg[long] = True
+            else:
+                # Is option is a "negative alias" for some other option (eg.
+                # "quiet" == "!verbose")?
+                alias_to = self.negative_alias.get(long)
+                if alias_to is not None:
+                    if self.takes_arg[alias_to]:
+                        raise DistutilsGetoptError(
+                            f"invalid negative alias '{long}': "
+                            f"aliased option '{alias_to}' takes a value"
+                        )
+
+                    self.long_opts[-1] = long  # XXX redundant?!
+                self.takes_arg[long] = False
+
+            # If this is an alias option, make sure its "takes arg" flag is
+            # the same as the option it's aliased to.
+            alias_to = self.alias.get(long)
+            if alias_to is not None:
+                if self.takes_arg[long] != self.takes_arg[alias_to]:
+                    raise DistutilsGetoptError(
+                        f"invalid alias '{long}': inconsistent with "
+                        f"aliased option '{alias_to}' (one of them takes a value, "
+                        "the other doesn't"
+                    )
+
+            # Now enforce some bondage on the long option name, so we can
+            # later translate it to an attribute name on some object.  Have
+            # to do this a bit late to make sure we've removed any trailing
+            # '='.
+            if not longopt_re.match(long):
+                raise DistutilsGetoptError(
+                    f"invalid long option name '{long}' "
+                    "(must be letters, numbers, hyphens only"
+                )
+
+            self.attr_name[long] = self.get_attr_name(long)
+            if short:
+                self.short_opts.append(short)
+                self.short2long[short[0]] = long
+
+    def getopt(self, args: Sequence[str] | None = None, object=None):  # noqa: C901
+        """Parse command-line options in args. Store as attributes on object.
+
+        If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If
+        'object' is None or not supplied, creates a new OptionDummy
+        object, stores option values there, and returns a tuple (args,
+        object).  If 'object' is supplied, it is modified in place and
+        'getopt()' just returns 'args'; in both cases, the returned
+        'args' is a modified copy of the passed-in 'args' list, which
+        is left untouched.
+        """
+        if args is None:
+            args = sys.argv[1:]
+        if object is None:
+            object = OptionDummy()
+            created_object = True
+        else:
+            created_object = False
+
+        self._grok_option_table()
+
+        short_opts = ' '.join(self.short_opts)
+        try:
+            opts, args = getopt.getopt(args, short_opts, self.long_opts)
+        except getopt.error as msg:
+            raise DistutilsArgError(msg)
+
+        for opt, val in opts:
+            if len(opt) == 2 and opt[0] == '-':  # it's a short option
+                opt = self.short2long[opt[1]]
+            else:
+                assert len(opt) > 2 and opt[:2] == '--'
+                opt = opt[2:]
+
+            alias = self.alias.get(opt)
+            if alias:
+                opt = alias
+
+            if not self.takes_arg[opt]:  # boolean option?
+                assert val == '', "boolean option can't have value"
+                alias = self.negative_alias.get(opt)
+                if alias:
+                    opt = alias
+                    val = 0
+                else:
+                    val = 1
+
+            attr = self.attr_name[opt]
+            # The only repeating option at the moment is 'verbose'.
+            # It has a negative option -q quiet, which should set verbose = False.
+            if val and self.repeat.get(attr) is not None:
+                val = getattr(object, attr, 0) + 1
+            setattr(object, attr, val)
+            self.option_order.append((opt, val))
+
+        # for opts
+        if created_object:
+            return args, object
+        else:
+            return args
+
+    def get_option_order(self):
+        """Returns the list of (option, value) tuples processed by the
+        previous run of 'getopt()'.  Raises RuntimeError if
+        'getopt()' hasn't been called yet.
+        """
+        if self.option_order is None:
+            raise RuntimeError("'getopt()' hasn't been called yet")
+        else:
+            return self.option_order
+
+    def generate_help(self, header=None):  # noqa: C901
+        """Generate help text (a list of strings, one per suggested line of
+        output) from the option table for this FancyGetopt object.
+        """
+        # Blithely assume the option table is good: probably wouldn't call
+        # 'generate_help()' unless you've already called 'getopt()'.
+
+        # First pass: determine maximum length of long option names
+        max_opt = 0
+        for option in self.option_table:
+            long = option[0]
+            short = option[1]
+            ell = len(long)
+            if long[-1] == '=':
+                ell = ell - 1
+            if short is not None:
+                ell = ell + 5  # " (-x)" where short == 'x'
+            if ell > max_opt:
+                max_opt = ell
+
+        opt_width = max_opt + 2 + 2 + 2  # room for indent + dashes + gutter
+
+        # Typical help block looks like this:
+        #   --foo       controls foonabulation
+        # Help block for longest option looks like this:
+        #   --flimflam  set the flim-flam level
+        # and with wrapped text:
+        #   --flimflam  set the flim-flam level (must be between
+        #               0 and 100, except on Tuesdays)
+        # Options with short names will have the short name shown (but
+        # it doesn't contribute to max_opt):
+        #   --foo (-f)  controls foonabulation
+        # If adding the short option would make the left column too wide,
+        # we push the explanation off to the next line
+        #   --flimflam (-l)
+        #               set the flim-flam level
+        # Important parameters:
+        #   - 2 spaces before option block start lines
+        #   - 2 dashes for each long option name
+        #   - min. 2 spaces between option and explanation (gutter)
+        #   - 5 characters (incl. space) for short option name
+
+        # Now generate lines of help text.  (If 80 columns were good enough
+        # for Jesus, then 78 columns are good enough for me!)
+        line_width = 78
+        text_width = line_width - opt_width
+        big_indent = ' ' * opt_width
+        if header:
+            lines = [header]
+        else:
+            lines = ['Option summary:']
+
+        for option in self.option_table:
+            long, short, help = option[:3]
+            text = wrap_text(help, text_width)
+            if long[-1] == '=':
+                long = long[0:-1]
+
+            # Case 1: no short option at all (makes life easy)
+            if short is None:
+                if text:
+                    lines.append(f"  --{long:<{max_opt}}  {text[0]}")
+                else:
+                    lines.append(f"  --{long:<{max_opt}}")
+
+            # Case 2: we have a short option, so we have to include it
+            # just after the long option
+            else:
+                opt_names = f"{long} (-{short})"
+                if text:
+                    lines.append(f"  --{opt_names:<{max_opt}}  {text[0]}")
+                else:
+                    lines.append(f"  --{opt_names:<{max_opt}}")
+
+            for ell in text[1:]:
+                lines.append(big_indent + ell)
+        return lines
+
+    def print_help(self, header=None, file=None):
+        if file is None:
+            file = sys.stdout
+        for line in self.generate_help(header):
+            file.write(line + "\n")
+
+
+def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None):
+    parser = FancyGetopt(options)
+    parser.set_negative_aliases(negative_opt)
+    return parser.getopt(args, object)
+
+
+WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}
+
+
+def wrap_text(text, width):
+    """wrap_text(text : string, width : int) -> [string]
+
+    Split 'text' into multiple lines of no more than 'width' characters
+    each, and return the list of strings that results.
+    """
+    if text is None:
+        return []
+    if len(text) <= width:
+        return [text]
+
+    text = text.expandtabs()
+    text = text.translate(WS_TRANS)
+    chunks = re.split(r'( +|-+)', text)
+    chunks = [ch for ch in chunks if ch]  # ' - ' results in empty strings
+    lines = []
+
+    while chunks:
+        cur_line = []  # list of chunks (to-be-joined)
+        cur_len = 0  # length of current line
+
+        while chunks:
+            ell = len(chunks[0])
+            if cur_len + ell <= width:  # can squeeze (at least) this chunk in
+                cur_line.append(chunks[0])
+                del chunks[0]
+                cur_len = cur_len + ell
+            else:  # this line is full
+                # drop last chunk if all space
+                if cur_line and cur_line[-1][0] == ' ':
+                    del cur_line[-1]
+                break
+
+        if chunks:  # any chunks left to process?
+            # if the current line is still empty, then we had a single
+            # chunk that's too big too fit on a line -- so we break
+            # down and break it up at the line width
+            if cur_len == 0:
+                cur_line.append(chunks[0][0:width])
+                chunks[0] = chunks[0][width:]
+
+            # all-whitespace chunks at the end of a line can be discarded
+            # (and we know from the re.split above that if a chunk has
+            # *any* whitespace, it is *all* whitespace)
+            if chunks[0][0] == ' ':
+                del chunks[0]
+
+        # and store this line in the list-of-all-lines -- as a single
+        # string, of course!
+        lines.append(''.join(cur_line))
+
+    return lines
+
+
+def translate_longopt(opt):
+    """Convert a long option name to a valid Python identifier by
+    changing "-" to "_".
+    """
+    return opt.translate(longopt_xlate)
+
+
+class OptionDummy:
+    """Dummy class just used as a place to hold command-line option
+    values as instance attributes."""
+
+    def __init__(self, options: Sequence[Any] = []):
+        """Create a new OptionDummy instance.  The attributes listed in
+        'options' will be initialized to None."""
+        for opt in options:
+            setattr(self, opt, None)
+
+
+if __name__ == "__main__":
+    text = """\
+Tra-la-la, supercalifragilisticexpialidocious.
+How *do* you spell that odd word, anyways?
+(Someone ask Mary -- she'll know [or she'll
+say, "How should I know?"].)"""
+
+    for w in (10, 20, 30, 40):
+        print(f"width: {w}")
+        print("\n".join(wrap_text(text, w)))
+        print()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/file_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/file_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..0acc8cb84bd4d28363c4e33e7ff18d691bebfa48
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/file_util.py
@@ -0,0 +1,236 @@
+"""distutils.file_util
+
+Utility functions for operating on single files.
+"""
+
+import os
+
+from ._log import log
+from .errors import DistutilsFileError
+
+# for generating verbose output in 'copy_file()'
+_copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
+
+
+def _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901
+    """Copy the file 'src' to 'dst'; both must be filenames.  Any error
+    opening either file, reading from 'src', or writing to 'dst', raises
+    DistutilsFileError.  Data is read/written in chunks of 'buffer_size'
+    bytes (default 16k).  No attempt is made to handle anything apart from
+    regular files.
+    """
+    # Stolen from shutil module in the standard library, but with
+    # custom error-handling added.
+    fsrc = None
+    fdst = None
+    try:
+        try:
+            fsrc = open(src, 'rb')
+        except OSError as e:
+            raise DistutilsFileError(f"could not open '{src}': {e.strerror}")
+
+        if os.path.exists(dst):
+            try:
+                os.unlink(dst)
+            except OSError as e:
+                raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}")
+
+        try:
+            fdst = open(dst, 'wb')
+        except OSError as e:
+            raise DistutilsFileError(f"could not create '{dst}': {e.strerror}")
+
+        while True:
+            try:
+                buf = fsrc.read(buffer_size)
+            except OSError as e:
+                raise DistutilsFileError(f"could not read from '{src}': {e.strerror}")
+
+            if not buf:
+                break
+
+            try:
+                fdst.write(buf)
+            except OSError as e:
+                raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}")
+    finally:
+        if fdst:
+            fdst.close()
+        if fsrc:
+            fsrc.close()
+
+
+def copy_file(  # noqa: C901
+    src,
+    dst,
+    preserve_mode=True,
+    preserve_times=True,
+    update=False,
+    link=None,
+    verbose=True,
+    dry_run=False,
+):
+    """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
+    copied there with the same name; otherwise, it must be a filename.  (If
+    the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'
+    is true (the default), the file's mode (type and permission bits, or
+    whatever is analogous on the current platform) is copied.  If
+    'preserve_times' is true (the default), the last-modified and
+    last-access times are copied as well.  If 'update' is true, 'src' will
+    only be copied if 'dst' does not exist, or if 'dst' does exist but is
+    older than 'src'.
+
+    'link' allows you to make hard links (os.link) or symbolic links
+    (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
+    None (the default), files are copied.  Don't set 'link' on systems that
+    don't support it: 'copy_file()' doesn't check if hard or symbolic
+    linking is available. If hardlink fails, falls back to
+    _copy_file_contents().
+
+    Under Mac OS, uses the native file copy function in macostools; on
+    other systems, uses '_copy_file_contents()' to copy file contents.
+
+    Return a tuple (dest_name, copied): 'dest_name' is the actual name of
+    the output file, and 'copied' is true if the file was copied (or would
+    have been copied, if 'dry_run' true).
+    """
+    # XXX if the destination file already exists, we clobber it if
+    # copying, but blow up if linking.  Hmmm.  And I don't know what
+    # macostools.copyfile() does.  Should definitely be consistent, and
+    # should probably blow up if destination exists and we would be
+    # changing it (ie. it's not already a hard/soft link to src OR
+    # (not update) and (src newer than dst).
+
+    from distutils._modified import newer
+    from stat import S_IMODE, ST_ATIME, ST_MODE, ST_MTIME
+
+    if not os.path.isfile(src):
+        raise DistutilsFileError(
+            f"can't copy '{src}': doesn't exist or not a regular file"
+        )
+
+    if os.path.isdir(dst):
+        dir = dst
+        dst = os.path.join(dst, os.path.basename(src))
+    else:
+        dir = os.path.dirname(dst)
+
+    if update and not newer(src, dst):
+        if verbose >= 1:
+            log.debug("not copying %s (output up-to-date)", src)
+        return (dst, False)
+
+    try:
+        action = _copy_action[link]
+    except KeyError:
+        raise ValueError(f"invalid value '{link}' for 'link' argument")
+
+    if verbose >= 1:
+        if os.path.basename(dst) == os.path.basename(src):
+            log.info("%s %s -> %s", action, src, dir)
+        else:
+            log.info("%s %s -> %s", action, src, dst)
+
+    if dry_run:
+        return (dst, True)
+
+    # If linking (hard or symbolic), use the appropriate system call
+    # (Unix only, of course, but that's the caller's responsibility)
+    elif link == 'hard':
+        if not (os.path.exists(dst) and os.path.samefile(src, dst)):
+            try:
+                os.link(src, dst)
+            except OSError:
+                # If hard linking fails, fall back on copying file
+                # (some special filesystems don't support hard linking
+                #  even under Unix, see issue #8876).
+                pass
+            else:
+                return (dst, True)
+    elif link == 'sym':
+        if not (os.path.exists(dst) and os.path.samefile(src, dst)):
+            os.symlink(src, dst)
+            return (dst, True)
+
+    # Otherwise (non-Mac, not linking), copy the file contents and
+    # (optionally) copy the times and mode.
+    _copy_file_contents(src, dst)
+    if preserve_mode or preserve_times:
+        st = os.stat(src)
+
+        # According to David Ascher , utime() should be done
+        # before chmod() (at least under NT).
+        if preserve_times:
+            os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
+        if preserve_mode:
+            os.chmod(dst, S_IMODE(st[ST_MODE]))
+
+    return (dst, True)
+
+
+# XXX I suspect this is Unix-specific -- need porting help!
+def move_file(src, dst, verbose=True, dry_run=False):  # noqa: C901
+    """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
+    be moved into it with the same name; otherwise, 'src' is just renamed
+    to 'dst'.  Return the new full name of the file.
+
+    Handles cross-device moves on Unix using 'copy_file()'.  What about
+    other systems???
+    """
+    import errno
+    from os.path import basename, dirname, exists, isdir, isfile
+
+    if verbose >= 1:
+        log.info("moving %s -> %s", src, dst)
+
+    if dry_run:
+        return dst
+
+    if not isfile(src):
+        raise DistutilsFileError(f"can't move '{src}': not a regular file")
+
+    if isdir(dst):
+        dst = os.path.join(dst, basename(src))
+    elif exists(dst):
+        raise DistutilsFileError(
+            f"can't move '{src}': destination '{dst}' already exists"
+        )
+
+    if not isdir(dirname(dst)):
+        raise DistutilsFileError(
+            f"can't move '{src}': destination '{dst}' not a valid path"
+        )
+
+    copy_it = False
+    try:
+        os.rename(src, dst)
+    except OSError as e:
+        (num, msg) = e.args
+        if num == errno.EXDEV:
+            copy_it = True
+        else:
+            raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}")
+
+    if copy_it:
+        copy_file(src, dst, verbose=verbose)
+        try:
+            os.unlink(src)
+        except OSError as e:
+            (num, msg) = e.args
+            try:
+                os.unlink(dst)
+            except OSError:
+                pass
+            raise DistutilsFileError(
+                f"couldn't move '{src}' to '{dst}' by copy/delete: "
+                f"delete '{src}' failed: {msg}"
+            )
+    return dst
+
+
+def write_file(filename, contents):
+    """Create a file with the specified name and write 'contents' (a
+    sequence of strings without line terminators) to it.
+    """
+    with open(filename, 'w', encoding='utf-8') as f:
+        f.writelines(line + '\n' for line in contents)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/filelist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/filelist.py
new file mode 100644
index 0000000000000000000000000000000000000000..70dc0fdebc3f4200245aa1c6280ab39861dcf8b0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/filelist.py
@@ -0,0 +1,431 @@
+"""distutils.filelist
+
+Provides the FileList class, used for poking about the filesystem
+and building lists of files.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import functools
+import os
+import re
+from collections.abc import Iterable
+from typing import Literal, overload
+
+from ._log import log
+from .errors import DistutilsInternalError, DistutilsTemplateError
+from .util import convert_path
+
+
+class FileList:
+    """A list of files built by on exploring the filesystem and filtered by
+    applying various patterns to what we find there.
+
+    Instance attributes:
+      dir
+        directory from which files will be taken -- only used if
+        'allfiles' not supplied to constructor
+      files
+        list of filenames currently being built/filtered/manipulated
+      allfiles
+        complete list of files under consideration (ie. without any
+        filtering applied)
+    """
+
+    def __init__(self, warn: object = None, debug_print: object = None) -> None:
+        # ignore argument to FileList, but keep them for backwards
+        # compatibility
+        self.allfiles: Iterable[str] | None = None
+        self.files: list[str] = []
+
+    def set_allfiles(self, allfiles: Iterable[str]) -> None:
+        self.allfiles = allfiles
+
+    def findall(self, dir: str | os.PathLike[str] = os.curdir) -> None:
+        self.allfiles = findall(dir)
+
+    def debug_print(self, msg: object) -> None:
+        """Print 'msg' to stdout if the global DEBUG (taken from the
+        DISTUTILS_DEBUG environment variable) flag is true.
+        """
+        from distutils.debug import DEBUG
+
+        if DEBUG:
+            print(msg)
+
+    # Collection methods
+
+    def append(self, item: str) -> None:
+        self.files.append(item)
+
+    def extend(self, items: Iterable[str]) -> None:
+        self.files.extend(items)
+
+    def sort(self) -> None:
+        # Not a strict lexical sort!
+        sortable_files = sorted(map(os.path.split, self.files))
+        self.files = []
+        for sort_tuple in sortable_files:
+            self.files.append(os.path.join(*sort_tuple))
+
+    # Other miscellaneous utility methods
+
+    def remove_duplicates(self) -> None:
+        # Assumes list has been sorted!
+        for i in range(len(self.files) - 1, 0, -1):
+            if self.files[i] == self.files[i - 1]:
+                del self.files[i]
+
+    # "File template" methods
+
+    def _parse_template_line(self, line):
+        words = line.split()
+        action = words[0]
+
+        patterns = dir = dir_pattern = None
+
+        if action in ('include', 'exclude', 'global-include', 'global-exclude'):
+            if len(words) < 2:
+                raise DistutilsTemplateError(
+                    f"'{action}' expects   ..."
+                )
+            patterns = [convert_path(w) for w in words[1:]]
+        elif action in ('recursive-include', 'recursive-exclude'):
+            if len(words) < 3:
+                raise DistutilsTemplateError(
+                    f"'{action}' expects    ..."
+                )
+            dir = convert_path(words[1])
+            patterns = [convert_path(w) for w in words[2:]]
+        elif action in ('graft', 'prune'):
+            if len(words) != 2:
+                raise DistutilsTemplateError(
+                    f"'{action}' expects a single "
+                )
+            dir_pattern = convert_path(words[1])
+        else:
+            raise DistutilsTemplateError(f"unknown action '{action}'")
+
+        return (action, patterns, dir, dir_pattern)
+
+    def process_template_line(self, line: str) -> None:  # noqa: C901
+        # Parse the line: split it up, make sure the right number of words
+        # is there, and return the relevant words.  'action' is always
+        # defined: it's the first word of the line.  Which of the other
+        # three are defined depends on the action; it'll be either
+        # patterns, (dir and patterns), or (dir_pattern).
+        (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
+
+        # OK, now we know that the action is valid and we have the
+        # right number of words on the line for that action -- so we
+        # can proceed with minimal error-checking.
+        if action == 'include':
+            self.debug_print("include " + ' '.join(patterns))
+            for pattern in patterns:
+                if not self.include_pattern(pattern, anchor=True):
+                    log.warning("warning: no files found matching '%s'", pattern)
+
+        elif action == 'exclude':
+            self.debug_print("exclude " + ' '.join(patterns))
+            for pattern in patterns:
+                if not self.exclude_pattern(pattern, anchor=True):
+                    log.warning(
+                        "warning: no previously-included files found matching '%s'",
+                        pattern,
+                    )
+
+        elif action == 'global-include':
+            self.debug_print("global-include " + ' '.join(patterns))
+            for pattern in patterns:
+                if not self.include_pattern(pattern, anchor=False):
+                    log.warning(
+                        (
+                            "warning: no files found matching '%s' "
+                            "anywhere in distribution"
+                        ),
+                        pattern,
+                    )
+
+        elif action == 'global-exclude':
+            self.debug_print("global-exclude " + ' '.join(patterns))
+            for pattern in patterns:
+                if not self.exclude_pattern(pattern, anchor=False):
+                    log.warning(
+                        (
+                            "warning: no previously-included files matching "
+                            "'%s' found anywhere in distribution"
+                        ),
+                        pattern,
+                    )
+
+        elif action == 'recursive-include':
+            self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns)))
+            for pattern in patterns:
+                if not self.include_pattern(pattern, prefix=dir):
+                    msg = "warning: no files found matching '%s' under directory '%s'"
+                    log.warning(msg, pattern, dir)
+
+        elif action == 'recursive-exclude':
+            self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns)))
+            for pattern in patterns:
+                if not self.exclude_pattern(pattern, prefix=dir):
+                    log.warning(
+                        (
+                            "warning: no previously-included files matching "
+                            "'%s' found under directory '%s'"
+                        ),
+                        pattern,
+                        dir,
+                    )
+
+        elif action == 'graft':
+            self.debug_print("graft " + dir_pattern)
+            if not self.include_pattern(None, prefix=dir_pattern):
+                log.warning("warning: no directories found matching '%s'", dir_pattern)
+
+        elif action == 'prune':
+            self.debug_print("prune " + dir_pattern)
+            if not self.exclude_pattern(None, prefix=dir_pattern):
+                log.warning(
+                    ("no previously-included directories found matching '%s'"),
+                    dir_pattern,
+                )
+        else:
+            raise DistutilsInternalError(
+                f"this cannot happen: invalid action '{action}'"
+            )
+
+    # Filtering/selection methods
+    @overload
+    def include_pattern(
+        self,
+        pattern: str,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: Literal[False] = False,
+    ) -> bool: ...
+    @overload
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool = True,
+        prefix: str | None = None,
+        *,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    @overload
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool,
+        prefix: str | None,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    def include_pattern(
+        self,
+        pattern: str | re.Pattern,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: bool = False,
+    ) -> bool:
+        """Select strings (presumably filenames) from 'self.files' that
+        match 'pattern', a Unix-style wildcard (glob) pattern.  Patterns
+        are not quite the same as implemented by the 'fnmatch' module: '*'
+        and '?'  match non-special characters, where "special" is platform-
+        dependent: slash on Unix; colon, slash, and backslash on
+        DOS/Windows; and colon on Mac OS.
+
+        If 'anchor' is true (the default), then the pattern match is more
+        stringent: "*.py" will match "foo.py" but not "foo/bar.py".  If
+        'anchor' is false, both of these will match.
+
+        If 'prefix' is supplied, then only filenames starting with 'prefix'
+        (itself a pattern) and ending with 'pattern', with anything in between
+        them, will match.  'anchor' is ignored in this case.
+
+        If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
+        'pattern' is assumed to be either a string containing a regex or a
+        regex object -- no translation is done, the regex is just compiled
+        and used as-is.
+
+        Selected strings will be added to self.files.
+
+        Return True if files are found, False otherwise.
+        """
+        # XXX docstring lying about what the special chars are?
+        files_found = False
+        pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
+        self.debug_print(f"include_pattern: applying regex r'{pattern_re.pattern}'")
+
+        # delayed loading of allfiles list
+        if self.allfiles is None:
+            self.findall()
+
+        for name in self.allfiles:
+            if pattern_re.search(name):
+                self.debug_print(" adding " + name)
+                self.files.append(name)
+                files_found = True
+        return files_found
+
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: Literal[False] = False,
+    ) -> bool: ...
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool = True,
+        prefix: str | None = None,
+        *,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    @overload
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern[str],
+        anchor: bool,
+        prefix: str | None,
+        is_regex: Literal[True],
+    ) -> bool: ...
+    def exclude_pattern(
+        self,
+        pattern: str | re.Pattern,
+        anchor: bool = True,
+        prefix: str | None = None,
+        is_regex: bool = False,
+    ) -> bool:
+        """Remove strings (presumably filenames) from 'files' that match
+        'pattern'.  Other parameters are the same as for
+        'include_pattern()', above.
+        The list 'self.files' is modified in place.
+        Return True if files are found, False otherwise.
+        """
+        files_found = False
+        pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
+        self.debug_print(f"exclude_pattern: applying regex r'{pattern_re.pattern}'")
+        for i in range(len(self.files) - 1, -1, -1):
+            if pattern_re.search(self.files[i]):
+                self.debug_print(" removing " + self.files[i])
+                del self.files[i]
+                files_found = True
+        return files_found
+
+
+# Utility functions
+
+
+def _find_all_simple(path):
+    """
+    Find all files under 'path'
+    """
+    all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))
+    results = (
+        os.path.join(base, file) for base, dirs, files in all_unique for file in files
+    )
+    return filter(os.path.isfile, results)
+
+
+class _UniqueDirs(set):
+    """
+    Exclude previously-seen dirs from walk results,
+    avoiding infinite recursion.
+    Ref https://bugs.python.org/issue44497.
+    """
+
+    def __call__(self, walk_item):
+        """
+        Given an item from an os.walk result, determine
+        if the item represents a unique dir for this instance
+        and if not, prevent further traversal.
+        """
+        base, dirs, files = walk_item
+        stat = os.stat(base)
+        candidate = stat.st_dev, stat.st_ino
+        found = candidate in self
+        if found:
+            del dirs[:]
+        self.add(candidate)
+        return not found
+
+    @classmethod
+    def filter(cls, items):
+        return filter(cls(), items)
+
+
+def findall(dir: str | os.PathLike[str] = os.curdir):
+    """
+    Find all files under 'dir' and return the list of full filenames.
+    Unless dir is '.', return full filenames with dir prepended.
+    """
+    files = _find_all_simple(dir)
+    if dir == os.curdir:
+        make_rel = functools.partial(os.path.relpath, start=dir)
+        files = map(make_rel, files)
+    return list(files)
+
+
+def glob_to_re(pattern):
+    """Translate a shell-like glob pattern to a regular expression; return
+    a string containing the regex.  Differs from 'fnmatch.translate()' in
+    that '*' does not match "special characters" (which are
+    platform-specific).
+    """
+    pattern_re = fnmatch.translate(pattern)
+
+    # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
+    # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
+    # and by extension they shouldn't match such "special characters" under
+    # any OS.  So change all non-escaped dots in the RE to match any
+    # character except the special characters (currently: just os.sep).
+    sep = os.sep
+    if os.sep == '\\':
+        # we're using a regex to manipulate a regex, so we need
+        # to escape the backslash twice
+        sep = r'\\\\'
+    escaped = rf'\1[^{sep}]'
+    pattern_re = re.sub(r'((?= 2:
+        set_threshold(logging.DEBUG)
+
+
+class Log(logging.Logger):
+    """distutils.log.Log is deprecated, please use an alternative from `logging`."""
+
+    def __init__(self, threshold=WARN):
+        warnings.warn(Log.__doc__)  # avoid DeprecationWarning to ensure warn is shown
+        super().__init__(__name__, level=threshold)
+
+    @property
+    def threshold(self):
+        return self.level
+
+    @threshold.setter
+    def threshold(self, level):
+        self.setLevel(level)
+
+    warn = logging.Logger.warning
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/spawn.py b/python_embeded/Lib/site-packages/setuptools/_distutils/spawn.py
new file mode 100644
index 0000000000000000000000000000000000000000..973668f2684054741b109bd8bbb573611309cc2f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/spawn.py
@@ -0,0 +1,134 @@
+"""distutils.spawn
+
+Provides the 'spawn()' function, a front-end to various platform-
+specific functions for launching another program in a sub-process.
+"""
+
+from __future__ import annotations
+
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import warnings
+from collections.abc import Mapping, MutableSequence
+from typing import TYPE_CHECKING, TypeVar, overload
+
+from ._log import log
+from .debug import DEBUG
+from .errors import DistutilsExecError
+
+if TYPE_CHECKING:
+    from subprocess import _ENV
+
+
+_MappingT = TypeVar("_MappingT", bound=Mapping)
+
+
+def _debug(cmd):
+    """
+    Render a subprocess command differently depending on DEBUG.
+    """
+    return cmd if DEBUG else cmd[0]
+
+
+def _inject_macos_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None:
+    if platform.system() != 'Darwin':
+        return env
+
+    from .util import MACOSX_VERSION_VAR, get_macosx_target_ver
+
+    target_ver = get_macosx_target_ver()
+    update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {}
+    return {**_resolve(env), **update}
+
+
+@overload
+def _resolve(env: None) -> os._Environ[str]: ...
+@overload
+def _resolve(env: _MappingT) -> _MappingT: ...
+def _resolve(env: _MappingT | None) -> _MappingT | os._Environ[str]:
+    return os.environ if env is None else env
+
+
+def spawn(
+    cmd: MutableSequence[bytes | str | os.PathLike[str]],
+    search_path: bool = True,
+    verbose: bool = False,
+    dry_run: bool = False,
+    env: _ENV | None = None,
+) -> None:
+    """Run another program, specified as a command list 'cmd', in a new process.
+
+    'cmd' is just the argument list for the new process, ie.
+    cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
+    There is no way to run a program with a name different from that of its
+    executable.
+
+    If 'search_path' is true (the default), the system's executable
+    search path will be used to find the program; otherwise, cmd[0]
+    must be the exact path to the executable.  If 'dry_run' is true,
+    the command will not actually be run.
+
+    Raise DistutilsExecError if running the program fails in any way; just
+    return on success.
+    """
+    log.info(subprocess.list2cmdline(cmd))
+    if dry_run:
+        return
+
+    if search_path:
+        executable = shutil.which(cmd[0])
+        if executable is not None:
+            cmd[0] = executable
+
+    try:
+        subprocess.check_call(cmd, env=_inject_macos_ver(env))
+    except OSError as exc:
+        raise DistutilsExecError(
+            f"command {_debug(cmd)!r} failed: {exc.args[-1]}"
+        ) from exc
+    except subprocess.CalledProcessError as err:
+        raise DistutilsExecError(
+            f"command {_debug(cmd)!r} failed with exit code {err.returncode}"
+        ) from err
+
+
+def find_executable(executable: str, path: str | None = None) -> str | None:
+    """Tries to find 'executable' in the directories listed in 'path'.
+
+    A string listing directories separated by 'os.pathsep'; defaults to
+    os.environ['PATH'].  Returns the complete filename or None if not found.
+    """
+    warnings.warn(
+        'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2
+    )
+    _, ext = os.path.splitext(executable)
+    if (sys.platform == 'win32') and (ext != '.exe'):
+        executable = executable + '.exe'
+
+    if os.path.isfile(executable):
+        return executable
+
+    if path is None:
+        path = os.environ.get('PATH', None)
+        # bpo-35755: Don't fall through if PATH is the empty string
+        if path is None:
+            try:
+                path = os.confstr("CS_PATH")
+            except (AttributeError, ValueError):
+                # os.confstr() or CS_PATH is not available
+                path = os.defpath
+
+    # PATH='' doesn't match, whereas PATH=':' looks in the current directory
+    if not path:
+        return None
+
+    paths = path.split(os.pathsep)
+    for p in paths:
+        f = os.path.join(p, executable)
+        if os.path.isfile(f):
+            # the file exists, we have a shot at spawn working
+            return f
+    return None
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/sysconfig.py b/python_embeded/Lib/site-packages/setuptools/_distutils/sysconfig.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ddc869ab5603d691a8863988da89ec84689de84
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/sysconfig.py
@@ -0,0 +1,598 @@
+"""Provide access to Python's configuration information.  The specific
+configuration variables available depend heavily on the platform and
+configuration.  The values may be retrieved using
+get_config_var(name), and the list of variables is available via
+get_config_vars().keys().  Additional convenience functions are also
+available.
+
+Written by:   Fred L. Drake, Jr.
+Email:        
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import pathlib
+import re
+import sys
+import sysconfig
+from typing import TYPE_CHECKING, Literal, overload
+
+from jaraco.functools import pass_none
+
+from .ccompiler import CCompiler
+from .compat import py39
+from .errors import DistutilsPlatformError
+from .util import is_mingw
+
+if TYPE_CHECKING:
+    from typing_extensions import deprecated
+else:
+
+    def deprecated(message):
+        return lambda fn: fn
+
+
+IS_PYPY = '__pypy__' in sys.builtin_module_names
+
+# These are needed in a couple of spots, so just compute them once.
+PREFIX = os.path.normpath(sys.prefix)
+EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
+BASE_PREFIX = os.path.normpath(sys.base_prefix)
+BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
+
+# Path to the base directory of the project. On Windows the binary may
+# live in project/PCbuild/win32 or project/PCbuild/amd64.
+# set for cross builds
+if "_PYTHON_PROJECT_BASE" in os.environ:
+    project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
+else:
+    if sys.executable:
+        project_base = os.path.dirname(os.path.abspath(sys.executable))
+    else:
+        # sys.executable can be empty if argv[0] has been changed and Python is
+        # unable to retrieve the real program name
+        project_base = os.getcwd()
+
+
+def _is_python_source_dir(d):
+    """
+    Return True if the target directory appears to point to an
+    un-installed Python.
+    """
+    modules = pathlib.Path(d).joinpath('Modules')
+    return any(modules.joinpath(fn).is_file() for fn in ('Setup', 'Setup.local'))
+
+
+_sys_home = getattr(sys, '_home', None)
+
+
+def _is_parent(dir_a, dir_b):
+    """
+    Return True if a is a parent of b.
+    """
+    return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b))
+
+
+if os.name == 'nt':
+
+    @pass_none
+    def _fix_pcbuild(d):
+        # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX.
+        prefixes = PREFIX, BASE_PREFIX
+        matched = (
+            prefix
+            for prefix in prefixes
+            if _is_parent(d, os.path.join(prefix, "PCbuild"))
+        )
+        return next(matched, d)
+
+    project_base = _fix_pcbuild(project_base)
+    _sys_home = _fix_pcbuild(_sys_home)
+
+
+def _python_build():
+    if _sys_home:
+        return _is_python_source_dir(_sys_home)
+    return _is_python_source_dir(project_base)
+
+
+python_build = _python_build()
+
+
+# Calculate the build qualifier flags if they are defined.  Adding the flags
+# to the include and lib directories only makes sense for an installation, not
+# an in-source build.
+build_flags = ''
+try:
+    if not python_build:
+        build_flags = sys.abiflags
+except AttributeError:
+    # It's not a configure-based build, so the sys module doesn't have
+    # this attribute, which is fine.
+    pass
+
+
+def get_python_version():
+    """Return a string containing the major and minor Python version,
+    leaving off the patchlevel.  Sample return values could be '1.5'
+    or '2.2'.
+    """
+    return f'{sys.version_info.major}.{sys.version_info.minor}'
+
+
+def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str:
+    """Return the directory containing installed Python header files.
+
+    If 'plat_specific' is false (the default), this is the path to the
+    non-platform-specific header files, i.e. Python.h and so on;
+    otherwise, this is the path to platform-specific header files
+    (namely pyconfig.h).
+
+    If 'prefix' is supplied, use it instead of sys.base_prefix or
+    sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
+    """
+    default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX
+    resolved_prefix = prefix if prefix is not None else default_prefix
+    # MinGW imitates posix like layout, but os.name != posix
+    os_name = "posix" if is_mingw() else os.name
+    try:
+        getter = globals()[f'_get_python_inc_{os_name}']
+    except KeyError:
+        raise DistutilsPlatformError(
+            "I don't know where Python installs its C header files "
+            f"on platform '{os.name}'"
+        )
+    return getter(resolved_prefix, prefix, plat_specific)
+
+
+@pass_none
+def _extant(path):
+    """
+    Replace path with None if it doesn't exist.
+    """
+    return path if os.path.exists(path) else None
+
+
+def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
+    return (
+        _get_python_inc_posix_python(plat_specific)
+        or _extant(_get_python_inc_from_config(plat_specific, spec_prefix))
+        or _get_python_inc_posix_prefix(prefix)
+    )
+
+
+def _get_python_inc_posix_python(plat_specific):
+    """
+    Assume the executable is in the build directory. The
+    pyconfig.h file should be in the same directory. Since
+    the build directory may not be the source directory,
+    use "srcdir" from the makefile to find the "Include"
+    directory.
+    """
+    if not python_build:
+        return
+    if plat_specific:
+        return _sys_home or project_base
+    incdir = os.path.join(get_config_var('srcdir'), 'Include')
+    return os.path.normpath(incdir)
+
+
+def _get_python_inc_from_config(plat_specific, spec_prefix):
+    """
+    If no prefix was explicitly specified, provide the include
+    directory from the config vars. Useful when
+    cross-compiling, since the config vars may come from
+    the host
+    platform Python installation, while the current Python
+    executable is from the build platform installation.
+
+    >>> monkeypatch = getfixture('monkeypatch')
+    >>> gpifc = _get_python_inc_from_config
+    >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower)
+    >>> gpifc(False, '/usr/bin/')
+    >>> gpifc(False, '')
+    >>> gpifc(False, None)
+    'includepy'
+    >>> gpifc(True, None)
+    'confincludepy'
+    """
+    if spec_prefix is None:
+        return get_config_var('CONF' * plat_specific + 'INCLUDEPY')
+
+
+def _get_python_inc_posix_prefix(prefix):
+    implementation = 'pypy' if IS_PYPY else 'python'
+    python_dir = implementation + get_python_version() + build_flags
+    return os.path.join(prefix, "include", python_dir)
+
+
+def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
+    if python_build:
+        # Include both include dirs to ensure we can find pyconfig.h
+        return (
+            os.path.join(prefix, "include")
+            + os.path.pathsep
+            + os.path.dirname(sysconfig.get_config_h_filename())
+        )
+    return os.path.join(prefix, "include")
+
+
+# allow this behavior to be monkey-patched. Ref pypa/distutils#2.
+def _posix_lib(standard_lib, libpython, early_prefix, prefix):
+    if standard_lib:
+        return libpython
+    else:
+        return os.path.join(libpython, "site-packages")
+
+
+def get_python_lib(
+    plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None
+) -> str:
+    """Return the directory containing the Python library (standard or
+    site additions).
+
+    If 'plat_specific' is true, return the directory containing
+    platform-specific modules, i.e. any module from a non-pure-Python
+    module distribution; otherwise, return the platform-shared library
+    directory.  If 'standard_lib' is true, return the directory
+    containing standard Python library modules; otherwise, return the
+    directory for site-specific modules.
+
+    If 'prefix' is supplied, use it instead of sys.base_prefix or
+    sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
+    """
+
+    early_prefix = prefix
+
+    if prefix is None:
+        if standard_lib:
+            prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
+        else:
+            prefix = plat_specific and EXEC_PREFIX or PREFIX
+
+    if os.name == "posix" or is_mingw():
+        if plat_specific or standard_lib:
+            # Platform-specific modules (any module from a non-pure-Python
+            # module distribution) or standard Python library modules.
+            libdir = getattr(sys, "platlibdir", "lib")
+        else:
+            # Pure Python
+            libdir = "lib"
+        implementation = 'pypy' if IS_PYPY else 'python'
+        libpython = os.path.join(prefix, libdir, implementation + get_python_version())
+        return _posix_lib(standard_lib, libpython, early_prefix, prefix)
+    elif os.name == "nt":
+        if standard_lib:
+            return os.path.join(prefix, "Lib")
+        else:
+            return os.path.join(prefix, "Lib", "site-packages")
+    else:
+        raise DistutilsPlatformError(
+            f"I don't know where Python installs its library on platform '{os.name}'"
+        )
+
+
+@functools.lru_cache
+def _customize_macos():
+    """
+    Perform first-time customization of compiler-related
+    config vars on macOS. Use after a compiler is known
+    to be needed. This customization exists primarily to support Pythons
+    from binary installers. The kind and paths to build tools on
+    the user system may vary significantly from the system
+    that Python itself was built on.  Also the user OS
+    version and build tools may not support the same set
+    of CPU architectures for universal builds.
+    """
+
+    sys.platform == "darwin" and __import__('_osx_support').customize_compiler(
+        get_config_vars()
+    )
+
+
+def customize_compiler(compiler: CCompiler) -> None:
+    """Do any platform-specific customization of a CCompiler instance.
+
+    Mainly needed on Unix, so we can plug in the information that
+    varies across Unices and is stored in Python's Makefile.
+    """
+    if compiler.compiler_type in ["unix", "cygwin"] or (
+        compiler.compiler_type == "mingw32" and is_mingw()
+    ):
+        _customize_macos()
+
+        (
+            cc,
+            cxx,
+            cflags,
+            ccshared,
+            ldshared,
+            ldcxxshared,
+            shlib_suffix,
+            ar,
+            ar_flags,
+        ) = get_config_vars(
+            'CC',
+            'CXX',
+            'CFLAGS',
+            'CCSHARED',
+            'LDSHARED',
+            'LDCXXSHARED',
+            'SHLIB_SUFFIX',
+            'AR',
+            'ARFLAGS',
+        )
+
+        cxxflags = cflags
+
+        if 'CC' in os.environ:
+            newcc = os.environ['CC']
+            if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
+                # If CC is overridden, use that as the default
+                #       command for LDSHARED as well
+                ldshared = newcc + ldshared[len(cc) :]
+            cc = newcc
+        cxx = os.environ.get('CXX', cxx)
+        ldshared = os.environ.get('LDSHARED', ldshared)
+        ldcxxshared = os.environ.get('LDCXXSHARED', ldcxxshared)
+        cpp = os.environ.get(
+            'CPP',
+            cc + " -E",  # not always
+        )
+
+        ldshared = _add_flags(ldshared, 'LD')
+        ldcxxshared = _add_flags(ldcxxshared, 'LD')
+        cflags = os.environ.get('CFLAGS', cflags)
+        ldshared = _add_flags(ldshared, 'C')
+        cxxflags = os.environ.get('CXXFLAGS', cxxflags)
+        ldcxxshared = _add_flags(ldcxxshared, 'CXX')
+        cpp = _add_flags(cpp, 'CPP')
+        cflags = _add_flags(cflags, 'CPP')
+        cxxflags = _add_flags(cxxflags, 'CPP')
+        ldshared = _add_flags(ldshared, 'CPP')
+        ldcxxshared = _add_flags(ldcxxshared, 'CPP')
+
+        ar = os.environ.get('AR', ar)
+
+        archiver = ar + ' ' + os.environ.get('ARFLAGS', ar_flags)
+        cc_cmd = cc + ' ' + cflags
+        cxx_cmd = cxx + ' ' + cxxflags
+
+        compiler.set_executables(
+            preprocessor=cpp,
+            compiler=cc_cmd,
+            compiler_so=cc_cmd + ' ' + ccshared,
+            compiler_cxx=cxx_cmd,
+            compiler_so_cxx=cxx_cmd + ' ' + ccshared,
+            linker_so=ldshared,
+            linker_so_cxx=ldcxxshared,
+            linker_exe=cc,
+            linker_exe_cxx=cxx,
+            archiver=archiver,
+        )
+
+        if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
+            compiler.set_executables(ranlib=os.environ['RANLIB'])
+
+        compiler.shared_lib_extension = shlib_suffix
+
+
+def get_config_h_filename() -> str:
+    """Return full pathname of installed pyconfig.h file."""
+    return sysconfig.get_config_h_filename()
+
+
+def get_makefile_filename() -> str:
+    """Return full pathname of installed Makefile from the Python build."""
+    return sysconfig.get_makefile_filename()
+
+
+def parse_config_h(fp, g=None):
+    """Parse a config.h-style file.
+
+    A dictionary containing name/value pairs is returned.  If an
+    optional dictionary is passed in as the second argument, it is
+    used instead of a new dictionary.
+    """
+    return sysconfig.parse_config_h(fp, vars=g)
+
+
+# Regexes needed for parsing Makefile (and similar syntaxes,
+# like old-style Setup files).
+_variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
+_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
+_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
+
+
+def parse_makefile(fn, g=None):  # noqa: C901
+    """Parse a Makefile-style file.
+
+    A dictionary containing name/value pairs is returned.  If an
+    optional dictionary is passed in as the second argument, it is
+    used instead of a new dictionary.
+    """
+    from distutils.text_file import TextFile
+
+    fp = TextFile(
+        fn,
+        strip_comments=True,
+        skip_blanks=True,
+        join_lines=True,
+        errors="surrogateescape",
+    )
+
+    if g is None:
+        g = {}
+    done = {}
+    notdone = {}
+
+    while True:
+        line = fp.readline()
+        if line is None:  # eof
+            break
+        m = _variable_rx.match(line)
+        if m:
+            n, v = m.group(1, 2)
+            v = v.strip()
+            # `$$' is a literal `$' in make
+            tmpv = v.replace('$$', '')
+
+            if "$" in tmpv:
+                notdone[n] = v
+            else:
+                try:
+                    v = int(v)
+                except ValueError:
+                    # insert literal `$'
+                    done[n] = v.replace('$$', '$')
+                else:
+                    done[n] = v
+
+    # Variables with a 'PY_' prefix in the makefile. These need to
+    # be made available without that prefix through sysconfig.
+    # Special care is needed to ensure that variable expansion works, even
+    # if the expansion uses the name without a prefix.
+    renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
+
+    # do variable interpolation here
+    while notdone:
+        for name in list(notdone):
+            value = notdone[name]
+            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
+            if m:
+                n = m.group(1)
+                found = True
+                if n in done:
+                    item = str(done[n])
+                elif n in notdone:
+                    # get it on a subsequent round
+                    found = False
+                elif n in os.environ:
+                    # do it like make: fall back to environment
+                    item = os.environ[n]
+
+                elif n in renamed_variables:
+                    if name.startswith('PY_') and name[3:] in renamed_variables:
+                        item = ""
+
+                    elif 'PY_' + n in notdone:
+                        found = False
+
+                    else:
+                        item = str(done['PY_' + n])
+                else:
+                    done[n] = item = ""
+                if found:
+                    after = value[m.end() :]
+                    value = value[: m.start()] + item + after
+                    if "$" in after:
+                        notdone[name] = value
+                    else:
+                        try:
+                            value = int(value)
+                        except ValueError:
+                            done[name] = value.strip()
+                        else:
+                            done[name] = value
+                        del notdone[name]
+
+                        if name.startswith('PY_') and name[3:] in renamed_variables:
+                            name = name[3:]
+                            if name not in done:
+                                done[name] = value
+            else:
+                # bogus variable reference; just drop it since we can't deal
+                del notdone[name]
+
+    fp.close()
+
+    # strip spurious spaces
+    for k, v in done.items():
+        if isinstance(v, str):
+            done[k] = v.strip()
+
+    # save the results in the global dictionary
+    g.update(done)
+    return g
+
+
+def expand_makefile_vars(s, vars):
+    """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
+    'string' according to 'vars' (a dictionary mapping variable names to
+    values).  Variables not present in 'vars' are silently expanded to the
+    empty string.  The variable values in 'vars' should not contain further
+    variable expansions; if 'vars' is the output of 'parse_makefile()',
+    you're fine.  Returns a variable-expanded version of 's'.
+    """
+
+    # This algorithm does multiple expansion, so if vars['foo'] contains
+    # "${bar}", it will expand ${foo} to ${bar}, and then expand
+    # ${bar}... and so forth.  This is fine as long as 'vars' comes from
+    # 'parse_makefile()', which takes care of such expansions eagerly,
+    # according to make's variable expansion semantics.
+
+    while True:
+        m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
+        if m:
+            (beg, end) = m.span()
+            s = s[0:beg] + vars.get(m.group(1)) + s[end:]
+        else:
+            break
+    return s
+
+
+_config_vars = None
+
+
+@overload
+def get_config_vars() -> dict[str, str | int]: ...
+@overload
+def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ...
+def get_config_vars(*args: str) -> list[str | int] | dict[str, str | int]:
+    """With no arguments, return a dictionary of all configuration
+    variables relevant for the current platform.  Generally this includes
+    everything needed to build extensions and install both pure modules and
+    extensions.  On Unix, this means every variable defined in Python's
+    installed Makefile; on Windows it's a much smaller set.
+
+    With arguments, return a list of values that result from looking up
+    each argument in the configuration variable dictionary.
+    """
+    global _config_vars
+    if _config_vars is None:
+        _config_vars = sysconfig.get_config_vars().copy()
+        py39.add_ext_suffix(_config_vars)
+
+    return [_config_vars.get(name) for name in args] if args else _config_vars
+
+
+@overload
+@deprecated(
+    "SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11"
+)
+def get_config_var(name: Literal["SO"]) -> int | str | None: ...
+@overload
+def get_config_var(name: str) -> int | str | None: ...
+def get_config_var(name: str) -> int | str | None:
+    """Return the value of a single variable using the dictionary
+    returned by 'get_config_vars()'.  Equivalent to
+    get_config_vars().get(name)
+    """
+    if name == 'SO':
+        import warnings
+
+        warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
+    return get_config_vars().get(name)
+
+
+@pass_none
+def _add_flags(value: str, type: str) -> str:
+    """
+    Add any flags from the environment for the given type.
+
+    type is the prefix to FLAGS in the environment key (e.g. "C" for "CFLAGS").
+    """
+    flags = os.environ.get(f'{type}FLAGS')
+    return f'{value} {flags}' if flags else value
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/__init__.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a8ab061009f1cd87a53ce51eff3bc9e9a632273
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/__init__.py
@@ -0,0 +1,42 @@
+"""
+Test suite for distutils.
+
+Tests for the command classes in the distutils.command package are
+included in distutils.tests as well, instead of using a separate
+distutils.command.tests package, since command identification is done
+by import rather than matching pre-defined names.
+"""
+
+import shutil
+from collections.abc import Sequence
+
+
+def missing_compiler_executable(cmd_names: Sequence[str] = []):  # pragma: no cover
+    """Check if the compiler components used to build the interpreter exist.
+
+    Check for the existence of the compiler executables whose names are listed
+    in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
+    and return the first missing executable or None when none is found
+    missing.
+
+    """
+    from distutils import ccompiler, errors, sysconfig
+
+    compiler = ccompiler.new_compiler()
+    sysconfig.customize_compiler(compiler)
+    if compiler.compiler_type == "msvc":
+        # MSVC has no executables, so check whether initialization succeeds
+        try:
+            compiler.initialize()
+        except errors.DistutilsPlatformError:
+            return "msvc"
+    for name in compiler.executables:
+        if cmd_names and name not in cmd_names:
+            continue
+        cmd = getattr(compiler, name)
+        if cmd_names:
+            assert cmd is not None, f"the '{name}' executable is not configured"
+        elif not cmd:
+            continue
+        if shutil.which(cmd[0]) is None:
+            return cmd[0]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/compat/py39.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..aca3939a0cea90dd0a90d7f36fcf83a5167cbfc4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/compat/py39.py
@@ -0,0 +1,40 @@
+import sys
+
+if sys.version_info >= (3, 10):
+    from test.support.import_helper import (
+        CleanImport as CleanImport,
+    )
+    from test.support.import_helper import (
+        DirsOnSysPath as DirsOnSysPath,
+    )
+    from test.support.os_helper import (
+        EnvironmentVarGuard as EnvironmentVarGuard,
+    )
+    from test.support.os_helper import (
+        rmtree as rmtree,
+    )
+    from test.support.os_helper import (
+        skip_unless_symlink as skip_unless_symlink,
+    )
+    from test.support.os_helper import (
+        unlink as unlink,
+    )
+else:
+    from test.support import (
+        CleanImport as CleanImport,
+    )
+    from test.support import (
+        DirsOnSysPath as DirsOnSysPath,
+    )
+    from test.support import (
+        EnvironmentVarGuard as EnvironmentVarGuard,
+    )
+    from test.support import (
+        rmtree as rmtree,
+    )
+    from test.support import (
+        skip_unless_symlink as skip_unless_symlink,
+    )
+    from test.support import (
+        unlink as unlink,
+    )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/support.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/support.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cd2b8a9eedbb9f11a3ed793af57b3290c5febef
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/support.py
@@ -0,0 +1,134 @@
+"""Support code for distutils test cases."""
+
+import itertools
+import os
+import pathlib
+import shutil
+import sys
+import sysconfig
+import tempfile
+from distutils.core import Distribution
+
+import pytest
+from more_itertools import always_iterable
+
+
+@pytest.mark.usefixtures('distutils_managed_tempdir')
+class TempdirManager:
+    """
+    Mix-in class that handles temporary directories for test cases.
+    """
+
+    def mkdtemp(self):
+        """Create a temporary directory that will be cleaned up.
+
+        Returns the path of the directory.
+        """
+        d = tempfile.mkdtemp()
+        self.tempdirs.append(d)
+        return d
+
+    def write_file(self, path, content='xxx'):
+        """Writes a file in the given path.
+
+        path can be a string or a sequence.
+        """
+        pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8')
+
+    def create_dist(self, pkg_name='foo', **kw):
+        """Will generate a test environment.
+
+        This function creates:
+         - a Distribution instance using keywords
+         - a temporary directory with a package structure
+
+        It returns the package directory and the distribution
+        instance.
+        """
+        tmp_dir = self.mkdtemp()
+        pkg_dir = os.path.join(tmp_dir, pkg_name)
+        os.mkdir(pkg_dir)
+        dist = Distribution(attrs=kw)
+
+        return pkg_dir, dist
+
+
+class DummyCommand:
+    """Class to store options for retrieval via set_undefined_options()."""
+
+    def __init__(self, **kwargs):
+        vars(self).update(kwargs)
+
+    def ensure_finalized(self):
+        pass
+
+
+def copy_xxmodule_c(directory):
+    """Helper for tests that need the xxmodule.c source file.
+
+    Example use:
+
+        def test_compile(self):
+            copy_xxmodule_c(self.tmpdir)
+            self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
+
+    If the source file can be found, it will be copied to *directory*.  If not,
+    the test will be skipped.  Errors during copy are not caught.
+    """
+    shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c'))
+
+
+def _get_xxmodule_path():
+    source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c'
+    return os.path.join(os.path.dirname(__file__), source_name)
+
+
+def fixup_build_ext(cmd):
+    """Function needed to make build_ext tests pass.
+
+    When Python was built with --enable-shared on Unix, -L. is not enough to
+    find libpython.so, because regrtest runs in a tempdir, not in the
+    source directory where the .so lives.
+
+    When Python was built with in debug mode on Windows, build_ext commands
+    need their debug attribute set, and it is not done automatically for
+    some reason.
+
+    This function handles both of these things.  Example use:
+
+        cmd = build_ext(dist)
+        support.fixup_build_ext(cmd)
+        cmd.ensure_finalized()
+
+    Unlike most other Unix platforms, Mac OS X embeds absolute paths
+    to shared libraries into executables, so the fixup is not needed there.
+    """
+    if os.name == 'nt':
+        cmd.debug = sys.executable.endswith('_d.exe')
+    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
+        # To further add to the shared builds fun on Unix, we can't just add
+        # library_dirs to the Extension() instance because that doesn't get
+        # plumbed through to the final compiler command.
+        runshared = sysconfig.get_config_var('RUNSHARED')
+        if runshared is None:
+            cmd.library_dirs = ['.']
+        else:
+            if sys.platform == 'darwin':
+                cmd.library_dirs = []
+            else:
+                name, equals, value = runshared.partition('=')
+                cmd.library_dirs = [d for d in value.split(os.pathsep) if d]
+
+
+def combine_markers(cls):
+    """
+    pytest will honor markers as found on the class, but when
+    markers are on multiple subclasses, only one appears. Use
+    this decorator to combine those markers.
+    """
+    cls.pytestmark = [
+        mark
+        for base in itertools.chain([cls], cls.__bases__)
+        for mark in getattr(base, 'pytestmark', [])
+    ]
+    return cls
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_archive_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_archive_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e4ed75a761dc26fc7dc29066138a02531c6e9c3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_archive_util.py
@@ -0,0 +1,353 @@
+"""Tests for distutils.archive_util."""
+
+import functools
+import operator
+import os
+import pathlib
+import sys
+import tarfile
+from distutils import archive_util
+from distutils.archive_util import (
+    ARCHIVE_FORMATS,
+    check_archive_formats,
+    make_archive,
+    make_tarball,
+    make_zipfile,
+)
+from distutils.spawn import spawn
+from distutils.tests import support
+from os.path import splitdrive
+
+import path
+import pytest
+from test.support import patch
+
+from .unix_compat import UID_0_SUPPORT, grp, pwd, require_uid_0, require_unix_id
+
+
+def can_fs_encode(filename):
+    """
+    Return True if the filename can be saved in the file system.
+    """
+    if os.path.supports_unicode_filenames:
+        return True
+    try:
+        filename.encode(sys.getfilesystemencoding())
+    except UnicodeEncodeError:
+        return False
+    return True
+
+
+def all_equal(values):
+    return functools.reduce(operator.eq, values)
+
+
+def same_drive(*paths):
+    return all_equal(pathlib.Path(path).drive for path in paths)
+
+
+class ArchiveUtilTestCase(support.TempdirManager):
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_make_tarball(self, name='archive'):
+        # creating something to tar
+        tmpdir = self._create_files()
+        self._make_tarball(tmpdir, name, '.tar.gz')
+        # trying an uncompressed one
+        self._make_tarball(tmpdir, name, '.tar', compress=None)
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_make_tarball_gzip(self):
+        tmpdir = self._create_files()
+        self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip')
+
+    def test_make_tarball_bzip2(self):
+        pytest.importorskip('bz2')
+        tmpdir = self._create_files()
+        self._make_tarball(tmpdir, 'archive', '.tar.bz2', compress='bzip2')
+
+    def test_make_tarball_xz(self):
+        pytest.importorskip('lzma')
+        tmpdir = self._create_files()
+        self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz')
+
+    @pytest.mark.skipif("not can_fs_encode('årchiv')")
+    def test_make_tarball_latin1(self):
+        """
+        Mirror test_make_tarball, except filename contains latin characters.
+        """
+        self.test_make_tarball('årchiv')  # note this isn't a real word
+
+    @pytest.mark.skipif("not can_fs_encode('のアーカイブ')")
+    def test_make_tarball_extended(self):
+        """
+        Mirror test_make_tarball, except filename contains extended
+        characters outside the latin charset.
+        """
+        self.test_make_tarball('のアーカイブ')  # japanese for archive
+
+    def _make_tarball(self, tmpdir, target_name, suffix, **kwargs):
+        tmpdir2 = self.mkdtemp()
+        if same_drive(tmpdir, tmpdir2):
+            pytest.skip("source and target should be on same drive")
+
+        base_name = os.path.join(tmpdir2, target_name)
+
+        # working with relative paths to avoid tar warnings
+        with path.Path(tmpdir):
+            make_tarball(splitdrive(base_name)[1], 'dist', **kwargs)
+
+        # check if the compressed tarball was created
+        tarball = base_name + suffix
+        assert os.path.exists(tarball)
+        assert self._tarinfo(tarball) == self._created_files
+
+    def _tarinfo(self, path):
+        tar = tarfile.open(path)
+        try:
+            names = tar.getnames()
+            names.sort()
+            return names
+        finally:
+            tar.close()
+
+    _zip_created_files = [
+        'dist/',
+        'dist/file1',
+        'dist/file2',
+        'dist/sub/',
+        'dist/sub/file3',
+        'dist/sub2/',
+    ]
+    _created_files = [p.rstrip('/') for p in _zip_created_files]
+
+    def _create_files(self):
+        # creating something to tar
+        tmpdir = self.mkdtemp()
+        dist = os.path.join(tmpdir, 'dist')
+        os.mkdir(dist)
+        self.write_file([dist, 'file1'], 'xxx')
+        self.write_file([dist, 'file2'], 'xxx')
+        os.mkdir(os.path.join(dist, 'sub'))
+        self.write_file([dist, 'sub', 'file3'], 'xxx')
+        os.mkdir(os.path.join(dist, 'sub2'))
+        return tmpdir
+
+    @pytest.mark.usefixtures('needs_zlib')
+    @pytest.mark.skipif("not (shutil.which('tar') and shutil.which('gzip'))")
+    def test_tarfile_vs_tar(self):
+        tmpdir = self._create_files()
+        tmpdir2 = self.mkdtemp()
+        base_name = os.path.join(tmpdir2, 'archive')
+        old_dir = os.getcwd()
+        os.chdir(tmpdir)
+        try:
+            make_tarball(base_name, 'dist')
+        finally:
+            os.chdir(old_dir)
+
+        # check if the compressed tarball was created
+        tarball = base_name + '.tar.gz'
+        assert os.path.exists(tarball)
+
+        # now create another tarball using `tar`
+        tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
+        tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
+        gzip_cmd = ['gzip', '-f', '-9', 'archive2.tar']
+        old_dir = os.getcwd()
+        os.chdir(tmpdir)
+        try:
+            spawn(tar_cmd)
+            spawn(gzip_cmd)
+        finally:
+            os.chdir(old_dir)
+
+        assert os.path.exists(tarball2)
+        # let's compare both tarballs
+        assert self._tarinfo(tarball) == self._created_files
+        assert self._tarinfo(tarball2) == self._created_files
+
+        # trying an uncompressed one
+        base_name = os.path.join(tmpdir2, 'archive')
+        old_dir = os.getcwd()
+        os.chdir(tmpdir)
+        try:
+            make_tarball(base_name, 'dist', compress=None)
+        finally:
+            os.chdir(old_dir)
+        tarball = base_name + '.tar'
+        assert os.path.exists(tarball)
+
+        # now for a dry_run
+        base_name = os.path.join(tmpdir2, 'archive')
+        old_dir = os.getcwd()
+        os.chdir(tmpdir)
+        try:
+            make_tarball(base_name, 'dist', compress=None, dry_run=True)
+        finally:
+            os.chdir(old_dir)
+        tarball = base_name + '.tar'
+        assert os.path.exists(tarball)
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_make_zipfile(self):
+        zipfile = pytest.importorskip('zipfile')
+        # creating something to tar
+        tmpdir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        with path.Path(tmpdir):
+            make_zipfile(base_name, 'dist')
+
+        # check if the compressed tarball was created
+        tarball = base_name + '.zip'
+        assert os.path.exists(tarball)
+        with zipfile.ZipFile(tarball) as zf:
+            assert sorted(zf.namelist()) == self._zip_created_files
+
+    def test_make_zipfile_no_zlib(self):
+        zipfile = pytest.importorskip('zipfile')
+        patch(self, archive_util.zipfile, 'zlib', None)  # force zlib ImportError
+
+        called = []
+        zipfile_class = zipfile.ZipFile
+
+        def fake_zipfile(*a, **kw):
+            if kw.get('compression', None) == zipfile.ZIP_STORED:
+                called.append((a, kw))
+            return zipfile_class(*a, **kw)
+
+        patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)
+
+        # create something to tar and compress
+        tmpdir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        with path.Path(tmpdir):
+            make_zipfile(base_name, 'dist')
+
+        tarball = base_name + '.zip'
+        assert called == [((tarball, "w"), {'compression': zipfile.ZIP_STORED})]
+        assert os.path.exists(tarball)
+        with zipfile.ZipFile(tarball) as zf:
+            assert sorted(zf.namelist()) == self._zip_created_files
+
+    def test_check_archive_formats(self):
+        assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx'
+        assert (
+            check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip'])
+            is None
+        )
+
+    def test_make_archive(self):
+        tmpdir = self.mkdtemp()
+        base_name = os.path.join(tmpdir, 'archive')
+        with pytest.raises(ValueError):
+            make_archive(base_name, 'xxx')
+
+    def test_make_archive_cwd(self):
+        current_dir = os.getcwd()
+
+        def _breaks(*args, **kw):
+            raise RuntimeError()
+
+        ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
+        try:
+            try:
+                make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
+            except Exception:
+                pass
+            assert os.getcwd() == current_dir
+        finally:
+            ARCHIVE_FORMATS.pop('xxx')
+
+    def test_make_archive_tar(self):
+        base_dir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        res = make_archive(base_name, 'tar', base_dir, 'dist')
+        assert os.path.exists(res)
+        assert os.path.basename(res) == 'archive.tar'
+        assert self._tarinfo(res) == self._created_files
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_make_archive_gztar(self):
+        base_dir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        res = make_archive(base_name, 'gztar', base_dir, 'dist')
+        assert os.path.exists(res)
+        assert os.path.basename(res) == 'archive.tar.gz'
+        assert self._tarinfo(res) == self._created_files
+
+    def test_make_archive_bztar(self):
+        pytest.importorskip('bz2')
+        base_dir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        res = make_archive(base_name, 'bztar', base_dir, 'dist')
+        assert os.path.exists(res)
+        assert os.path.basename(res) == 'archive.tar.bz2'
+        assert self._tarinfo(res) == self._created_files
+
+    def test_make_archive_xztar(self):
+        pytest.importorskip('lzma')
+        base_dir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        res = make_archive(base_name, 'xztar', base_dir, 'dist')
+        assert os.path.exists(res)
+        assert os.path.basename(res) == 'archive.tar.xz'
+        assert self._tarinfo(res) == self._created_files
+
+    def test_make_archive_owner_group(self):
+        # testing make_archive with owner and group, with various combinations
+        # this works even if there's not gid/uid support
+        if UID_0_SUPPORT:
+            group = grp.getgrgid(0)[0]
+            owner = pwd.getpwuid(0)[0]
+        else:
+            group = owner = 'root'
+
+        base_dir = self._create_files()
+        root_dir = self.mkdtemp()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        res = make_archive(
+            base_name, 'zip', root_dir, base_dir, owner=owner, group=group
+        )
+        assert os.path.exists(res)
+
+        res = make_archive(base_name, 'zip', root_dir, base_dir)
+        assert os.path.exists(res)
+
+        res = make_archive(
+            base_name, 'tar', root_dir, base_dir, owner=owner, group=group
+        )
+        assert os.path.exists(res)
+
+        res = make_archive(
+            base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh'
+        )
+        assert os.path.exists(res)
+
+    @pytest.mark.usefixtures('needs_zlib')
+    @require_unix_id
+    @require_uid_0
+    def test_tarfile_root_owner(self):
+        tmpdir = self._create_files()
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        old_dir = os.getcwd()
+        os.chdir(tmpdir)
+        group = grp.getgrgid(0)[0]
+        owner = pwd.getpwuid(0)[0]
+        try:
+            archive_name = make_tarball(
+                base_name, 'dist', compress=None, owner=owner, group=group
+            )
+        finally:
+            os.chdir(old_dir)
+
+        # check if the compressed tarball was created
+        assert os.path.exists(archive_name)
+
+        # now checks the rights
+        archive = tarfile.open(archive_name)
+        try:
+            for member in archive.getmembers():
+                assert member.uid == 0
+                assert member.gid == 0
+        finally:
+            archive.close()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5696fc3dcd8081335606dc92badd73a69ceac69
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist.py
@@ -0,0 +1,47 @@
+"""Tests for distutils.command.bdist."""
+
+from distutils.command.bdist import bdist
+from distutils.tests import support
+
+
+class TestBuild(support.TempdirManager):
+    def test_formats(self):
+        # let's create a command and make sure
+        # we can set the format
+        dist = self.create_dist()[1]
+        cmd = bdist(dist)
+        cmd.formats = ['gztar']
+        cmd.ensure_finalized()
+        assert cmd.formats == ['gztar']
+
+        # what formats does bdist offer?
+        formats = [
+            'bztar',
+            'gztar',
+            'rpm',
+            'tar',
+            'xztar',
+            'zip',
+            'ztar',
+        ]
+        found = sorted(cmd.format_commands)
+        assert found == formats
+
+    def test_skip_build(self):
+        # bug #10946: bdist --skip-build should trickle down to subcommands
+        dist = self.create_dist()[1]
+        cmd = bdist(dist)
+        cmd.skip_build = True
+        cmd.ensure_finalized()
+        dist.command_obj['bdist'] = cmd
+
+        names = [
+            'bdist_dumb',
+        ]  # bdist_rpm does not support --skip-build
+
+        for name in names:
+            subcmd = cmd.get_finalized_command(name)
+            if getattr(subcmd, '_unsupported', False):
+                # command is not supported on this build
+                continue
+            assert subcmd.skip_build, f'{name} should take --skip-build from bdist'
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fc51d244a78058329c56a618b092e466715e565
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py
@@ -0,0 +1,78 @@
+"""Tests for distutils.command.bdist_dumb."""
+
+import os
+import sys
+import zipfile
+from distutils.command.bdist_dumb import bdist_dumb
+from distutils.core import Distribution
+from distutils.tests import support
+
+import pytest
+
+SETUP_PY = """\
+from distutils.core import setup
+import foo
+
+setup(name='foo', version='0.1', py_modules=['foo'],
+      url='xxx', author='xxx', author_email='xxx')
+
+"""
+
+
+@support.combine_markers
+@pytest.mark.usefixtures('save_env')
+@pytest.mark.usefixtures('save_argv')
+@pytest.mark.usefixtures('save_cwd')
+class TestBuildDumb(
+    support.TempdirManager,
+):
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_simple_built(self):
+        # let's create a simple package
+        tmp_dir = self.mkdtemp()
+        pkg_dir = os.path.join(tmp_dir, 'foo')
+        os.mkdir(pkg_dir)
+        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
+        self.write_file((pkg_dir, 'foo.py'), '#')
+        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
+        self.write_file((pkg_dir, 'README'), '')
+
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
+        dist.script_name = 'setup.py'
+        os.chdir(pkg_dir)
+
+        sys.argv = ['setup.py']
+        cmd = bdist_dumb(dist)
+
+        # so the output is the same no matter
+        # what is the platform
+        cmd.format = 'zip'
+
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # see what we have
+        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
+        base = f"{dist.get_fullname()}.{cmd.plat_name}.zip"
+
+        assert dist_created == [base]
+
+        # now let's check what we have in the zip file
+        fp = zipfile.ZipFile(os.path.join('dist', base))
+        try:
+            contents = fp.namelist()
+        finally:
+            fp.close()
+
+        contents = sorted(filter(None, map(os.path.basename, contents)))
+        wanted = ['foo-0.1-py{}.{}.egg-info'.format(*sys.version_info[:2]), 'foo.py']
+        if not sys.dont_write_bytecode:
+            wanted.append(f'foo.{sys.implementation.cache_tag}.pyc')
+        assert contents == sorted(wanted)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py
new file mode 100644
index 0000000000000000000000000000000000000000..75051430e224c8908e22601133a40f5f82ee455a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py
@@ -0,0 +1,127 @@
+"""Tests for distutils.command.bdist_rpm."""
+
+import os
+import shutil  # noqa: F401
+import sys
+from distutils.command.bdist_rpm import bdist_rpm
+from distutils.core import Distribution
+from distutils.tests import support
+
+import pytest
+from test.support import requires_zlib
+
+SETUP_PY = """\
+from distutils.core import setup
+import foo
+
+setup(name='foo', version='0.1', py_modules=['foo'],
+      url='xxx', author='xxx', author_email='xxx')
+
+"""
+
+
+@pytest.fixture(autouse=True)
+def sys_executable_encodable():
+    try:
+        sys.executable.encode('UTF-8')
+    except UnicodeEncodeError:
+        pytest.skip("sys.executable is not encodable to UTF-8")
+
+
+mac_woes = pytest.mark.skipif(
+    "not sys.platform.startswith('linux')",
+    reason='spurious sdtout/stderr output under macOS',
+)
+
+
+@pytest.mark.usefixtures('save_env')
+@pytest.mark.usefixtures('save_argv')
+@pytest.mark.usefixtures('save_cwd')
+class TestBuildRpm(
+    support.TempdirManager,
+):
+    @mac_woes
+    @requires_zlib()
+    @pytest.mark.skipif("not shutil.which('rpm')")
+    @pytest.mark.skipif("not shutil.which('rpmbuild')")
+    def test_quiet(self):
+        # let's create a package
+        tmp_dir = self.mkdtemp()
+        os.environ['HOME'] = tmp_dir  # to confine dir '.rpmdb' creation
+        pkg_dir = os.path.join(tmp_dir, 'foo')
+        os.mkdir(pkg_dir)
+        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
+        self.write_file((pkg_dir, 'foo.py'), '#')
+        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
+        self.write_file((pkg_dir, 'README'), '')
+
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
+        dist.script_name = 'setup.py'
+        os.chdir(pkg_dir)
+
+        sys.argv = ['setup.py']
+        cmd = bdist_rpm(dist)
+        cmd.fix_python = True
+
+        # running in quiet mode
+        cmd.quiet = True
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
+        assert 'foo-0.1-1.noarch.rpm' in dist_created
+
+        # bug #2945: upload ignores bdist_rpm files
+        assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files
+        assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files
+
+    @mac_woes
+    @requires_zlib()
+    # https://bugs.python.org/issue1533164
+    @pytest.mark.skipif("not shutil.which('rpm')")
+    @pytest.mark.skipif("not shutil.which('rpmbuild')")
+    def test_no_optimize_flag(self):
+        # let's create a package that breaks bdist_rpm
+        tmp_dir = self.mkdtemp()
+        os.environ['HOME'] = tmp_dir  # to confine dir '.rpmdb' creation
+        pkg_dir = os.path.join(tmp_dir, 'foo')
+        os.mkdir(pkg_dir)
+        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
+        self.write_file((pkg_dir, 'foo.py'), '#')
+        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
+        self.write_file((pkg_dir, 'README'), '')
+
+        dist = Distribution({
+            'name': 'foo',
+            'version': '0.1',
+            'py_modules': ['foo'],
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+        })
+        dist.script_name = 'setup.py'
+        os.chdir(pkg_dir)
+
+        sys.argv = ['setup.py']
+        cmd = bdist_rpm(dist)
+        cmd.fix_python = True
+
+        cmd.quiet = True
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
+        assert 'foo-0.1-1.noarch.rpm' in dist_created
+
+        # bug #2945: upload ignores bdist_rpm files
+        assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files
+        assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files
+
+        os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7fe69acd1ad39cf40d277afd6409648b18df146
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build.py
@@ -0,0 +1,49 @@
+"""Tests for distutils.command.build."""
+
+import os
+import sys
+from distutils.command.build import build
+from distutils.tests import support
+from sysconfig import get_config_var, get_platform
+
+
+class TestBuild(support.TempdirManager):
+    def test_finalize_options(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build(dist)
+        cmd.finalize_options()
+
+        # if not specified, plat_name gets the current platform
+        assert cmd.plat_name == get_platform()
+
+        # build_purelib is build + lib
+        wanted = os.path.join(cmd.build_base, 'lib')
+        assert cmd.build_purelib == wanted
+
+        # build_platlib is 'build/lib.platform-cache_tag[-pydebug]'
+        # examples:
+        #   build/lib.macosx-10.3-i386-cpython39
+        plat_spec = f'.{cmd.plat_name}-{sys.implementation.cache_tag}'
+        if get_config_var('Py_GIL_DISABLED'):
+            plat_spec += 't'
+        if hasattr(sys, 'gettotalrefcount'):
+            assert cmd.build_platlib.endswith('-pydebug')
+            plat_spec += '-pydebug'
+        wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
+        assert cmd.build_platlib == wanted
+
+        # by default, build_lib = build_purelib
+        assert cmd.build_lib == cmd.build_purelib
+
+        # build_temp is build/temp.
+        wanted = os.path.join(cmd.build_base, 'temp' + plat_spec)
+        assert cmd.build_temp == wanted
+
+        # build_scripts is build/scripts-x.x
+        wanted = os.path.join(
+            cmd.build_base, f'scripts-{sys.version_info.major}.{sys.version_info.minor}'
+        )
+        assert cmd.build_scripts == wanted
+
+        # executable is os.path.normpath(sys.executable)
+        assert cmd.executable == os.path.normpath(sys.executable)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_clib.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_clib.py
new file mode 100644
index 0000000000000000000000000000000000000000..f76f26bcea04ebeaeba20d3c65881198f841c9b5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_clib.py
@@ -0,0 +1,134 @@
+"""Tests for distutils.command.build_clib."""
+
+import os
+from distutils.command.build_clib import build_clib
+from distutils.errors import DistutilsSetupError
+from distutils.tests import missing_compiler_executable, support
+
+import pytest
+
+
+class TestBuildCLib(support.TempdirManager):
+    def test_check_library_dist(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build_clib(dist)
+
+        # 'libraries' option must be a list
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_library_list('foo')
+
+        # each element of 'libraries' must a 2-tuple
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_library_list(['foo1', 'foo2'])
+
+        # first element of each tuple in 'libraries'
+        # must be a string (the library name)
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_library_list([(1, 'foo1'), ('name', 'foo2')])
+
+        # library name may not contain directory separators
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_library_list(
+                [('name', 'foo1'), ('another/name', 'foo2')],
+            )
+
+        # second element of each tuple must be a dictionary (build info)
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_library_list(
+                [('name', {}), ('another', 'foo2')],
+            )
+
+        # those work
+        libs = [('name', {}), ('name', {'ok': 'good'})]
+        cmd.check_library_list(libs)
+
+    def test_get_source_files(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build_clib(dist)
+
+        # "in 'libraries' option 'sources' must be present and must be
+        # a list of source filenames
+        cmd.libraries = [('name', {})]
+        with pytest.raises(DistutilsSetupError):
+            cmd.get_source_files()
+
+        cmd.libraries = [('name', {'sources': 1})]
+        with pytest.raises(DistutilsSetupError):
+            cmd.get_source_files()
+
+        cmd.libraries = [('name', {'sources': ['a', 'b']})]
+        assert cmd.get_source_files() == ['a', 'b']
+
+        cmd.libraries = [('name', {'sources': ('a', 'b')})]
+        assert cmd.get_source_files() == ['a', 'b']
+
+        cmd.libraries = [
+            ('name', {'sources': ('a', 'b')}),
+            ('name2', {'sources': ['c', 'd']}),
+        ]
+        assert cmd.get_source_files() == ['a', 'b', 'c', 'd']
+
+    def test_build_libraries(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build_clib(dist)
+
+        class FakeCompiler:
+            def compile(*args, **kw):
+                pass
+
+            create_static_lib = compile
+
+        cmd.compiler = FakeCompiler()
+
+        # build_libraries is also doing a bit of typo checking
+        lib = [('name', {'sources': 'notvalid'})]
+        with pytest.raises(DistutilsSetupError):
+            cmd.build_libraries(lib)
+
+        lib = [('name', {'sources': list()})]
+        cmd.build_libraries(lib)
+
+        lib = [('name', {'sources': tuple()})]
+        cmd.build_libraries(lib)
+
+    def test_finalize_options(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build_clib(dist)
+
+        cmd.include_dirs = 'one-dir'
+        cmd.finalize_options()
+        assert cmd.include_dirs == ['one-dir']
+
+        cmd.include_dirs = None
+        cmd.finalize_options()
+        assert cmd.include_dirs == []
+
+        cmd.distribution.libraries = 'WONTWORK'
+        with pytest.raises(DistutilsSetupError):
+            cmd.finalize_options()
+
+    @pytest.mark.skipif('platform.system() == "Windows"')
+    def test_run(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = build_clib(dist)
+
+        foo_c = os.path.join(pkg_dir, 'foo.c')
+        self.write_file(foo_c, 'int main(void) { return 1;}\n')
+        cmd.libraries = [('foo', {'sources': [foo_c]})]
+
+        build_temp = os.path.join(pkg_dir, 'build')
+        os.mkdir(build_temp)
+        cmd.build_temp = build_temp
+        cmd.build_clib = build_temp
+
+        # Before we run the command, we want to make sure
+        # all commands are present on the system.
+        ccmd = missing_compiler_executable()
+        if ccmd is not None:
+            self.skipTest(f'The {ccmd!r} command is not found')
+
+        # this should work
+        cmd.run()
+
+        # let's check the result
+        assert 'libfoo.a' in os.listdir(build_temp)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_ext.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_ext.py
new file mode 100644
index 0000000000000000000000000000000000000000..dab0507f3d3ec104fb4acfe5b15f92661ff33a37
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_ext.py
@@ -0,0 +1,628 @@
+import contextlib
+import glob
+import importlib
+import os.path
+import platform
+import re
+import shutil
+import site
+import subprocess
+import sys
+import tempfile
+import textwrap
+import time
+from distutils import sysconfig
+from distutils.command.build_ext import build_ext
+from distutils.core import Distribution
+from distutils.errors import (
+    CompileError,
+    DistutilsPlatformError,
+    DistutilsSetupError,
+    UnknownFileError,
+)
+from distutils.extension import Extension
+from distutils.tests import missing_compiler_executable
+from distutils.tests.support import TempdirManager, copy_xxmodule_c, fixup_build_ext
+from io import StringIO
+
+import jaraco.path
+import path
+import pytest
+from test import support
+
+from .compat import py39 as import_helper
+
+
+@pytest.fixture()
+def user_site_dir(request):
+    self = request.instance
+    self.tmp_dir = self.mkdtemp()
+    self.tmp_path = path.Path(self.tmp_dir)
+    from distutils.command import build_ext
+
+    orig_user_base = site.USER_BASE
+
+    site.USER_BASE = self.mkdtemp()
+    build_ext.USER_BASE = site.USER_BASE
+
+    # bpo-30132: On Windows, a .pdb file may be created in the current
+    # working directory. Create a temporary working directory to cleanup
+    # everything at the end of the test.
+    with self.tmp_path:
+        yield
+
+    site.USER_BASE = orig_user_base
+    build_ext.USER_BASE = orig_user_base
+
+    if sys.platform == 'cygwin':
+        time.sleep(1)
+
+
+@contextlib.contextmanager
+def safe_extension_import(name, path):
+    with import_helper.CleanImport(name):
+        with extension_redirect(name, path) as new_path:
+            with import_helper.DirsOnSysPath(new_path):
+                yield
+
+
+@contextlib.contextmanager
+def extension_redirect(mod, path):
+    """
+    Tests will fail to tear down an extension module if it's been imported.
+
+    Before importing, copy the file to a temporary directory that won't
+    be cleaned up. Yield the new path.
+    """
+    if platform.system() != "Windows" and sys.platform != "cygwin":
+        yield path
+        return
+    with import_helper.DirsOnSysPath(path):
+        spec = importlib.util.find_spec(mod)
+    filename = os.path.basename(spec.origin)
+    trash_dir = tempfile.mkdtemp(prefix='deleteme')
+    dest = os.path.join(trash_dir, os.path.basename(filename))
+    shutil.copy(spec.origin, dest)
+    yield trash_dir
+    # TODO: can the file be scheduled for deletion?
+
+
+@pytest.mark.usefixtures('user_site_dir')
+class TestBuildExt(TempdirManager):
+    def build_ext(self, *args, **kwargs):
+        return build_ext(*args, **kwargs)
+
+    @pytest.mark.parametrize("copy_so", [False])
+    def test_build_ext(self, copy_so):
+        missing_compiler_executable()
+        copy_xxmodule_c(self.tmp_dir)
+        xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
+        xx_ext = Extension('xx', [xx_c])
+        if sys.platform != "win32":
+            if not copy_so:
+                xx_ext = Extension(
+                    'xx',
+                    [xx_c],
+                    library_dirs=['/usr/lib'],
+                    libraries=['z'],
+                    runtime_library_dirs=['/usr/lib'],
+                )
+            elif sys.platform == 'linux':
+                libz_so = {
+                    os.path.realpath(name) for name in glob.iglob('/usr/lib*/libz.so*')
+                }
+                libz_so = sorted(libz_so, key=lambda lib_path: len(lib_path))
+                shutil.copyfile(libz_so[-1], '/tmp/libxx_z.so')
+
+                xx_ext = Extension(
+                    'xx',
+                    [xx_c],
+                    library_dirs=['/tmp'],
+                    libraries=['xx_z'],
+                    runtime_library_dirs=['/tmp'],
+                )
+        dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
+        dist.package_dir = self.tmp_dir
+        cmd = self.build_ext(dist)
+        fixup_build_ext(cmd)
+        cmd.build_lib = self.tmp_dir
+        cmd.build_temp = self.tmp_dir
+
+        old_stdout = sys.stdout
+        if not support.verbose:
+            # silence compiler output
+            sys.stdout = StringIO()
+        try:
+            cmd.ensure_finalized()
+            cmd.run()
+        finally:
+            sys.stdout = old_stdout
+
+        with safe_extension_import('xx', self.tmp_dir):
+            self._test_xx(copy_so)
+
+        if sys.platform == 'linux' and copy_so:
+            os.unlink('/tmp/libxx_z.so')
+
+    @staticmethod
+    def _test_xx(copy_so):
+        import xx  # type: ignore[import-not-found] # Module generated for tests
+
+        for attr in ('error', 'foo', 'new', 'roj'):
+            assert hasattr(xx, attr)
+
+        assert xx.foo(2, 5) == 7
+        assert xx.foo(13, 15) == 28
+        assert xx.new().demo() is None
+        if support.HAVE_DOCSTRINGS:
+            doc = 'This is a template module just for instruction.'
+            assert xx.__doc__ == doc
+        assert isinstance(xx.Null(), xx.Null)
+        assert isinstance(xx.Str(), xx.Str)
+
+        if sys.platform == 'linux':
+            so_headers = subprocess.check_output(
+                ["readelf", "-d", xx.__file__], universal_newlines=True
+            )
+            import pprint
+
+            pprint.pprint(so_headers)
+            rpaths = [
+                rpath
+                for line in so_headers.split("\n")
+                if "RPATH" in line or "RUNPATH" in line
+                for rpath in line.split()[2][1:-1].split(":")
+            ]
+            if not copy_so:
+                pprint.pprint(rpaths)
+                # Linked against a library in /usr/lib{,64}
+                assert "/usr/lib" not in rpaths and "/usr/lib64" not in rpaths
+            else:
+                # Linked against a library in /tmp
+                assert "/tmp" in rpaths
+                # The import is the real test here
+
+    def test_solaris_enable_shared(self):
+        dist = Distribution({'name': 'xx'})
+        cmd = self.build_ext(dist)
+        old = sys.platform
+
+        sys.platform = 'sunos'  # fooling finalize_options
+        from distutils.sysconfig import _config_vars
+
+        old_var = _config_vars.get('Py_ENABLE_SHARED')
+        _config_vars['Py_ENABLE_SHARED'] = True
+        try:
+            cmd.ensure_finalized()
+        finally:
+            sys.platform = old
+            if old_var is None:
+                del _config_vars['Py_ENABLE_SHARED']
+            else:
+                _config_vars['Py_ENABLE_SHARED'] = old_var
+
+        # make sure we get some library dirs under solaris
+        assert len(cmd.library_dirs) > 0
+
+    def test_user_site(self):
+        import site
+
+        dist = Distribution({'name': 'xx'})
+        cmd = self.build_ext(dist)
+
+        # making sure the user option is there
+        options = [name for name, short, label in cmd.user_options]
+        assert 'user' in options
+
+        # setting a value
+        cmd.user = True
+
+        # setting user based lib and include
+        lib = os.path.join(site.USER_BASE, 'lib')
+        incl = os.path.join(site.USER_BASE, 'include')
+        os.mkdir(lib)
+        os.mkdir(incl)
+
+        # let's run finalize
+        cmd.ensure_finalized()
+
+        # see if include_dirs and library_dirs
+        # were set
+        assert lib in cmd.library_dirs
+        assert lib in cmd.rpath
+        assert incl in cmd.include_dirs
+
+    def test_optional_extension(self):
+        # this extension will fail, but let's ignore this failure
+        # with the optional argument.
+        modules = [Extension('foo', ['xxx'], optional=False)]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        with pytest.raises((UnknownFileError, CompileError)):
+            cmd.run()  # should raise an error
+
+        modules = [Extension('foo', ['xxx'], optional=True)]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        cmd.run()  # should pass
+
+    def test_finalize_options(self):
+        # Make sure Python's include directories (for Python.h, pyconfig.h,
+        # etc.) are in the include search path.
+        modules = [Extension('foo', ['xxx'], optional=False)]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.finalize_options()
+
+        py_include = sysconfig.get_python_inc()
+        for p in py_include.split(os.path.pathsep):
+            assert p in cmd.include_dirs
+
+        plat_py_include = sysconfig.get_python_inc(plat_specific=True)
+        for p in plat_py_include.split(os.path.pathsep):
+            assert p in cmd.include_dirs
+
+        # make sure cmd.libraries is turned into a list
+        # if it's a string
+        cmd = self.build_ext(dist)
+        cmd.libraries = 'my_lib, other_lib lastlib'
+        cmd.finalize_options()
+        assert cmd.libraries == ['my_lib', 'other_lib', 'lastlib']
+
+        # make sure cmd.library_dirs is turned into a list
+        # if it's a string
+        cmd = self.build_ext(dist)
+        cmd.library_dirs = f'my_lib_dir{os.pathsep}other_lib_dir'
+        cmd.finalize_options()
+        assert 'my_lib_dir' in cmd.library_dirs
+        assert 'other_lib_dir' in cmd.library_dirs
+
+        # make sure rpath is turned into a list
+        # if it's a string
+        cmd = self.build_ext(dist)
+        cmd.rpath = f'one{os.pathsep}two'
+        cmd.finalize_options()
+        assert cmd.rpath == ['one', 'two']
+
+        # make sure cmd.link_objects is turned into a list
+        # if it's a string
+        cmd = build_ext(dist)
+        cmd.link_objects = 'one two,three'
+        cmd.finalize_options()
+        assert cmd.link_objects == ['one', 'two', 'three']
+
+        # XXX more tests to perform for win32
+
+        # make sure define is turned into 2-tuples
+        # strings if they are ','-separated strings
+        cmd = self.build_ext(dist)
+        cmd.define = 'one,two'
+        cmd.finalize_options()
+        assert cmd.define == [('one', '1'), ('two', '1')]
+
+        # make sure undef is turned into a list of
+        # strings if they are ','-separated strings
+        cmd = self.build_ext(dist)
+        cmd.undef = 'one,two'
+        cmd.finalize_options()
+        assert cmd.undef == ['one', 'two']
+
+        # make sure swig_opts is turned into a list
+        cmd = self.build_ext(dist)
+        cmd.swig_opts = None
+        cmd.finalize_options()
+        assert cmd.swig_opts == []
+
+        cmd = self.build_ext(dist)
+        cmd.swig_opts = '1 2'
+        cmd.finalize_options()
+        assert cmd.swig_opts == ['1', '2']
+
+    def test_check_extensions_list(self):
+        dist = Distribution()
+        cmd = self.build_ext(dist)
+        cmd.finalize_options()
+
+        # 'extensions' option must be a list of Extension instances
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_extensions_list('foo')
+
+        # each element of 'ext_modules' option must be an
+        # Extension instance or 2-tuple
+        exts = [('bar', 'foo', 'bar'), 'foo']
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_extensions_list(exts)
+
+        # first element of each tuple in 'ext_modules'
+        # must be the extension name (a string) and match
+        # a python dotted-separated name
+        exts = [('foo-bar', '')]
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_extensions_list(exts)
+
+        # second element of each tuple in 'ext_modules'
+        # must be a dictionary (build info)
+        exts = [('foo.bar', '')]
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_extensions_list(exts)
+
+        # ok this one should pass
+        exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})]
+        cmd.check_extensions_list(exts)
+        ext = exts[0]
+        assert isinstance(ext, Extension)
+
+        # check_extensions_list adds in ext the values passed
+        # when they are in ('include_dirs', 'library_dirs', 'libraries'
+        # 'extra_objects', 'extra_compile_args', 'extra_link_args')
+        assert ext.libraries == 'foo'
+        assert not hasattr(ext, 'some')
+
+        # 'macros' element of build info dict must be 1- or 2-tuple
+        exts = [
+            (
+                'foo.bar',
+                {
+                    'sources': [''],
+                    'libraries': 'foo',
+                    'some': 'bar',
+                    'macros': [('1', '2', '3'), 'foo'],
+                },
+            )
+        ]
+        with pytest.raises(DistutilsSetupError):
+            cmd.check_extensions_list(exts)
+
+        exts[0][1]['macros'] = [('1', '2'), ('3',)]
+        cmd.check_extensions_list(exts)
+        assert exts[0].undef_macros == ['3']
+        assert exts[0].define_macros == [('1', '2')]
+
+    def test_get_source_files(self):
+        modules = [Extension('foo', ['xxx'], optional=False)]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        assert cmd.get_source_files() == ['xxx']
+
+    def test_unicode_module_names(self):
+        modules = [
+            Extension('foo', ['aaa'], optional=False),
+            Extension('föö', ['uuu'], optional=False),
+        ]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        assert re.search(r'foo(_d)?\..*', cmd.get_ext_filename(modules[0].name))
+        assert re.search(r'föö(_d)?\..*', cmd.get_ext_filename(modules[1].name))
+        assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
+        assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
+
+    def test_export_symbols__init__(self):
+        # https://github.com/python/cpython/issues/80074
+        # https://github.com/pypa/setuptools/issues/4826
+        modules = [
+            Extension('foo.__init__', ['aaa']),
+            Extension('föö.__init__', ['uuu']),
+        ]
+        dist = Distribution({'name': 'xx', 'ext_modules': modules})
+        cmd = self.build_ext(dist)
+        cmd.ensure_finalized()
+        assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
+        assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
+
+    def test_compiler_option(self):
+        # cmd.compiler is an option and
+        # should not be overridden by a compiler instance
+        # when the command is run
+        dist = Distribution()
+        cmd = self.build_ext(dist)
+        cmd.compiler = 'unix'
+        cmd.ensure_finalized()
+        cmd.run()
+        assert cmd.compiler == 'unix'
+
+    def test_get_outputs(self):
+        missing_compiler_executable()
+        tmp_dir = self.mkdtemp()
+        c_file = os.path.join(tmp_dir, 'foo.c')
+        self.write_file(c_file, 'void PyInit_foo(void) {}\n')
+        ext = Extension('foo', [c_file], optional=False)
+        dist = Distribution({'name': 'xx', 'ext_modules': [ext]})
+        cmd = self.build_ext(dist)
+        fixup_build_ext(cmd)
+        cmd.ensure_finalized()
+        assert len(cmd.get_outputs()) == 1
+
+        cmd.build_lib = os.path.join(self.tmp_dir, 'build')
+        cmd.build_temp = os.path.join(self.tmp_dir, 'tempt')
+
+        # issue #5977 : distutils build_ext.get_outputs
+        # returns wrong result with --inplace
+        other_tmp_dir = os.path.realpath(self.mkdtemp())
+        old_wd = os.getcwd()
+        os.chdir(other_tmp_dir)
+        try:
+            cmd.inplace = True
+            cmd.run()
+            so_file = cmd.get_outputs()[0]
+        finally:
+            os.chdir(old_wd)
+        assert os.path.exists(so_file)
+        ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
+        assert so_file.endswith(ext_suffix)
+        so_dir = os.path.dirname(so_file)
+        assert so_dir == other_tmp_dir
+
+        cmd.inplace = False
+        cmd.compiler = None
+        cmd.run()
+        so_file = cmd.get_outputs()[0]
+        assert os.path.exists(so_file)
+        assert so_file.endswith(ext_suffix)
+        so_dir = os.path.dirname(so_file)
+        assert so_dir == cmd.build_lib
+
+        # inplace = False, cmd.package = 'bar'
+        build_py = cmd.get_finalized_command('build_py')
+        build_py.package_dir = {'': 'bar'}
+        path = cmd.get_ext_fullpath('foo')
+        # checking that the last directory is the build_dir
+        path = os.path.split(path)[0]
+        assert path == cmd.build_lib
+
+        # inplace = True, cmd.package = 'bar'
+        cmd.inplace = True
+        other_tmp_dir = os.path.realpath(self.mkdtemp())
+        old_wd = os.getcwd()
+        os.chdir(other_tmp_dir)
+        try:
+            path = cmd.get_ext_fullpath('foo')
+        finally:
+            os.chdir(old_wd)
+        # checking that the last directory is bar
+        path = os.path.split(path)[0]
+        lastdir = os.path.split(path)[-1]
+        assert lastdir == 'bar'
+
+    def test_ext_fullpath(self):
+        ext = sysconfig.get_config_var('EXT_SUFFIX')
+        # building lxml.etree inplace
+        # etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
+        # etree_ext = Extension('lxml.etree', [etree_c])
+        # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
+        dist = Distribution()
+        cmd = self.build_ext(dist)
+        cmd.inplace = True
+        cmd.distribution.package_dir = {'': 'src'}
+        cmd.distribution.packages = ['lxml', 'lxml.html']
+        curdir = os.getcwd()
+        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
+        path = cmd.get_ext_fullpath('lxml.etree')
+        assert wanted == path
+
+        # building lxml.etree not inplace
+        cmd.inplace = False
+        cmd.build_lib = os.path.join(curdir, 'tmpdir')
+        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
+        path = cmd.get_ext_fullpath('lxml.etree')
+        assert wanted == path
+
+        # building twisted.runner.portmap not inplace
+        build_py = cmd.get_finalized_command('build_py')
+        build_py.package_dir = {}
+        cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
+        path = cmd.get_ext_fullpath('twisted.runner.portmap')
+        wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext)
+        assert wanted == path
+
+        # building twisted.runner.portmap inplace
+        cmd.inplace = True
+        path = cmd.get_ext_fullpath('twisted.runner.portmap')
+        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
+        assert wanted == path
+
+    @pytest.mark.skipif('platform.system() != "Darwin"')
+    @pytest.mark.usefixtures('save_env')
+    def test_deployment_target_default(self):
+        # Issue 9516: Test that, in the absence of the environment variable,
+        # an extension module is compiled with the same deployment target as
+        #  the interpreter.
+        self._try_compile_deployment_target('==', None)
+
+    @pytest.mark.skipif('platform.system() != "Darwin"')
+    @pytest.mark.usefixtures('save_env')
+    def test_deployment_target_too_low(self):
+        # Issue 9516: Test that an extension module is not allowed to be
+        # compiled with a deployment target less than that of the interpreter.
+        with pytest.raises(DistutilsPlatformError):
+            self._try_compile_deployment_target('>', '10.1')
+
+    @pytest.mark.skipif('platform.system() != "Darwin"')
+    @pytest.mark.usefixtures('save_env')
+    def test_deployment_target_higher_ok(self):  # pragma: no cover
+        # Issue 9516: Test that an extension module can be compiled with a
+        # deployment target higher than that of the interpreter: the ext
+        # module may depend on some newer OS feature.
+        deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
+        if deptarget:
+            # increment the minor version number (i.e. 10.6 -> 10.7)
+            deptarget = [int(x) for x in deptarget.split('.')]
+            deptarget[-1] += 1
+            deptarget = '.'.join(str(i) for i in deptarget)
+            self._try_compile_deployment_target('<', deptarget)
+
+    def _try_compile_deployment_target(self, operator, target):  # pragma: no cover
+        if target is None:
+            if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
+                del os.environ['MACOSX_DEPLOYMENT_TARGET']
+        else:
+            os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
+
+        jaraco.path.build(
+            {
+                'deptargetmodule.c': textwrap.dedent(f"""\
+                    #include 
+
+                    int dummy;
+
+                    #if TARGET {operator} MAC_OS_X_VERSION_MIN_REQUIRED
+                    #else
+                    #error "Unexpected target"
+                    #endif
+
+                    """),
+            },
+            self.tmp_path,
+        )
+
+        # get the deployment target that the interpreter was built with
+        target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
+        target = tuple(map(int, target.split('.')[0:2]))
+        # format the target value as defined in the Apple
+        # Availability Macros.  We can't use the macro names since
+        # at least one value we test with will not exist yet.
+        if target[:2] < (10, 10):
+            # for 10.1 through 10.9.x -> "10n0"
+            tmpl = '{:02}{:01}0'
+        else:
+            # for 10.10 and beyond -> "10nn00"
+            if len(target) >= 2:
+                tmpl = '{:02}{:02}00'
+            else:
+                # 11 and later can have no minor version (11 instead of 11.0)
+                tmpl = '{:02}0000'
+        target = tmpl.format(*target)
+        deptarget_ext = Extension(
+            'deptarget',
+            [self.tmp_path / 'deptargetmodule.c'],
+            extra_compile_args=[f'-DTARGET={target}'],
+        )
+        dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]})
+        dist.package_dir = self.tmp_dir
+        cmd = self.build_ext(dist)
+        cmd.build_lib = self.tmp_dir
+        cmd.build_temp = self.tmp_dir
+
+        try:
+            old_stdout = sys.stdout
+            if not support.verbose:
+                # silence compiler output
+                sys.stdout = StringIO()
+            try:
+                cmd.ensure_finalized()
+                cmd.run()
+            finally:
+                sys.stdout = old_stdout
+
+        except CompileError:
+            self.fail("Wrong deployment target during compilation")
+
+
+class TestParallelBuildExt(TestBuildExt):
+    def build_ext(self, *args, **kwargs):
+        build_ext = super().build_ext(*args, **kwargs)
+        build_ext.parallel = True
+        return build_ext
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_py.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..b316ed43a11836210caeb7177bd8890a1f61d1bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_py.py
@@ -0,0 +1,196 @@
+"""Tests for distutils.command.build_py."""
+
+import os
+import sys
+from distutils.command.build_py import build_py
+from distutils.core import Distribution
+from distutils.errors import DistutilsFileError
+from distutils.tests import support
+
+import jaraco.path
+import pytest
+
+
+@support.combine_markers
+class TestBuildPy(support.TempdirManager):
+    def test_package_data(self):
+        sources = self.mkdtemp()
+        jaraco.path.build(
+            {
+                '__init__.py': "# Pretend this is a package.",
+                'README.txt': 'Info about this package',
+            },
+            sources,
+        )
+
+        destination = self.mkdtemp()
+
+        dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}})
+        # script_name need not exist, it just need to be initialized
+        dist.script_name = os.path.join(sources, "setup.py")
+        dist.command_obj["build"] = support.DummyCommand(
+            force=False, build_lib=destination
+        )
+        dist.packages = ["pkg"]
+        dist.package_data = {"pkg": ["README.txt"]}
+        dist.package_dir = {"pkg": sources}
+
+        cmd = build_py(dist)
+        cmd.compile = True
+        cmd.ensure_finalized()
+        assert cmd.package_data == dist.package_data
+
+        cmd.run()
+
+        # This makes sure the list of outputs includes byte-compiled
+        # files for Python modules but not for package data files
+        # (there shouldn't *be* byte-code files for those!).
+        assert len(cmd.get_outputs()) == 3
+        pkgdest = os.path.join(destination, "pkg")
+        files = os.listdir(pkgdest)
+        pycache_dir = os.path.join(pkgdest, "__pycache__")
+        assert "__init__.py" in files
+        assert "README.txt" in files
+        if sys.dont_write_bytecode:
+            assert not os.path.exists(pycache_dir)
+        else:
+            pyc_files = os.listdir(pycache_dir)
+            assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files
+
+    def test_empty_package_dir(self):
+        # See bugs #1668596/#1720897
+        sources = self.mkdtemp()
+        jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources)
+
+        os.chdir(sources)
+        dist = Distribution({
+            "packages": ["pkg"],
+            "package_dir": {"pkg": ""},
+            "package_data": {"pkg": ["doc/*"]},
+        })
+        # script_name need not exist, it just need to be initialized
+        dist.script_name = os.path.join(sources, "setup.py")
+        dist.script_args = ["build"]
+        dist.parse_command_line()
+
+        try:
+            dist.run_commands()
+        except DistutilsFileError:
+            self.fail("failed package_data test when package_dir is ''")
+
+    @pytest.mark.skipif('sys.dont_write_bytecode')
+    def test_byte_compile(self):
+        project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
+        os.chdir(project_dir)
+        self.write_file('boiledeggs.py', 'import antigravity')
+        cmd = build_py(dist)
+        cmd.compile = True
+        cmd.build_lib = 'here'
+        cmd.finalize_options()
+        cmd.run()
+
+        found = os.listdir(cmd.build_lib)
+        assert sorted(found) == ['__pycache__', 'boiledeggs.py']
+        found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
+        assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc']
+
+    @pytest.mark.skipif('sys.dont_write_bytecode')
+    def test_byte_compile_optimized(self):
+        project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
+        os.chdir(project_dir)
+        self.write_file('boiledeggs.py', 'import antigravity')
+        cmd = build_py(dist)
+        cmd.compile = False
+        cmd.optimize = 1
+        cmd.build_lib = 'here'
+        cmd.finalize_options()
+        cmd.run()
+
+        found = os.listdir(cmd.build_lib)
+        assert sorted(found) == ['__pycache__', 'boiledeggs.py']
+        found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
+        expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc'
+        assert sorted(found) == [expect]
+
+    def test_dir_in_package_data(self):
+        """
+        A directory in package_data should not be added to the filelist.
+        """
+        # See bug 19286
+        sources = self.mkdtemp()
+        jaraco.path.build(
+            {
+                'pkg': {
+                    '__init__.py': '',
+                    'doc': {
+                        'testfile': '',
+                        # create a directory that could be incorrectly detected as a file
+                        'otherdir': {},
+                    },
+                }
+            },
+            sources,
+        )
+
+        os.chdir(sources)
+        dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}})
+        # script_name need not exist, it just need to be initialized
+        dist.script_name = os.path.join(sources, "setup.py")
+        dist.script_args = ["build"]
+        dist.parse_command_line()
+
+        try:
+            dist.run_commands()
+        except DistutilsFileError:
+            self.fail("failed package_data when data dir includes a dir")
+
+    def test_dont_write_bytecode(self, caplog):
+        # makes sure byte_compile is not used
+        dist = self.create_dist()[1]
+        cmd = build_py(dist)
+        cmd.compile = True
+        cmd.optimize = 1
+
+        old_dont_write_bytecode = sys.dont_write_bytecode
+        sys.dont_write_bytecode = True
+        try:
+            cmd.byte_compile([])
+        finally:
+            sys.dont_write_bytecode = old_dont_write_bytecode
+
+        assert 'byte-compiling is disabled' in caplog.records[0].message
+
+    def test_namespace_package_does_not_warn(self, caplog):
+        """
+        Originally distutils implementation did not account for PEP 420
+        and included warns for package directories that did not contain
+        ``__init__.py`` files.
+        After the acceptance of PEP 420, these warnings don't make more sense
+        so we want to ensure there are not displayed to not confuse the users.
+        """
+        # Create a fake project structure with a package namespace:
+        tmp = self.mkdtemp()
+        jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp)
+        os.chdir(tmp)
+
+        # Configure the package:
+        attrs = {
+            "name": "ns.pkg",
+            "packages": ["ns", "ns.pkg"],
+            "script_name": "setup.py",
+        }
+        dist = Distribution(attrs)
+
+        # Run code paths that would trigger the trap:
+        cmd = dist.get_command_obj("build_py")
+        cmd.finalize_options()
+        modules = cmd.find_all_modules()
+        assert len(modules) == 1
+        module_path = modules[0][-1]
+        assert module_path.replace(os.sep, "/") == "ns/pkg/module.py"
+
+        cmd.run()
+
+        assert not any(
+            "package init file" in msg and "not found" in msg for msg in caplog.messages
+        )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_scripts.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_scripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..3582f691ef578a419555c6ffbba6a619310517a6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_build_scripts.py
@@ -0,0 +1,96 @@
+"""Tests for distutils.command.build_scripts."""
+
+import os
+import textwrap
+from distutils import sysconfig
+from distutils.command.build_scripts import build_scripts
+from distutils.core import Distribution
+from distutils.tests import support
+
+import jaraco.path
+
+
+class TestBuildScripts(support.TempdirManager):
+    def test_default_settings(self):
+        cmd = self.get_build_scripts_cmd("/foo/bar", [])
+        assert not cmd.force
+        assert cmd.build_dir is None
+
+        cmd.finalize_options()
+
+        assert cmd.force
+        assert cmd.build_dir == "/foo/bar"
+
+    def test_build(self):
+        source = self.mkdtemp()
+        target = self.mkdtemp()
+        expected = self.write_sample_scripts(source)
+
+        cmd = self.get_build_scripts_cmd(
+            target, [os.path.join(source, fn) for fn in expected]
+        )
+        cmd.finalize_options()
+        cmd.run()
+
+        built = os.listdir(target)
+        for name in expected:
+            assert name in built
+
+    def get_build_scripts_cmd(self, target, scripts):
+        import sys
+
+        dist = Distribution()
+        dist.scripts = scripts
+        dist.command_obj["build"] = support.DummyCommand(
+            build_scripts=target, force=True, executable=sys.executable
+        )
+        return build_scripts(dist)
+
+    @staticmethod
+    def write_sample_scripts(dir):
+        spec = {
+            'script1.py': textwrap.dedent("""
+                #! /usr/bin/env python2.3
+                # bogus script w/ Python sh-bang
+                pass
+                """).lstrip(),
+            'script2.py': textwrap.dedent("""
+                #!/usr/bin/python
+                # bogus script w/ Python sh-bang
+                pass
+                """).lstrip(),
+            'shell.sh': textwrap.dedent("""
+                #!/bin/sh
+                # bogus shell script w/ sh-bang
+                exit 0
+                """).lstrip(),
+        }
+        jaraco.path.build(spec, dir)
+        return list(spec)
+
+    def test_version_int(self):
+        source = self.mkdtemp()
+        target = self.mkdtemp()
+        expected = self.write_sample_scripts(source)
+
+        cmd = self.get_build_scripts_cmd(
+            target, [os.path.join(source, fn) for fn in expected]
+        )
+        cmd.finalize_options()
+
+        # https://bugs.python.org/issue4524
+        #
+        # On linux-g++-32 with command line `./configure --enable-ipv6
+        # --with-suffix=3`, python is compiled okay but the build scripts
+        # failed when writing the name of the executable
+        old = sysconfig.get_config_vars().get('VERSION')
+        sysconfig._config_vars['VERSION'] = 4
+        try:
+            cmd.run()
+        finally:
+            if old is not None:
+                sysconfig._config_vars['VERSION'] = old
+
+        built = os.listdir(target)
+        for name in expected:
+            assert name in built
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_check.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..b672b1f972b46f399eb5b2ef263da2548d52ef89
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_check.py
@@ -0,0 +1,194 @@
+"""Tests for distutils.command.check."""
+
+import os
+import textwrap
+from distutils.command.check import check
+from distutils.errors import DistutilsSetupError
+from distutils.tests import support
+
+import pytest
+
+try:
+    import pygments
+except ImportError:
+    pygments = None
+
+
+HERE = os.path.dirname(__file__)
+
+
+@support.combine_markers
+class TestCheck(support.TempdirManager):
+    def _run(self, metadata=None, cwd=None, **options):
+        if metadata is None:
+            metadata = {}
+        if cwd is not None:
+            old_dir = os.getcwd()
+            os.chdir(cwd)
+        pkg_info, dist = self.create_dist(**metadata)
+        cmd = check(dist)
+        cmd.initialize_options()
+        for name, value in options.items():
+            setattr(cmd, name, value)
+        cmd.ensure_finalized()
+        cmd.run()
+        if cwd is not None:
+            os.chdir(old_dir)
+        return cmd
+
+    def test_check_metadata(self):
+        # let's run the command with no metadata at all
+        # by default, check is checking the metadata
+        # should have some warnings
+        cmd = self._run()
+        assert cmd._warnings == 1
+
+        # now let's add the required fields
+        # and run it again, to make sure we don't get
+        # any warning anymore
+        metadata = {
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+            'name': 'xxx',
+            'version': 'xxx',
+        }
+        cmd = self._run(metadata)
+        assert cmd._warnings == 0
+
+        # now with the strict mode, we should
+        # get an error if there are missing metadata
+        with pytest.raises(DistutilsSetupError):
+            self._run({}, **{'strict': 1})
+
+        # and of course, no error when all metadata are present
+        cmd = self._run(metadata, strict=True)
+        assert cmd._warnings == 0
+
+        # now a test with non-ASCII characters
+        metadata = {
+            'url': 'xxx',
+            'author': '\u00c9ric',
+            'author_email': 'xxx',
+            'name': 'xxx',
+            'version': 'xxx',
+            'description': 'Something about esszet \u00df',
+            'long_description': 'More things about esszet \u00df',
+        }
+        cmd = self._run(metadata)
+        assert cmd._warnings == 0
+
+    def test_check_author_maintainer(self):
+        for kind in ("author", "maintainer"):
+            # ensure no warning when author_email or maintainer_email is given
+            # (the spec allows these fields to take the form "Name ")
+            metadata = {
+                'url': 'xxx',
+                kind + '_email': 'Name ',
+                'name': 'xxx',
+                'version': 'xxx',
+            }
+            cmd = self._run(metadata)
+            assert cmd._warnings == 0
+
+            # the check should not warn if only email is given
+            metadata[kind + '_email'] = 'name@email.com'
+            cmd = self._run(metadata)
+            assert cmd._warnings == 0
+
+            # the check should not warn if only the name is given
+            metadata[kind] = "Name"
+            del metadata[kind + '_email']
+            cmd = self._run(metadata)
+            assert cmd._warnings == 0
+
+    def test_check_document(self):
+        pytest.importorskip('docutils')
+        pkg_info, dist = self.create_dist()
+        cmd = check(dist)
+
+        # let's see if it detects broken rest
+        broken_rest = 'title\n===\n\ntest'
+        msgs = cmd._check_rst_data(broken_rest)
+        assert len(msgs) == 1
+
+        # and non-broken rest
+        rest = 'title\n=====\n\ntest'
+        msgs = cmd._check_rst_data(rest)
+        assert len(msgs) == 0
+
+    def test_check_restructuredtext(self):
+        pytest.importorskip('docutils')
+        # let's see if it detects broken rest in long_description
+        broken_rest = 'title\n===\n\ntest'
+        pkg_info, dist = self.create_dist(long_description=broken_rest)
+        cmd = check(dist)
+        cmd.check_restructuredtext()
+        assert cmd._warnings == 1
+
+        # let's see if we have an error with strict=True
+        metadata = {
+            'url': 'xxx',
+            'author': 'xxx',
+            'author_email': 'xxx',
+            'name': 'xxx',
+            'version': 'xxx',
+            'long_description': broken_rest,
+        }
+        with pytest.raises(DistutilsSetupError):
+            self._run(metadata, **{'strict': 1, 'restructuredtext': 1})
+
+        # and non-broken rest, including a non-ASCII character to test #12114
+        metadata['long_description'] = 'title\n=====\n\ntest \u00df'
+        cmd = self._run(metadata, strict=True, restructuredtext=True)
+        assert cmd._warnings == 0
+
+        # check that includes work to test #31292
+        metadata['long_description'] = 'title\n=====\n\n.. include:: includetest.rst'
+        cmd = self._run(metadata, cwd=HERE, strict=True, restructuredtext=True)
+        assert cmd._warnings == 0
+
+    def test_check_restructuredtext_with_syntax_highlight(self):
+        pytest.importorskip('docutils')
+        # Don't fail if there is a `code` or `code-block` directive
+
+        example_rst_docs = [
+            textwrap.dedent(
+                """\
+            Here's some code:
+
+            .. code:: python
+
+                def foo():
+                    pass
+            """
+            ),
+            textwrap.dedent(
+                """\
+            Here's some code:
+
+            .. code-block:: python
+
+                def foo():
+                    pass
+            """
+            ),
+        ]
+
+        for rest_with_code in example_rst_docs:
+            pkg_info, dist = self.create_dist(long_description=rest_with_code)
+            cmd = check(dist)
+            cmd.check_restructuredtext()
+            msgs = cmd._check_rst_data(rest_with_code)
+            if pygments is not None:
+                assert len(msgs) == 0
+            else:
+                assert len(msgs) == 1
+                assert (
+                    str(msgs[0][1])
+                    == 'Cannot analyze code. Pygments package not found.'
+                )
+
+    def test_check_all(self):
+        with pytest.raises(DistutilsSetupError):
+            self._run({}, **{'strict': 1, 'restructuredtext': 1})
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_clean.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_clean.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc78f30f34b323845b977b9147c2153390774bd3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_clean.py
@@ -0,0 +1,45 @@
+"""Tests for distutils.command.clean."""
+
+import os
+from distutils.command.clean import clean
+from distutils.tests import support
+
+
+class TestClean(support.TempdirManager):
+    def test_simple_run(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = clean(dist)
+
+        # let's add some elements clean should remove
+        dirs = [
+            (d, os.path.join(pkg_dir, d))
+            for d in (
+                'build_temp',
+                'build_lib',
+                'bdist_base',
+                'build_scripts',
+                'build_base',
+            )
+        ]
+
+        for name, path in dirs:
+            os.mkdir(path)
+            setattr(cmd, name, path)
+            if name == 'build_base':
+                continue
+            for f in ('one', 'two', 'three'):
+                self.write_file(os.path.join(path, f))
+
+        # let's run the command
+        cmd.all = 1
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # make sure the files where removed
+        for _name, path in dirs:
+            assert not os.path.exists(path), f'{path} was not removed'
+
+        # let's run the command again (should spit warnings but succeed)
+        cmd.all = 1
+        cmd.ensure_finalized()
+        cmd.run()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_cmd.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e8f5989b3b102a32239436ff3b65f26e09e029
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_cmd.py
@@ -0,0 +1,107 @@
+"""Tests for distutils.cmd."""
+
+import os
+from distutils import debug
+from distutils.cmd import Command
+from distutils.dist import Distribution
+from distutils.errors import DistutilsOptionError
+
+import pytest
+
+
+class MyCmd(Command):
+    def initialize_options(self):
+        pass
+
+
+@pytest.fixture
+def cmd(request):
+    return MyCmd(Distribution())
+
+
+class TestCommand:
+    def test_ensure_string_list(self, cmd):
+        cmd.not_string_list = ['one', 2, 'three']
+        cmd.yes_string_list = ['one', 'two', 'three']
+        cmd.not_string_list2 = object()
+        cmd.yes_string_list2 = 'ok'
+        cmd.ensure_string_list('yes_string_list')
+        cmd.ensure_string_list('yes_string_list2')
+
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_string_list('not_string_list')
+
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_string_list('not_string_list2')
+
+        cmd.option1 = 'ok,dok'
+        cmd.ensure_string_list('option1')
+        assert cmd.option1 == ['ok', 'dok']
+
+        cmd.option2 = ['xxx', 'www']
+        cmd.ensure_string_list('option2')
+
+        cmd.option3 = ['ok', 2]
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_string_list('option3')
+
+    def test_make_file(self, cmd):
+        # making sure it raises when infiles is not a string or a list/tuple
+        with pytest.raises(TypeError):
+            cmd.make_file(infiles=True, outfile='', func='func', args=())
+
+        # making sure execute gets called properly
+        def _execute(func, args, exec_msg, level):
+            assert exec_msg == 'generating out from in'
+
+        cmd.force = True
+        cmd.execute = _execute
+        cmd.make_file(infiles='in', outfile='out', func='func', args=())
+
+    def test_dump_options(self, cmd):
+        msgs = []
+
+        def _announce(msg, level):
+            msgs.append(msg)
+
+        cmd.announce = _announce
+        cmd.option1 = 1
+        cmd.option2 = 1
+        cmd.user_options = [('option1', '', ''), ('option2', '', '')]
+        cmd.dump_options()
+
+        wanted = ["command options for 'MyCmd':", '  option1 = 1', '  option2 = 1']
+        assert msgs == wanted
+
+    def test_ensure_string(self, cmd):
+        cmd.option1 = 'ok'
+        cmd.ensure_string('option1')
+
+        cmd.option2 = None
+        cmd.ensure_string('option2', 'xxx')
+        assert hasattr(cmd, 'option2')
+
+        cmd.option3 = 1
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_string('option3')
+
+    def test_ensure_filename(self, cmd):
+        cmd.option1 = __file__
+        cmd.ensure_filename('option1')
+        cmd.option2 = 'xxx'
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_filename('option2')
+
+    def test_ensure_dirname(self, cmd):
+        cmd.option1 = os.path.dirname(__file__) or os.curdir
+        cmd.ensure_dirname('option1')
+        cmd.option2 = 'xxx'
+        with pytest.raises(DistutilsOptionError):
+            cmd.ensure_dirname('option2')
+
+    def test_debug_print(self, cmd, capsys, monkeypatch):
+        cmd.debug_print('xxx')
+        assert capsys.readouterr().out == ''
+        monkeypatch.setattr(debug, 'DEBUG', True)
+        cmd.debug_print('xxx')
+        assert capsys.readouterr().out == 'xxx\n'
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_config_cmd.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_config_cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebee2ef93f0bc9d422984e2e4872665b1be3a1de
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_config_cmd.py
@@ -0,0 +1,87 @@
+"""Tests for distutils.command.config."""
+
+import os
+import sys
+from distutils._log import log
+from distutils.command.config import config, dump_file
+from distutils.tests import missing_compiler_executable, support
+
+import more_itertools
+import path
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def info_log(request, monkeypatch):
+    self = request.instance
+    self._logs = []
+    monkeypatch.setattr(log, 'info', self._info)
+
+
+@support.combine_markers
+class TestConfig(support.TempdirManager):
+    def _info(self, msg, *args):
+        for line in msg.splitlines():
+            self._logs.append(line)
+
+    def test_dump_file(self):
+        this_file = path.Path(__file__).with_suffix('.py')
+        with this_file.open(encoding='utf-8') as f:
+            numlines = more_itertools.ilen(f)
+
+        dump_file(this_file, 'I am the header')
+        assert len(self._logs) == numlines + 1
+
+    @pytest.mark.skipif('platform.system() == "Windows"')
+    def test_search_cpp(self):
+        cmd = missing_compiler_executable(['preprocessor'])
+        if cmd is not None:
+            self.skipTest(f'The {cmd!r} command is not found')
+        pkg_dir, dist = self.create_dist()
+        cmd = config(dist)
+        cmd._check_compiler()
+        compiler = cmd.compiler
+        if sys.platform[:3] == "aix" and "xlc" in compiler.preprocessor[0].lower():
+            self.skipTest(
+                'xlc: The -E option overrides the -P, -o, and -qsyntaxonly options'
+            )
+
+        # simple pattern searches
+        match = cmd.search_cpp(pattern='xxx', body='/* xxx */')
+        assert match == 0
+
+        match = cmd.search_cpp(pattern='_configtest', body='/* xxx */')
+        assert match == 1
+
+    def test_finalize_options(self):
+        # finalize_options does a bit of transformation
+        # on options
+        pkg_dir, dist = self.create_dist()
+        cmd = config(dist)
+        cmd.include_dirs = f'one{os.pathsep}two'
+        cmd.libraries = 'one'
+        cmd.library_dirs = f'three{os.pathsep}four'
+        cmd.ensure_finalized()
+
+        assert cmd.include_dirs == ['one', 'two']
+        assert cmd.libraries == ['one']
+        assert cmd.library_dirs == ['three', 'four']
+
+    def test_clean(self):
+        # _clean removes files
+        tmp_dir = self.mkdtemp()
+        f1 = os.path.join(tmp_dir, 'one')
+        f2 = os.path.join(tmp_dir, 'two')
+
+        self.write_file(f1, 'xxx')
+        self.write_file(f2, 'xxx')
+
+        for f in (f1, f2):
+            assert os.path.exists(f)
+
+        pkg_dir, dist = self.create_dist()
+        cmd = config(dist)
+        cmd._clean(f1, f2)
+
+        for f in (f1, f2):
+            assert not os.path.exists(f)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_core.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..bad3fb7e8318d3ee73ecabe20ed98c279f606a77
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_core.py
@@ -0,0 +1,130 @@
+"""Tests for distutils.core."""
+
+import distutils.core
+import io
+import os
+import sys
+from distutils.dist import Distribution
+
+import pytest
+
+# setup script that uses __file__
+setup_using___file__ = """\
+
+__file__
+
+from distutils.core import setup
+setup()
+"""
+
+setup_prints_cwd = """\
+
+import os
+print(os.getcwd())
+
+from distutils.core import setup
+setup()
+"""
+
+setup_does_nothing = """\
+from distutils.core import setup
+setup()
+"""
+
+
+setup_defines_subclass = """\
+from distutils.core import setup
+from distutils.command.install import install as _install
+
+class install(_install):
+    sub_commands = _install.sub_commands + ['cmd']
+
+setup(cmdclass={'install': install})
+"""
+
+setup_within_if_main = """\
+from distutils.core import setup
+
+def main():
+    return setup(name="setup_within_if_main")
+
+if __name__ == "__main__":
+    main()
+"""
+
+
+@pytest.fixture(autouse=True)
+def save_stdout(monkeypatch):
+    monkeypatch.setattr(sys, 'stdout', sys.stdout)
+
+
+@pytest.fixture
+def temp_file(tmp_path):
+    return tmp_path / 'file'
+
+
+@pytest.mark.usefixtures('save_env')
+@pytest.mark.usefixtures('save_argv')
+class TestCore:
+    def test_run_setup_provides_file(self, temp_file):
+        # Make sure the script can use __file__; if that's missing, the test
+        # setup.py script will raise NameError.
+        temp_file.write_text(setup_using___file__, encoding='utf-8')
+        distutils.core.run_setup(temp_file)
+
+    def test_run_setup_preserves_sys_argv(self, temp_file):
+        # Make sure run_setup does not clobber sys.argv
+        argv_copy = sys.argv.copy()
+        temp_file.write_text(setup_does_nothing, encoding='utf-8')
+        distutils.core.run_setup(temp_file)
+        assert sys.argv == argv_copy
+
+    def test_run_setup_defines_subclass(self, temp_file):
+        # Make sure the script can use __file__; if that's missing, the test
+        # setup.py script will raise NameError.
+        temp_file.write_text(setup_defines_subclass, encoding='utf-8')
+        dist = distutils.core.run_setup(temp_file)
+        install = dist.get_command_obj('install')
+        assert 'cmd' in install.sub_commands
+
+    def test_run_setup_uses_current_dir(self, tmp_path):
+        """
+        Test that the setup script is run with the current directory
+        as its own current directory.
+        """
+        sys.stdout = io.StringIO()
+        cwd = os.getcwd()
+
+        # Create a directory and write the setup.py file there:
+        setup_py = tmp_path / 'setup.py'
+        setup_py.write_text(setup_prints_cwd, encoding='utf-8')
+        distutils.core.run_setup(setup_py)
+
+        output = sys.stdout.getvalue()
+        if output.endswith("\n"):
+            output = output[:-1]
+        assert cwd == output
+
+    def test_run_setup_within_if_main(self, temp_file):
+        temp_file.write_text(setup_within_if_main, encoding='utf-8')
+        dist = distutils.core.run_setup(temp_file, stop_after="config")
+        assert isinstance(dist, Distribution)
+        assert dist.get_name() == "setup_within_if_main"
+
+    def test_run_commands(self, temp_file):
+        sys.argv = ['setup.py', 'build']
+        temp_file.write_text(setup_within_if_main, encoding='utf-8')
+        dist = distutils.core.run_setup(temp_file, stop_after="commandline")
+        assert 'build' not in dist.have_run
+        distutils.core.run_commands(dist)
+        assert 'build' in dist.have_run
+
+    def test_debug_mode(self, capsys, monkeypatch):
+        # this covers the code called when DEBUG is set
+        sys.argv = ['setup.py', '--name']
+        distutils.core.setup(name='bar')
+        assert capsys.readouterr().out == 'bar\n'
+        monkeypatch.setattr(distutils.core, 'DEBUG', True)
+        distutils.core.setup(name='bar')
+        wanted = "options (after parsing config files):\n"
+        assert capsys.readouterr().out.startswith(wanted)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dir_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dir_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..326cb346145ec7e3a1dd0384c33d4125131feaae
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dir_util.py
@@ -0,0 +1,139 @@
+"""Tests for distutils.dir_util."""
+
+import os
+import pathlib
+import stat
+import sys
+import unittest.mock as mock
+from distutils import dir_util, errors
+from distutils.dir_util import (
+    copy_tree,
+    create_tree,
+    ensure_relative,
+    mkpath,
+    remove_tree,
+)
+from distutils.tests import support
+
+import jaraco.path
+import path
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def stuff(request, monkeypatch, distutils_managed_tempdir):
+    self = request.instance
+    tmp_dir = self.mkdtemp()
+    self.root_target = os.path.join(tmp_dir, 'deep')
+    self.target = os.path.join(self.root_target, 'here')
+    self.target2 = os.path.join(tmp_dir, 'deep2')
+
+
+class TestDirUtil(support.TempdirManager):
+    def test_mkpath_remove_tree_verbosity(self, caplog):
+        mkpath(self.target, verbose=False)
+        assert not caplog.records
+        remove_tree(self.root_target, verbose=False)
+
+        mkpath(self.target, verbose=True)
+        wanted = [f'creating {self.target}']
+        assert caplog.messages == wanted
+        caplog.clear()
+
+        remove_tree(self.root_target, verbose=True)
+        wanted = [f"removing '{self.root_target}' (and everything under it)"]
+        assert caplog.messages == wanted
+
+    @pytest.mark.skipif("platform.system() == 'Windows'")
+    def test_mkpath_with_custom_mode(self):
+        # Get and set the current umask value for testing mode bits.
+        umask = os.umask(0o002)
+        os.umask(umask)
+        mkpath(self.target, 0o700)
+        assert stat.S_IMODE(os.stat(self.target).st_mode) == 0o700 & ~umask
+        mkpath(self.target2, 0o555)
+        assert stat.S_IMODE(os.stat(self.target2).st_mode) == 0o555 & ~umask
+
+    def test_create_tree_verbosity(self, caplog):
+        create_tree(self.root_target, ['one', 'two', 'three'], verbose=False)
+        assert caplog.messages == []
+        remove_tree(self.root_target, verbose=False)
+
+        wanted = [f'creating {self.root_target}']
+        create_tree(self.root_target, ['one', 'two', 'three'], verbose=True)
+        assert caplog.messages == wanted
+
+        remove_tree(self.root_target, verbose=False)
+
+    def test_copy_tree_verbosity(self, caplog):
+        mkpath(self.target, verbose=False)
+
+        copy_tree(self.target, self.target2, verbose=False)
+        assert caplog.messages == []
+
+        remove_tree(self.root_target, verbose=False)
+
+        mkpath(self.target, verbose=False)
+        a_file = path.Path(self.target) / 'ok.txt'
+        jaraco.path.build({'ok.txt': 'some content'}, self.target)
+
+        wanted = [f'copying {a_file} -> {self.target2}']
+        copy_tree(self.target, self.target2, verbose=True)
+        assert caplog.messages == wanted
+
+        remove_tree(self.root_target, verbose=False)
+        remove_tree(self.target2, verbose=False)
+
+    def test_copy_tree_skips_nfs_temp_files(self):
+        mkpath(self.target, verbose=False)
+
+        jaraco.path.build({'ok.txt': 'some content', '.nfs123abc': ''}, self.target)
+
+        copy_tree(self.target, self.target2)
+        assert os.listdir(self.target2) == ['ok.txt']
+
+        remove_tree(self.root_target, verbose=False)
+        remove_tree(self.target2, verbose=False)
+
+    def test_ensure_relative(self):
+        if os.sep == '/':
+            assert ensure_relative('/home/foo') == 'home/foo'
+            assert ensure_relative('some/path') == 'some/path'
+        else:  # \\
+            assert ensure_relative('c:\\home\\foo') == 'c:home\\foo'
+            assert ensure_relative('home\\foo') == 'home\\foo'
+
+    def test_copy_tree_exception_in_listdir(self):
+        """
+        An exception in listdir should raise a DistutilsFileError
+        """
+        with (
+            mock.patch("os.listdir", side_effect=OSError()),
+            pytest.raises(errors.DistutilsFileError),
+        ):
+            src = self.tempdirs[-1]
+            dir_util.copy_tree(src, None)
+
+    def test_mkpath_exception_uncached(self, monkeypatch, tmp_path):
+        """
+        Caching should not remember failed attempts.
+
+        pypa/distutils#304
+        """
+
+        class FailPath(pathlib.Path):
+            def mkdir(self, *args, **kwargs):
+                raise OSError("Failed to create directory")
+
+            if sys.version_info < (3, 12):
+                _flavour = pathlib.Path()._flavour
+
+        target = tmp_path / 'foodir'
+
+        with pytest.raises(errors.DistutilsFileError):
+            mkpath(FailPath(target))
+
+        assert not target.exists()
+
+        mkpath(target)
+        assert target.exists()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c5beebe64eb9d747088cf117082a546330b29f3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_dist.py
@@ -0,0 +1,552 @@
+"""Tests for distutils.dist."""
+
+import email
+import email.generator
+import email.policy
+import functools
+import io
+import os
+import sys
+import textwrap
+import unittest.mock as mock
+import warnings
+from distutils.cmd import Command
+from distutils.dist import Distribution, fix_help_options
+from distutils.tests import support
+from typing import ClassVar
+
+import jaraco.path
+import pytest
+
+pydistutils_cfg = '.' * (os.name == 'posix') + 'pydistutils.cfg'
+
+
+class test_dist(Command):
+    """Sample distutils extension command."""
+
+    user_options: ClassVar[list[tuple[str, str, str]]] = [
+        ("sample-option=", "S", "help text"),
+    ]
+
+    def initialize_options(self):
+        self.sample_option = None
+
+
+class TestDistribution(Distribution):
+    """Distribution subclasses that avoids the default search for
+    configuration files.
+
+    The ._config_files attribute must be set before
+    .parse_config_files() is called.
+    """
+
+    def find_config_files(self):
+        return self._config_files
+
+
+@pytest.fixture
+def clear_argv():
+    del sys.argv[1:]
+
+
+@support.combine_markers
+@pytest.mark.usefixtures('save_env')
+@pytest.mark.usefixtures('save_argv')
+class TestDistributionBehavior(support.TempdirManager):
+    def create_distribution(self, configfiles=()):
+        d = TestDistribution()
+        d._config_files = configfiles
+        d.parse_config_files()
+        d.parse_command_line()
+        return d
+
+    def test_command_packages_unspecified(self, clear_argv):
+        sys.argv.append("build")
+        d = self.create_distribution()
+        assert d.get_command_packages() == ["distutils.command"]
+
+    def test_command_packages_cmdline(self, clear_argv):
+        from distutils.tests.test_dist import test_dist
+
+        sys.argv.extend([
+            "--command-packages",
+            "foo.bar,distutils.tests",
+            "test_dist",
+            "-Ssometext",
+        ])
+        d = self.create_distribution()
+        # let's actually try to load our test command:
+        assert d.get_command_packages() == [
+            "distutils.command",
+            "foo.bar",
+            "distutils.tests",
+        ]
+        cmd = d.get_command_obj("test_dist")
+        assert isinstance(cmd, test_dist)
+        assert cmd.sample_option == "sometext"
+
+    @pytest.mark.skipif(
+        'distutils' not in Distribution.parse_config_files.__module__,
+        reason='Cannot test when virtualenv has monkey-patched Distribution',
+    )
+    def test_venv_install_options(self, tmp_path, clear_argv):
+        sys.argv.append("install")
+        file = str(tmp_path / 'file')
+
+        fakepath = '/somedir'
+
+        jaraco.path.build({
+            file: f"""
+                    [install]
+                    install-base = {fakepath}
+                    install-platbase = {fakepath}
+                    install-lib = {fakepath}
+                    install-platlib = {fakepath}
+                    install-purelib = {fakepath}
+                    install-headers = {fakepath}
+                    install-scripts = {fakepath}
+                    install-data = {fakepath}
+                    prefix = {fakepath}
+                    exec-prefix = {fakepath}
+                    home = {fakepath}
+                    user = {fakepath}
+                    root = {fakepath}
+                    """,
+        })
+
+        # Base case: Not in a Virtual Environment
+        with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'):
+            d = self.create_distribution([file])
+
+        option_tuple = (file, fakepath)
+
+        result_dict = {
+            'install_base': option_tuple,
+            'install_platbase': option_tuple,
+            'install_lib': option_tuple,
+            'install_platlib': option_tuple,
+            'install_purelib': option_tuple,
+            'install_headers': option_tuple,
+            'install_scripts': option_tuple,
+            'install_data': option_tuple,
+            'prefix': option_tuple,
+            'exec_prefix': option_tuple,
+            'home': option_tuple,
+            'user': option_tuple,
+            'root': option_tuple,
+        }
+
+        assert sorted(d.command_options.get('install').keys()) == sorted(
+            result_dict.keys()
+        )
+
+        for key, value in d.command_options.get('install').items():
+            assert value == result_dict[key]
+
+        # Test case: In a Virtual Environment
+        with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'):
+            d = self.create_distribution([file])
+
+        for key in result_dict.keys():
+            assert key not in d.command_options.get('install', {})
+
+    def test_command_packages_configfile(self, tmp_path, clear_argv):
+        sys.argv.append("build")
+        file = str(tmp_path / "file")
+        jaraco.path.build({
+            file: """
+                    [global]
+                    command_packages = foo.bar, splat
+                    """,
+        })
+
+        d = self.create_distribution([file])
+        assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"]
+
+        # ensure command line overrides config:
+        sys.argv[1:] = ["--command-packages", "spork", "build"]
+        d = self.create_distribution([file])
+        assert d.get_command_packages() == ["distutils.command", "spork"]
+
+        # Setting --command-packages to '' should cause the default to
+        # be used even if a config file specified something else:
+        sys.argv[1:] = ["--command-packages", "", "build"]
+        d = self.create_distribution([file])
+        assert d.get_command_packages() == ["distutils.command"]
+
+    def test_empty_options(self, request):
+        # an empty options dictionary should not stay in the
+        # list of attributes
+
+        # catching warnings
+        warns = []
+
+        def _warn(msg):
+            warns.append(msg)
+
+        request.addfinalizer(
+            functools.partial(setattr, warnings, 'warn', warnings.warn)
+        )
+        warnings.warn = _warn
+        dist = Distribution(
+            attrs={
+                'author': 'xxx',
+                'name': 'xxx',
+                'version': 'xxx',
+                'url': 'xxxx',
+                'options': {},
+            }
+        )
+
+        assert len(warns) == 0
+        assert 'options' not in dir(dist)
+
+    def test_finalize_options(self):
+        attrs = {'keywords': 'one,two', 'platforms': 'one,two'}
+
+        dist = Distribution(attrs=attrs)
+        dist.finalize_options()
+
+        # finalize_option splits platforms and keywords
+        assert dist.metadata.platforms == ['one', 'two']
+        assert dist.metadata.keywords == ['one', 'two']
+
+        attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'}
+        dist = Distribution(attrs=attrs)
+        dist.finalize_options()
+        assert dist.metadata.platforms == ['foo bar']
+        assert dist.metadata.keywords == ['foo bar']
+
+    def test_get_command_packages(self):
+        dist = Distribution()
+        assert dist.command_packages is None
+        cmds = dist.get_command_packages()
+        assert cmds == ['distutils.command']
+        assert dist.command_packages == ['distutils.command']
+
+        dist.command_packages = 'one,two'
+        cmds = dist.get_command_packages()
+        assert cmds == ['distutils.command', 'one', 'two']
+
+    def test_announce(self):
+        # make sure the level is known
+        dist = Distribution()
+        with pytest.raises(TypeError):
+            dist.announce('ok', level='ok2')
+
+    def test_find_config_files_disable(self, temp_home):
+        # Ticket #1180: Allow user to disable their home config file.
+        jaraco.path.build({pydistutils_cfg: '[distutils]\n'}, temp_home)
+
+        d = Distribution()
+        all_files = d.find_config_files()
+
+        d = Distribution(attrs={'script_args': ['--no-user-cfg']})
+        files = d.find_config_files()
+
+        # make sure --no-user-cfg disables the user cfg file
+        assert len(all_files) - 1 == len(files)
+
+    def test_script_args_list_coercion(self):
+        d = Distribution(attrs={'script_args': ('build', '--no-user-cfg')})
+
+        # make sure script_args is a list even if it started as a different iterable
+        assert d.script_args == ['build', '--no-user-cfg']
+
+    @pytest.mark.skipif(
+        'platform.system() == "Windows"',
+        reason='Windows does not honor chmod 000',
+    )
+    def test_find_config_files_permission_error(self, fake_home):
+        """
+        Finding config files should not fail when directory is inaccessible.
+        """
+        fake_home.joinpath(pydistutils_cfg).write_text('', encoding='utf-8')
+        fake_home.chmod(0o000)
+        Distribution().find_config_files()
+
+
+@pytest.mark.usefixtures('save_env')
+@pytest.mark.usefixtures('save_argv')
+class TestMetadata(support.TempdirManager):
+    def format_metadata(self, dist):
+        sio = io.StringIO()
+        dist.metadata.write_pkg_file(sio)
+        return sio.getvalue()
+
+    def test_simple_metadata(self):
+        attrs = {"name": "package", "version": "1.0"}
+        dist = Distribution(attrs)
+        meta = self.format_metadata(dist)
+        assert "Metadata-Version: 1.0" in meta
+        assert "provides:" not in meta.lower()
+        assert "requires:" not in meta.lower()
+        assert "obsoletes:" not in meta.lower()
+
+    def test_provides(self):
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "provides": ["package", "package.sub"],
+        }
+        dist = Distribution(attrs)
+        assert dist.metadata.get_provides() == ["package", "package.sub"]
+        assert dist.get_provides() == ["package", "package.sub"]
+        meta = self.format_metadata(dist)
+        assert "Metadata-Version: 1.1" in meta
+        assert "requires:" not in meta.lower()
+        assert "obsoletes:" not in meta.lower()
+
+    def test_provides_illegal(self):
+        with pytest.raises(ValueError):
+            Distribution(
+                {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},
+            )
+
+    def test_requires(self):
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "requires": ["other", "another (==1.0)"],
+        }
+        dist = Distribution(attrs)
+        assert dist.metadata.get_requires() == ["other", "another (==1.0)"]
+        assert dist.get_requires() == ["other", "another (==1.0)"]
+        meta = self.format_metadata(dist)
+        assert "Metadata-Version: 1.1" in meta
+        assert "provides:" not in meta.lower()
+        assert "Requires: other" in meta
+        assert "Requires: another (==1.0)" in meta
+        assert "obsoletes:" not in meta.lower()
+
+    def test_requires_illegal(self):
+        with pytest.raises(ValueError):
+            Distribution(
+                {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},
+            )
+
+    def test_requires_to_list(self):
+        attrs = {"name": "package", "requires": iter(["other"])}
+        dist = Distribution(attrs)
+        assert isinstance(dist.metadata.requires, list)
+
+    def test_obsoletes(self):
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "obsoletes": ["other", "another (<1.0)"],
+        }
+        dist = Distribution(attrs)
+        assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"]
+        assert dist.get_obsoletes() == ["other", "another (<1.0)"]
+        meta = self.format_metadata(dist)
+        assert "Metadata-Version: 1.1" in meta
+        assert "provides:" not in meta.lower()
+        assert "requires:" not in meta.lower()
+        assert "Obsoletes: other" in meta
+        assert "Obsoletes: another (<1.0)" in meta
+
+    def test_obsoletes_illegal(self):
+        with pytest.raises(ValueError):
+            Distribution(
+                {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},
+            )
+
+    def test_obsoletes_to_list(self):
+        attrs = {"name": "package", "obsoletes": iter(["other"])}
+        dist = Distribution(attrs)
+        assert isinstance(dist.metadata.obsoletes, list)
+
+    def test_classifier(self):
+        attrs = {
+            'name': 'Boa',
+            'version': '3.0',
+            'classifiers': ['Programming Language :: Python :: 3'],
+        }
+        dist = Distribution(attrs)
+        assert dist.get_classifiers() == ['Programming Language :: Python :: 3']
+        meta = self.format_metadata(dist)
+        assert 'Metadata-Version: 1.1' in meta
+
+    def test_classifier_invalid_type(self, caplog):
+        attrs = {
+            'name': 'Boa',
+            'version': '3.0',
+            'classifiers': ('Programming Language :: Python :: 3',),
+        }
+        d = Distribution(attrs)
+        # should have warning about passing a non-list
+        assert 'should be a list' in caplog.messages[0]
+        # should be converted to a list
+        assert isinstance(d.metadata.classifiers, list)
+        assert d.metadata.classifiers == list(attrs['classifiers'])
+
+    def test_keywords(self):
+        attrs = {
+            'name': 'Monty',
+            'version': '1.0',
+            'keywords': ['spam', 'eggs', 'life of brian'],
+        }
+        dist = Distribution(attrs)
+        assert dist.get_keywords() == ['spam', 'eggs', 'life of brian']
+
+    def test_keywords_invalid_type(self, caplog):
+        attrs = {
+            'name': 'Monty',
+            'version': '1.0',
+            'keywords': ('spam', 'eggs', 'life of brian'),
+        }
+        d = Distribution(attrs)
+        # should have warning about passing a non-list
+        assert 'should be a list' in caplog.messages[0]
+        # should be converted to a list
+        assert isinstance(d.metadata.keywords, list)
+        assert d.metadata.keywords == list(attrs['keywords'])
+
+    def test_platforms(self):
+        attrs = {
+            'name': 'Monty',
+            'version': '1.0',
+            'platforms': ['GNU/Linux', 'Some Evil Platform'],
+        }
+        dist = Distribution(attrs)
+        assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform']
+
+    def test_platforms_invalid_types(self, caplog):
+        attrs = {
+            'name': 'Monty',
+            'version': '1.0',
+            'platforms': ('GNU/Linux', 'Some Evil Platform'),
+        }
+        d = Distribution(attrs)
+        # should have warning about passing a non-list
+        assert 'should be a list' in caplog.messages[0]
+        # should be converted to a list
+        assert isinstance(d.metadata.platforms, list)
+        assert d.metadata.platforms == list(attrs['platforms'])
+
+    def test_download_url(self):
+        attrs = {
+            'name': 'Boa',
+            'version': '3.0',
+            'download_url': 'http://example.org/boa',
+        }
+        dist = Distribution(attrs)
+        meta = self.format_metadata(dist)
+        assert 'Metadata-Version: 1.1' in meta
+
+    def test_long_description(self):
+        long_desc = textwrap.dedent(
+            """\
+        example::
+              We start here
+            and continue here
+          and end here."""
+        )
+        attrs = {"name": "package", "version": "1.0", "long_description": long_desc}
+
+        dist = Distribution(attrs)
+        meta = self.format_metadata(dist)
+        meta = meta.replace('\n' + 8 * ' ', '\n')
+        assert long_desc in meta
+
+    def test_custom_pydistutils(self, temp_home):
+        """
+        pydistutils.cfg is found
+        """
+        jaraco.path.build({pydistutils_cfg: ''}, temp_home)
+        config_path = temp_home / pydistutils_cfg
+
+        assert str(config_path) in Distribution().find_config_files()
+
+    def test_extra_pydistutils(self, monkeypatch, tmp_path):
+        jaraco.path.build({'overrides.cfg': ''}, tmp_path)
+        filename = tmp_path / 'overrides.cfg'
+        monkeypatch.setenv('DIST_EXTRA_CONFIG', str(filename))
+        assert str(filename) in Distribution().find_config_files()
+
+    def test_fix_help_options(self):
+        help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
+        fancy_options = fix_help_options(help_tuples)
+        assert fancy_options[0] == ('a', 'b', 'c')
+        assert fancy_options[1] == (1, 2, 3)
+
+    def test_show_help(self, request, capsys):
+        # smoke test, just makes sure some help is displayed
+        dist = Distribution()
+        sys.argv = []
+        dist.help = True
+        dist.script_name = 'setup.py'
+        dist.parse_command_line()
+
+        output = [
+            line for line in capsys.readouterr().out.split('\n') if line.strip() != ''
+        ]
+        assert output
+
+    def test_read_metadata(self):
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "long_description": "desc",
+            "description": "xxx",
+            "download_url": "http://example.com",
+            "keywords": ['one', 'two'],
+            "requires": ['foo'],
+        }
+
+        dist = Distribution(attrs)
+        metadata = dist.metadata
+
+        # write it then reloads it
+        PKG_INFO = io.StringIO()
+        metadata.write_pkg_file(PKG_INFO)
+        PKG_INFO.seek(0)
+        metadata.read_pkg_file(PKG_INFO)
+
+        assert metadata.name == "package"
+        assert metadata.version == "1.0"
+        assert metadata.description == "xxx"
+        assert metadata.download_url == 'http://example.com'
+        assert metadata.keywords == ['one', 'two']
+        assert metadata.platforms is None
+        assert metadata.obsoletes is None
+        assert metadata.requires == ['foo']
+
+    def test_round_trip_through_email_generator(self):
+        """
+        In pypa/setuptools#4033, it was shown that once PKG-INFO is
+        re-generated using ``email.generator.Generator``, some control
+        characters might cause problems.
+        """
+        # Given a PKG-INFO file ...
+        attrs = {
+            "name": "package",
+            "version": "1.0",
+            "long_description": "hello\x0b\nworld\n",
+        }
+        dist = Distribution(attrs)
+        metadata = dist.metadata
+
+        with io.StringIO() as buffer:
+            metadata.write_pkg_file(buffer)
+            msg = buffer.getvalue()
+
+        # ... when it is read and re-written using stdlib's email library,
+        orig = email.message_from_string(msg)
+        policy = email.policy.EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with io.StringIO() as buffer:
+            email.generator.Generator(buffer, policy=policy).flatten(orig)
+
+            buffer.seek(0)
+            regen = email.message_from_file(buffer)
+
+        # ... then it should be the same as the original
+        # (except for the specific line break characters)
+        orig_desc = set(orig["Description"].splitlines())
+        regen_desc = set(regen["Description"].splitlines())
+        assert regen_desc == orig_desc
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_extension.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_extension.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e8e768223ea40d7a629111db181a946cf8ca5b0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_extension.py
@@ -0,0 +1,117 @@
+"""Tests for distutils.extension."""
+
+import os
+import pathlib
+import warnings
+from distutils.extension import Extension, read_setup_file
+
+import pytest
+from test.support.warnings_helper import check_warnings
+
+
+class TestExtension:
+    def test_read_setup_file(self):
+        # trying to read a Setup file
+        # (sample extracted from the PyGame project)
+        setup = os.path.join(os.path.dirname(__file__), 'Setup.sample')
+
+        exts = read_setup_file(setup)
+        names = [ext.name for ext in exts]
+        names.sort()
+
+        # here are the extensions read_setup_file should have created
+        # out of the file
+        wanted = [
+            '_arraysurfarray',
+            '_camera',
+            '_numericsndarray',
+            '_numericsurfarray',
+            'base',
+            'bufferproxy',
+            'cdrom',
+            'color',
+            'constants',
+            'display',
+            'draw',
+            'event',
+            'fastevent',
+            'font',
+            'gfxdraw',
+            'image',
+            'imageext',
+            'joystick',
+            'key',
+            'mask',
+            'mixer',
+            'mixer_music',
+            'mouse',
+            'movie',
+            'overlay',
+            'pixelarray',
+            'pypm',
+            'rect',
+            'rwobject',
+            'scrap',
+            'surface',
+            'surflock',
+            'time',
+            'transform',
+        ]
+
+        assert names == wanted
+
+    def test_extension_init(self):
+        # the first argument, which is the name, must be a string
+        with pytest.raises(TypeError):
+            Extension(1, [])
+        ext = Extension('name', [])
+        assert ext.name == 'name'
+
+        # the second argument, which is the list of files, must
+        # be an iterable of strings or PathLike objects, and not a string
+        with pytest.raises(TypeError):
+            Extension('name', 'file')
+        with pytest.raises(TypeError):
+            Extension('name', ['file', 1])
+        ext = Extension('name', ['file1', 'file2'])
+        assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', [pathlib.Path('file1'), pathlib.Path('file2')])
+        assert ext.sources == ['file1', 'file2']
+
+        # any non-string iterable of strings or PathLike objects should work
+        ext = Extension('name', ('file1', 'file2'))  # tuple
+        assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', {'file1', 'file2'})  # set
+        assert sorted(ext.sources) == ['file1', 'file2']
+        ext = Extension('name', iter(['file1', 'file2']))  # iterator
+        assert ext.sources == ['file1', 'file2']
+        ext = Extension('name', [pathlib.Path('file1'), 'file2'])  # mixed types
+        assert ext.sources == ['file1', 'file2']
+
+        # others arguments have defaults
+        for attr in (
+            'include_dirs',
+            'define_macros',
+            'undef_macros',
+            'library_dirs',
+            'libraries',
+            'runtime_library_dirs',
+            'extra_objects',
+            'extra_compile_args',
+            'extra_link_args',
+            'export_symbols',
+            'swig_opts',
+            'depends',
+        ):
+            assert getattr(ext, attr) == []
+
+        assert ext.language is None
+        assert ext.optional is None
+
+        # if there are unknown keyword options, warn about them
+        with check_warnings() as w:
+            warnings.simplefilter('always')
+            ext = Extension('name', ['file1', 'file2'], chic=True)
+
+        assert len(w.warnings) == 1
+        assert str(w.warnings[0].message) == "Unknown Extension options: 'chic'"
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_file_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_file_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..a75d4a0317dc717c24f67127370aa87089eeba1a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_file_util.py
@@ -0,0 +1,95 @@
+"""Tests for distutils.file_util."""
+
+import errno
+import os
+import unittest.mock as mock
+from distutils.errors import DistutilsFileError
+from distutils.file_util import copy_file, move_file
+
+import jaraco.path
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def stuff(request, tmp_path):
+    self = request.instance
+    self.source = tmp_path / 'f1'
+    self.target = tmp_path / 'f2'
+    self.target_dir = tmp_path / 'd1'
+
+
+class TestFileUtil:
+    def test_move_file_verbosity(self, caplog):
+        jaraco.path.build({self.source: 'some content'})
+
+        move_file(self.source, self.target, verbose=False)
+        assert not caplog.messages
+
+        # back to original state
+        move_file(self.target, self.source, verbose=False)
+
+        move_file(self.source, self.target, verbose=True)
+        wanted = [f'moving {self.source} -> {self.target}']
+        assert caplog.messages == wanted
+
+        # back to original state
+        move_file(self.target, self.source, verbose=False)
+
+        caplog.clear()
+        # now the target is a dir
+        os.mkdir(self.target_dir)
+        move_file(self.source, self.target_dir, verbose=True)
+        wanted = [f'moving {self.source} -> {self.target_dir}']
+        assert caplog.messages == wanted
+
+    def test_move_file_exception_unpacking_rename(self):
+        # see issue 22182
+        with (
+            mock.patch("os.rename", side_effect=OSError("wrong", 1)),
+            pytest.raises(DistutilsFileError),
+        ):
+            jaraco.path.build({self.source: 'spam eggs'})
+            move_file(self.source, self.target, verbose=False)
+
+    def test_move_file_exception_unpacking_unlink(self):
+        # see issue 22182
+        with (
+            mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")),
+            mock.patch("os.unlink", side_effect=OSError("wrong", 1)),
+            pytest.raises(DistutilsFileError),
+        ):
+            jaraco.path.build({self.source: 'spam eggs'})
+            move_file(self.source, self.target, verbose=False)
+
+    def test_copy_file_hard_link(self):
+        jaraco.path.build({self.source: 'some content'})
+        # Check first that copy_file() will not fall back on copying the file
+        # instead of creating the hard link.
+        try:
+            os.link(self.source, self.target)
+        except OSError as e:
+            self.skipTest(f'os.link: {e}')
+        else:
+            self.target.unlink()
+        st = os.stat(self.source)
+        copy_file(self.source, self.target, link='hard')
+        st2 = os.stat(self.source)
+        st3 = os.stat(self.target)
+        assert os.path.samestat(st, st2), (st, st2)
+        assert os.path.samestat(st2, st3), (st2, st3)
+        assert self.source.read_text(encoding='utf-8') == 'some content'
+
+    def test_copy_file_hard_link_failure(self):
+        # If hard linking fails, copy_file() falls back on copying file
+        # (some special filesystems don't support hard linking even under
+        #  Unix, see issue #8876).
+        jaraco.path.build({self.source: 'some content'})
+        st = os.stat(self.source)
+        with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")):
+            copy_file(self.source, self.target, link='hard')
+        st2 = os.stat(self.source)
+        st3 = os.stat(self.target)
+        assert os.path.samestat(st, st2), (st, st2)
+        assert not os.path.samestat(st2, st3), (st2, st3)
+        for fn in (self.source, self.target):
+            assert fn.read_text(encoding='utf-8') == 'some content'
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_filelist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_filelist.py
new file mode 100644
index 0000000000000000000000000000000000000000..130e6fb53b0bd9670bdcfe6d4bc7fcf8fd90416e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_filelist.py
@@ -0,0 +1,336 @@
+"""Tests for distutils.filelist."""
+
+import logging
+import os
+import re
+from distutils import debug, filelist
+from distutils.errors import DistutilsTemplateError
+from distutils.filelist import FileList, glob_to_re, translate_pattern
+
+import jaraco.path
+import pytest
+
+from .compat import py39 as os_helper
+
+MANIFEST_IN = """\
+include ok
+include xo
+exclude xo
+include foo.tmp
+include buildout.cfg
+global-include *.x
+global-include *.txt
+global-exclude *.tmp
+recursive-include f *.oo
+recursive-exclude global *.x
+graft dir
+prune dir3
+"""
+
+
+def make_local_path(s):
+    """Converts '/' in a string to os.sep"""
+    return s.replace('/', os.sep)
+
+
+class TestFileList:
+    def assertNoWarnings(self, caplog):
+        warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING]
+        assert not warnings
+        caplog.clear()
+
+    def assertWarnings(self, caplog):
+        warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING]
+        assert warnings
+        caplog.clear()
+
+    def test_glob_to_re(self):
+        sep = os.sep
+        if os.sep == '\\':
+            sep = re.escape(os.sep)
+
+        for glob, regex in (
+            # simple cases
+            ('foo*', r'(?s:foo[^%(sep)s]*)\Z'),
+            ('foo?', r'(?s:foo[^%(sep)s])\Z'),
+            ('foo??', r'(?s:foo[^%(sep)s][^%(sep)s])\Z'),
+            # special cases
+            (r'foo\\*', r'(?s:foo\\\\[^%(sep)s]*)\Z'),
+            (r'foo\\\*', r'(?s:foo\\\\\\[^%(sep)s]*)\Z'),
+            ('foo????', r'(?s:foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s])\Z'),
+            (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z'),
+        ):
+            regex = regex % {'sep': sep}
+            assert glob_to_re(glob) == regex
+
+    def test_process_template_line(self):
+        # testing  all MANIFEST.in template patterns
+        file_list = FileList()
+        mlp = make_local_path
+
+        # simulated file list
+        file_list.allfiles = [
+            'foo.tmp',
+            'ok',
+            'xo',
+            'four.txt',
+            'buildout.cfg',
+            # filelist does not filter out VCS directories,
+            # it's sdist that does
+            mlp('.hg/last-message.txt'),
+            mlp('global/one.txt'),
+            mlp('global/two.txt'),
+            mlp('global/files.x'),
+            mlp('global/here.tmp'),
+            mlp('f/o/f.oo'),
+            mlp('dir/graft-one'),
+            mlp('dir/dir2/graft2'),
+            mlp('dir3/ok'),
+            mlp('dir3/sub/ok.txt'),
+        ]
+
+        for line in MANIFEST_IN.split('\n'):
+            if line.strip() == '':
+                continue
+            file_list.process_template_line(line)
+
+        wanted = [
+            'ok',
+            'buildout.cfg',
+            'four.txt',
+            mlp('.hg/last-message.txt'),
+            mlp('global/one.txt'),
+            mlp('global/two.txt'),
+            mlp('f/o/f.oo'),
+            mlp('dir/graft-one'),
+            mlp('dir/dir2/graft2'),
+        ]
+
+        assert file_list.files == wanted
+
+    def test_debug_print(self, capsys, monkeypatch):
+        file_list = FileList()
+        file_list.debug_print('xxx')
+        assert capsys.readouterr().out == ''
+
+        monkeypatch.setattr(debug, 'DEBUG', True)
+        file_list.debug_print('xxx')
+        assert capsys.readouterr().out == 'xxx\n'
+
+    def test_set_allfiles(self):
+        file_list = FileList()
+        files = ['a', 'b', 'c']
+        file_list.set_allfiles(files)
+        assert file_list.allfiles == files
+
+    def test_remove_duplicates(self):
+        file_list = FileList()
+        file_list.files = ['a', 'b', 'a', 'g', 'c', 'g']
+        # files must be sorted beforehand (sdist does it)
+        file_list.sort()
+        file_list.remove_duplicates()
+        assert file_list.files == ['a', 'b', 'c', 'g']
+
+    def test_translate_pattern(self):
+        # not regex
+        assert hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search')
+
+        # is a regex
+        regex = re.compile('a')
+        assert translate_pattern(regex, anchor=True, is_regex=True) == regex
+
+        # plain string flagged as regex
+        assert hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search')
+
+        # glob support
+        assert translate_pattern('*.py', anchor=True, is_regex=False).search(
+            'filelist.py'
+        )
+
+    def test_exclude_pattern(self):
+        # return False if no match
+        file_list = FileList()
+        assert not file_list.exclude_pattern('*.py')
+
+        # return True if files match
+        file_list = FileList()
+        file_list.files = ['a.py', 'b.py']
+        assert file_list.exclude_pattern('*.py')
+
+        # test excludes
+        file_list = FileList()
+        file_list.files = ['a.py', 'a.txt']
+        file_list.exclude_pattern('*.py')
+        assert file_list.files == ['a.txt']
+
+    def test_include_pattern(self):
+        # return False if no match
+        file_list = FileList()
+        file_list.set_allfiles([])
+        assert not file_list.include_pattern('*.py')
+
+        # return True if files match
+        file_list = FileList()
+        file_list.set_allfiles(['a.py', 'b.txt'])
+        assert file_list.include_pattern('*.py')
+
+        # test * matches all files
+        file_list = FileList()
+        assert file_list.allfiles is None
+        file_list.set_allfiles(['a.py', 'b.txt'])
+        file_list.include_pattern('*')
+        assert file_list.allfiles == ['a.py', 'b.txt']
+
+    def test_process_template(self, caplog):
+        mlp = make_local_path
+        # invalid lines
+        file_list = FileList()
+        for action in (
+            'include',
+            'exclude',
+            'global-include',
+            'global-exclude',
+            'recursive-include',
+            'recursive-exclude',
+            'graft',
+            'prune',
+            'blarg',
+        ):
+            with pytest.raises(DistutilsTemplateError):
+                file_list.process_template_line(action)
+
+        # include
+        file_list = FileList()
+        file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
+
+        file_list.process_template_line('include *.py')
+        assert file_list.files == ['a.py']
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('include *.rb')
+        assert file_list.files == ['a.py']
+        self.assertWarnings(caplog)
+
+        # exclude
+        file_list = FileList()
+        file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
+
+        file_list.process_template_line('exclude *.py')
+        assert file_list.files == ['b.txt', mlp('d/c.py')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('exclude *.rb')
+        assert file_list.files == ['b.txt', mlp('d/c.py')]
+        self.assertWarnings(caplog)
+
+        # global-include
+        file_list = FileList()
+        file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
+
+        file_list.process_template_line('global-include *.py')
+        assert file_list.files == ['a.py', mlp('d/c.py')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('global-include *.rb')
+        assert file_list.files == ['a.py', mlp('d/c.py')]
+        self.assertWarnings(caplog)
+
+        # global-exclude
+        file_list = FileList()
+        file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
+
+        file_list.process_template_line('global-exclude *.py')
+        assert file_list.files == ['b.txt']
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('global-exclude *.rb')
+        assert file_list.files == ['b.txt']
+        self.assertWarnings(caplog)
+
+        # recursive-include
+        file_list = FileList()
+        file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')])
+
+        file_list.process_template_line('recursive-include d *.py')
+        assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('recursive-include e *.py')
+        assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
+        self.assertWarnings(caplog)
+
+        # recursive-exclude
+        file_list = FileList()
+        file_list.files = ['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')]
+
+        file_list.process_template_line('recursive-exclude d *.py')
+        assert file_list.files == ['a.py', mlp('d/c.txt')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('recursive-exclude e *.py')
+        assert file_list.files == ['a.py', mlp('d/c.txt')]
+        self.assertWarnings(caplog)
+
+        # graft
+        file_list = FileList()
+        file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')])
+
+        file_list.process_template_line('graft d')
+        assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('graft e')
+        assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
+        self.assertWarnings(caplog)
+
+        # prune
+        file_list = FileList()
+        file_list.files = ['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')]
+
+        file_list.process_template_line('prune d')
+        assert file_list.files == ['a.py', mlp('f/f.py')]
+        self.assertNoWarnings(caplog)
+
+        file_list.process_template_line('prune e')
+        assert file_list.files == ['a.py', mlp('f/f.py')]
+        self.assertWarnings(caplog)
+
+
+class TestFindAll:
+    @os_helper.skip_unless_symlink
+    def test_missing_symlink(self, temp_cwd):
+        os.symlink('foo', 'bar')
+        assert filelist.findall() == []
+
+    def test_basic_discovery(self, temp_cwd):
+        """
+        When findall is called with no parameters or with
+        '.' as the parameter, the dot should be omitted from
+        the results.
+        """
+        jaraco.path.build({'foo': {'file1.txt': ''}, 'bar': {'file2.txt': ''}})
+        file1 = os.path.join('foo', 'file1.txt')
+        file2 = os.path.join('bar', 'file2.txt')
+        expected = [file2, file1]
+        assert sorted(filelist.findall()) == expected
+
+    def test_non_local_discovery(self, tmp_path):
+        """
+        When findall is called with another path, the full
+        path name should be returned.
+        """
+        jaraco.path.build({'file1.txt': ''}, tmp_path)
+        expected = [str(tmp_path / 'file1.txt')]
+        assert filelist.findall(tmp_path) == expected
+
+    @os_helper.skip_unless_symlink
+    def test_symlink_loop(self, tmp_path):
+        jaraco.path.build(
+            {
+                'link-to-parent': jaraco.path.Symlink('.'),
+                'somefile': '',
+            },
+            tmp_path,
+        )
+        files = filelist.findall(tmp_path)
+        assert len(files) == 1
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3ffb2e668ac5a042c5a2889d7b51b5755b73157
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install.py
@@ -0,0 +1,245 @@
+"""Tests for distutils.command.install."""
+
+import logging
+import os
+import pathlib
+import site
+import sys
+from distutils import sysconfig
+from distutils.command import install as install_module
+from distutils.command.build_ext import build_ext
+from distutils.command.install import INSTALL_SCHEMES, install
+from distutils.core import Distribution
+from distutils.errors import DistutilsOptionError
+from distutils.extension import Extension
+from distutils.tests import missing_compiler_executable, support
+from distutils.util import is_mingw
+
+import pytest
+
+
+def _make_ext_name(modname):
+    return modname + sysconfig.get_config_var('EXT_SUFFIX')
+
+
+@support.combine_markers
+@pytest.mark.usefixtures('save_env')
+class TestInstall(
+    support.TempdirManager,
+):
+    @pytest.mark.xfail(
+        'platform.system() == "Windows" and sys.version_info > (3, 11)',
+        reason="pypa/distutils#148",
+    )
+    def test_home_installation_scheme(self):
+        # This ensure two things:
+        # - that --home generates the desired set of directory names
+        # - test --home is supported on all platforms
+        builddir = self.mkdtemp()
+        destination = os.path.join(builddir, "installation")
+
+        dist = Distribution({"name": "foopkg"})
+        # script_name need not exist, it just need to be initialized
+        dist.script_name = os.path.join(builddir, "setup.py")
+        dist.command_obj["build"] = support.DummyCommand(
+            build_base=builddir,
+            build_lib=os.path.join(builddir, "lib"),
+        )
+
+        cmd = install(dist)
+        cmd.home = destination
+        cmd.ensure_finalized()
+
+        assert cmd.install_base == destination
+        assert cmd.install_platbase == destination
+
+        def check_path(got, expected):
+            got = os.path.normpath(got)
+            expected = os.path.normpath(expected)
+            assert got == expected
+
+        impl_name = sys.implementation.name.replace("cpython", "python")
+        libdir = os.path.join(destination, "lib", impl_name)
+        check_path(cmd.install_lib, libdir)
+        _platlibdir = getattr(sys, "platlibdir", "lib")
+        platlibdir = os.path.join(destination, _platlibdir, impl_name)
+        check_path(cmd.install_platlib, platlibdir)
+        check_path(cmd.install_purelib, libdir)
+        check_path(
+            cmd.install_headers,
+            os.path.join(destination, "include", impl_name, "foopkg"),
+        )
+        check_path(cmd.install_scripts, os.path.join(destination, "bin"))
+        check_path(cmd.install_data, destination)
+
+    def test_user_site(self, monkeypatch):
+        # test install with --user
+        # preparing the environment for the test
+        self.tmpdir = self.mkdtemp()
+        orig_site = site.USER_SITE
+        orig_base = site.USER_BASE
+        monkeypatch.setattr(site, 'USER_BASE', os.path.join(self.tmpdir, 'B'))
+        monkeypatch.setattr(site, 'USER_SITE', os.path.join(self.tmpdir, 'S'))
+        monkeypatch.setattr(install_module, 'USER_BASE', site.USER_BASE)
+        monkeypatch.setattr(install_module, 'USER_SITE', site.USER_SITE)
+
+        def _expanduser(path):
+            if path.startswith('~'):
+                return os.path.normpath(self.tmpdir + path[1:])
+            return path
+
+        monkeypatch.setattr(os.path, 'expanduser', _expanduser)
+
+        for key in ('nt_user', 'posix_user'):
+            assert key in INSTALL_SCHEMES
+
+        dist = Distribution({'name': 'xx'})
+        cmd = install(dist)
+
+        # making sure the user option is there
+        options = [name for name, short, label in cmd.user_options]
+        assert 'user' in options
+
+        # setting a value
+        cmd.user = True
+
+        # user base and site shouldn't be created yet
+        assert not os.path.exists(site.USER_BASE)
+        assert not os.path.exists(site.USER_SITE)
+
+        # let's run finalize
+        cmd.ensure_finalized()
+
+        # now they should
+        assert os.path.exists(site.USER_BASE)
+        assert os.path.exists(site.USER_SITE)
+
+        assert 'userbase' in cmd.config_vars
+        assert 'usersite' in cmd.config_vars
+
+        actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE)
+        if os.name == 'nt' and not is_mingw():
+            site_path = os.path.relpath(os.path.dirname(orig_site), orig_base)
+            include = os.path.join(site_path, 'Include')
+        else:
+            include = sysconfig.get_python_inc(0, '')
+        expect_headers = os.path.join(include, 'xx')
+
+        assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers)
+
+    def test_handle_extra_path(self):
+        dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
+        cmd = install(dist)
+
+        # two elements
+        cmd.handle_extra_path()
+        assert cmd.extra_path == ['path', 'dirs']
+        assert cmd.extra_dirs == 'dirs'
+        assert cmd.path_file == 'path'
+
+        # one element
+        cmd.extra_path = ['path']
+        cmd.handle_extra_path()
+        assert cmd.extra_path == ['path']
+        assert cmd.extra_dirs == 'path'
+        assert cmd.path_file == 'path'
+
+        # none
+        dist.extra_path = cmd.extra_path = None
+        cmd.handle_extra_path()
+        assert cmd.extra_path is None
+        assert cmd.extra_dirs == ''
+        assert cmd.path_file is None
+
+        # three elements (no way !)
+        cmd.extra_path = 'path,dirs,again'
+        with pytest.raises(DistutilsOptionError):
+            cmd.handle_extra_path()
+
+    def test_finalize_options(self):
+        dist = Distribution({'name': 'xx'})
+        cmd = install(dist)
+
+        # must supply either prefix/exec-prefix/home or
+        # install-base/install-platbase -- not both
+        cmd.prefix = 'prefix'
+        cmd.install_base = 'base'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+
+        # must supply either home or prefix/exec-prefix -- not both
+        cmd.install_base = None
+        cmd.home = 'home'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+
+        # can't combine user with prefix/exec_prefix/home or
+        # install_(plat)base
+        cmd.prefix = None
+        cmd.user = 'user'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+
+    def test_record(self):
+        install_dir = self.mkdtemp()
+        project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi'])
+        os.chdir(project_dir)
+        self.write_file('hello.py', "def main(): print('o hai')")
+        self.write_file('sayhi', 'from hello import main; main()')
+
+        cmd = install(dist)
+        dist.command_obj['install'] = cmd
+        cmd.root = install_dir
+        cmd.record = os.path.join(project_dir, 'filelist')
+        cmd.ensure_finalized()
+        cmd.run()
+
+        content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
+
+        found = [pathlib.Path(line).name for line in content.splitlines()]
+        expected = [
+            'hello.py',
+            f'hello.{sys.implementation.cache_tag}.pyc',
+            'sayhi',
+            'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
+        ]
+        assert found == expected
+
+    def test_record_extensions(self):
+        cmd = missing_compiler_executable()
+        if cmd is not None:
+            pytest.skip(f'The {cmd!r} command is not found')
+        install_dir = self.mkdtemp()
+        project_dir, dist = self.create_dist(
+            ext_modules=[Extension('xx', ['xxmodule.c'])]
+        )
+        os.chdir(project_dir)
+        support.copy_xxmodule_c(project_dir)
+
+        buildextcmd = build_ext(dist)
+        support.fixup_build_ext(buildextcmd)
+        buildextcmd.ensure_finalized()
+
+        cmd = install(dist)
+        dist.command_obj['install'] = cmd
+        dist.command_obj['build_ext'] = buildextcmd
+        cmd.root = install_dir
+        cmd.record = os.path.join(project_dir, 'filelist')
+        cmd.ensure_finalized()
+        cmd.run()
+
+        content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
+
+        found = [pathlib.Path(line).name for line in content.splitlines()]
+        expected = [
+            _make_ext_name('xx'),
+            'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
+        ]
+        assert found == expected
+
+    def test_debug_mode(self, caplog, monkeypatch):
+        # this covers the code called when DEBUG is set
+        monkeypatch.setattr(install_module, 'DEBUG', True)
+        caplog.set_level(logging.DEBUG)
+        self.test_record()
+        assert any(rec for rec in caplog.records if rec.levelno == logging.DEBUG)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_data.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c800f86c645d86fcb11aa3bef1513325ef163132
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_data.py
@@ -0,0 +1,74 @@
+"""Tests for distutils.command.install_data."""
+
+import os
+import pathlib
+from distutils.command.install_data import install_data
+from distutils.tests import support
+
+import pytest
+
+
+@pytest.mark.usefixtures('save_env')
+class TestInstallData(
+    support.TempdirManager,
+):
+    def test_simple_run(self):
+        pkg_dir, dist = self.create_dist()
+        cmd = install_data(dist)
+        cmd.install_dir = inst = os.path.join(pkg_dir, 'inst')
+
+        # data_files can contain
+        #  - simple files
+        #  - a Path object
+        #  - a tuple with a path, and a list of file
+        one = os.path.join(pkg_dir, 'one')
+        self.write_file(one, 'xxx')
+        inst2 = os.path.join(pkg_dir, 'inst2')
+        two = os.path.join(pkg_dir, 'two')
+        self.write_file(two, 'xxx')
+        three = pathlib.Path(pkg_dir) / 'three'
+        self.write_file(three, 'xxx')
+
+        cmd.data_files = [one, (inst2, [two]), three]
+        assert cmd.get_inputs() == [one, (inst2, [two]), three]
+
+        # let's run the command
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # let's check the result
+        assert len(cmd.get_outputs()) == 3
+        rthree = os.path.split(one)[-1]
+        assert os.path.exists(os.path.join(inst, rthree))
+        rtwo = os.path.split(two)[-1]
+        assert os.path.exists(os.path.join(inst2, rtwo))
+        rone = os.path.split(one)[-1]
+        assert os.path.exists(os.path.join(inst, rone))
+        cmd.outfiles = []
+
+        # let's try with warn_dir one
+        cmd.warn_dir = True
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # let's check the result
+        assert len(cmd.get_outputs()) == 3
+        assert os.path.exists(os.path.join(inst, rthree))
+        assert os.path.exists(os.path.join(inst2, rtwo))
+        assert os.path.exists(os.path.join(inst, rone))
+        cmd.outfiles = []
+
+        # now using root and empty dir
+        cmd.root = os.path.join(pkg_dir, 'root')
+        inst5 = os.path.join(pkg_dir, 'inst5')
+        four = os.path.join(cmd.install_dir, 'four')
+        self.write_file(four, 'xx')
+        cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])]
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # let's check the result
+        assert len(cmd.get_outputs()) == 5
+        assert os.path.exists(os.path.join(inst, rthree))
+        assert os.path.exists(os.path.join(inst2, rtwo))
+        assert os.path.exists(os.path.join(inst, rone))
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_headers.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_headers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c74f06b976f3c3ea977667a5c16c0e7f201a558
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_headers.py
@@ -0,0 +1,33 @@
+"""Tests for distutils.command.install_headers."""
+
+import os
+from distutils.command.install_headers import install_headers
+from distutils.tests import support
+
+import pytest
+
+
+@pytest.mark.usefixtures('save_env')
+class TestInstallHeaders(
+    support.TempdirManager,
+):
+    def test_simple_run(self):
+        # we have two headers
+        header_list = self.mkdtemp()
+        header1 = os.path.join(header_list, 'header1')
+        header2 = os.path.join(header_list, 'header2')
+        self.write_file(header1)
+        self.write_file(header2)
+        headers = [header1, header2]
+
+        pkg_dir, dist = self.create_dist(headers=headers)
+        cmd = install_headers(dist)
+        assert cmd.get_inputs() == headers
+
+        # let's run the command
+        cmd.install_dir = os.path.join(pkg_dir, 'inst')
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # let's check the results
+        assert len(cmd.get_outputs()) == 2
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_lib.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..f685a579560ea70bceea221de0e54485975ce180
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_lib.py
@@ -0,0 +1,110 @@
+"""Tests for distutils.command.install_data."""
+
+import importlib.util
+import os
+import sys
+from distutils.command.install_lib import install_lib
+from distutils.errors import DistutilsOptionError
+from distutils.extension import Extension
+from distutils.tests import support
+
+import pytest
+
+
+@support.combine_markers
+@pytest.mark.usefixtures('save_env')
+class TestInstallLib(
+    support.TempdirManager,
+):
+    def test_finalize_options(self):
+        dist = self.create_dist()[1]
+        cmd = install_lib(dist)
+
+        cmd.finalize_options()
+        assert cmd.compile == 1
+        assert cmd.optimize == 0
+
+        # optimize must be 0, 1, or 2
+        cmd.optimize = 'foo'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+        cmd.optimize = '4'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+
+        cmd.optimize = '2'
+        cmd.finalize_options()
+        assert cmd.optimize == 2
+
+    @pytest.mark.skipif('sys.dont_write_bytecode')
+    def test_byte_compile(self):
+        project_dir, dist = self.create_dist()
+        os.chdir(project_dir)
+        cmd = install_lib(dist)
+        cmd.compile = cmd.optimize = 1
+
+        f = os.path.join(project_dir, 'foo.py')
+        self.write_file(f, '# python file')
+        cmd.byte_compile([f])
+        pyc_file = importlib.util.cache_from_source('foo.py', optimization='')
+        pyc_opt_file = importlib.util.cache_from_source(
+            'foo.py', optimization=cmd.optimize
+        )
+        assert os.path.exists(pyc_file)
+        assert os.path.exists(pyc_opt_file)
+
+    def test_get_outputs(self):
+        project_dir, dist = self.create_dist()
+        os.chdir(project_dir)
+        os.mkdir('spam')
+        cmd = install_lib(dist)
+
+        # setting up a dist environment
+        cmd.compile = cmd.optimize = 1
+        cmd.install_dir = self.mkdtemp()
+        f = os.path.join(project_dir, 'spam', '__init__.py')
+        self.write_file(f, '# python package')
+        cmd.distribution.ext_modules = [Extension('foo', ['xxx'])]
+        cmd.distribution.packages = ['spam']
+        cmd.distribution.script_name = 'setup.py'
+
+        # get_outputs should return 4 elements: spam/__init__.py and .pyc,
+        # foo.import-tag-abiflags.so / foo.pyd
+        outputs = cmd.get_outputs()
+        assert len(outputs) == 4, outputs
+
+    def test_get_inputs(self):
+        project_dir, dist = self.create_dist()
+        os.chdir(project_dir)
+        os.mkdir('spam')
+        cmd = install_lib(dist)
+
+        # setting up a dist environment
+        cmd.compile = cmd.optimize = 1
+        cmd.install_dir = self.mkdtemp()
+        f = os.path.join(project_dir, 'spam', '__init__.py')
+        self.write_file(f, '# python package')
+        cmd.distribution.ext_modules = [Extension('foo', ['xxx'])]
+        cmd.distribution.packages = ['spam']
+        cmd.distribution.script_name = 'setup.py'
+
+        # get_inputs should return 2 elements: spam/__init__.py and
+        # foo.import-tag-abiflags.so / foo.pyd
+        inputs = cmd.get_inputs()
+        assert len(inputs) == 2, inputs
+
+    def test_dont_write_bytecode(self, caplog):
+        # makes sure byte_compile is not used
+        dist = self.create_dist()[1]
+        cmd = install_lib(dist)
+        cmd.compile = True
+        cmd.optimize = 1
+
+        old_dont_write_bytecode = sys.dont_write_bytecode
+        sys.dont_write_bytecode = True
+        try:
+            cmd.byte_compile([])
+        finally:
+            sys.dont_write_bytecode = old_dont_write_bytecode
+
+        assert 'byte-compiling is disabled' in caplog.messages[0]
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_scripts.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_scripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..868b1c22521f23a5dd398e4636c94330d4c238ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_install_scripts.py
@@ -0,0 +1,52 @@
+"""Tests for distutils.command.install_scripts."""
+
+import os
+from distutils.command.install_scripts import install_scripts
+from distutils.core import Distribution
+from distutils.tests import support
+
+from . import test_build_scripts
+
+
+class TestInstallScripts(support.TempdirManager):
+    def test_default_settings(self):
+        dist = Distribution()
+        dist.command_obj["build"] = support.DummyCommand(build_scripts="/foo/bar")
+        dist.command_obj["install"] = support.DummyCommand(
+            install_scripts="/splat/funk",
+            force=True,
+            skip_build=True,
+        )
+        cmd = install_scripts(dist)
+        assert not cmd.force
+        assert not cmd.skip_build
+        assert cmd.build_dir is None
+        assert cmd.install_dir is None
+
+        cmd.finalize_options()
+
+        assert cmd.force
+        assert cmd.skip_build
+        assert cmd.build_dir == "/foo/bar"
+        assert cmd.install_dir == "/splat/funk"
+
+    def test_installation(self):
+        source = self.mkdtemp()
+
+        expected = test_build_scripts.TestBuildScripts.write_sample_scripts(source)
+
+        target = self.mkdtemp()
+        dist = Distribution()
+        dist.command_obj["build"] = support.DummyCommand(build_scripts=source)
+        dist.command_obj["install"] = support.DummyCommand(
+            install_scripts=target,
+            force=True,
+            skip_build=True,
+        )
+        cmd = install_scripts(dist)
+        cmd.finalize_options()
+        cmd.run()
+
+        installed = os.listdir(target)
+        for name in expected:
+            assert name in installed
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_log.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..d67779fc9fa0f58a010929d5a456890c6dde3376
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_log.py
@@ -0,0 +1,12 @@
+"""Tests for distutils.log"""
+
+import logging
+from distutils._log import log
+
+
+class TestLog:
+    def test_non_ascii(self, caplog):
+        caplog.set_level(logging.DEBUG)
+        log.debug('Dεbug\tMėssãge')
+        log.fatal('Fαtal\tÈrrōr')
+        assert caplog.messages == ['Dεbug\tMėssãge', 'Fαtal\tÈrrōr']
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_modified.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_modified.py
new file mode 100644
index 0000000000000000000000000000000000000000..e35cec2d6f1a8d27619e33c253f0a83f0f72a75d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_modified.py
@@ -0,0 +1,126 @@
+"""Tests for distutils._modified."""
+
+import os
+import types
+from distutils._modified import newer, newer_group, newer_pairwise, newer_pairwise_group
+from distutils.errors import DistutilsFileError
+from distutils.tests import support
+
+import pytest
+
+
+class TestDepUtil(support.TempdirManager):
+    def test_newer(self):
+        tmpdir = self.mkdtemp()
+        new_file = os.path.join(tmpdir, 'new')
+        old_file = os.path.abspath(__file__)
+
+        # Raise DistutilsFileError if 'new_file' does not exist.
+        with pytest.raises(DistutilsFileError):
+            newer(new_file, old_file)
+
+        # Return true if 'new_file' exists and is more recently modified than
+        # 'old_file', or if 'new_file' exists and 'old_file' doesn't.
+        self.write_file(new_file)
+        assert newer(new_file, 'I_dont_exist')
+        assert newer(new_file, old_file)
+
+        # Return false if both exist and 'old_file' is the same age or younger
+        # than 'new_file'.
+        assert not newer(old_file, new_file)
+
+    def _setup_1234(self):
+        tmpdir = self.mkdtemp()
+        sources = os.path.join(tmpdir, 'sources')
+        targets = os.path.join(tmpdir, 'targets')
+        os.mkdir(sources)
+        os.mkdir(targets)
+        one = os.path.join(sources, 'one')
+        two = os.path.join(sources, 'two')
+        three = os.path.abspath(__file__)  # I am the old file
+        four = os.path.join(targets, 'four')
+        self.write_file(one)
+        self.write_file(two)
+        self.write_file(four)
+        return one, two, three, four
+
+    def test_newer_pairwise(self):
+        one, two, three, four = self._setup_1234()
+
+        assert newer_pairwise([one, two], [three, four]) == ([one], [three])
+
+    def test_newer_pairwise_mismatch(self):
+        one, two, three, four = self._setup_1234()
+
+        with pytest.raises(ValueError):
+            newer_pairwise([one], [three, four])
+
+        with pytest.raises(ValueError):
+            newer_pairwise([one, two], [three])
+
+    def test_newer_pairwise_empty(self):
+        assert newer_pairwise([], []) == ([], [])
+
+    def test_newer_pairwise_fresh(self):
+        one, two, three, four = self._setup_1234()
+
+        assert newer_pairwise([one, three], [two, four]) == ([], [])
+
+    def test_newer_group(self):
+        tmpdir = self.mkdtemp()
+        sources = os.path.join(tmpdir, 'sources')
+        os.mkdir(sources)
+        one = os.path.join(sources, 'one')
+        two = os.path.join(sources, 'two')
+        three = os.path.join(sources, 'three')
+        old_file = os.path.abspath(__file__)
+
+        # return true if 'old_file' is out-of-date with respect to any file
+        # listed in 'sources'.
+        self.write_file(one)
+        self.write_file(two)
+        self.write_file(three)
+        assert newer_group([one, two, three], old_file)
+        assert not newer_group([one, two, old_file], three)
+
+        # missing handling
+        os.remove(one)
+        with pytest.raises(OSError):
+            newer_group([one, two, old_file], three)
+
+        assert not newer_group([one, two, old_file], three, missing='ignore')
+
+        assert newer_group([one, two, old_file], three, missing='newer')
+
+
+@pytest.fixture
+def groups_target(tmp_path):
+    """
+    Set up some older sources, a target, and newer sources.
+
+    Returns a simple namespace with these values.
+    """
+    filenames = ['older.c', 'older.h', 'target.o', 'newer.c', 'newer.h']
+    paths = [tmp_path / name for name in filenames]
+
+    for mtime, path in enumerate(paths):
+        path.write_text('', encoding='utf-8')
+
+        # make sure modification times are sequential
+        os.utime(path, (mtime, mtime))
+
+    return types.SimpleNamespace(older=paths[:2], target=paths[2], newer=paths[3:])
+
+
+def test_newer_pairwise_group(groups_target):
+    older = newer_pairwise_group([groups_target.older], [groups_target.target])
+    newer = newer_pairwise_group([groups_target.newer], [groups_target.target])
+    assert older == ([], [])
+    assert newer == ([groups_target.newer], [groups_target.target])
+
+
+def test_newer_group_no_sources_no_target(tmp_path):
+    """
+    Consider no sources and no target "newer".
+    """
+    assert newer_group([], str(tmp_path / 'does-not-exist'))
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sdist.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b1a376b262162aa7c8d3d989709c05b38563d6c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sdist.py
@@ -0,0 +1,470 @@
+"""Tests for distutils.command.sdist."""
+
+import os
+import pathlib
+import shutil  # noqa: F401
+import tarfile
+import zipfile
+from distutils.archive_util import ARCHIVE_FORMATS
+from distutils.command.sdist import sdist, show_formats
+from distutils.core import Distribution
+from distutils.errors import DistutilsOptionError
+from distutils.filelist import FileList
+from os.path import join
+from textwrap import dedent
+
+import jaraco.path
+import path
+import pytest
+from more_itertools import ilen
+
+from . import support
+from .unix_compat import grp, pwd, require_uid_0, require_unix_id
+
+SETUP_PY = """
+from distutils.core import setup
+import somecode
+
+setup(name='fake')
+"""
+
+MANIFEST = """\
+# file GENERATED by distutils, do NOT edit
+README
+buildout.cfg
+inroot.txt
+setup.py
+data%(sep)sdata.dt
+scripts%(sep)sscript.py
+some%(sep)sfile.txt
+some%(sep)sother_file.txt
+somecode%(sep)s__init__.py
+somecode%(sep)sdoc.dat
+somecode%(sep)sdoc.txt
+"""
+
+
+@pytest.fixture(autouse=True)
+def project_dir(request, distutils_managed_tempdir):
+    self = request.instance
+    self.tmp_dir = self.mkdtemp()
+    jaraco.path.build(
+        {
+            'somecode': {
+                '__init__.py': '#',
+            },
+            'README': 'xxx',
+            'setup.py': SETUP_PY,
+        },
+        self.tmp_dir,
+    )
+    with path.Path(self.tmp_dir):
+        yield
+
+
+def clean_lines(filepath):
+    with pathlib.Path(filepath).open(encoding='utf-8') as f:
+        yield from filter(None, map(str.strip, f))
+
+
+class TestSDist(support.TempdirManager):
+    def get_cmd(self, metadata=None):
+        """Returns a cmd"""
+        if metadata is None:
+            metadata = {
+                'name': 'ns.fake--pkg',
+                'version': '1.0',
+                'url': 'xxx',
+                'author': 'xxx',
+                'author_email': 'xxx',
+            }
+        dist = Distribution(metadata)
+        dist.script_name = 'setup.py'
+        dist.packages = ['somecode']
+        dist.include_package_data = True
+        cmd = sdist(dist)
+        cmd.dist_dir = 'dist'
+        return dist, cmd
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_prune_file_list(self):
+        # this test creates a project with some VCS dirs and an NFS rename
+        # file, then launches sdist to check they get pruned on all systems
+
+        # creating VCS directories with some files in them
+        os.mkdir(join(self.tmp_dir, 'somecode', '.svn'))
+        self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx')
+
+        os.mkdir(join(self.tmp_dir, 'somecode', '.hg'))
+        self.write_file((self.tmp_dir, 'somecode', '.hg', 'ok'), 'xxx')
+
+        os.mkdir(join(self.tmp_dir, 'somecode', '.git'))
+        self.write_file((self.tmp_dir, 'somecode', '.git', 'ok'), 'xxx')
+
+        self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx')
+
+        # now building a sdist
+        dist, cmd = self.get_cmd()
+
+        # zip is available universally
+        # (tar might not be installed under win32)
+        cmd.formats = ['zip']
+
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # now let's check what we have
+        dist_folder = join(self.tmp_dir, 'dist')
+        files = os.listdir(dist_folder)
+        assert files == ['ns_fake_pkg-1.0.zip']
+
+        zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip'))
+        try:
+            content = zip_file.namelist()
+        finally:
+            zip_file.close()
+
+        # making sure everything has been pruned correctly
+        expected = [
+            '',
+            'PKG-INFO',
+            'README',
+            'setup.py',
+            'somecode/',
+            'somecode/__init__.py',
+        ]
+        assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected]
+
+    @pytest.mark.usefixtures('needs_zlib')
+    @pytest.mark.skipif("not shutil.which('tar')")
+    @pytest.mark.skipif("not shutil.which('gzip')")
+    def test_make_distribution(self):
+        # now building a sdist
+        dist, cmd = self.get_cmd()
+
+        # creating a gztar then a tar
+        cmd.formats = ['gztar', 'tar']
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # making sure we have two files
+        dist_folder = join(self.tmp_dir, 'dist')
+        result = os.listdir(dist_folder)
+        result.sort()
+        assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz']
+
+        os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar'))
+        os.remove(join(dist_folder, 'ns_fake_pkg-1.0.tar.gz'))
+
+        # now trying a tar then a gztar
+        cmd.formats = ['tar', 'gztar']
+
+        cmd.ensure_finalized()
+        cmd.run()
+
+        result = os.listdir(dist_folder)
+        result.sort()
+        assert result == ['ns_fake_pkg-1.0.tar', 'ns_fake_pkg-1.0.tar.gz']
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_add_defaults(self):
+        # https://bugs.python.org/issue2279
+
+        # add_default should also include
+        # data_files and package_data
+        dist, cmd = self.get_cmd()
+
+        # filling data_files by pointing files
+        # in package_data
+        dist.package_data = {'': ['*.cfg', '*.dat'], 'somecode': ['*.txt']}
+        self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
+        self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#')
+
+        # adding some data in data_files
+        data_dir = join(self.tmp_dir, 'data')
+        os.mkdir(data_dir)
+        self.write_file((data_dir, 'data.dt'), '#')
+        some_dir = join(self.tmp_dir, 'some')
+        os.mkdir(some_dir)
+        # make sure VCS directories are pruned (#14004)
+        hg_dir = join(self.tmp_dir, '.hg')
+        os.mkdir(hg_dir)
+        self.write_file((hg_dir, 'last-message.txt'), '#')
+        # a buggy regex used to prevent this from working on windows (#6884)
+        self.write_file((self.tmp_dir, 'buildout.cfg'), '#')
+        self.write_file((self.tmp_dir, 'inroot.txt'), '#')
+        self.write_file((some_dir, 'file.txt'), '#')
+        self.write_file((some_dir, 'other_file.txt'), '#')
+
+        dist.data_files = [
+            ('data', ['data/data.dt', 'buildout.cfg', 'inroot.txt', 'notexisting']),
+            'some/file.txt',
+            'some/other_file.txt',
+        ]
+
+        # adding a script
+        script_dir = join(self.tmp_dir, 'scripts')
+        os.mkdir(script_dir)
+        self.write_file((script_dir, 'script.py'), '#')
+        dist.scripts = [join('scripts', 'script.py')]
+
+        cmd.formats = ['zip']
+        cmd.use_defaults = True
+
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # now let's check what we have
+        dist_folder = join(self.tmp_dir, 'dist')
+        files = os.listdir(dist_folder)
+        assert files == ['ns_fake_pkg-1.0.zip']
+
+        zip_file = zipfile.ZipFile(join(dist_folder, 'ns_fake_pkg-1.0.zip'))
+        try:
+            content = zip_file.namelist()
+        finally:
+            zip_file.close()
+
+        # making sure everything was added
+        expected = [
+            '',
+            'PKG-INFO',
+            'README',
+            'buildout.cfg',
+            'data/',
+            'data/data.dt',
+            'inroot.txt',
+            'scripts/',
+            'scripts/script.py',
+            'setup.py',
+            'some/',
+            'some/file.txt',
+            'some/other_file.txt',
+            'somecode/',
+            'somecode/__init__.py',
+            'somecode/doc.dat',
+            'somecode/doc.txt',
+        ]
+        assert sorted(content) == ['ns_fake_pkg-1.0/' + x for x in expected]
+
+        # checking the MANIFEST
+        manifest = pathlib.Path(self.tmp_dir, 'MANIFEST').read_text(encoding='utf-8')
+        assert manifest == MANIFEST % {'sep': os.sep}
+
+    @staticmethod
+    def warnings(messages, prefix='warning: '):
+        return [msg for msg in messages if msg.startswith(prefix)]
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_metadata_check_option(self, caplog):
+        # testing the `medata-check` option
+        dist, cmd = self.get_cmd(metadata={})
+
+        # this should raise some warnings !
+        # with the `check` subcommand
+        cmd.ensure_finalized()
+        cmd.run()
+        assert len(self.warnings(caplog.messages, 'warning: check: ')) == 1
+
+        # trying with a complete set of metadata
+        caplog.clear()
+        dist, cmd = self.get_cmd()
+        cmd.ensure_finalized()
+        cmd.metadata_check = False
+        cmd.run()
+        assert len(self.warnings(caplog.messages, 'warning: check: ')) == 0
+
+    def test_show_formats(self, capsys):
+        show_formats()
+
+        # the output should be a header line + one line per format
+        num_formats = len(ARCHIVE_FORMATS.keys())
+        output = [
+            line
+            for line in capsys.readouterr().out.split('\n')
+            if line.strip().startswith('--formats=')
+        ]
+        assert len(output) == num_formats
+
+    def test_finalize_options(self):
+        dist, cmd = self.get_cmd()
+        cmd.finalize_options()
+
+        # default options set by finalize
+        assert cmd.manifest == 'MANIFEST'
+        assert cmd.template == 'MANIFEST.in'
+        assert cmd.dist_dir == 'dist'
+
+        # formats has to be a string splitable on (' ', ',') or
+        # a stringlist
+        cmd.formats = 1
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+        cmd.formats = ['zip']
+        cmd.finalize_options()
+
+        # formats has to be known
+        cmd.formats = 'supazipa'
+        with pytest.raises(DistutilsOptionError):
+            cmd.finalize_options()
+
+    # the following tests make sure there is a nice error message instead
+    # of a traceback when parsing an invalid manifest template
+
+    def _check_template(self, content, caplog):
+        dist, cmd = self.get_cmd()
+        os.chdir(self.tmp_dir)
+        self.write_file('MANIFEST.in', content)
+        cmd.ensure_finalized()
+        cmd.filelist = FileList()
+        cmd.read_template()
+        assert len(self.warnings(caplog.messages)) == 1
+
+    def test_invalid_template_unknown_command(self, caplog):
+        self._check_template('taunt knights *', caplog)
+
+    def test_invalid_template_wrong_arguments(self, caplog):
+        # this manifest command takes one argument
+        self._check_template('prune', caplog)
+
+    @pytest.mark.skipif("platform.system() != 'Windows'")
+    def test_invalid_template_wrong_path(self, caplog):
+        # on Windows, trailing slashes are not allowed
+        # this used to crash instead of raising a warning: #8286
+        self._check_template('include examples/', caplog)
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_get_file_list(self):
+        # make sure MANIFEST is recalculated
+        dist, cmd = self.get_cmd()
+
+        # filling data_files by pointing files in package_data
+        dist.package_data = {'somecode': ['*.txt']}
+        self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
+        cmd.formats = ['gztar']
+        cmd.ensure_finalized()
+        cmd.run()
+
+        assert ilen(clean_lines(cmd.manifest)) == 5
+
+        # adding a file
+        self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
+
+        # make sure build_py is reinitialized, like a fresh run
+        build_py = dist.get_command_obj('build_py')
+        build_py.finalized = False
+        build_py.ensure_finalized()
+
+        cmd.run()
+
+        manifest2 = list(clean_lines(cmd.manifest))
+
+        # do we have the new file in MANIFEST ?
+        assert len(manifest2) == 6
+        assert 'doc2.txt' in manifest2[-1]
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_manifest_marker(self):
+        # check that autogenerated MANIFESTs have a marker
+        dist, cmd = self.get_cmd()
+        cmd.ensure_finalized()
+        cmd.run()
+
+        assert (
+            next(clean_lines(cmd.manifest))
+            == '# file GENERATED by distutils, do NOT edit'
+        )
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_manifest_comments(self):
+        # make sure comments don't cause exceptions or wrong includes
+        contents = dedent(
+            """\
+            # bad.py
+            #bad.py
+            good.py
+            """
+        )
+        dist, cmd = self.get_cmd()
+        cmd.ensure_finalized()
+        self.write_file((self.tmp_dir, cmd.manifest), contents)
+        self.write_file((self.tmp_dir, 'good.py'), '# pick me!')
+        self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!")
+        self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!")
+        cmd.run()
+        assert cmd.filelist.files == ['good.py']
+
+    @pytest.mark.usefixtures('needs_zlib')
+    def test_manual_manifest(self):
+        # check that a MANIFEST without a marker is left alone
+        dist, cmd = self.get_cmd()
+        cmd.formats = ['gztar']
+        cmd.ensure_finalized()
+        self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
+        self.write_file(
+            (self.tmp_dir, 'README.manual'),
+            'This project maintains its MANIFEST file itself.',
+        )
+        cmd.run()
+        assert cmd.filelist.files == ['README.manual']
+
+        assert list(clean_lines(cmd.manifest)) == ['README.manual']
+
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
+        archive = tarfile.open(archive_name)
+        try:
+            filenames = [tarinfo.name for tarinfo in archive]
+        finally:
+            archive.close()
+        assert sorted(filenames) == [
+            'ns_fake_pkg-1.0',
+            'ns_fake_pkg-1.0/PKG-INFO',
+            'ns_fake_pkg-1.0/README.manual',
+        ]
+
+    @pytest.mark.usefixtures('needs_zlib')
+    @require_unix_id
+    @require_uid_0
+    @pytest.mark.skipif("not shutil.which('tar')")
+    @pytest.mark.skipif("not shutil.which('gzip')")
+    def test_make_distribution_owner_group(self):
+        # now building a sdist
+        dist, cmd = self.get_cmd()
+
+        # creating a gztar and specifying the owner+group
+        cmd.formats = ['gztar']
+        cmd.owner = pwd.getpwuid(0)[0]
+        cmd.group = grp.getgrgid(0)[0]
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # making sure we have the good rights
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
+        archive = tarfile.open(archive_name)
+        try:
+            for member in archive.getmembers():
+                assert member.uid == 0
+                assert member.gid == 0
+        finally:
+            archive.close()
+
+        # building a sdist again
+        dist, cmd = self.get_cmd()
+
+        # creating a gztar
+        cmd.formats = ['gztar']
+        cmd.ensure_finalized()
+        cmd.run()
+
+        # making sure we have the good rights
+        archive_name = join(self.tmp_dir, 'dist', 'ns_fake_pkg-1.0.tar.gz')
+        archive = tarfile.open(archive_name)
+
+        # note that we are not testing the group ownership here
+        # because, depending on the platforms and the container
+        # rights (see #7408)
+        try:
+            for member in archive.getmembers():
+                assert member.uid == os.getuid()
+        finally:
+            archive.close()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_spawn.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_spawn.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b9fc926f6ffc41673630fbf5775e6f4ad638b18
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_spawn.py
@@ -0,0 +1,141 @@
+"""Tests for distutils.spawn."""
+
+import os
+import stat
+import sys
+import unittest.mock as mock
+from distutils.errors import DistutilsExecError
+from distutils.spawn import find_executable, spawn
+from distutils.tests import support
+
+import path
+import pytest
+from test.support import unix_shell
+
+from .compat import py39 as os_helper
+
+
+class TestSpawn(support.TempdirManager):
+    @pytest.mark.skipif("os.name not in ('nt', 'posix')")
+    def test_spawn(self):
+        tmpdir = self.mkdtemp()
+
+        # creating something executable
+        # through the shell that returns 1
+        if sys.platform != 'win32':
+            exe = os.path.join(tmpdir, 'foo.sh')
+            self.write_file(exe, f'#!{unix_shell}\nexit 1')
+        else:
+            exe = os.path.join(tmpdir, 'foo.bat')
+            self.write_file(exe, 'exit 1')
+
+        os.chmod(exe, 0o777)
+        with pytest.raises(DistutilsExecError):
+            spawn([exe])
+
+        # now something that works
+        if sys.platform != 'win32':
+            exe = os.path.join(tmpdir, 'foo.sh')
+            self.write_file(exe, f'#!{unix_shell}\nexit 0')
+        else:
+            exe = os.path.join(tmpdir, 'foo.bat')
+            self.write_file(exe, 'exit 0')
+
+        os.chmod(exe, 0o777)
+        spawn([exe])  # should work without any error
+
+    def test_find_executable(self, tmp_path):
+        program_path = self._make_executable(tmp_path, '.exe')
+        program = program_path.name
+        program_noeext = program_path.with_suffix('').name
+        filename = str(program_path)
+        tmp_dir = path.Path(tmp_path)
+
+        # test path parameter
+        rv = find_executable(program, path=tmp_dir)
+        assert rv == filename
+
+        if sys.platform == 'win32':
+            # test without ".exe" extension
+            rv = find_executable(program_noeext, path=tmp_dir)
+            assert rv == filename
+
+        # test find in the current directory
+        with tmp_dir:
+            rv = find_executable(program)
+            assert rv == program
+
+        # test non-existent program
+        dont_exist_program = "dontexist_" + program
+        rv = find_executable(dont_exist_program, path=tmp_dir)
+        assert rv is None
+
+        # PATH='': no match, except in the current directory
+        with os_helper.EnvironmentVarGuard() as env:
+            env['PATH'] = ''
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', tmp_dir),
+            ):
+                rv = find_executable(program)
+                assert rv is None
+
+                # look in current directory
+                with tmp_dir:
+                    rv = find_executable(program)
+                    assert rv == program
+
+        # PATH=':': explicitly looks in the current directory
+        with os_helper.EnvironmentVarGuard() as env:
+            env['PATH'] = os.pathsep
+            with (
+                mock.patch('distutils.spawn.os.confstr', return_value='', create=True),
+                mock.patch('distutils.spawn.os.defpath', ''),
+            ):
+                rv = find_executable(program)
+                assert rv is None
+
+                # look in current directory
+                with tmp_dir:
+                    rv = find_executable(program)
+                    assert rv == program
+
+        # missing PATH: test os.confstr("CS_PATH") and os.defpath
+        with os_helper.EnvironmentVarGuard() as env:
+            env.pop('PATH', None)
+
+            # without confstr
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', side_effect=ValueError, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', tmp_dir),
+            ):
+                rv = find_executable(program)
+                assert rv == filename
+
+            # with confstr
+            with (
+                mock.patch(
+                    'distutils.spawn.os.confstr', return_value=tmp_dir, create=True
+                ),
+                mock.patch('distutils.spawn.os.defpath', ''),
+            ):
+                rv = find_executable(program)
+                assert rv == filename
+
+    @staticmethod
+    def _make_executable(tmp_path, ext):
+        # Give the temporary program a suffix regardless of platform.
+        # It's needed on Windows and not harmful on others.
+        program = tmp_path.joinpath('program').with_suffix(ext)
+        program.write_text("", encoding='utf-8')
+        program.chmod(stat.S_IXUSR)
+        return program
+
+    def test_spawn_missing_exe(self):
+        with pytest.raises(DistutilsExecError) as ctx:
+            spawn(['does-not-exist'])
+        assert "command 'does-not-exist' failed" in str(ctx.value)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sysconfig.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sysconfig.py
new file mode 100644
index 0000000000000000000000000000000000000000..43d77c23fad426be237b9f91a6d98d7c36233d84
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_sysconfig.py
@@ -0,0 +1,319 @@
+"""Tests for distutils.sysconfig."""
+
+import contextlib
+import distutils
+import os
+import pathlib
+import subprocess
+import sys
+from distutils import sysconfig
+from distutils.ccompiler import new_compiler  # noqa: F401
+from distutils.unixccompiler import UnixCCompiler
+
+import jaraco.envs
+import path
+import pytest
+from jaraco.text import trim
+from test.support import swap_item
+
+
+def _gen_makefile(root, contents):
+    jaraco.path.build({'Makefile': trim(contents)}, root)
+    return root / 'Makefile'
+
+
+@pytest.mark.usefixtures('save_env')
+class TestSysconfig:
+    def test_get_config_h_filename(self):
+        config_h = sysconfig.get_config_h_filename()
+        assert os.path.isfile(config_h)
+
+    @pytest.mark.skipif("platform.system() == 'Windows'")
+    @pytest.mark.skipif("sys.implementation.name != 'cpython'")
+    def test_get_makefile_filename(self):
+        makefile = sysconfig.get_makefile_filename()
+        assert os.path.isfile(makefile)
+
+    def test_get_python_lib(self, tmp_path):
+        assert sysconfig.get_python_lib() != sysconfig.get_python_lib(prefix=tmp_path)
+
+    def test_get_config_vars(self):
+        cvars = sysconfig.get_config_vars()
+        assert isinstance(cvars, dict)
+        assert cvars
+
+    @pytest.mark.skipif('sysconfig.IS_PYPY')
+    @pytest.mark.skipif('sysconfig.python_build')
+    @pytest.mark.xfail('platform.system() == "Windows"')
+    def test_srcdir_simple(self):
+        # See #15364.
+        srcdir = pathlib.Path(sysconfig.get_config_var('srcdir'))
+
+        assert srcdir.absolute()
+        assert srcdir.is_dir()
+
+        makefile = pathlib.Path(sysconfig.get_makefile_filename())
+        assert makefile.parent.samefile(srcdir)
+
+    @pytest.mark.skipif('sysconfig.IS_PYPY')
+    @pytest.mark.skipif('not sysconfig.python_build')
+    def test_srcdir_python_build(self):
+        # See #15364.
+        srcdir = pathlib.Path(sysconfig.get_config_var('srcdir'))
+
+        # The python executable has not been installed so srcdir
+        # should be a full source checkout.
+        Python_h = srcdir.joinpath('Include', 'Python.h')
+        assert Python_h.is_file()
+        assert sysconfig._is_python_source_dir(srcdir)
+        assert sysconfig._is_python_source_dir(str(srcdir))
+
+    def test_srcdir_independent_of_cwd(self):
+        """
+        srcdir should be independent of the current working directory
+        """
+        # See #15364.
+        srcdir = sysconfig.get_config_var('srcdir')
+        with path.Path('..'):
+            srcdir2 = sysconfig.get_config_var('srcdir')
+        assert srcdir == srcdir2
+
+    def customize_compiler(self):
+        # make sure AR gets caught
+        class compiler:
+            compiler_type = 'unix'
+            executables = UnixCCompiler.executables
+
+            def __init__(self):
+                self.exes = {}
+
+            def set_executables(self, **kw):
+                for k, v in kw.items():
+                    self.exes[k] = v
+
+        sysconfig_vars = {
+            'AR': 'sc_ar',
+            'CC': 'sc_cc',
+            'CXX': 'sc_cxx',
+            'ARFLAGS': '--sc-arflags',
+            'CFLAGS': '--sc-cflags',
+            'CCSHARED': '--sc-ccshared',
+            'LDSHARED': 'sc_ldshared',
+            'SHLIB_SUFFIX': 'sc_shutil_suffix',
+        }
+
+        comp = compiler()
+        with contextlib.ExitStack() as cm:
+            for key, value in sysconfig_vars.items():
+                cm.enter_context(swap_item(sysconfig._config_vars, key, value))
+            sysconfig.customize_compiler(comp)
+
+        return comp
+
+    @pytest.mark.skipif("not isinstance(new_compiler(), UnixCCompiler)")
+    @pytest.mark.usefixtures('disable_macos_customization')
+    def test_customize_compiler(self):
+        # Make sure that sysconfig._config_vars is initialized
+        sysconfig.get_config_vars()
+
+        os.environ['AR'] = 'env_ar'
+        os.environ['CC'] = 'env_cc'
+        os.environ['CPP'] = 'env_cpp'
+        os.environ['CXX'] = 'env_cxx --env-cxx-flags'
+        os.environ['LDSHARED'] = 'env_ldshared'
+        os.environ['LDFLAGS'] = '--env-ldflags'
+        os.environ['ARFLAGS'] = '--env-arflags'
+        os.environ['CFLAGS'] = '--env-cflags'
+        os.environ['CPPFLAGS'] = '--env-cppflags'
+        os.environ['RANLIB'] = 'env_ranlib'
+
+        comp = self.customize_compiler()
+        assert comp.exes['archiver'] == 'env_ar --env-arflags'
+        assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags'
+        assert comp.exes['compiler'] == 'env_cc --env-cflags --env-cppflags'
+        assert comp.exes['compiler_so'] == (
+            'env_cc --env-cflags --env-cppflags --sc-ccshared'
+        )
+        assert (
+            comp.exes['compiler_cxx']
+            == 'env_cxx --env-cxx-flags --sc-cflags --env-cppflags'
+        )
+        assert comp.exes['linker_exe'] == 'env_cc'
+        assert comp.exes['linker_so'] == (
+            'env_ldshared --env-ldflags --env-cflags --env-cppflags'
+        )
+        assert comp.shared_lib_extension == 'sc_shutil_suffix'
+
+        if sys.platform == "darwin":
+            assert comp.exes['ranlib'] == 'env_ranlib'
+        else:
+            assert 'ranlib' not in comp.exes
+
+        del os.environ['AR']
+        del os.environ['CC']
+        del os.environ['CPP']
+        del os.environ['CXX']
+        del os.environ['LDSHARED']
+        del os.environ['LDFLAGS']
+        del os.environ['ARFLAGS']
+        del os.environ['CFLAGS']
+        del os.environ['CPPFLAGS']
+        del os.environ['RANLIB']
+
+        comp = self.customize_compiler()
+        assert comp.exes['archiver'] == 'sc_ar --sc-arflags'
+        assert comp.exes['preprocessor'] == 'sc_cc -E'
+        assert comp.exes['compiler'] == 'sc_cc --sc-cflags'
+        assert comp.exes['compiler_so'] == 'sc_cc --sc-cflags --sc-ccshared'
+        assert comp.exes['compiler_cxx'] == 'sc_cxx --sc-cflags'
+        assert comp.exes['linker_exe'] == 'sc_cc'
+        assert comp.exes['linker_so'] == 'sc_ldshared'
+        assert comp.shared_lib_extension == 'sc_shutil_suffix'
+        assert 'ranlib' not in comp.exes
+
+    def test_parse_makefile_base(self, tmp_path):
+        makefile = _gen_makefile(
+            tmp_path,
+            """
+            CONFIG_ARGS=  '--arg1=optarg1' 'ENV=LIB'
+            VAR=$OTHER
+            OTHER=foo
+            """,
+        )
+        d = sysconfig.parse_makefile(makefile)
+        assert d == {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'}
+
+    def test_parse_makefile_literal_dollar(self, tmp_path):
+        makefile = _gen_makefile(
+            tmp_path,
+            """
+            CONFIG_ARGS=  '--arg1=optarg1' 'ENV=\\$$LIB'
+            VAR=$OTHER
+            OTHER=foo
+            """,
+        )
+        d = sysconfig.parse_makefile(makefile)
+        assert d == {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'}
+
+    def test_sysconfig_module(self):
+        import sysconfig as global_sysconfig
+
+        assert global_sysconfig.get_config_var('CFLAGS') == sysconfig.get_config_var(
+            'CFLAGS'
+        )
+        assert global_sysconfig.get_config_var('LDFLAGS') == sysconfig.get_config_var(
+            'LDFLAGS'
+        )
+
+    # On macOS, binary installers support extension module building on
+    # various levels of the operating system with differing Xcode
+    # configurations, requiring customization of some of the
+    # compiler configuration directives to suit the environment on
+    # the installed machine. Some of these customizations may require
+    # running external programs and are thus deferred until needed by
+    # the first extension module build. Only
+    # the Distutils version of sysconfig is used for extension module
+    # builds, which happens earlier in the Distutils tests. This may
+    # cause the following tests to fail since no tests have caused
+    # the global version of sysconfig to call the customization yet.
+    # The solution for now is to simply skip this test in this case.
+    # The longer-term solution is to only have one version of sysconfig.
+    @pytest.mark.skipif("sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER')")
+    def test_sysconfig_compiler_vars(self):
+        import sysconfig as global_sysconfig
+
+        if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'):
+            pytest.skip('compiler flags customized')
+        assert global_sysconfig.get_config_var('LDSHARED') == sysconfig.get_config_var(
+            'LDSHARED'
+        )
+        assert global_sysconfig.get_config_var('CC') == sysconfig.get_config_var('CC')
+
+    @pytest.mark.skipif("not sysconfig.get_config_var('EXT_SUFFIX')")
+    def test_SO_deprecation(self):
+        with pytest.warns(DeprecationWarning):
+            sysconfig.get_config_var('SO')
+
+    def test_customize_compiler_before_get_config_vars(self, tmp_path):
+        # Issue #21923: test that a Distribution compiler
+        # instance can be called without an explicit call to
+        # get_config_vars().
+        jaraco.path.build(
+            {
+                'file': trim("""
+                    from distutils.core import Distribution
+                    config = Distribution().get_command_obj('config')
+                    # try_compile may pass or it may fail if no compiler
+                    # is found but it should not raise an exception.
+                    rc = config.try_compile('int x;')
+                    """)
+            },
+            tmp_path,
+        )
+        p = subprocess.Popen(
+            [sys.executable, tmp_path / 'file'],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            universal_newlines=True,
+            encoding='utf-8',
+        )
+        outs, errs = p.communicate()
+        assert 0 == p.returncode, "Subprocess failed: " + outs
+
+    def test_parse_config_h(self):
+        config_h = sysconfig.get_config_h_filename()
+        input = {}
+        with open(config_h, encoding="utf-8") as f:
+            result = sysconfig.parse_config_h(f, g=input)
+        assert input is result
+        with open(config_h, encoding="utf-8") as f:
+            result = sysconfig.parse_config_h(f)
+        assert isinstance(result, dict)
+
+    @pytest.mark.skipif("platform.system() != 'Windows'")
+    @pytest.mark.skipif("sys.implementation.name != 'cpython'")
+    def test_win_ext_suffix(self):
+        assert sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd")
+        assert sysconfig.get_config_var("EXT_SUFFIX") != ".pyd"
+
+    @pytest.mark.skipif("platform.system() != 'Windows'")
+    @pytest.mark.skipif("sys.implementation.name != 'cpython'")
+    @pytest.mark.skipif(
+        '\\PCbuild\\'.casefold() not in sys.executable.casefold(),
+        reason='Need sys.executable to be in a source tree',
+    )
+    def test_win_build_venv_from_source_tree(self, tmp_path):
+        """Ensure distutils.sysconfig detects venvs from source tree builds."""
+        env = jaraco.envs.VEnv()
+        env.create_opts = env.clean_opts
+        env.root = tmp_path
+        env.ensure_env()
+        cmd = [
+            env.exe(),
+            "-c",
+            "import distutils.sysconfig; print(distutils.sysconfig.python_build)",
+        ]
+        distutils_path = os.path.dirname(os.path.dirname(distutils.__file__))
+        out = subprocess.check_output(
+            cmd, env={**os.environ, "PYTHONPATH": distutils_path}
+        )
+        assert out == "True"
+
+    def test_get_python_inc_missing_config_dir(self, monkeypatch):
+        """
+        In portable Python installations, the sysconfig will be broken,
+        pointing to the directories where the installation was built and
+        not where it currently is. In this case, ensure that the missing
+        directory isn't used for get_python_inc.
+
+        See pypa/distutils#178.
+        """
+
+        def override(name):
+            if name == 'INCLUDEPY':
+                return '/does-not-exist'
+            return sysconfig.get_config_var(name)
+
+        monkeypatch.setattr(sysconfig, 'get_config_var', override)
+
+        assert os.path.exists(sysconfig.get_python_inc())
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_text_file.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_text_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..f51115656135cd3f348a45d4a14f97eeee47fb98
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_text_file.py
@@ -0,0 +1,127 @@
+"""Tests for distutils.text_file."""
+
+from distutils.tests import support
+from distutils.text_file import TextFile
+
+import jaraco.path
+import path
+
+TEST_DATA = """# test file
+
+line 3 \\
+# intervening comment
+  continues on next line
+"""
+
+
+class TestTextFile(support.TempdirManager):
+    def test_class(self):
+        # old tests moved from text_file.__main__
+        # so they are really called by the buildbots
+
+        # result 1: no fancy options
+        result1 = [
+            '# test file\n',
+            '\n',
+            'line 3 \\\n',
+            '# intervening comment\n',
+            '  continues on next line\n',
+        ]
+
+        # result 2: just strip comments
+        result2 = ["\n", "line 3 \\\n", "  continues on next line\n"]
+
+        # result 3: just strip blank lines
+        result3 = [
+            "# test file\n",
+            "line 3 \\\n",
+            "# intervening comment\n",
+            "  continues on next line\n",
+        ]
+
+        # result 4: default, strip comments, blank lines,
+        # and trailing whitespace
+        result4 = ["line 3 \\", "  continues on next line"]
+
+        # result 5: strip comments and blanks, plus join lines (but don't
+        # "collapse" joined lines
+        result5 = ["line 3   continues on next line"]
+
+        # result 6: strip comments and blanks, plus join lines (and
+        # "collapse" joined lines
+        result6 = ["line 3 continues on next line"]
+
+        def test_input(count, description, file, expected_result):
+            result = file.readlines()
+            assert result == expected_result
+
+        tmp_path = path.Path(self.mkdtemp())
+        filename = tmp_path / 'test.txt'
+        jaraco.path.build({filename.name: TEST_DATA}, tmp_path)
+
+        in_file = TextFile(
+            filename,
+            strip_comments=False,
+            skip_blanks=False,
+            lstrip_ws=False,
+            rstrip_ws=False,
+        )
+        try:
+            test_input(1, "no processing", in_file, result1)
+        finally:
+            in_file.close()
+
+        in_file = TextFile(
+            filename,
+            strip_comments=True,
+            skip_blanks=False,
+            lstrip_ws=False,
+            rstrip_ws=False,
+        )
+        try:
+            test_input(2, "strip comments", in_file, result2)
+        finally:
+            in_file.close()
+
+        in_file = TextFile(
+            filename,
+            strip_comments=False,
+            skip_blanks=True,
+            lstrip_ws=False,
+            rstrip_ws=False,
+        )
+        try:
+            test_input(3, "strip blanks", in_file, result3)
+        finally:
+            in_file.close()
+
+        in_file = TextFile(filename)
+        try:
+            test_input(4, "default processing", in_file, result4)
+        finally:
+            in_file.close()
+
+        in_file = TextFile(
+            filename,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            rstrip_ws=True,
+        )
+        try:
+            test_input(5, "join lines without collapsing", in_file, result5)
+        finally:
+            in_file.close()
+
+        in_file = TextFile(
+            filename,
+            strip_comments=True,
+            skip_blanks=True,
+            join_lines=True,
+            rstrip_ws=True,
+            collapse_join=True,
+        )
+        try:
+            test_input(6, "join lines with collapsing", in_file, result6)
+        finally:
+            in_file.close()
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..00c9743ed0a2664039060ef149d30f165bf2f465
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_util.py
@@ -0,0 +1,243 @@
+"""Tests for distutils.util."""
+
+import email
+import email.generator
+import email.policy
+import io
+import os
+import pathlib
+import sys
+import sysconfig as stdlib_sysconfig
+import unittest.mock as mock
+from copy import copy
+from distutils import sysconfig, util
+from distutils.errors import DistutilsByteCompileError, DistutilsPlatformError
+from distutils.util import (
+    byte_compile,
+    change_root,
+    check_environ,
+    convert_path,
+    get_host_platform,
+    get_platform,
+    grok_environment_error,
+    rfc822_escape,
+    split_quoted,
+    strtobool,
+)
+
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def environment(monkeypatch):
+    monkeypatch.setattr(os, 'name', os.name)
+    monkeypatch.setattr(sys, 'platform', sys.platform)
+    monkeypatch.setattr(sys, 'version', sys.version)
+    monkeypatch.setattr(os, 'sep', os.sep)
+    monkeypatch.setattr(os.path, 'join', os.path.join)
+    monkeypatch.setattr(os.path, 'isabs', os.path.isabs)
+    monkeypatch.setattr(os.path, 'splitdrive', os.path.splitdrive)
+    monkeypatch.setattr(sysconfig, '_config_vars', copy(sysconfig._config_vars))
+
+
+@pytest.mark.usefixtures('save_env')
+class TestUtil:
+    def test_get_host_platform(self):
+        with mock.patch('os.name', 'nt'):
+            with mock.patch('sys.version', '... [... (ARM64)]'):
+                assert get_host_platform() == 'win-arm64'
+            with mock.patch('sys.version', '... [... (ARM)]'):
+                assert get_host_platform() == 'win-arm32'
+
+        with mock.patch('sys.version_info', (3, 9, 0, 'final', 0)):
+            assert get_host_platform() == stdlib_sysconfig.get_platform()
+
+    def test_get_platform(self):
+        with mock.patch('os.name', 'nt'):
+            with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}):
+                assert get_platform() == 'win32'
+            with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}):
+                assert get_platform() == 'win-amd64'
+            with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}):
+                assert get_platform() == 'win-arm32'
+            with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}):
+                assert get_platform() == 'win-arm64'
+
+    def test_convert_path(self):
+        expected = os.sep.join(('', 'home', 'to', 'my', 'stuff'))
+        assert convert_path('/home/to/my/stuff') == expected
+        assert convert_path(pathlib.Path('/home/to/my/stuff')) == expected
+        assert convert_path('.') == os.curdir
+
+    def test_change_root(self):
+        # linux/mac
+        os.name = 'posix'
+
+        def _isabs(path):
+            return path[0] == '/'
+
+        os.path.isabs = _isabs
+
+        def _join(*path):
+            return '/'.join(path)
+
+        os.path.join = _join
+
+        assert change_root('/root', '/old/its/here') == '/root/old/its/here'
+        assert change_root('/root', 'its/here') == '/root/its/here'
+
+        # windows
+        os.name = 'nt'
+        os.sep = '\\'
+
+        def _isabs(path):
+            return path.startswith('c:\\')
+
+        os.path.isabs = _isabs
+
+        def _splitdrive(path):
+            if path.startswith('c:'):
+                return ('', path.replace('c:', ''))
+            return ('', path)
+
+        os.path.splitdrive = _splitdrive
+
+        def _join(*path):
+            return '\\'.join(path)
+
+        os.path.join = _join
+
+        assert (
+            change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here'
+        )
+        assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here'
+
+        # BugsBunny os (it's a great os)
+        os.name = 'BugsBunny'
+        with pytest.raises(DistutilsPlatformError):
+            change_root('c:\\root', 'its\\here')
+
+        # XXX platforms to be covered: mac
+
+    def test_check_environ(self):
+        util.check_environ.cache_clear()
+        os.environ.pop('HOME', None)
+
+        check_environ()
+
+        assert os.environ['PLAT'] == get_platform()
+
+    @pytest.mark.skipif("os.name != 'posix'")
+    def test_check_environ_getpwuid(self):
+        util.check_environ.cache_clear()
+        os.environ.pop('HOME', None)
+
+        import pwd
+
+        # only set pw_dir field, other fields are not used
+        result = pwd.struct_passwd((
+            None,
+            None,
+            None,
+            None,
+            None,
+            '/home/distutils',
+            None,
+        ))
+        with mock.patch.object(pwd, 'getpwuid', return_value=result):
+            check_environ()
+            assert os.environ['HOME'] == '/home/distutils'
+
+        util.check_environ.cache_clear()
+        os.environ.pop('HOME', None)
+
+        # bpo-10496: Catch pwd.getpwuid() error
+        with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError):
+            check_environ()
+            assert 'HOME' not in os.environ
+
+    def test_split_quoted(self):
+        assert split_quoted('""one"" "two" \'three\' \\four') == [
+            'one',
+            'two',
+            'three',
+            'four',
+        ]
+
+    def test_strtobool(self):
+        yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
+        no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N')
+
+        for y in yes:
+            assert strtobool(y)
+
+        for n in no:
+            assert not strtobool(n)
+
+    indent = 8 * ' '
+
+    @pytest.mark.parametrize(
+        "given,wanted",
+        [
+            # 0x0b, 0x0c, ..., etc are also considered a line break by Python
+            ("hello\x0b\nworld\n", f"hello\x0b{indent}\n{indent}world\n{indent}"),
+            ("hello\x1eworld", f"hello\x1e{indent}world"),
+            ("", ""),
+            (
+                "I am a\npoor\nlonesome\nheader\n",
+                f"I am a\n{indent}poor\n{indent}lonesome\n{indent}header\n{indent}",
+            ),
+        ],
+    )
+    def test_rfc822_escape(self, given, wanted):
+        """
+        We want to ensure a multi-line header parses correctly.
+
+        For interoperability, the escaped value should also "round-trip" over
+        `email.generator.Generator.flatten` and `email.message_from_*`
+        (see pypa/setuptools#4033).
+
+        The main issue is that internally `email.policy.EmailPolicy` uses
+        `splitlines` which will split on some control chars. If all the new lines
+        are not prefixed with spaces, the parser will interrupt reading
+        the current header and produce an incomplete value, while
+        incorrectly interpreting the rest of the headers as part of the payload.
+        """
+        res = rfc822_escape(given)
+
+        policy = email.policy.EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with io.StringIO() as buffer:
+            raw = f"header: {res}\nother-header: 42\n\npayload\n"
+            orig = email.message_from_string(raw)
+            email.generator.Generator(buffer, policy=policy).flatten(orig)
+            buffer.seek(0)
+            regen = email.message_from_file(buffer)
+
+        for msg in (orig, regen):
+            assert msg.get_payload() == "payload\n"
+            assert msg["other-header"] == "42"
+            # Generator may replace control chars with `\n`
+            assert set(msg["header"].splitlines()) == set(res.splitlines())
+
+        assert res == wanted
+
+    def test_dont_write_bytecode(self):
+        # makes sure byte_compile raise a DistutilsError
+        # if sys.dont_write_bytecode is True
+        old_dont_write_bytecode = sys.dont_write_bytecode
+        sys.dont_write_bytecode = True
+        try:
+            with pytest.raises(DistutilsByteCompileError):
+                byte_compile([])
+        finally:
+            sys.dont_write_bytecode = old_dont_write_bytecode
+
+    def test_grok_environment_error(self):
+        # test obsolete function to ensure backward compat (#4931)
+        exc = OSError("Unable to find batch file")
+        msg = grok_environment_error(exc)
+        assert msg == "error: Unable to find batch file"
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_version.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..b68f0977249aa23aafbf31cf74a0e4127f777d05
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_version.py
@@ -0,0 +1,80 @@
+"""Tests for distutils.version."""
+
+import distutils
+from distutils.version import LooseVersion, StrictVersion
+
+import pytest
+
+
+@pytest.fixture(autouse=True)
+def suppress_deprecation():
+    with distutils.version.suppress_known_deprecation():
+        yield
+
+
+class TestVersion:
+    def test_prerelease(self):
+        version = StrictVersion('1.2.3a1')
+        assert version.version == (1, 2, 3)
+        assert version.prerelease == ('a', 1)
+        assert str(version) == '1.2.3a1'
+
+        version = StrictVersion('1.2.0')
+        assert str(version) == '1.2'
+
+    def test_cmp_strict(self):
+        versions = (
+            ('1.5.1', '1.5.2b2', -1),
+            ('161', '3.10a', ValueError),
+            ('8.02', '8.02', 0),
+            ('3.4j', '1996.07.12', ValueError),
+            ('3.2.pl0', '3.1.1.6', ValueError),
+            ('2g6', '11g', ValueError),
+            ('0.9', '2.2', -1),
+            ('1.2.1', '1.2', 1),
+            ('1.1', '1.2.2', -1),
+            ('1.2', '1.1', 1),
+            ('1.2.1', '1.2.2', -1),
+            ('1.2.2', '1.2', 1),
+            ('1.2', '1.2.2', -1),
+            ('0.4.0', '0.4', 0),
+            ('1.13++', '5.5.kw', ValueError),
+        )
+
+        for v1, v2, wanted in versions:
+            try:
+                res = StrictVersion(v1)._cmp(StrictVersion(v2))
+            except ValueError:
+                if wanted is ValueError:
+                    continue
+                else:
+                    raise AssertionError(f"cmp({v1}, {v2}) shouldn't raise ValueError")
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
+            res = StrictVersion(v1)._cmp(v2)
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
+            res = StrictVersion(v1)._cmp(object())
+            assert res is NotImplemented, (
+                f'cmp({v1}, {v2}) should be NotImplemented, got {res}'
+            )
+
+    def test_cmp(self):
+        versions = (
+            ('1.5.1', '1.5.2b2', -1),
+            ('161', '3.10a', 1),
+            ('8.02', '8.02', 0),
+            ('3.4j', '1996.07.12', -1),
+            ('3.2.pl0', '3.1.1.6', 1),
+            ('2g6', '11g', -1),
+            ('0.960923', '2.2beta29', -1),
+            ('1.13++', '5.5.kw', -1),
+        )
+
+        for v1, v2, wanted in versions:
+            res = LooseVersion(v1)._cmp(LooseVersion(v2))
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
+            res = LooseVersion(v1)._cmp(v2)
+            assert res == wanted, f'cmp({v1}, {v2}) should be {wanted}, got {res}'
+            res = LooseVersion(v1)._cmp(object())
+            assert res is NotImplemented, (
+                f'cmp({v1}, {v2}) should be NotImplemented, got {res}'
+            )
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_versionpredicate.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/test_versionpredicate.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/tests/unix_compat.py b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/unix_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5d9ee45ccc639794d29ba0a5fd24f781ee5ecf5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/tests/unix_compat.py
@@ -0,0 +1,17 @@
+import sys
+
+try:
+    import grp
+    import pwd
+except ImportError:
+    grp = pwd = None
+
+import pytest
+
+UNIX_ID_SUPPORT = grp and pwd
+UID_0_SUPPORT = UNIX_ID_SUPPORT and sys.platform != "cygwin"
+
+require_unix_id = pytest.mark.skipif(
+    not UNIX_ID_SUPPORT, reason="Requires grp and pwd support"
+)
+require_uid_0 = pytest.mark.skipif(not UID_0_SUPPORT, reason="Requires UID 0 support")
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/text_file.py b/python_embeded/Lib/site-packages/setuptools/_distutils/text_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..89d9048d5902950516c3541ad212bff7b6cb2045
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/text_file.py
@@ -0,0 +1,286 @@
+"""text_file
+
+provides the TextFile class, which gives an interface to text files
+that (optionally) takes care of stripping comments, ignoring blank
+lines, and joining lines with backslashes."""
+
+import sys
+
+
+class TextFile:
+    """Provides a file-like object that takes care of all the things you
+    commonly want to do when processing a text file that has some
+    line-by-line syntax: strip comments (as long as "#" is your
+    comment character), skip blank lines, join adjacent lines by
+    escaping the newline (ie. backslash at end of line), strip
+    leading and/or trailing whitespace.  All of these are optional
+    and independently controllable.
+
+    Provides a 'warn()' method so you can generate warning messages that
+    report physical line number, even if the logical line in question
+    spans multiple physical lines.  Also provides 'unreadline()' for
+    implementing line-at-a-time lookahead.
+
+    Constructor is called as:
+
+        TextFile (filename=None, file=None, **options)
+
+    It bombs (RuntimeError) if both 'filename' and 'file' are None;
+    'filename' should be a string, and 'file' a file object (or
+    something that provides 'readline()' and 'close()' methods).  It is
+    recommended that you supply at least 'filename', so that TextFile
+    can include it in warning messages.  If 'file' is not supplied,
+    TextFile creates its own using 'io.open()'.
+
+    The options are all boolean, and affect the value returned by
+    'readline()':
+      strip_comments [default: true]
+        strip from "#" to end-of-line, as well as any whitespace
+        leading up to the "#" -- unless it is escaped by a backslash
+      lstrip_ws [default: false]
+        strip leading whitespace from each line before returning it
+      rstrip_ws [default: true]
+        strip trailing whitespace (including line terminator!) from
+        each line before returning it
+      skip_blanks [default: true}
+        skip lines that are empty *after* stripping comments and
+        whitespace.  (If both lstrip_ws and rstrip_ws are false,
+        then some lines may consist of solely whitespace: these will
+        *not* be skipped, even if 'skip_blanks' is true.)
+      join_lines [default: false]
+        if a backslash is the last non-newline character on a line
+        after stripping comments and whitespace, join the following line
+        to it to form one "logical line"; if N consecutive lines end
+        with a backslash, then N+1 physical lines will be joined to
+        form one logical line.
+      collapse_join [default: false]
+        strip leading whitespace from lines that are joined to their
+        predecessor; only matters if (join_lines and not lstrip_ws)
+      errors [default: 'strict']
+        error handler used to decode the file content
+
+    Note that since 'rstrip_ws' can strip the trailing newline, the
+    semantics of 'readline()' must differ from those of the builtin file
+    object's 'readline()' method!  In particular, 'readline()' returns
+    None for end-of-file: an empty string might just be a blank line (or
+    an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
+    not."""
+
+    default_options = {
+        'strip_comments': 1,
+        'skip_blanks': 1,
+        'lstrip_ws': 0,
+        'rstrip_ws': 1,
+        'join_lines': 0,
+        'collapse_join': 0,
+        'errors': 'strict',
+    }
+
+    def __init__(self, filename=None, file=None, **options):
+        """Construct a new TextFile object.  At least one of 'filename'
+        (a string) and 'file' (a file-like object) must be supplied.
+        They keyword argument options are described above and affect
+        the values returned by 'readline()'."""
+        if filename is None and file is None:
+            raise RuntimeError(
+                "you must supply either or both of 'filename' and 'file'"
+            )
+
+        # set values for all options -- either from client option hash
+        # or fallback to default_options
+        for opt in self.default_options.keys():
+            if opt in options:
+                setattr(self, opt, options[opt])
+            else:
+                setattr(self, opt, self.default_options[opt])
+
+        # sanity check client option hash
+        for opt in options.keys():
+            if opt not in self.default_options:
+                raise KeyError(f"invalid TextFile option '{opt}'")
+
+        if file is None:
+            self.open(filename)
+        else:
+            self.filename = filename
+            self.file = file
+            self.current_line = 0  # assuming that file is at BOF!
+
+        # 'linebuf' is a stack of lines that will be emptied before we
+        # actually read from the file; it's only populated by an
+        # 'unreadline()' operation
+        self.linebuf = []
+
+    def open(self, filename):
+        """Open a new file named 'filename'.  This overrides both the
+        'filename' and 'file' arguments to the constructor."""
+        self.filename = filename
+        self.file = open(self.filename, errors=self.errors, encoding='utf-8')
+        self.current_line = 0
+
+    def close(self):
+        """Close the current file and forget everything we know about it
+        (filename, current line number)."""
+        file = self.file
+        self.file = None
+        self.filename = None
+        self.current_line = None
+        file.close()
+
+    def gen_error(self, msg, line=None):
+        outmsg = []
+        if line is None:
+            line = self.current_line
+        outmsg.append(self.filename + ", ")
+        if isinstance(line, (list, tuple)):
+            outmsg.append("lines {}-{}: ".format(*line))
+        else:
+            outmsg.append(f"line {int(line)}: ")
+        outmsg.append(str(msg))
+        return "".join(outmsg)
+
+    def error(self, msg, line=None):
+        raise ValueError("error: " + self.gen_error(msg, line))
+
+    def warn(self, msg, line=None):
+        """Print (to stderr) a warning message tied to the current logical
+        line in the current file.  If the current logical line in the
+        file spans multiple physical lines, the warning refers to the
+        whole range, eg. "lines 3-5".  If 'line' supplied, it overrides
+        the current line number; it may be a list or tuple to indicate a
+        range of physical lines, or an integer for a single physical
+        line."""
+        sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
+
+    def readline(self):  # noqa: C901
+        """Read and return a single logical line from the current file (or
+        from an internal buffer if lines have previously been "unread"
+        with 'unreadline()').  If the 'join_lines' option is true, this
+        may involve reading multiple physical lines concatenated into a
+        single string.  Updates the current line number, so calling
+        'warn()' after 'readline()' emits a warning about the physical
+        line(s) just read.  Returns None on end-of-file, since the empty
+        string can occur if 'rstrip_ws' is true but 'strip_blanks' is
+        not."""
+        # If any "unread" lines waiting in 'linebuf', return the top
+        # one.  (We don't actually buffer read-ahead data -- lines only
+        # get put in 'linebuf' if the client explicitly does an
+        # 'unreadline()'.
+        if self.linebuf:
+            line = self.linebuf[-1]
+            del self.linebuf[-1]
+            return line
+
+        buildup_line = ''
+
+        while True:
+            # read the line, make it None if EOF
+            line = self.file.readline()
+            if line == '':
+                line = None
+
+            if self.strip_comments and line:
+                # Look for the first "#" in the line.  If none, never
+                # mind.  If we find one and it's the first character, or
+                # is not preceded by "\", then it starts a comment --
+                # strip the comment, strip whitespace before it, and
+                # carry on.  Otherwise, it's just an escaped "#", so
+                # unescape it (and any other escaped "#"'s that might be
+                # lurking in there) and otherwise leave the line alone.
+
+                pos = line.find("#")
+                if pos == -1:  # no "#" -- no comments
+                    pass
+
+                # It's definitely a comment -- either "#" is the first
+                # character, or it's elsewhere and unescaped.
+                elif pos == 0 or line[pos - 1] != "\\":
+                    # Have to preserve the trailing newline, because it's
+                    # the job of a later step (rstrip_ws) to remove it --
+                    # and if rstrip_ws is false, we'd better preserve it!
+                    # (NB. this means that if the final line is all comment
+                    # and has no trailing newline, we will think that it's
+                    # EOF; I think that's OK.)
+                    eol = (line[-1] == '\n') and '\n' or ''
+                    line = line[0:pos] + eol
+
+                    # If all that's left is whitespace, then skip line
+                    # *now*, before we try to join it to 'buildup_line' --
+                    # that way constructs like
+                    #   hello \\
+                    #   # comment that should be ignored
+                    #   there
+                    # result in "hello there".
+                    if line.strip() == "":
+                        continue
+                else:  # it's an escaped "#"
+                    line = line.replace("\\#", "#")
+
+            # did previous line end with a backslash? then accumulate
+            if self.join_lines and buildup_line:
+                # oops: end of file
+                if line is None:
+                    self.warn("continuation line immediately precedes end-of-file")
+                    return buildup_line
+
+                if self.collapse_join:
+                    line = line.lstrip()
+                line = buildup_line + line
+
+                # careful: pay attention to line number when incrementing it
+                if isinstance(self.current_line, list):
+                    self.current_line[1] = self.current_line[1] + 1
+                else:
+                    self.current_line = [self.current_line, self.current_line + 1]
+            # just an ordinary line, read it as usual
+            else:
+                if line is None:  # eof
+                    return None
+
+                # still have to be careful about incrementing the line number!
+                if isinstance(self.current_line, list):
+                    self.current_line = self.current_line[1] + 1
+                else:
+                    self.current_line = self.current_line + 1
+
+            # strip whitespace however the client wants (leading and
+            # trailing, or one or the other, or neither)
+            if self.lstrip_ws and self.rstrip_ws:
+                line = line.strip()
+            elif self.lstrip_ws:
+                line = line.lstrip()
+            elif self.rstrip_ws:
+                line = line.rstrip()
+
+            # blank line (whether we rstrip'ed or not)? skip to next line
+            # if appropriate
+            if line in ('', '\n') and self.skip_blanks:
+                continue
+
+            if self.join_lines:
+                if line[-1] == '\\':
+                    buildup_line = line[:-1]
+                    continue
+
+                if line[-2:] == '\\\n':
+                    buildup_line = line[0:-2] + '\n'
+                    continue
+
+            # well, I guess there's some actual content there: return it
+            return line
+
+    def readlines(self):
+        """Read and return the list of all logical lines remaining in the
+        current file."""
+        lines = []
+        while True:
+            line = self.readline()
+            if line is None:
+                return lines
+            lines.append(line)
+
+    def unreadline(self, line):
+        """Push 'line' (a string) onto an internal buffer that will be
+        checked by future 'readline()' calls.  Handy for implementing
+        a parser with line-at-a-time lookahead."""
+        self.linebuf.append(line)
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/unixccompiler.py b/python_embeded/Lib/site-packages/setuptools/_distutils/unixccompiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b8ce6b9bba21bd709b77249bdcae5b4119e9ca
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/unixccompiler.py
@@ -0,0 +1,9 @@
+import importlib
+
+from .compilers.C import unix
+
+UnixCCompiler = unix.Compiler
+
+# ensure import of unixccompiler implies ccompiler imported
+# (pypa/setuptools#4871)
+importlib.import_module('distutils.ccompiler')
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/util.py b/python_embeded/Lib/site-packages/setuptools/_distutils/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dbe049f4274f7177295491d7f433e8ca303df48
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/util.py
@@ -0,0 +1,518 @@
+"""distutils.util
+
+Miscellaneous utility functions -- anything that doesn't fit into
+one of the other *util.py modules.
+"""
+
+from __future__ import annotations
+
+import functools
+import importlib.util
+import os
+import pathlib
+import re
+import string
+import subprocess
+import sys
+import sysconfig
+import tempfile
+from collections.abc import Callable, Iterable, Mapping
+from typing import TYPE_CHECKING, AnyStr
+
+from jaraco.functools import pass_none
+
+from ._log import log
+from ._modified import newer
+from .errors import DistutilsByteCompileError, DistutilsPlatformError
+from .spawn import spawn
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeVarTuple, Unpack
+
+    _Ts = TypeVarTuple("_Ts")
+
+
+def get_host_platform() -> str:
+    """
+    Return a string that identifies the current platform. Use this
+    function to distinguish platform-specific build directories and
+    platform-specific built distributions.
+    """
+
+    # This function initially exposed platforms as defined in Python 3.9
+    # even with older Python versions when distutils was split out.
+    # Now it delegates to stdlib sysconfig.
+
+    return sysconfig.get_platform()
+
+
+def get_platform() -> str:
+    if os.name == 'nt':
+        TARGET_TO_PLAT = {
+            'x86': 'win32',
+            'x64': 'win-amd64',
+            'arm': 'win-arm32',
+            'arm64': 'win-arm64',
+        }
+        target = os.environ.get('VSCMD_ARG_TGT_ARCH')
+        return TARGET_TO_PLAT.get(target) or get_host_platform()
+    return get_host_platform()
+
+
+if sys.platform == 'darwin':
+    _syscfg_macosx_ver = None  # cache the version pulled from sysconfig
+MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'
+
+
+def _clear_cached_macosx_ver():
+    """For testing only. Do not call."""
+    global _syscfg_macosx_ver
+    _syscfg_macosx_ver = None
+
+
+def get_macosx_target_ver_from_syscfg():
+    """Get the version of macOS latched in the Python interpreter configuration.
+    Returns the version as a string or None if can't obtain one. Cached."""
+    global _syscfg_macosx_ver
+    if _syscfg_macosx_ver is None:
+        from distutils import sysconfig
+
+        ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''
+        if ver:
+            _syscfg_macosx_ver = ver
+    return _syscfg_macosx_ver
+
+
+def get_macosx_target_ver():
+    """Return the version of macOS for which we are building.
+
+    The target version defaults to the version in sysconfig latched at time
+    the Python interpreter was built, unless overridden by an environment
+    variable. If neither source has a value, then None is returned"""
+
+    syscfg_ver = get_macosx_target_ver_from_syscfg()
+    env_ver = os.environ.get(MACOSX_VERSION_VAR)
+
+    if env_ver:
+        # Validate overridden version against sysconfig version, if have both.
+        # Ensure that the deployment target of the build process is not less
+        # than 10.3 if the interpreter was built for 10.3 or later.  This
+        # ensures extension modules are built with correct compatibility
+        # values, specifically LDSHARED which can use
+        # '-undefined dynamic_lookup' which only works on >= 10.3.
+        if (
+            syscfg_ver
+            and split_version(syscfg_ver) >= [10, 3]
+            and split_version(env_ver) < [10, 3]
+        ):
+            my_msg = (
+                '$' + MACOSX_VERSION_VAR + ' mismatch: '
+                f'now "{env_ver}" but "{syscfg_ver}" during configure; '
+                'must use 10.3 or later'
+            )
+            raise DistutilsPlatformError(my_msg)
+        return env_ver
+    return syscfg_ver
+
+
+def split_version(s: str) -> list[int]:
+    """Convert a dot-separated string into a list of numbers for comparisons"""
+    return [int(n) for n in s.split('.')]
+
+
+@pass_none
+def convert_path(pathname: str | os.PathLike[str]) -> str:
+    r"""
+    Allow for pathlib.Path inputs, coax to a native path string.
+
+    If None is passed, will just pass it through as
+    Setuptools relies on this behavior.
+
+    >>> convert_path(None) is None
+    True
+
+    Removes empty paths.
+
+    >>> convert_path('foo/./bar').replace('\\', '/')
+    'foo/bar'
+    """
+    return os.fspath(pathlib.PurePath(pathname))
+
+
+def change_root(
+    new_root: AnyStr | os.PathLike[AnyStr], pathname: AnyStr | os.PathLike[AnyStr]
+) -> AnyStr:
+    """Return 'pathname' with 'new_root' prepended.  If 'pathname' is
+    relative, this is equivalent to "os.path.join(new_root,pathname)".
+    Otherwise, it requires making 'pathname' relative and then joining the
+    two, which is tricky on DOS/Windows and Mac OS.
+    """
+    if os.name == 'posix':
+        if not os.path.isabs(pathname):
+            return os.path.join(new_root, pathname)
+        else:
+            return os.path.join(new_root, pathname[1:])
+
+    elif os.name == 'nt':
+        (drive, path) = os.path.splitdrive(pathname)
+        if path[0] == os.sep:
+            path = path[1:]
+        return os.path.join(new_root, path)
+
+    raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
+
+
+@functools.lru_cache
+def check_environ() -> None:
+    """Ensure that 'os.environ' has all the environment variables we
+    guarantee that users can use in config files, command-line options,
+    etc.  Currently this includes:
+      HOME - user's home directory (Unix only)
+      PLAT - description of the current platform, including hardware
+             and OS (see 'get_platform()')
+    """
+    if os.name == 'posix' and 'HOME' not in os.environ:
+        try:
+            import pwd
+
+            os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
+        except (ImportError, KeyError):
+            # bpo-10496: if the current user identifier doesn't exist in the
+            # password database, do nothing
+            pass
+
+    if 'PLAT' not in os.environ:
+        os.environ['PLAT'] = get_platform()
+
+
+def subst_vars(s, local_vars: Mapping[str, object]) -> str:
+    """
+    Perform variable substitution on 'string'.
+    Variables are indicated by format-style braces ("{var}").
+    Variable is substituted by the value found in the 'local_vars'
+    dictionary or in 'os.environ' if it's not in 'local_vars'.
+    'os.environ' is first checked/augmented to guarantee that it contains
+    certain values: see 'check_environ()'.  Raise ValueError for any
+    variables not found in either 'local_vars' or 'os.environ'.
+    """
+    check_environ()
+    lookup = dict(os.environ)
+    lookup.update((name, str(value)) for name, value in local_vars.items())
+    try:
+        return _subst_compat(s).format_map(lookup)
+    except KeyError as var:
+        raise ValueError(f"invalid variable {var}")
+
+
+def _subst_compat(s):
+    """
+    Replace shell/Perl-style variable substitution with
+    format-style. For compatibility.
+    """
+
+    def _subst(match):
+        return f'{{{match.group(1)}}}'
+
+    repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
+    if repl != s:
+        import warnings
+
+        warnings.warn(
+            "shell/Perl-style substitutions are deprecated",
+            DeprecationWarning,
+        )
+    return repl
+
+
+def grok_environment_error(exc: object, prefix: str = "error: ") -> str:
+    # Function kept for backward compatibility.
+    # Used to try clever things with EnvironmentErrors,
+    # but nowadays str(exception) produces good messages.
+    return prefix + str(exc)
+
+
+# Needed by 'split_quoted()'
+_wordchars_re = _squote_re = _dquote_re = None
+
+
+def _init_regex():
+    global _wordchars_re, _squote_re, _dquote_re
+    _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*')
+    _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
+    _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
+
+
+def split_quoted(s: str) -> list[str]:
+    """Split a string up according to Unix shell-like rules for quotes and
+    backslashes.  In short: words are delimited by spaces, as long as those
+    spaces are not escaped by a backslash, or inside a quoted string.
+    Single and double quotes are equivalent, and the quote characters can
+    be backslash-escaped.  The backslash is stripped from any two-character
+    escape sequence, leaving only the escaped character.  The quote
+    characters are stripped from any quoted string.  Returns a list of
+    words.
+    """
+
+    # This is a nice algorithm for splitting up a single string, since it
+    # doesn't require character-by-character examination.  It was a little
+    # bit of a brain-bender to get it working right, though...
+    if _wordchars_re is None:
+        _init_regex()
+
+    s = s.strip()
+    words = []
+    pos = 0
+
+    while s:
+        m = _wordchars_re.match(s, pos)
+        end = m.end()
+        if end == len(s):
+            words.append(s[:end])
+            break
+
+        if s[end] in string.whitespace:
+            # unescaped, unquoted whitespace: now
+            # we definitely have a word delimiter
+            words.append(s[:end])
+            s = s[end:].lstrip()
+            pos = 0
+
+        elif s[end] == '\\':
+            # preserve whatever is being escaped;
+            # will become part of the current word
+            s = s[:end] + s[end + 1 :]
+            pos = end + 1
+
+        else:
+            if s[end] == "'":  # slurp singly-quoted string
+                m = _squote_re.match(s, end)
+            elif s[end] == '"':  # slurp doubly-quoted string
+                m = _dquote_re.match(s, end)
+            else:
+                raise RuntimeError(f"this can't happen (bad char '{s[end]}')")
+
+            if m is None:
+                raise ValueError(f"bad string (mismatched {s[end]} quotes?)")
+
+            (beg, end) = m.span()
+            s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
+            pos = m.end() - 2
+
+        if pos >= len(s):
+            words.append(s)
+            break
+
+    return words
+
+
+# split_quoted ()
+
+
+def execute(
+    func: Callable[[Unpack[_Ts]], object],
+    args: tuple[Unpack[_Ts]],
+    msg: object = None,
+    verbose: bool = False,
+    dry_run: bool = False,
+) -> None:
+    """
+    Perform some action that affects the outside world (e.g. by
+    writing to the filesystem). Such actions are special because they
+    are disabled by the 'dry_run' flag. This method handles that
+    complication; simply supply the
+    function to call and an argument tuple for it (to embody the
+    "external action" being performed) and an optional message to
+    emit.
+    """
+    if msg is None:
+        msg = f"{func.__name__}{args!r}"
+        if msg[-2:] == ',)':  # correct for singleton tuple
+            msg = msg[0:-2] + ')'
+
+    log.info(msg)
+    if not dry_run:
+        func(*args)
+
+
+def strtobool(val: str) -> bool:
+    """Convert a string representation of truth to true (1) or false (0).
+
+    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
+    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
+    'val' is anything else.
+    """
+    val = val.lower()
+    if val in ('y', 'yes', 't', 'true', 'on', '1'):
+        return True
+    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
+        return False
+    else:
+        raise ValueError(f"invalid truth value {val!r}")
+
+
+def byte_compile(  # noqa: C901
+    py_files: Iterable[str],
+    optimize: int = 0,
+    force: bool = False,
+    prefix: str | None = None,
+    base_dir: str | None = None,
+    verbose: bool = True,
+    dry_run: bool = False,
+    direct: bool | None = None,
+) -> None:
+    """Byte-compile a collection of Python source files to .pyc
+    files in a __pycache__ subdirectory.  'py_files' is a list
+    of files to compile; any files that don't end in ".py" are silently
+    skipped.  'optimize' must be one of the following:
+      0 - don't optimize
+      1 - normal optimization (like "python -O")
+      2 - extra optimization (like "python -OO")
+    If 'force' is true, all files are recompiled regardless of
+    timestamps.
+
+    The source filename encoded in each bytecode file defaults to the
+    filenames listed in 'py_files'; you can modify these with 'prefix' and
+    'basedir'.  'prefix' is a string that will be stripped off of each
+    source filename, and 'base_dir' is a directory name that will be
+    prepended (after 'prefix' is stripped).  You can supply either or both
+    (or neither) of 'prefix' and 'base_dir', as you wish.
+
+    If 'dry_run' is true, doesn't actually do anything that would
+    affect the filesystem.
+
+    Byte-compilation is either done directly in this interpreter process
+    with the standard py_compile module, or indirectly by writing a
+    temporary script and executing it.  Normally, you should let
+    'byte_compile()' figure out to use direct compilation or not (see
+    the source for details).  The 'direct' flag is used by the script
+    generated in indirect mode; unless you know what you're doing, leave
+    it set to None.
+    """
+
+    # nothing is done if sys.dont_write_bytecode is True
+    if sys.dont_write_bytecode:
+        raise DistutilsByteCompileError('byte-compiling is disabled.')
+
+    # First, if the caller didn't force us into direct or indirect mode,
+    # figure out which mode we should be in.  We take a conservative
+    # approach: choose direct mode *only* if the current interpreter is
+    # in debug mode and optimize is 0.  If we're not in debug mode (-O
+    # or -OO), we don't know which level of optimization this
+    # interpreter is running with, so we can't do direct
+    # byte-compilation and be certain that it's the right thing.  Thus,
+    # always compile indirectly if the current interpreter is in either
+    # optimize mode, or if either optimization level was requested by
+    # the caller.
+    if direct is None:
+        direct = __debug__ and optimize == 0
+
+    # "Indirect" byte-compilation: write a temporary script and then
+    # run it with the appropriate flags.
+    if not direct:
+        (script_fd, script_name) = tempfile.mkstemp(".py")
+        log.info("writing byte-compilation script '%s'", script_name)
+        if not dry_run:
+            script = os.fdopen(script_fd, "w", encoding='utf-8')
+
+            with script:
+                script.write(
+                    """\
+from distutils.util import byte_compile
+files = [
+"""
+                )
+
+                # XXX would be nice to write absolute filenames, just for
+                # safety's sake (script should be more robust in the face of
+                # chdir'ing before running it).  But this requires abspath'ing
+                # 'prefix' as well, and that breaks the hack in build_lib's
+                # 'byte_compile()' method that carefully tacks on a trailing
+                # slash (os.sep really) to make sure the prefix here is "just
+                # right".  This whole prefix business is rather delicate -- the
+                # problem is that it's really a directory, but I'm treating it
+                # as a dumb string, so trailing slashes and so forth matter.
+
+                script.write(",\n".join(map(repr, py_files)) + "]\n")
+                script.write(
+                    f"""
+byte_compile(files, optimize={optimize!r}, force={force!r},
+             prefix={prefix!r}, base_dir={base_dir!r},
+             verbose={verbose!r}, dry_run=False,
+             direct=True)
+"""
+                )
+
+        cmd = [sys.executable]
+        cmd.extend(subprocess._optim_args_from_interpreter_flags())
+        cmd.append(script_name)
+        spawn(cmd, dry_run=dry_run)
+        execute(os.remove, (script_name,), f"removing {script_name}", dry_run=dry_run)
+
+    # "Direct" byte-compilation: use the py_compile module to compile
+    # right here, right now.  Note that the script generated in indirect
+    # mode simply calls 'byte_compile()' in direct mode, a weird sort of
+    # cross-process recursion.  Hey, it works!
+    else:
+        from py_compile import compile
+
+        for file in py_files:
+            if file[-3:] != ".py":
+                # This lets us be lazy and not filter filenames in
+                # the "install_lib" command.
+                continue
+
+            # Terminology from the py_compile module:
+            #   cfile - byte-compiled file
+            #   dfile - purported source filename (same as 'file' by default)
+            if optimize >= 0:
+                opt = '' if optimize == 0 else optimize
+                cfile = importlib.util.cache_from_source(file, optimization=opt)
+            else:
+                cfile = importlib.util.cache_from_source(file)
+            dfile = file
+            if prefix:
+                if file[: len(prefix)] != prefix:
+                    raise ValueError(
+                        f"invalid prefix: filename {file!r} doesn't start with {prefix!r}"
+                    )
+                dfile = dfile[len(prefix) :]
+            if base_dir:
+                dfile = os.path.join(base_dir, dfile)
+
+            cfile_base = os.path.basename(cfile)
+            if direct:
+                if force or newer(file, cfile):
+                    log.info("byte-compiling %s to %s", file, cfile_base)
+                    if not dry_run:
+                        compile(file, cfile, dfile)
+                else:
+                    log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
+
+
+def rfc822_escape(header: str) -> str:
+    """Return a version of the string escaped for inclusion in an
+    RFC-822 header, by ensuring there are 8 spaces space after each newline.
+    """
+    indent = 8 * " "
+    lines = header.splitlines(keepends=True)
+
+    # Emulate the behaviour of `str.split`
+    # (the terminal line break in `splitlines` does not result in an extra line):
+    ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1]
+    suffix = indent if ends_in_newline else ""
+
+    return indent.join(lines) + suffix
+
+
+def is_mingw() -> bool:
+    """Returns True if the current platform is mingw.
+
+    Python compiled with Mingw-w64 has sys.platform == 'win32' and
+    get_platform() starts with 'mingw'.
+    """
+    return sys.platform == 'win32' and get_platform().startswith('mingw')
+
+
+def is_freethreaded():
+    """Return True if the Python interpreter is built with free threading support."""
+    return bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/version.py b/python_embeded/Lib/site-packages/setuptools/_distutils/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2223ee9c8cab2495034a57d4585625feb81a8330
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/version.py
@@ -0,0 +1,348 @@
+#
+# distutils/version.py
+#
+# Implements multiple version numbering conventions for the
+# Python Module Distribution Utilities.
+#
+# $Id$
+#
+
+"""Provides classes to represent module version numbers (one class for
+each style of version numbering).  There are currently two such classes
+implemented: StrictVersion and LooseVersion.
+
+Every version number class implements the following interface:
+  * the 'parse' method takes a string and parses it to some internal
+    representation; if the string is an invalid version number,
+    'parse' raises a ValueError exception
+  * the class constructor takes an optional string argument which,
+    if supplied, is passed to 'parse'
+  * __str__ reconstructs the string that was passed to 'parse' (or
+    an equivalent string -- ie. one that will generate an equivalent
+    version number instance)
+  * __repr__ generates Python code to recreate the version number instance
+  * _cmp compares the current instance with either another instance
+    of the same class or a string (which will be parsed to an instance
+    of the same class, thus must follow the same rules)
+"""
+
+import contextlib
+import re
+import warnings
+
+
+@contextlib.contextmanager
+def suppress_known_deprecation():
+    with warnings.catch_warnings(record=True) as ctx:
+        warnings.filterwarnings(
+            action='default',
+            category=DeprecationWarning,
+            message="distutils Version classes are deprecated.",
+        )
+        yield ctx
+
+
+class Version:
+    """Abstract base class for version numbering classes.  Just provides
+    constructor (__init__) and reproducer (__repr__), because those
+    seem to be the same for all version numbering classes; and route
+    rich comparisons to _cmp.
+    """
+
+    def __init__(self, vstring=None):
+        if vstring:
+            self.parse(vstring)
+        warnings.warn(
+            "distutils Version classes are deprecated. Use packaging.version instead.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    def __repr__(self):
+        return f"{self.__class__.__name__} ('{self}')"
+
+    def __eq__(self, other):
+        c = self._cmp(other)
+        if c is NotImplemented:
+            return c
+        return c == 0
+
+    def __lt__(self, other):
+        c = self._cmp(other)
+        if c is NotImplemented:
+            return c
+        return c < 0
+
+    def __le__(self, other):
+        c = self._cmp(other)
+        if c is NotImplemented:
+            return c
+        return c <= 0
+
+    def __gt__(self, other):
+        c = self._cmp(other)
+        if c is NotImplemented:
+            return c
+        return c > 0
+
+    def __ge__(self, other):
+        c = self._cmp(other)
+        if c is NotImplemented:
+            return c
+        return c >= 0
+
+
+# Interface for version-number classes -- must be implemented
+# by the following classes (the concrete ones -- Version should
+# be treated as an abstract class).
+#    __init__ (string) - create and take same action as 'parse'
+#                        (string parameter is optional)
+#    parse (string)    - convert a string representation to whatever
+#                        internal representation is appropriate for
+#                        this style of version numbering
+#    __str__ (self)    - convert back to a string; should be very similar
+#                        (if not identical to) the string supplied to parse
+#    __repr__ (self)   - generate Python code to recreate
+#                        the instance
+#    _cmp (self, other) - compare two version numbers ('other' may
+#                        be an unparsed version string, or another
+#                        instance of your version class)
+
+
+class StrictVersion(Version):
+    """Version numbering for anal retentives and software idealists.
+    Implements the standard interface for version number classes as
+    described above.  A version number consists of two or three
+    dot-separated numeric components, with an optional "pre-release" tag
+    on the end.  The pre-release tag consists of the letter 'a' or 'b'
+    followed by a number.  If the numeric components of two version
+    numbers are equal, then one with a pre-release tag will always
+    be deemed earlier (lesser) than one without.
+
+    The following are valid version numbers (shown in the order that
+    would be obtained by sorting according to the supplied cmp function):
+
+        0.4       0.4.0  (these two are equivalent)
+        0.4.1
+        0.5a1
+        0.5b3
+        0.5
+        0.9.6
+        1.0
+        1.0.4a3
+        1.0.4b1
+        1.0.4
+
+    The following are examples of invalid version numbers:
+
+        1
+        2.7.2.2
+        1.3.a4
+        1.3pl1
+        1.3c4
+
+    The rationale for this version numbering system will be explained
+    in the distutils documentation.
+    """
+
+    version_re = re.compile(
+        r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII
+    )
+
+    def parse(self, vstring):
+        match = self.version_re.match(vstring)
+        if not match:
+            raise ValueError(f"invalid version number '{vstring}'")
+
+        (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
+
+        if patch:
+            self.version = tuple(map(int, [major, minor, patch]))
+        else:
+            self.version = tuple(map(int, [major, minor])) + (0,)
+
+        if prerelease:
+            self.prerelease = (prerelease[0], int(prerelease_num))
+        else:
+            self.prerelease = None
+
+    def __str__(self):
+        if self.version[2] == 0:
+            vstring = '.'.join(map(str, self.version[0:2]))
+        else:
+            vstring = '.'.join(map(str, self.version))
+
+        if self.prerelease:
+            vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
+
+        return vstring
+
+    def _cmp(self, other):
+        if isinstance(other, str):
+            with suppress_known_deprecation():
+                other = StrictVersion(other)
+        elif not isinstance(other, StrictVersion):
+            return NotImplemented
+
+        if self.version == other.version:
+            # versions match; pre-release drives the comparison
+            return self._cmp_prerelease(other)
+
+        return -1 if self.version < other.version else 1
+
+    def _cmp_prerelease(self, other):
+        """
+        case 1: self has prerelease, other doesn't; other is greater
+        case 2: self doesn't have prerelease, other does: self is greater
+        case 3: both or neither have prerelease: compare them!
+        """
+        if self.prerelease and not other.prerelease:
+            return -1
+        elif not self.prerelease and other.prerelease:
+            return 1
+
+        if self.prerelease == other.prerelease:
+            return 0
+        elif self.prerelease < other.prerelease:
+            return -1
+        else:
+            return 1
+
+
+# end class StrictVersion
+
+
+# The rules according to Greg Stein:
+# 1) a version number has 1 or more numbers separated by a period or by
+#    sequences of letters. If only periods, then these are compared
+#    left-to-right to determine an ordering.
+# 2) sequences of letters are part of the tuple for comparison and are
+#    compared lexicographically
+# 3) recognize the numeric components may have leading zeroes
+#
+# The LooseVersion class below implements these rules: a version number
+# string is split up into a tuple of integer and string components, and
+# comparison is a simple tuple comparison.  This means that version
+# numbers behave in a predictable and obvious way, but a way that might
+# not necessarily be how people *want* version numbers to behave.  There
+# wouldn't be a problem if people could stick to purely numeric version
+# numbers: just split on period and compare the numbers as tuples.
+# However, people insist on putting letters into their version numbers;
+# the most common purpose seems to be:
+#   - indicating a "pre-release" version
+#     ('alpha', 'beta', 'a', 'b', 'pre', 'p')
+#   - indicating a post-release patch ('p', 'pl', 'patch')
+# but of course this can't cover all version number schemes, and there's
+# no way to know what a programmer means without asking him.
+#
+# The problem is what to do with letters (and other non-numeric
+# characters) in a version number.  The current implementation does the
+# obvious and predictable thing: keep them as strings and compare
+# lexically within a tuple comparison.  This has the desired effect if
+# an appended letter sequence implies something "post-release":
+# eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
+#
+# However, if letters in a version number imply a pre-release version,
+# the "obvious" thing isn't correct.  Eg. you would expect that
+# "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
+# implemented here, this just isn't so.
+#
+# Two possible solutions come to mind.  The first is to tie the
+# comparison algorithm to a particular set of semantic rules, as has
+# been done in the StrictVersion class above.  This works great as long
+# as everyone can go along with bondage and discipline.  Hopefully a
+# (large) subset of Python module programmers will agree that the
+# particular flavour of bondage and discipline provided by StrictVersion
+# provides enough benefit to be worth using, and will submit their
+# version numbering scheme to its domination.  The free-thinking
+# anarchists in the lot will never give in, though, and something needs
+# to be done to accommodate them.
+#
+# Perhaps a "moderately strict" version class could be implemented that
+# lets almost anything slide (syntactically), and makes some heuristic
+# assumptions about non-digits in version number strings.  This could
+# sink into special-case-hell, though; if I was as talented and
+# idiosyncratic as Larry Wall, I'd go ahead and implement a class that
+# somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
+# just as happy dealing with things like "2g6" and "1.13++".  I don't
+# think I'm smart enough to do it right though.
+#
+# In any case, I've coded the test suite for this module (see
+# ../test/test_version.py) specifically to fail on things like comparing
+# "1.2a2" and "1.2".  That's not because the *code* is doing anything
+# wrong, it's because the simple, obvious design doesn't match my
+# complicated, hairy expectations for real-world version numbers.  It
+# would be a snap to fix the test suite to say, "Yep, LooseVersion does
+# the Right Thing" (ie. the code matches the conception).  But I'd rather
+# have a conception that matches common notions about version numbers.
+
+
+class LooseVersion(Version):
+    """Version numbering for anarchists and software realists.
+    Implements the standard interface for version number classes as
+    described above.  A version number consists of a series of numbers,
+    separated by either periods or strings of letters.  When comparing
+    version numbers, the numeric components will be compared
+    numerically, and the alphabetic components lexically.  The following
+    are all valid version numbers, in no particular order:
+
+        1.5.1
+        1.5.2b2
+        161
+        3.10a
+        8.02
+        3.4j
+        1996.07.12
+        3.2.pl0
+        3.1.1.6
+        2g6
+        11g
+        0.960923
+        2.2beta29
+        1.13++
+        5.5.kw
+        2.0b1pl0
+
+    In fact, there is no such thing as an invalid version number under
+    this scheme; the rules for comparison are simple and predictable,
+    but may not always give the results you want (for some definition
+    of "want").
+    """
+
+    component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
+
+    def parse(self, vstring):
+        # I've given up on thinking I can reconstruct the version string
+        # from the parsed tuple -- so I just store the string here for
+        # use by __str__
+        self.vstring = vstring
+        components = [x for x in self.component_re.split(vstring) if x and x != '.']
+        for i, obj in enumerate(components):
+            try:
+                components[i] = int(obj)
+            except ValueError:
+                pass
+
+        self.version = components
+
+    def __str__(self):
+        return self.vstring
+
+    def __repr__(self):
+        return f"LooseVersion ('{self}')"
+
+    def _cmp(self, other):
+        if isinstance(other, str):
+            other = LooseVersion(other)
+        elif not isinstance(other, LooseVersion):
+            return NotImplemented
+
+        if self.version == other.version:
+            return 0
+        if self.version < other.version:
+            return -1
+        if self.version > other.version:
+            return 1
+
+
+# end class LooseVersion
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/versionpredicate.py b/python_embeded/Lib/site-packages/setuptools/_distutils/versionpredicate.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe31b0ed8ef843080ea64df9f58a398d317434ad
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/versionpredicate.py
@@ -0,0 +1,175 @@
+"""Module for parsing and testing package version predicate strings."""
+
+import operator
+import re
+
+from . import version
+
+re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
+# (package) (rest)
+
+re_paren = re.compile(r"^\s*\((.*)\)\s*$")  # (list) inside of parentheses
+re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
+# (comp) (version)
+
+
+def splitUp(pred):
+    """Parse a single version comparison.
+
+    Return (comparison string, StrictVersion)
+    """
+    res = re_splitComparison.match(pred)
+    if not res:
+        raise ValueError(f"bad package restriction syntax: {pred!r}")
+    comp, verStr = res.groups()
+    with version.suppress_known_deprecation():
+        other = version.StrictVersion(verStr)
+    return (comp, other)
+
+
+compmap = {
+    "<": operator.lt,
+    "<=": operator.le,
+    "==": operator.eq,
+    ">": operator.gt,
+    ">=": operator.ge,
+    "!=": operator.ne,
+}
+
+
+class VersionPredicate:
+    """Parse and test package version predicates.
+
+    >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')
+
+    The `name` attribute provides the full dotted name that is given::
+
+    >>> v.name
+    'pyepat.abc'
+
+    The str() of a `VersionPredicate` provides a normalized
+    human-readable version of the expression::
+
+    >>> print(v)
+    pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
+
+    The `satisfied_by()` method can be used to determine with a given
+    version number is included in the set described by the version
+    restrictions::
+
+    >>> v.satisfied_by('1.1')
+    True
+    >>> v.satisfied_by('1.4')
+    True
+    >>> v.satisfied_by('1.0')
+    False
+    >>> v.satisfied_by('4444.4')
+    False
+    >>> v.satisfied_by('1555.1b3')
+    False
+
+    `VersionPredicate` is flexible in accepting extra whitespace::
+
+    >>> v = VersionPredicate(' pat( ==  0.1  )  ')
+    >>> v.name
+    'pat'
+    >>> v.satisfied_by('0.1')
+    True
+    >>> v.satisfied_by('0.2')
+    False
+
+    If any version numbers passed in do not conform to the
+    restrictions of `StrictVersion`, a `ValueError` is raised::
+
+    >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')
+    Traceback (most recent call last):
+      ...
+    ValueError: invalid version number '1.2zb3'
+
+    It the module or package name given does not conform to what's
+    allowed as a legal module or package name, `ValueError` is
+    raised::
+
+    >>> v = VersionPredicate('foo-bar')
+    Traceback (most recent call last):
+      ...
+    ValueError: expected parenthesized list: '-bar'
+
+    >>> v = VersionPredicate('foo bar (12.21)')
+    Traceback (most recent call last):
+      ...
+    ValueError: expected parenthesized list: 'bar (12.21)'
+
+    """
+
+    def __init__(self, versionPredicateStr):
+        """Parse a version predicate string."""
+        # Fields:
+        #    name:  package name
+        #    pred:  list of (comparison string, StrictVersion)
+
+        versionPredicateStr = versionPredicateStr.strip()
+        if not versionPredicateStr:
+            raise ValueError("empty package restriction")
+        match = re_validPackage.match(versionPredicateStr)
+        if not match:
+            raise ValueError(f"bad package name in {versionPredicateStr!r}")
+        self.name, paren = match.groups()
+        paren = paren.strip()
+        if paren:
+            match = re_paren.match(paren)
+            if not match:
+                raise ValueError(f"expected parenthesized list: {paren!r}")
+            str = match.groups()[0]
+            self.pred = [splitUp(aPred) for aPred in str.split(",")]
+            if not self.pred:
+                raise ValueError(f"empty parenthesized list in {versionPredicateStr!r}")
+        else:
+            self.pred = []
+
+    def __str__(self):
+        if self.pred:
+            seq = [cond + " " + str(ver) for cond, ver in self.pred]
+            return self.name + " (" + ", ".join(seq) + ")"
+        else:
+            return self.name
+
+    def satisfied_by(self, version):
+        """True if version is compatible with all the predicates in self.
+        The parameter version must be acceptable to the StrictVersion
+        constructor.  It may be either a string or StrictVersion.
+        """
+        for cond, ver in self.pred:
+            if not compmap[cond](version, ver):
+                return False
+        return True
+
+
+_provision_rx = None
+
+
+def split_provision(value):
+    """Return the name and optional version number of a provision.
+
+    The version number, if given, will be returned as a `StrictVersion`
+    instance, otherwise it will be `None`.
+
+    >>> split_provision('mypkg')
+    ('mypkg', None)
+    >>> split_provision(' mypkg( 1.2 ) ')
+    ('mypkg', StrictVersion ('1.2'))
+    """
+    global _provision_rx
+    if _provision_rx is None:
+        _provision_rx = re.compile(
+            r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII
+        )
+    value = value.strip()
+    m = _provision_rx.match(value)
+    if not m:
+        raise ValueError(f"illegal provides specification: {value!r}")
+    ver = m.group(2) or None
+    if ver:
+        with version.suppress_known_deprecation():
+            ver = version.StrictVersion(ver)
+    return m.group(1), ver
diff --git a/python_embeded/Lib/site-packages/setuptools/_distutils/zosccompiler.py b/python_embeded/Lib/site-packages/setuptools/_distutils/zosccompiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..e49630ac6ed8cad62c4d2ff8361758519e6dc83b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_distutils/zosccompiler.py
@@ -0,0 +1,3 @@
+from .compilers.C import zos
+
+zOSCCompiler = zos.Compiler
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b49c3af060ce6326b8d91b9b73e76456ea0d9d2b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE
@@ -0,0 +1,166 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. 
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..32214fb4400035788bfe5c0de42dad106a4f54f1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA
@@ -0,0 +1,420 @@
+Metadata-Version: 2.1
+Name: autocommand
+Version: 2.2.2
+Summary: A library to create a command-line program from a function
+Home-page: https://github.com/Lucretiel/autocommand
+Author: Nathan West
+License: LGPLv3
+Project-URL: Homepage, https://github.com/Lucretiel/autocommand
+Project-URL: Bug Tracker, https://github.com/Lucretiel/autocommand/issues
+Platform: any
+Classifier: Development Status :: 6 - Mature
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Topic :: Software Development
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+License-File: LICENSE
+
+[![PyPI version](https://badge.fury.io/py/autocommand.svg)](https://badge.fury.io/py/autocommand)
+
+# autocommand
+
+A library to automatically generate and run simple argparse parsers from function signatures.
+
+## Installation
+
+Autocommand is installed via pip:
+
+```
+$ pip install autocommand
+```
+
+## Usage
+
+Autocommand turns a function into a command-line program. It converts the function's parameter signature into command-line arguments, and automatically runs the function if the module was called as `__main__`. In effect, it lets your create a smart main function.
+
+```python
+from autocommand import autocommand
+
+# This program takes exactly one argument and echos it.
+@autocommand(__name__)
+def echo(thing):
+    print(thing)
+```
+
+```
+$ python echo.py hello
+hello
+$ python echo.py -h
+usage: echo [-h] thing
+
+positional arguments:
+  thing
+
+optional arguments:
+  -h, --help  show this help message and exit
+$ python echo.py hello world  # too many arguments
+usage: echo.py [-h] thing
+echo.py: error: unrecognized arguments: world
+```
+
+As you can see, autocommand converts the signature of the function into an argument spec. When you run the file as a program, autocommand collects the command-line arguments and turns them into function arguments. The function is executed with these arguments, and then the program exits with the return value of the function, via `sys.exit`. Autocommand also automatically creates a usage message, which can be invoked with `-h` or `--help`, and automatically prints an error message when provided with invalid arguments.
+
+### Types
+
+You can use a type annotation to give an argument a type. Any type (or in fact any callable) that returns an object when given a string argument can be used, though there are a few special cases that are described later.
+
+```python
+@autocommand(__name__)
+def net_client(host, port: int):
+    ...
+```
+
+Autocommand will catch `TypeErrors` raised by the type during argument parsing, so you can supply a callable and do some basic argument validation as well.
+
+### Trailing Arguments
+
+You can add a `*args` parameter to your function to give it trailing arguments. The command will collect 0 or more trailing arguments and supply them to `args` as a tuple. If a type annotation is supplied, the type is applied to each argument.
+
+```python
+# Write the contents of each file, one by one
+@autocommand(__name__)
+def cat(*files):
+    for filename in files:
+        with open(filename) as file:
+            for line in file:
+                print(line.rstrip())
+```
+
+```
+$ python cat.py -h
+usage: ipython [-h] [file [file ...]]
+
+positional arguments:
+  file
+
+optional arguments:
+  -h, --help  show this help message and exit
+```
+
+### Options
+
+To create `--option` switches, just assign a default. Autocommand will automatically create `--long` and `-s`hort switches.
+
+```python
+@autocommand(__name__)
+def do_with_config(argument, config='~/foo.conf'):
+    pass
+```
+
+```
+$ python example.py -h
+usage: example.py [-h] [-c CONFIG] argument
+
+positional arguments:
+  argument
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -c CONFIG, --config CONFIG
+```
+
+The option's type is automatically deduced from the default, unless one is explicitly given in an annotation:
+
+```python
+@autocommand(__name__)
+def http_connect(host, port=80):
+    print('{}:{}'.format(host, port))
+```
+
+```
+$ python http.py -h
+usage: http.py [-h] [-p PORT] host
+
+positional arguments:
+  host
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -p PORT, --port PORT
+$ python http.py localhost
+localhost:80
+$ python http.py localhost -p 8080
+localhost:8080
+$ python http.py localhost -p blah
+usage: http.py [-h] [-p PORT] host
+http.py: error: argument -p/--port: invalid int value: 'blah'
+```
+
+#### None
+
+If an option is given a default value of `None`, it reads in a value as normal, but supplies `None` if the option isn't provided.
+
+#### Switches
+
+If an argument is given a default value of `True` or `False`, or
+given an explicit `bool` type, it becomes an option switch.
+
+```python
+    @autocommand(__name__)
+    def example(verbose=False, quiet=False):
+        pass
+```
+
+```
+$ python example.py -h
+usage: example.py [-h] [-v] [-q]
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  -q, --quiet
+```
+
+Autocommand attempts to do the "correct thing" in these cases- if the default is `True`, then supplying the switch makes the argument `False`; if the type is `bool` and the default is some other `True` value, then supplying the switch makes the argument `False`, while not supplying the switch makes the argument the default value.
+
+Autocommand also supports the creation of switch inverters. Pass `add_nos=True` to `autocommand` to enable this.
+
+```
+    @autocommand(__name__, add_nos=True)
+    def example(verbose=False):
+        pass
+```
+
+```
+$ python example.py -h
+usage: ipython [-h] [-v] [--no-verbose]
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  --no-verbose
+```
+
+Using the `--no-` version of a switch will pass the opposite value in as a function argument. If multiple switches are present, the last one takes precedence.
+
+#### Files
+
+If the default value is a file object, such as `sys.stdout`, then autocommand just looks for a string, for a file path. It doesn't do any special checking on the string, though (such as checking if the file exists); it's better to let the client decide how to handle errors in this case. Instead, it provides a special context manager called `smart_open`, which behaves exactly like `open` if a filename or other openable type is provided, but also lets you use already open files:
+
+```python
+from autocommand import autocommand, smart_open
+import sys
+
+# Write the contents of stdin, or a file, to stdout
+@autocommand(__name__)
+def write_out(infile=sys.stdin):
+    with smart_open(infile) as f:
+        for line in f:
+            print(line.rstrip())
+    # If a file was opened, it is closed here. If it was just stdin, it is untouched.
+```
+
+```
+$ echo "Hello World!" | python write_out.py | tee hello.txt
+Hello World!
+$ python write_out.py --infile hello.txt
+Hello World!
+```
+
+### Descriptions and docstrings
+
+The `autocommand` decorator accepts `description` and `epilog` kwargs, corresponding to the `description `_ and `epilog `_ of the `ArgumentParser`. If no description is given, but the decorated function has a docstring, then it is taken as the `description` for the `ArgumentParser`. You can also provide both the description and epilog in the docstring by splitting it into two sections with 4 or more - characters.
+
+```python
+@autocommand(__name__)
+def copy(infile=sys.stdin, outfile=sys.stdout):
+    '''
+    Copy an the contents of a file (or stdin) to another file (or stdout)
+    ----------
+    Some extra documentation in the epilog
+    '''
+    with smart_open(infile) as istr:
+        with smart_open(outfile, 'w') as ostr:
+            for line in istr:
+                ostr.write(line)
+```
+
+```
+$ python copy.py -h
+usage: copy.py [-h] [-i INFILE] [-o OUTFILE]
+
+Copy an the contents of a file (or stdin) to another file (or stdout)
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -i INFILE, --infile INFILE
+  -o OUTFILE, --outfile OUTFILE
+
+Some extra documentation in the epilog
+$ echo "Hello World" | python copy.py --outfile hello.txt
+$ python copy.py --infile hello.txt --outfile hello2.txt
+$ python copy.py --infile hello2.txt
+Hello World
+```
+
+### Parameter descriptions
+
+You can also attach description text to individual parameters in the annotation. To attach both a type and a description, supply them both in any order in a tuple
+
+```python
+@autocommand(__name__)
+def copy_net(
+    infile: 'The name of the file to send',
+    host: 'The host to send the file to',
+    port: (int, 'The port to connect to')):
+
+    '''
+    Copy a file over raw TCP to a remote destination.
+    '''
+    # Left as an exercise to the reader
+```
+
+### Decorators and wrappers
+
+Autocommand automatically follows wrapper chains created by `@functools.wraps`. This means that you can apply other wrapping decorators to your main function, and autocommand will still correctly detect the signature.
+
+```python
+from functools import wraps
+from autocommand import autocommand
+
+def print_yielded(func):
+    '''
+    Convert a generator into a function that prints all yielded elements
+    '''
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        for thing in func(*args, **kwargs):
+            print(thing)
+    return wrapper
+
+@autocommand(__name__,
+    description= 'Print all the values from START to STOP, inclusive, in steps of STEP',
+    epilog=      'STOP and STEP default to 1')
+@print_yielded
+def seq(stop, start=1, step=1):
+    for i in range(start, stop + 1, step):
+        yield i
+```
+
+```
+$ seq.py -h
+usage: seq.py [-h] [-s START] [-S STEP] stop
+
+Print all the values from START to STOP, inclusive, in steps of STEP
+
+positional arguments:
+  stop
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -s START, --start START
+  -S STEP, --step STEP
+
+STOP and STEP default to 1
+```
+
+Even though autocommand is being applied to the `wrapper` returned by `print_yielded`, it still retreives the signature of the underlying `seq` function to create the argument parsing.
+
+### Custom Parser
+
+While autocommand's automatic parser generator is a powerful convenience, it doesn't cover all of the different features that argparse provides. If you need these features, you can provide your own parser as a kwarg to `autocommand`:
+
+```python
+from argparse import ArgumentParser
+from autocommand import autocommand
+
+parser = ArgumentParser()
+# autocommand can't do optional positonal parameters
+parser.add_argument('arg', nargs='?')
+# or mutually exclusive options
+group = parser.add_mutually_exclusive_group()
+group.add_argument('-v', '--verbose', action='store_true')
+group.add_argument('-q', '--quiet', action='store_true')
+
+@autocommand(__name__, parser=parser)
+def main(arg, verbose, quiet):
+    print(arg, verbose, quiet)
+```
+
+```
+$ python parser.py -h
+usage: write_file.py [-h] [-v | -q] [arg]
+
+positional arguments:
+  arg
+
+optional arguments:
+  -h, --help     show this help message and exit
+  -v, --verbose
+  -q, --quiet
+$ python parser.py
+None False False
+$ python parser.py hello
+hello False False
+$ python parser.py -v
+None True False
+$ python parser.py -q
+None False True
+$ python parser.py -vq
+usage: parser.py [-h] [-v | -q] [arg]
+parser.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
+```
+
+Any parser should work fine, so long as each of the parser's arguments has a corresponding parameter in the decorated main function. The order of parameters doesn't matter, as long as they are all present. Note that when using a custom parser, autocommand doesn't modify the parser or the retrieved arguments. This means that no description/epilog will be added, and the function's type annotations and defaults (if present) will be ignored.
+
+## Testing and Library use
+
+The decorated function is only called and exited from if the first argument to `autocommand` is `'__main__'` or `True`. If it is neither of these values, or no argument is given, then a new main function is created by the decorator. This function has the signature `main(argv=None)`, and is intended to be called with arguments as if via `main(sys.argv[1:])`. The function has the attributes `parser` and `main`, which are the generated `ArgumentParser` and the original main function that was decorated. This is to facilitate testing and library use of your main. Calling the function triggers a `parse_args()` with the supplied arguments, and returns the result of the main function. Note that, while it returns instead of calling `sys.exit`, the `parse_args()` function will raise a `SystemExit` in the event of a parsing error or `-h/--help` argument.
+
+```python
+    @autocommand()
+    def test_prog(arg1, arg2: int, quiet=False, verbose=False):
+        if not quiet:
+            print(arg1, arg2)
+            if verbose:
+                print("LOUD NOISES")
+
+        return 0
+
+    print(test_prog(['-v', 'hello', '80']))
+```
+
+```
+$ python test_prog.py
+hello 80
+LOUD NOISES
+0
+```
+
+If the function is called with no arguments, `sys.argv[1:]` is used. This is to allow the autocommand function to be used as a setuptools entry point.
+
+## Exceptions and limitations
+
+- There are a few possible exceptions that `autocommand` can raise. All of them derive from `autocommand.AutocommandError`.
+
+  - If an invalid annotation is given (that is, it isn't a `type`, `str`, `(type, str)`, or `(str, type)`, an `AnnotationError` is raised. The `type` may be any callable, as described in the `Types`_ section.
+  - If the function has a `**kwargs` parameter, a `KWargError` is raised.
+  - If, somehow, the function has a positional-only parameter, a `PositionalArgError` is raised. This means that the argument doesn't have a name, which is currently not possible with a plain `def` or `lambda`, though many built-in functions have this kind of parameter.
+
+- There are a few argparse features that are not supported by autocommand.
+
+  - It isn't possible to have an optional positional argument (as opposed to a `--option`). POSIX thinks this is bad form anyway.
+  - It isn't possible to have mutually exclusive arguments or options
+  - It isn't possible to have subcommands or subparsers, though I'm working on a few solutions involving classes or nested function definitions to allow this.
+
+## Development
+
+Autocommand cannot be important from the project root; this is to enforce separation of concerns and prevent accidental importing of `setup.py` or tests. To develop, install the project in editable mode:
+
+```
+$ python setup.py develop
+```
+
+This will create a link to the source files in the deployment directory, so that any source changes are reflected when it is imported.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..e6e12ea51e18b270be6c5103c8cb1f6ef62f9e4a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD
@@ -0,0 +1,18 @@
+autocommand-2.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634
+autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006
+autocommand-2.2.2.dist-info/RECORD,,
+autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
+autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12
+autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037
+autocommand/__pycache__/__init__.cpython-312.pyc,,
+autocommand/__pycache__/autoasync.cpython-312.pyc,,
+autocommand/__pycache__/autocommand.cpython-312.pyc,,
+autocommand/__pycache__/automain.cpython-312.pyc,,
+autocommand/__pycache__/autoparse.cpython-312.pyc,,
+autocommand/__pycache__/errors.cpython-312.pyc,,
+autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680
+autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505
+autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076
+autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642
+autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.38.4)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dda5158ff6d263927861b19ef5a5d183d2aa77ed
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+autocommand
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..73fbfca6b36927c6371839df3dfe733bebb2066f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2014-2016 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+# flake8 flags all these imports as unused, hence the NOQAs everywhere.
+
+from .automain import automain  # NOQA
+from .autoparse import autoparse, smart_open  # NOQA
+from .autocommand import autocommand  # NOQA
+
+try:
+    from .autoasync import autoasync  # NOQA
+except ImportError:  # pragma: no cover
+    pass
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoasync.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoasync.py
new file mode 100644
index 0000000000000000000000000000000000000000..688f7e05544bb5b4914d290c9bfe73bb99f4e06a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoasync.py
@@ -0,0 +1,142 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+from asyncio import get_event_loop, iscoroutine
+from functools import wraps
+from inspect import signature
+
+
+async def _run_forever_coro(coro, args, kwargs, loop):
+    '''
+    This helper function launches an async main function that was tagged with
+    forever=True. There are two possibilities:
+
+    - The function is a normal function, which handles initializing the event
+      loop, which is then run forever
+    - The function is a coroutine, which needs to be scheduled in the event
+      loop, which is then run forever
+      - There is also the possibility that the function is a normal function
+        wrapping a coroutine function
+
+    The function is therefore called unconditionally and scheduled in the event
+    loop if the return value is a coroutine object.
+
+    The reason this is a separate function is to make absolutely sure that all
+    the objects created are garbage collected after all is said and done; we
+    do this to ensure that any exceptions raised in the tasks are collected
+    ASAP.
+    '''
+
+    # Personal note: I consider this an antipattern, as it relies on the use of
+    # unowned resources. The setup function dumps some stuff into the event
+    # loop where it just whirls in the ether without a well defined owner or
+    # lifetime. For this reason, there's a good chance I'll remove the
+    # forever=True feature from autoasync at some point in the future.
+    thing = coro(*args, **kwargs)
+    if iscoroutine(thing):
+        await thing
+
+
+def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False):
+    '''
+    Convert an asyncio coroutine into a function which, when called, is
+    evaluted in an event loop, and the return value returned. This is intented
+    to make it easy to write entry points into asyncio coroutines, which
+    otherwise need to be explictly evaluted with an event loop's
+    run_until_complete.
+
+    If `loop` is given, it is used as the event loop to run the coro in. If it
+    is None (the default), the loop is retreived using asyncio.get_event_loop.
+    This call is defered until the decorated function is called, so that
+    callers can install custom event loops or event loop policies after
+    @autoasync is applied.
+
+    If `forever` is True, the loop is run forever after the decorated coroutine
+    is finished. Use this for servers created with asyncio.start_server and the
+    like.
+
+    If `pass_loop` is True, the event loop object is passed into the coroutine
+    as the `loop` kwarg when the wrapper function is called. In this case, the
+    wrapper function's __signature__ is updated to remove this parameter, so
+    that autoparse can still be used on it without generating a parameter for
+    `loop`.
+
+    This coroutine can be called with ( @autoasync(...) ) or without
+    ( @autoasync ) arguments.
+
+    Examples:
+
+    @autoasync
+    def get_file(host, port):
+        reader, writer = yield from asyncio.open_connection(host, port)
+        data = reader.read()
+        sys.stdout.write(data.decode())
+
+    get_file(host, port)
+
+    @autoasync(forever=True, pass_loop=True)
+    def server(host, port, loop):
+        yield_from loop.create_server(Proto, host, port)
+
+    server('localhost', 8899)
+
+    '''
+    if coro is None:
+        return lambda c: autoasync(
+            c, loop=loop,
+            forever=forever,
+            pass_loop=pass_loop)
+
+    # The old and new signatures are required to correctly bind the loop
+    # parameter in 100% of cases, even if it's a positional parameter.
+    # NOTE: A future release will probably require the loop parameter to be
+    # a kwonly parameter.
+    if pass_loop:
+        old_sig = signature(coro)
+        new_sig = old_sig.replace(parameters=(
+            param for name, param in old_sig.parameters.items()
+            if name != "loop"))
+
+    @wraps(coro)
+    def autoasync_wrapper(*args, **kwargs):
+        # Defer the call to get_event_loop so that, if a custom policy is
+        # installed after the autoasync decorator, it is respected at call time
+        local_loop = get_event_loop() if loop is None else loop
+
+        # Inject the 'loop' argument. We have to use this signature binding to
+        # ensure it's injected in the correct place (positional, keyword, etc)
+        if pass_loop:
+            bound_args = old_sig.bind_partial()
+            bound_args.arguments.update(
+                loop=local_loop,
+                **new_sig.bind(*args, **kwargs).arguments)
+            args, kwargs = bound_args.args, bound_args.kwargs
+
+        if forever:
+            local_loop.create_task(_run_forever_coro(
+                coro, args, kwargs, local_loop
+            ))
+            local_loop.run_forever()
+        else:
+            return local_loop.run_until_complete(coro(*args, **kwargs))
+
+    # Attach the updated signature. This allows 'pass_loop' to be used with
+    # autoparse
+    if pass_loop:
+        autoasync_wrapper.__signature__ = new_sig
+
+    return autoasync_wrapper
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autocommand.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autocommand.py
new file mode 100644
index 0000000000000000000000000000000000000000..097e86de0720126a1390d728f7e50a4f89cac77f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autocommand.py
@@ -0,0 +1,70 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+from .autoparse import autoparse
+from .automain import automain
+try:
+    from .autoasync import autoasync
+except ImportError:  # pragma: no cover
+    pass
+
+
+def autocommand(
+        module, *,
+        description=None,
+        epilog=None,
+        add_nos=False,
+        parser=None,
+        loop=None,
+        forever=False,
+        pass_loop=False):
+
+    if callable(module):
+        raise TypeError('autocommand requires a module name argument')
+
+    def autocommand_decorator(func):
+        # Step 1: if requested, run it all in an asyncio event loop. autoasync
+        # patches the __signature__ of the decorated function, so that in the
+        # event that pass_loop is True, the `loop` parameter of the original
+        # function will *not* be interpreted as a command-line argument by
+        # autoparse
+        if loop is not None or forever or pass_loop:
+            func = autoasync(
+                func,
+                loop=None if loop is True else loop,
+                pass_loop=pass_loop,
+                forever=forever)
+
+        # Step 2: create parser. We do this second so that the arguments are
+        # parsed and passed *before* entering the asyncio event loop, if it
+        # exists. This simplifies the stack trace and ensures errors are
+        # reported earlier. It also ensures that errors raised during parsing &
+        # passing are still raised if `forever` is True.
+        func = autoparse(
+            func,
+            description=description,
+            epilog=epilog,
+            add_nos=add_nos,
+            parser=parser)
+
+        # Step 3: call the function automatically if __name__ == '__main__' (or
+        # if True was provided)
+        func = automain(module)(func)
+
+        return func
+
+    return autocommand_decorator
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/automain.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/automain.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cc45db66a1c1dbf1bedb993683b0700d0510643
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/automain.py
@@ -0,0 +1,59 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+import sys
+from .errors import AutocommandError
+
+
+class AutomainRequiresModuleError(AutocommandError, TypeError):
+    pass
+
+
+def automain(module, *, args=(), kwargs=None):
+    '''
+    This decorator automatically invokes a function if the module is being run
+    as the "__main__" module. Optionally, provide args or kwargs with which to
+    call the function. If `module` is "__main__", the function is called, and
+    the program is `sys.exit`ed with the return value. You can also pass `True`
+    to cause the function to be called unconditionally. If the function is not
+    called, it is returned unchanged by the decorator.
+
+    Usage:
+
+    @automain(__name__)  # Pass __name__ to check __name__=="__main__"
+    def main():
+        ...
+
+    If __name__ is "__main__" here, the main function is called, and then
+    sys.exit called with the return value.
+    '''
+
+    # Check that @automain(...) was called, rather than @automain
+    if callable(module):
+        raise AutomainRequiresModuleError(module)
+
+    if module == '__main__' or module is True:
+        if kwargs is None:
+            kwargs = {}
+
+        # Use a function definition instead of a lambda for a neater traceback
+        def automain_decorator(main):
+            sys.exit(main(*args, **kwargs))
+
+        return automain_decorator
+    else:
+        return lambda main: main
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoparse.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..0276a3fae10eb367af326543bcd69e62432b2f7b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/autoparse.py
@@ -0,0 +1,333 @@
+# Copyright 2014-2015 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+import sys
+from re import compile as compile_regex
+from inspect import signature, getdoc, Parameter
+from argparse import ArgumentParser
+from contextlib import contextmanager
+from functools import wraps
+from io import IOBase
+from autocommand.errors import AutocommandError
+
+
+_empty = Parameter.empty
+
+
+class AnnotationError(AutocommandError):
+    '''Annotation error: annotation must be a string, type, or tuple of both'''
+
+
+class PositionalArgError(AutocommandError):
+    '''
+    Postional Arg Error: autocommand can't handle postional-only parameters
+    '''
+
+
+class KWArgError(AutocommandError):
+    '''kwarg Error: autocommand can't handle a **kwargs parameter'''
+
+
+class DocstringError(AutocommandError):
+    '''Docstring error'''
+
+
+class TooManySplitsError(DocstringError):
+    '''
+    The docstring had too many ---- section splits. Currently we only support
+    using up to a single split, to split the docstring into description and
+    epilog parts.
+    '''
+
+
+def _get_type_description(annotation):
+    '''
+    Given an annotation, return the (type, description) for the parameter.
+    If you provide an annotation that is somehow both a string and a callable,
+    the behavior is undefined.
+    '''
+    if annotation is _empty:
+        return None, None
+    elif callable(annotation):
+        return annotation, None
+    elif isinstance(annotation, str):
+        return None, annotation
+    elif isinstance(annotation, tuple):
+        try:
+            arg1, arg2 = annotation
+        except ValueError as e:
+            raise AnnotationError(annotation) from e
+        else:
+            if callable(arg1) and isinstance(arg2, str):
+                return arg1, arg2
+            elif isinstance(arg1, str) and callable(arg2):
+                return arg2, arg1
+
+    raise AnnotationError(annotation)
+
+
+def _add_arguments(param, parser, used_char_args, add_nos):
+    '''
+    Add the argument(s) to an ArgumentParser (using add_argument) for a given
+    parameter. used_char_args is the set of -short options currently already in
+    use, and is updated (if necessary) by this function. If add_nos is True,
+    this will also add an inverse switch for all boolean options. For
+    instance, for the boolean parameter "verbose", this will create --verbose
+    and --no-verbose.
+    '''
+
+    # Impl note: This function is kept separate from make_parser because it's
+    # already very long and I wanted to separate out as much as possible into
+    # its own call scope, to prevent even the possibility of suble mutation
+    # bugs.
+    if param.kind is param.POSITIONAL_ONLY:
+        raise PositionalArgError(param)
+    elif param.kind is param.VAR_KEYWORD:
+        raise KWArgError(param)
+
+    # These are the kwargs for the add_argument function.
+    arg_spec = {}
+    is_option = False
+
+    # Get the type and default from the annotation.
+    arg_type, description = _get_type_description(param.annotation)
+
+    # Get the default value
+    default = param.default
+
+    # If there is no explicit type, and the default is present and not None,
+    # infer the type from the default.
+    if arg_type is None and default not in {_empty, None}:
+        arg_type = type(default)
+
+    # Add default. The presence of a default means this is an option, not an
+    # argument.
+    if default is not _empty:
+        arg_spec['default'] = default
+        is_option = True
+
+    # Add the type
+    if arg_type is not None:
+        # Special case for bool: make it just a --switch
+        if arg_type is bool:
+            if not default or default is _empty:
+                arg_spec['action'] = 'store_true'
+            else:
+                arg_spec['action'] = 'store_false'
+
+            # Switches are always options
+            is_option = True
+
+        # Special case for file types: make it a string type, for filename
+        elif isinstance(default, IOBase):
+            arg_spec['type'] = str
+
+        # TODO: special case for list type.
+        #   - How to specificy type of list members?
+        #       - param: [int]
+        #       - param: int =[]
+        #   - action='append' vs nargs='*'
+
+        else:
+            arg_spec['type'] = arg_type
+
+    # nargs: if the signature includes *args, collect them as trailing CLI
+    # arguments in a list. *args can't have a default value, so it can never be
+    # an option.
+    if param.kind is param.VAR_POSITIONAL:
+        # TODO: consider depluralizing metavar/name here.
+        arg_spec['nargs'] = '*'
+
+    # Add description.
+    if description is not None:
+        arg_spec['help'] = description
+
+    # Get the --flags
+    flags = []
+    name = param.name
+
+    if is_option:
+        # Add the first letter as a -short option.
+        for letter in name[0], name[0].swapcase():
+            if letter not in used_char_args:
+                used_char_args.add(letter)
+                flags.append('-{}'.format(letter))
+                break
+
+        # If the parameter is a --long option, or is a -short option that
+        # somehow failed to get a flag, add it.
+        if len(name) > 1 or not flags:
+            flags.append('--{}'.format(name))
+
+        arg_spec['dest'] = name
+    else:
+        flags.append(name)
+
+    parser.add_argument(*flags, **arg_spec)
+
+    # Create the --no- version for boolean switches
+    if add_nos and arg_type is bool:
+        parser.add_argument(
+            '--no-{}'.format(name),
+            action='store_const',
+            dest=name,
+            const=default if default is not _empty else False)
+
+
+def make_parser(func_sig, description, epilog, add_nos):
+    '''
+    Given the signature of a function, create an ArgumentParser
+    '''
+    parser = ArgumentParser(description=description, epilog=epilog)
+
+    used_char_args = {'h'}
+
+    # Arange the params so that single-character arguments are first. This
+    # esnures they don't have to get --long versions. sorted is stable, so the
+    # parameters will otherwise still be in relative order.
+    params = sorted(
+        func_sig.parameters.values(),
+        key=lambda param: len(param.name) > 1)
+
+    for param in params:
+        _add_arguments(param, parser, used_char_args, add_nos)
+
+    return parser
+
+
+_DOCSTRING_SPLIT = compile_regex(r'\n\s*-{4,}\s*\n')
+
+
+def parse_docstring(docstring):
+    '''
+    Given a docstring, parse it into a description and epilog part
+    '''
+    if docstring is None:
+        return '', ''
+
+    parts = _DOCSTRING_SPLIT.split(docstring)
+
+    if len(parts) == 1:
+        return docstring, ''
+    elif len(parts) == 2:
+        return parts[0], parts[1]
+    else:
+        raise TooManySplitsError()
+
+
+def autoparse(
+        func=None, *,
+        description=None,
+        epilog=None,
+        add_nos=False,
+        parser=None):
+    '''
+    This decorator converts a function that takes normal arguments into a
+    function which takes a single optional argument, argv, parses it using an
+    argparse.ArgumentParser, and calls the underlying function with the parsed
+    arguments. If it is not given, sys.argv[1:] is used. This is so that the
+    function can be used as a setuptools entry point, as well as a normal main
+    function. sys.argv[1:] is not evaluated until the function is called, to
+    allow injecting different arguments for testing.
+
+    It uses the argument signature of the function to create an
+    ArgumentParser. Parameters without defaults become positional parameters,
+    while parameters *with* defaults become --options. Use annotations to set
+    the type of the parameter.
+
+    The `desctiption` and `epilog` parameters corrospond to the same respective
+    argparse parameters. If no description is given, it defaults to the
+    decorated functions's docstring, if present.
+
+    If add_nos is True, every boolean option (that is, every parameter with a
+    default of True/False or a type of bool) will have a --no- version created
+    as well, which inverts the option. For instance, the --verbose option will
+    have a --no-verbose counterpart. These are not mutually exclusive-
+    whichever one appears last in the argument list will have precedence.
+
+    If a parser is given, it is used instead of one generated from the function
+    signature. In this case, no parser is created; instead, the given parser is
+    used to parse the argv argument. The parser's results' argument names must
+    match up with the parameter names of the decorated function.
+
+    The decorated function is attached to the result as the `func` attribute,
+    and the parser is attached as the `parser` attribute.
+    '''
+
+    # If @autoparse(...) is used instead of @autoparse
+    if func is None:
+        return lambda f: autoparse(
+            f, description=description,
+            epilog=epilog,
+            add_nos=add_nos,
+            parser=parser)
+
+    func_sig = signature(func)
+
+    docstr_description, docstr_epilog = parse_docstring(getdoc(func))
+
+    if parser is None:
+        parser = make_parser(
+            func_sig,
+            description or docstr_description,
+            epilog or docstr_epilog,
+            add_nos)
+
+    @wraps(func)
+    def autoparse_wrapper(argv=None):
+        if argv is None:
+            argv = sys.argv[1:]
+
+        # Get empty argument binding, to fill with parsed arguments. This
+        # object does all the heavy lifting of turning named arguments into
+        # into correctly bound *args and **kwargs.
+        parsed_args = func_sig.bind_partial()
+        parsed_args.arguments.update(vars(parser.parse_args(argv)))
+
+        return func(*parsed_args.args, **parsed_args.kwargs)
+
+    # TODO: attach an updated __signature__ to autoparse_wrapper, just in case.
+
+    # Attach the wrapped function and parser, and return the wrapper.
+    autoparse_wrapper.func = func
+    autoparse_wrapper.parser = parser
+    return autoparse_wrapper
+
+
+@contextmanager
+def smart_open(filename_or_file, *args, **kwargs):
+    '''
+    This context manager allows you to open a filename, if you want to default
+    some already-existing file object, like sys.stdout, which shouldn't be
+    closed at the end of the context. If the filename argument is a str, bytes,
+    or int, the file object is created via a call to open with the given *args
+    and **kwargs, sent to the context, and closed at the end of the context,
+    just like "with open(filename) as f:". If it isn't one of the openable
+    types, the object simply sent to the context unchanged, and left unclosed
+    at the end of the context. Example:
+
+        def work_with_file(name=sys.stdout):
+            with smart_open(name) as f:
+                # Works correctly if name is a str filename or sys.stdout
+                print("Some stuff", file=f)
+                # If it was a filename, f is closed at the end here.
+    '''
+    if isinstance(filename_or_file, (str, bytes, int)):
+        with open(filename_or_file, *args, **kwargs) as file:
+            yield file
+    else:
+        yield filename_or_file
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/errors.py b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..2570607399a3ae13cb92db65a9171d955d3248c6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/autocommand/errors.py
@@ -0,0 +1,23 @@
+# Copyright 2014-2016 Nathan West
+#
+# This file is part of autocommand.
+#
+# autocommand is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# autocommand is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with autocommand.  If not, see .
+
+
+class AutocommandError(Exception):
+    '''Base class for autocommand exceptions'''
+    pass
+
+# Individual modules will define errors specific to that module.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..db0a2dcdbe5f55f5815b2eaa243c507d0bdad002
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA
@@ -0,0 +1,46 @@
+Metadata-Version: 2.1
+Name: backports.tarfile
+Version: 1.2.0
+Summary: Backport of CPython tarfile module
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/backports.tarfile
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: docs
+Requires-Dist: sphinx >=3.5 ; extra == 'docs'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs'
+Requires-Dist: rst.linker >=1.9 ; extra == 'docs'
+Requires-Dist: furo ; extra == 'docs'
+Requires-Dist: sphinx-lint ; extra == 'docs'
+Provides-Extra: testing
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'testing'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing'
+Requires-Dist: pytest-cov ; extra == 'testing'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing'
+Requires-Dist: jaraco.test ; extra == 'testing'
+Requires-Dist: pytest !=8.0.* ; extra == 'testing'
+
+.. image:: https://img.shields.io/pypi/v/backports.tarfile.svg
+   :target: https://pypi.org/project/backports.tarfile
+
+.. image:: https://img.shields.io/pypi/pyversions/backports.tarfile.svg
+
+.. image:: https://github.com/jaraco/backports.tarfile/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/backports.tarfile/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. .. image:: https://readthedocs.org/projects/backportstarfile/badge/?version=latest
+..    :target: https://backportstarfile.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..536dc2f09ed8a2e9b04f98b82625101bb9f74715
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD
@@ -0,0 +1,17 @@
+backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020
+backports.tarfile-1.2.0.dist-info/RECORD,,
+backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10
+backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81
+backports/__pycache__/__init__.cpython-312.pyc,,
+backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491
+backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59
+backports/tarfile/__pycache__/__init__.cpython-312.pyc,,
+backports/tarfile/__pycache__/__main__.cpython-312.pyc,,
+backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+backports/tarfile/compat/__pycache__/__init__.cpython-312.pyc,,
+backports/tarfile/compat/__pycache__/py38.cpython-312.pyc,,
+backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..99d2be5b64d7dc414f8ab9c002de06456b4bada2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+backports
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d1f7edf5dc6343538563a8caa7de6829752c4f9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/__init__.py
@@ -0,0 +1 @@
+__path__ = __import__('pkgutil').extend_path(__path__, __name__)  # type: ignore
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c16881cb3ae1ea6e729b62bb2e5d625faa3f5fe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__init__.py
@@ -0,0 +1,2937 @@
+#-------------------------------------------------------------------
+# tarfile.py
+#-------------------------------------------------------------------
+# Copyright (C) 2002 Lars Gustaebel 
+# All rights reserved.
+#
+# 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.
+#
+"""Read from and write to tar format archives.
+"""
+
+version     = "0.9.0"
+__author__  = "Lars Gust\u00e4bel (lars@gustaebel.de)"
+__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
+
+#---------
+# Imports
+#---------
+from builtins import open as bltn_open
+import sys
+import os
+import io
+import shutil
+import stat
+import time
+import struct
+import copy
+import re
+
+from .compat.py38 import removesuffix
+
+try:
+    import pwd
+except ImportError:
+    pwd = None
+try:
+    import grp
+except ImportError:
+    grp = None
+
+# os.symlink on Windows prior to 6.0 raises NotImplementedError
+# OSError (winerror=1314) will be raised if the caller does not hold the
+# SeCreateSymbolicLinkPrivilege privilege
+symlink_exception = (AttributeError, NotImplementedError, OSError)
+
+# from tarfile import *
+__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError",
+           "CompressionError", "StreamError", "ExtractError", "HeaderError",
+           "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT",
+           "DEFAULT_FORMAT", "open","fully_trusted_filter", "data_filter",
+           "tar_filter", "FilterError", "AbsoluteLinkError",
+           "OutsideDestinationError", "SpecialFileError", "AbsolutePathError",
+           "LinkOutsideDestinationError"]
+
+
+#---------------------------------------------------------
+# tar constants
+#---------------------------------------------------------
+NUL = b"\0"                     # the null character
+BLOCKSIZE = 512                 # length of processing blocks
+RECORDSIZE = BLOCKSIZE * 20     # length of records
+GNU_MAGIC = b"ustar  \0"        # magic gnu tar string
+POSIX_MAGIC = b"ustar\x0000"    # magic posix tar string
+
+LENGTH_NAME = 100               # maximum length of a filename
+LENGTH_LINK = 100               # maximum length of a linkname
+LENGTH_PREFIX = 155             # maximum length of the prefix field
+
+REGTYPE = b"0"                  # regular file
+AREGTYPE = b"\0"                # regular file
+LNKTYPE = b"1"                  # link (inside tarfile)
+SYMTYPE = b"2"                  # symbolic link
+CHRTYPE = b"3"                  # character special device
+BLKTYPE = b"4"                  # block special device
+DIRTYPE = b"5"                  # directory
+FIFOTYPE = b"6"                 # fifo special device
+CONTTYPE = b"7"                 # contiguous file
+
+GNUTYPE_LONGNAME = b"L"         # GNU tar longname
+GNUTYPE_LONGLINK = b"K"         # GNU tar longlink
+GNUTYPE_SPARSE = b"S"           # GNU tar sparse file
+
+XHDTYPE = b"x"                  # POSIX.1-2001 extended header
+XGLTYPE = b"g"                  # POSIX.1-2001 global header
+SOLARIS_XHDTYPE = b"X"          # Solaris extended header
+
+USTAR_FORMAT = 0                # POSIX.1-1988 (ustar) format
+GNU_FORMAT = 1                  # GNU tar format
+PAX_FORMAT = 2                  # POSIX.1-2001 (pax) format
+DEFAULT_FORMAT = PAX_FORMAT
+
+#---------------------------------------------------------
+# tarfile constants
+#---------------------------------------------------------
+# File types that tarfile supports:
+SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
+                   SYMTYPE, DIRTYPE, FIFOTYPE,
+                   CONTTYPE, CHRTYPE, BLKTYPE,
+                   GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
+                   GNUTYPE_SPARSE)
+
+# File types that will be treated as a regular file.
+REGULAR_TYPES = (REGTYPE, AREGTYPE,
+                 CONTTYPE, GNUTYPE_SPARSE)
+
+# File types that are part of the GNU tar format.
+GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
+             GNUTYPE_SPARSE)
+
+# Fields from a pax header that override a TarInfo attribute.
+PAX_FIELDS = ("path", "linkpath", "size", "mtime",
+              "uid", "gid", "uname", "gname")
+
+# Fields from a pax header that are affected by hdrcharset.
+PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
+
+# Fields in a pax header that are numbers, all other fields
+# are treated as strings.
+PAX_NUMBER_FIELDS = {
+    "atime": float,
+    "ctime": float,
+    "mtime": float,
+    "uid": int,
+    "gid": int,
+    "size": int
+}
+
+#---------------------------------------------------------
+# initialization
+#---------------------------------------------------------
+if os.name == "nt":
+    ENCODING = "utf-8"
+else:
+    ENCODING = sys.getfilesystemencoding()
+
+#---------------------------------------------------------
+# Some useful functions
+#---------------------------------------------------------
+
+def stn(s, length, encoding, errors):
+    """Convert a string to a null-terminated bytes object.
+    """
+    if s is None:
+        raise ValueError("metadata cannot contain None")
+    s = s.encode(encoding, errors)
+    return s[:length] + (length - len(s)) * NUL
+
+def nts(s, encoding, errors):
+    """Convert a null-terminated bytes object to a string.
+    """
+    p = s.find(b"\0")
+    if p != -1:
+        s = s[:p]
+    return s.decode(encoding, errors)
+
+def nti(s):
+    """Convert a number field to a python number.
+    """
+    # There are two possible encodings for a number field, see
+    # itn() below.
+    if s[0] in (0o200, 0o377):
+        n = 0
+        for i in range(len(s) - 1):
+            n <<= 8
+            n += s[i + 1]
+        if s[0] == 0o377:
+            n = -(256 ** (len(s) - 1) - n)
+    else:
+        try:
+            s = nts(s, "ascii", "strict")
+            n = int(s.strip() or "0", 8)
+        except ValueError:
+            raise InvalidHeaderError("invalid header")
+    return n
+
+def itn(n, digits=8, format=DEFAULT_FORMAT):
+    """Convert a python number to a number field.
+    """
+    # POSIX 1003.1-1988 requires numbers to be encoded as a string of
+    # octal digits followed by a null-byte, this allows values up to
+    # (8**(digits-1))-1. GNU tar allows storing numbers greater than
+    # that if necessary. A leading 0o200 or 0o377 byte indicate this
+    # particular encoding, the following digits-1 bytes are a big-endian
+    # base-256 representation. This allows values up to (256**(digits-1))-1.
+    # A 0o200 byte indicates a positive number, a 0o377 byte a negative
+    # number.
+    original_n = n
+    n = int(n)
+    if 0 <= n < 8 ** (digits - 1):
+        s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL
+    elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1):
+        if n >= 0:
+            s = bytearray([0o200])
+        else:
+            s = bytearray([0o377])
+            n = 256 ** digits + n
+
+        for i in range(digits - 1):
+            s.insert(1, n & 0o377)
+            n >>= 8
+    else:
+        raise ValueError("overflow in number field")
+
+    return s
+
+def calc_chksums(buf):
+    """Calculate the checksum for a member's header by summing up all
+       characters except for the chksum field which is treated as if
+       it was filled with spaces. According to the GNU tar sources,
+       some tars (Sun and NeXT) calculate chksum with signed char,
+       which will be different if there are chars in the buffer with
+       the high bit set. So we calculate two checksums, unsigned and
+       signed.
+    """
+    unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
+    signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
+    return unsigned_chksum, signed_chksum
+
+def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None):
+    """Copy length bytes from fileobj src to fileobj dst.
+       If length is None, copy the entire content.
+    """
+    bufsize = bufsize or 16 * 1024
+    if length == 0:
+        return
+    if length is None:
+        shutil.copyfileobj(src, dst, bufsize)
+        return
+
+    blocks, remainder = divmod(length, bufsize)
+    for b in range(blocks):
+        buf = src.read(bufsize)
+        if len(buf) < bufsize:
+            raise exception("unexpected end of data")
+        dst.write(buf)
+
+    if remainder != 0:
+        buf = src.read(remainder)
+        if len(buf) < remainder:
+            raise exception("unexpected end of data")
+        dst.write(buf)
+    return
+
+def _safe_print(s):
+    encoding = getattr(sys.stdout, 'encoding', None)
+    if encoding is not None:
+        s = s.encode(encoding, 'backslashreplace').decode(encoding)
+    print(s, end=' ')
+
+
+class TarError(Exception):
+    """Base exception."""
+    pass
+class ExtractError(TarError):
+    """General exception for extract errors."""
+    pass
+class ReadError(TarError):
+    """Exception for unreadable tar archives."""
+    pass
+class CompressionError(TarError):
+    """Exception for unavailable compression methods."""
+    pass
+class StreamError(TarError):
+    """Exception for unsupported operations on stream-like TarFiles."""
+    pass
+class HeaderError(TarError):
+    """Base exception for header errors."""
+    pass
+class EmptyHeaderError(HeaderError):
+    """Exception for empty headers."""
+    pass
+class TruncatedHeaderError(HeaderError):
+    """Exception for truncated headers."""
+    pass
+class EOFHeaderError(HeaderError):
+    """Exception for end of file headers."""
+    pass
+class InvalidHeaderError(HeaderError):
+    """Exception for invalid headers."""
+    pass
+class SubsequentHeaderError(HeaderError):
+    """Exception for missing and invalid extended headers."""
+    pass
+
+#---------------------------
+# internal stream interface
+#---------------------------
+class _LowLevelFile:
+    """Low-level file object. Supports reading and writing.
+       It is used instead of a regular file object for streaming
+       access.
+    """
+
+    def __init__(self, name, mode):
+        mode = {
+            "r": os.O_RDONLY,
+            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+        }[mode]
+        if hasattr(os, "O_BINARY"):
+            mode |= os.O_BINARY
+        self.fd = os.open(name, mode, 0o666)
+
+    def close(self):
+        os.close(self.fd)
+
+    def read(self, size):
+        return os.read(self.fd, size)
+
+    def write(self, s):
+        os.write(self.fd, s)
+
+class _Stream:
+    """Class that serves as an adapter between TarFile and
+       a stream-like object.  The stream-like object only
+       needs to have a read() or write() method that works with bytes,
+       and the method is accessed blockwise.
+       Use of gzip or bzip2 compression is possible.
+       A stream-like object could be for example: sys.stdin.buffer,
+       sys.stdout.buffer, a socket, a tape device etc.
+
+       _Stream is intended to be used only internally.
+    """
+
+    def __init__(self, name, mode, comptype, fileobj, bufsize,
+                 compresslevel):
+        """Construct a _Stream object.
+        """
+        self._extfileobj = True
+        if fileobj is None:
+            fileobj = _LowLevelFile(name, mode)
+            self._extfileobj = False
+
+        if comptype == '*':
+            # Enable transparent compression detection for the
+            # stream interface
+            fileobj = _StreamProxy(fileobj)
+            comptype = fileobj.getcomptype()
+
+        self.name     = name or ""
+        self.mode     = mode
+        self.comptype = comptype
+        self.fileobj  = fileobj
+        self.bufsize  = bufsize
+        self.buf      = b""
+        self.pos      = 0
+        self.closed   = False
+
+        try:
+            if comptype == "gz":
+                try:
+                    import zlib
+                except ImportError:
+                    raise CompressionError("zlib module is not available") from None
+                self.zlib = zlib
+                self.crc = zlib.crc32(b"")
+                if mode == "r":
+                    self.exception = zlib.error
+                    self._init_read_gz()
+                else:
+                    self._init_write_gz(compresslevel)
+
+            elif comptype == "bz2":
+                try:
+                    import bz2
+                except ImportError:
+                    raise CompressionError("bz2 module is not available") from None
+                if mode == "r":
+                    self.dbuf = b""
+                    self.cmp = bz2.BZ2Decompressor()
+                    self.exception = OSError
+                else:
+                    self.cmp = bz2.BZ2Compressor(compresslevel)
+
+            elif comptype == "xz":
+                try:
+                    import lzma
+                except ImportError:
+                    raise CompressionError("lzma module is not available") from None
+                if mode == "r":
+                    self.dbuf = b""
+                    self.cmp = lzma.LZMADecompressor()
+                    self.exception = lzma.LZMAError
+                else:
+                    self.cmp = lzma.LZMACompressor()
+
+            elif comptype != "tar":
+                raise CompressionError("unknown compression type %r" % comptype)
+
+        except:
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+            raise
+
+    def __del__(self):
+        if hasattr(self, "closed") and not self.closed:
+            self.close()
+
+    def _init_write_gz(self, compresslevel):
+        """Initialize for writing with gzip compression.
+        """
+        self.cmp = self.zlib.compressobj(compresslevel,
+                                         self.zlib.DEFLATED,
+                                         -self.zlib.MAX_WBITS,
+                                         self.zlib.DEF_MEM_LEVEL,
+                                         0)
+        timestamp = struct.pack(" self.bufsize:
+            self.fileobj.write(self.buf[:self.bufsize])
+            self.buf = self.buf[self.bufsize:]
+
+    def close(self):
+        """Close the _Stream object. No operation should be
+           done on it afterwards.
+        """
+        if self.closed:
+            return
+
+        self.closed = True
+        try:
+            if self.mode == "w" and self.comptype != "tar":
+                self.buf += self.cmp.flush()
+
+            if self.mode == "w" and self.buf:
+                self.fileobj.write(self.buf)
+                self.buf = b""
+                if self.comptype == "gz":
+                    self.fileobj.write(struct.pack("= 0:
+            blocks, remainder = divmod(pos - self.pos, self.bufsize)
+            for i in range(blocks):
+                self.read(self.bufsize)
+            self.read(remainder)
+        else:
+            raise StreamError("seeking backwards is not allowed")
+        return self.pos
+
+    def read(self, size):
+        """Return the next size number of bytes from the stream."""
+        assert size is not None
+        buf = self._read(size)
+        self.pos += len(buf)
+        return buf
+
+    def _read(self, size):
+        """Return size bytes from the stream.
+        """
+        if self.comptype == "tar":
+            return self.__read(size)
+
+        c = len(self.dbuf)
+        t = [self.dbuf]
+        while c < size:
+            # Skip underlying buffer to avoid unaligned double buffering.
+            if self.buf:
+                buf = self.buf
+                self.buf = b""
+            else:
+                buf = self.fileobj.read(self.bufsize)
+                if not buf:
+                    break
+            try:
+                buf = self.cmp.decompress(buf)
+            except self.exception as e:
+                raise ReadError("invalid compressed data") from e
+            t.append(buf)
+            c += len(buf)
+        t = b"".join(t)
+        self.dbuf = t[size:]
+        return t[:size]
+
+    def __read(self, size):
+        """Return size bytes from stream. If internal buffer is empty,
+           read another block from the stream.
+        """
+        c = len(self.buf)
+        t = [self.buf]
+        while c < size:
+            buf = self.fileobj.read(self.bufsize)
+            if not buf:
+                break
+            t.append(buf)
+            c += len(buf)
+        t = b"".join(t)
+        self.buf = t[size:]
+        return t[:size]
+# class _Stream
+
+class _StreamProxy(object):
+    """Small proxy class that enables transparent compression
+       detection for the Stream interface (mode 'r|*').
+    """
+
+    def __init__(self, fileobj):
+        self.fileobj = fileobj
+        self.buf = self.fileobj.read(BLOCKSIZE)
+
+    def read(self, size):
+        self.read = self.fileobj.read
+        return self.buf
+
+    def getcomptype(self):
+        if self.buf.startswith(b"\x1f\x8b\x08"):
+            return "gz"
+        elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY":
+            return "bz2"
+        elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
+            return "xz"
+        else:
+            return "tar"
+
+    def close(self):
+        self.fileobj.close()
+# class StreamProxy
+
+#------------------------
+# Extraction file object
+#------------------------
+class _FileInFile(object):
+    """A thin wrapper around an existing file object that
+       provides a part of its data as an individual file
+       object.
+    """
+
+    def __init__(self, fileobj, offset, size, name, blockinfo=None):
+        self.fileobj = fileobj
+        self.offset = offset
+        self.size = size
+        self.position = 0
+        self.name = name
+        self.closed = False
+
+        if blockinfo is None:
+            blockinfo = [(0, size)]
+
+        # Construct a map with data and zero blocks.
+        self.map_index = 0
+        self.map = []
+        lastpos = 0
+        realpos = self.offset
+        for offset, size in blockinfo:
+            if offset > lastpos:
+                self.map.append((False, lastpos, offset, None))
+            self.map.append((True, offset, offset + size, realpos))
+            realpos += size
+            lastpos = offset + size
+        if lastpos < self.size:
+            self.map.append((False, lastpos, self.size, None))
+
+    def flush(self):
+        pass
+
+    @property
+    def mode(self):
+        return 'rb'
+
+    def readable(self):
+        return True
+
+    def writable(self):
+        return False
+
+    def seekable(self):
+        return self.fileobj.seekable()
+
+    def tell(self):
+        """Return the current file position.
+        """
+        return self.position
+
+    def seek(self, position, whence=io.SEEK_SET):
+        """Seek to a position in the file.
+        """
+        if whence == io.SEEK_SET:
+            self.position = min(max(position, 0), self.size)
+        elif whence == io.SEEK_CUR:
+            if position < 0:
+                self.position = max(self.position + position, 0)
+            else:
+                self.position = min(self.position + position, self.size)
+        elif whence == io.SEEK_END:
+            self.position = max(min(self.size + position, self.size), 0)
+        else:
+            raise ValueError("Invalid argument")
+        return self.position
+
+    def read(self, size=None):
+        """Read data from the file.
+        """
+        if size is None:
+            size = self.size - self.position
+        else:
+            size = min(size, self.size - self.position)
+
+        buf = b""
+        while size > 0:
+            while True:
+                data, start, stop, offset = self.map[self.map_index]
+                if start <= self.position < stop:
+                    break
+                else:
+                    self.map_index += 1
+                    if self.map_index == len(self.map):
+                        self.map_index = 0
+            length = min(size, stop - self.position)
+            if data:
+                self.fileobj.seek(offset + (self.position - start))
+                b = self.fileobj.read(length)
+                if len(b) != length:
+                    raise ReadError("unexpected end of data")
+                buf += b
+            else:
+                buf += NUL * length
+            size -= length
+            self.position += length
+        return buf
+
+    def readinto(self, b):
+        buf = self.read(len(b))
+        b[:len(buf)] = buf
+        return len(buf)
+
+    def close(self):
+        self.closed = True
+#class _FileInFile
+
+class ExFileObject(io.BufferedReader):
+
+    def __init__(self, tarfile, tarinfo):
+        fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data,
+                tarinfo.size, tarinfo.name, tarinfo.sparse)
+        super().__init__(fileobj)
+#class ExFileObject
+
+
+#-----------------------------
+# extraction filters (PEP 706)
+#-----------------------------
+
+class FilterError(TarError):
+    pass
+
+class AbsolutePathError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'member {tarinfo.name!r} has an absolute path')
+
+class OutsideDestinationError(FilterError):
+    def __init__(self, tarinfo, path):
+        self.tarinfo = tarinfo
+        self._path = path
+        super().__init__(f'{tarinfo.name!r} would be extracted to {path!r}, '
+                         + 'which is outside the destination')
+
+class SpecialFileError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'{tarinfo.name!r} is a special file')
+
+class AbsoluteLinkError(FilterError):
+    def __init__(self, tarinfo):
+        self.tarinfo = tarinfo
+        super().__init__(f'{tarinfo.name!r} is a link to an absolute path')
+
+class LinkOutsideDestinationError(FilterError):
+    def __init__(self, tarinfo, path):
+        self.tarinfo = tarinfo
+        self._path = path
+        super().__init__(f'{tarinfo.name!r} would link to {path!r}, '
+                         + 'which is outside the destination')
+
+def _get_filtered_attrs(member, dest_path, for_data=True):
+    new_attrs = {}
+    name = member.name
+    dest_path = os.path.realpath(dest_path)
+    # Strip leading / (tar's directory separator) from filenames.
+    # Include os.sep (target OS directory separator) as well.
+    if name.startswith(('/', os.sep)):
+        name = new_attrs['name'] = member.path.lstrip('/' + os.sep)
+    if os.path.isabs(name):
+        # Path is absolute even after stripping.
+        # For example, 'C:/foo' on Windows.
+        raise AbsolutePathError(member)
+    # Ensure we stay in the destination
+    target_path = os.path.realpath(os.path.join(dest_path, name))
+    if os.path.commonpath([target_path, dest_path]) != dest_path:
+        raise OutsideDestinationError(member, target_path)
+    # Limit permissions (no high bits, and go-w)
+    mode = member.mode
+    if mode is not None:
+        # Strip high bits & group/other write bits
+        mode = mode & 0o755
+        if for_data:
+            # For data, handle permissions & file types
+            if member.isreg() or member.islnk():
+                if not mode & 0o100:
+                    # Clear executable bits if not executable by user
+                    mode &= ~0o111
+                # Ensure owner can read & write
+                mode |= 0o600
+            elif member.isdir() or member.issym():
+                # Ignore mode for directories & symlinks
+                mode = None
+            else:
+                # Reject special files
+                raise SpecialFileError(member)
+        if mode != member.mode:
+            new_attrs['mode'] = mode
+    if for_data:
+        # Ignore ownership for 'data'
+        if member.uid is not None:
+            new_attrs['uid'] = None
+        if member.gid is not None:
+            new_attrs['gid'] = None
+        if member.uname is not None:
+            new_attrs['uname'] = None
+        if member.gname is not None:
+            new_attrs['gname'] = None
+        # Check link destination for 'data'
+        if member.islnk() or member.issym():
+            if os.path.isabs(member.linkname):
+                raise AbsoluteLinkError(member)
+            if member.issym():
+                target_path = os.path.join(dest_path,
+                                           os.path.dirname(name),
+                                           member.linkname)
+            else:
+                target_path = os.path.join(dest_path,
+                                           member.linkname)
+            target_path = os.path.realpath(target_path)
+            if os.path.commonpath([target_path, dest_path]) != dest_path:
+                raise LinkOutsideDestinationError(member, target_path)
+    return new_attrs
+
+def fully_trusted_filter(member, dest_path):
+    return member
+
+def tar_filter(member, dest_path):
+    new_attrs = _get_filtered_attrs(member, dest_path, False)
+    if new_attrs:
+        return member.replace(**new_attrs, deep=False)
+    return member
+
+def data_filter(member, dest_path):
+    new_attrs = _get_filtered_attrs(member, dest_path, True)
+    if new_attrs:
+        return member.replace(**new_attrs, deep=False)
+    return member
+
+_NAMED_FILTERS = {
+    "fully_trusted": fully_trusted_filter,
+    "tar": tar_filter,
+    "data": data_filter,
+}
+
+#------------------
+# Exported Classes
+#------------------
+
+# Sentinel for replace() defaults, meaning "don't change the attribute"
+_KEEP = object()
+
+class TarInfo(object):
+    """Informational class which holds the details about an
+       archive member given by a tar header block.
+       TarInfo objects are returned by TarFile.getmember(),
+       TarFile.getmembers() and TarFile.gettarinfo() and are
+       usually created internally.
+    """
+
+    __slots__ = dict(
+        name = 'Name of the archive member.',
+        mode = 'Permission bits.',
+        uid = 'User ID of the user who originally stored this member.',
+        gid = 'Group ID of the user who originally stored this member.',
+        size = 'Size in bytes.',
+        mtime = 'Time of last modification.',
+        chksum = 'Header checksum.',
+        type = ('File type. type is usually one of these constants: '
+                'REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, '
+                'CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'),
+        linkname = ('Name of the target file name, which is only present '
+                    'in TarInfo objects of type LNKTYPE and SYMTYPE.'),
+        uname = 'User name.',
+        gname = 'Group name.',
+        devmajor = 'Device major number.',
+        devminor = 'Device minor number.',
+        offset = 'The tar header starts here.',
+        offset_data = "The file's data starts here.",
+        pax_headers = ('A dictionary containing key-value pairs of an '
+                       'associated pax extended header.'),
+        sparse = 'Sparse member information.',
+        _tarfile = None,
+        _sparse_structs = None,
+        _link_target = None,
+        )
+
+    def __init__(self, name=""):
+        """Construct a TarInfo object. name is the optional name
+           of the member.
+        """
+        self.name = name        # member name
+        self.mode = 0o644       # file permissions
+        self.uid = 0            # user id
+        self.gid = 0            # group id
+        self.size = 0           # file size
+        self.mtime = 0          # modification time
+        self.chksum = 0         # header checksum
+        self.type = REGTYPE     # member type
+        self.linkname = ""      # link name
+        self.uname = ""         # user name
+        self.gname = ""         # group name
+        self.devmajor = 0       # device major number
+        self.devminor = 0       # device minor number
+
+        self.offset = 0         # the tar header starts here
+        self.offset_data = 0    # the file's data starts here
+
+        self.sparse = None      # sparse member information
+        self.pax_headers = {}   # pax header information
+
+    @property
+    def tarfile(self):
+        import warnings
+        warnings.warn(
+            'The undocumented "tarfile" attribute of TarInfo objects '
+            + 'is deprecated and will be removed in Python 3.16',
+            DeprecationWarning, stacklevel=2)
+        return self._tarfile
+
+    @tarfile.setter
+    def tarfile(self, tarfile):
+        import warnings
+        warnings.warn(
+            'The undocumented "tarfile" attribute of TarInfo objects '
+            + 'is deprecated and will be removed in Python 3.16',
+            DeprecationWarning, stacklevel=2)
+        self._tarfile = tarfile
+
+    @property
+    def path(self):
+        'In pax headers, "name" is called "path".'
+        return self.name
+
+    @path.setter
+    def path(self, name):
+        self.name = name
+
+    @property
+    def linkpath(self):
+        'In pax headers, "linkname" is called "linkpath".'
+        return self.linkname
+
+    @linkpath.setter
+    def linkpath(self, linkname):
+        self.linkname = linkname
+
+    def __repr__(self):
+        return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
+
+    def replace(self, *,
+                name=_KEEP, mtime=_KEEP, mode=_KEEP, linkname=_KEEP,
+                uid=_KEEP, gid=_KEEP, uname=_KEEP, gname=_KEEP,
+                deep=True, _KEEP=_KEEP):
+        """Return a deep copy of self with the given attributes replaced.
+        """
+        if deep:
+            result = copy.deepcopy(self)
+        else:
+            result = copy.copy(self)
+        if name is not _KEEP:
+            result.name = name
+        if mtime is not _KEEP:
+            result.mtime = mtime
+        if mode is not _KEEP:
+            result.mode = mode
+        if linkname is not _KEEP:
+            result.linkname = linkname
+        if uid is not _KEEP:
+            result.uid = uid
+        if gid is not _KEEP:
+            result.gid = gid
+        if uname is not _KEEP:
+            result.uname = uname
+        if gname is not _KEEP:
+            result.gname = gname
+        return result
+
+    def get_info(self):
+        """Return the TarInfo's attributes as a dictionary.
+        """
+        if self.mode is None:
+            mode = None
+        else:
+            mode = self.mode & 0o7777
+        info = {
+            "name":     self.name,
+            "mode":     mode,
+            "uid":      self.uid,
+            "gid":      self.gid,
+            "size":     self.size,
+            "mtime":    self.mtime,
+            "chksum":   self.chksum,
+            "type":     self.type,
+            "linkname": self.linkname,
+            "uname":    self.uname,
+            "gname":    self.gname,
+            "devmajor": self.devmajor,
+            "devminor": self.devminor
+        }
+
+        if info["type"] == DIRTYPE and not info["name"].endswith("/"):
+            info["name"] += "/"
+
+        return info
+
+    def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
+        """Return a tar header as a string of 512 byte blocks.
+        """
+        info = self.get_info()
+        for name, value in info.items():
+            if value is None:
+                raise ValueError("%s may not be None" % name)
+
+        if format == USTAR_FORMAT:
+            return self.create_ustar_header(info, encoding, errors)
+        elif format == GNU_FORMAT:
+            return self.create_gnu_header(info, encoding, errors)
+        elif format == PAX_FORMAT:
+            return self.create_pax_header(info, encoding)
+        else:
+            raise ValueError("invalid format")
+
+    def create_ustar_header(self, info, encoding, errors):
+        """Return the object as a ustar header block.
+        """
+        info["magic"] = POSIX_MAGIC
+
+        if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
+            raise ValueError("linkname is too long")
+
+        if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
+            info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors)
+
+        return self._create_header(info, USTAR_FORMAT, encoding, errors)
+
+    def create_gnu_header(self, info, encoding, errors):
+        """Return the object as a GNU header block sequence.
+        """
+        info["magic"] = GNU_MAGIC
+
+        buf = b""
+        if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
+            buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
+
+        if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
+            buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
+
+        return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
+
+    def create_pax_header(self, info, encoding):
+        """Return the object as a ustar header block. If it cannot be
+           represented this way, prepend a pax extended header sequence
+           with supplement information.
+        """
+        info["magic"] = POSIX_MAGIC
+        pax_headers = self.pax_headers.copy()
+
+        # Test string fields for values that exceed the field length or cannot
+        # be represented in ASCII encoding.
+        for name, hname, length in (
+                ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
+                ("uname", "uname", 32), ("gname", "gname", 32)):
+
+            if hname in pax_headers:
+                # The pax header has priority.
+                continue
+
+            # Try to encode the string as ASCII.
+            try:
+                info[name].encode("ascii", "strict")
+            except UnicodeEncodeError:
+                pax_headers[hname] = info[name]
+                continue
+
+            if len(info[name]) > length:
+                pax_headers[hname] = info[name]
+
+        # Test number fields for values that exceed the field limit or values
+        # that like to be stored as float.
+        for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
+            needs_pax = False
+
+            val = info[name]
+            val_is_float = isinstance(val, float)
+            val_int = round(val) if val_is_float else val
+            if not 0 <= val_int < 8 ** (digits - 1):
+                # Avoid overflow.
+                info[name] = 0
+                needs_pax = True
+            elif val_is_float:
+                # Put rounded value in ustar header, and full
+                # precision value in pax header.
+                info[name] = val_int
+                needs_pax = True
+
+            # The existing pax header has priority.
+            if needs_pax and name not in pax_headers:
+                pax_headers[name] = str(val)
+
+        # Create a pax extended header if necessary.
+        if pax_headers:
+            buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
+        else:
+            buf = b""
+
+        return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
+
+    @classmethod
+    def create_pax_global_header(cls, pax_headers):
+        """Return the object as a pax global header block sequence.
+        """
+        return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
+
+    def _posix_split_name(self, name, encoding, errors):
+        """Split a name longer than 100 chars into a prefix
+           and a name part.
+        """
+        components = name.split("/")
+        for i in range(1, len(components)):
+            prefix = "/".join(components[:i])
+            name = "/".join(components[i:])
+            if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \
+                    len(name.encode(encoding, errors)) <= LENGTH_NAME:
+                break
+        else:
+            raise ValueError("name is too long")
+
+        return prefix, name
+
+    @staticmethod
+    def _create_header(info, format, encoding, errors):
+        """Return a header block. info is a dictionary with file
+           information, format must be one of the *_FORMAT constants.
+        """
+        has_device_fields = info.get("type") in (CHRTYPE, BLKTYPE)
+        if has_device_fields:
+            devmajor = itn(info.get("devmajor", 0), 8, format)
+            devminor = itn(info.get("devminor", 0), 8, format)
+        else:
+            devmajor = stn("", 8, encoding, errors)
+            devminor = stn("", 8, encoding, errors)
+
+        # None values in metadata should cause ValueError.
+        # itn()/stn() do this for all fields except type.
+        filetype = info.get("type", REGTYPE)
+        if filetype is None:
+            raise ValueError("TarInfo.type must not be None")
+
+        parts = [
+            stn(info.get("name", ""), 100, encoding, errors),
+            itn(info.get("mode", 0) & 0o7777, 8, format),
+            itn(info.get("uid", 0), 8, format),
+            itn(info.get("gid", 0), 8, format),
+            itn(info.get("size", 0), 12, format),
+            itn(info.get("mtime", 0), 12, format),
+            b"        ", # checksum field
+            filetype,
+            stn(info.get("linkname", ""), 100, encoding, errors),
+            info.get("magic", POSIX_MAGIC),
+            stn(info.get("uname", ""), 32, encoding, errors),
+            stn(info.get("gname", ""), 32, encoding, errors),
+            devmajor,
+            devminor,
+            stn(info.get("prefix", ""), 155, encoding, errors)
+        ]
+
+        buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
+        chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
+        buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
+        return buf
+
+    @staticmethod
+    def _create_payload(payload):
+        """Return the string payload filled with zero bytes
+           up to the next 512 byte border.
+        """
+        blocks, remainder = divmod(len(payload), BLOCKSIZE)
+        if remainder > 0:
+            payload += (BLOCKSIZE - remainder) * NUL
+        return payload
+
+    @classmethod
+    def _create_gnu_long_header(cls, name, type, encoding, errors):
+        """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
+           for name.
+        """
+        name = name.encode(encoding, errors) + NUL
+
+        info = {}
+        info["name"] = "././@LongLink"
+        info["type"] = type
+        info["size"] = len(name)
+        info["magic"] = GNU_MAGIC
+
+        # create extended header + name blocks.
+        return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
+                cls._create_payload(name)
+
+    @classmethod
+    def _create_pax_generic_header(cls, pax_headers, type, encoding):
+        """Return a POSIX.1-2008 extended or global header sequence
+           that contains a list of keyword, value pairs. The values
+           must be strings.
+        """
+        # Check if one of the fields contains surrogate characters and thereby
+        # forces hdrcharset=BINARY, see _proc_pax() for more information.
+        binary = False
+        for keyword, value in pax_headers.items():
+            try:
+                value.encode("utf-8", "strict")
+            except UnicodeEncodeError:
+                binary = True
+                break
+
+        records = b""
+        if binary:
+            # Put the hdrcharset field at the beginning of the header.
+            records += b"21 hdrcharset=BINARY\n"
+
+        for keyword, value in pax_headers.items():
+            keyword = keyword.encode("utf-8")
+            if binary:
+                # Try to restore the original byte representation of 'value'.
+                # Needless to say, that the encoding must match the string.
+                value = value.encode(encoding, "surrogateescape")
+            else:
+                value = value.encode("utf-8")
+
+            l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
+            n = p = 0
+            while True:
+                n = l + len(str(p))
+                if n == p:
+                    break
+                p = n
+            records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
+
+        # We use a hardcoded "././@PaxHeader" name like star does
+        # instead of the one that POSIX recommends.
+        info = {}
+        info["name"] = "././@PaxHeader"
+        info["type"] = type
+        info["size"] = len(records)
+        info["magic"] = POSIX_MAGIC
+
+        # Create pax header + record blocks.
+        return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
+                cls._create_payload(records)
+
+    @classmethod
+    def frombuf(cls, buf, encoding, errors):
+        """Construct a TarInfo object from a 512 byte bytes object.
+        """
+        if len(buf) == 0:
+            raise EmptyHeaderError("empty header")
+        if len(buf) != BLOCKSIZE:
+            raise TruncatedHeaderError("truncated header")
+        if buf.count(NUL) == BLOCKSIZE:
+            raise EOFHeaderError("end of file header")
+
+        chksum = nti(buf[148:156])
+        if chksum not in calc_chksums(buf):
+            raise InvalidHeaderError("bad checksum")
+
+        obj = cls()
+        obj.name = nts(buf[0:100], encoding, errors)
+        obj.mode = nti(buf[100:108])
+        obj.uid = nti(buf[108:116])
+        obj.gid = nti(buf[116:124])
+        obj.size = nti(buf[124:136])
+        obj.mtime = nti(buf[136:148])
+        obj.chksum = chksum
+        obj.type = buf[156:157]
+        obj.linkname = nts(buf[157:257], encoding, errors)
+        obj.uname = nts(buf[265:297], encoding, errors)
+        obj.gname = nts(buf[297:329], encoding, errors)
+        obj.devmajor = nti(buf[329:337])
+        obj.devminor = nti(buf[337:345])
+        prefix = nts(buf[345:500], encoding, errors)
+
+        # Old V7 tar format represents a directory as a regular
+        # file with a trailing slash.
+        if obj.type == AREGTYPE and obj.name.endswith("/"):
+            obj.type = DIRTYPE
+
+        # The old GNU sparse format occupies some of the unused
+        # space in the buffer for up to 4 sparse structures.
+        # Save them for later processing in _proc_sparse().
+        if obj.type == GNUTYPE_SPARSE:
+            pos = 386
+            structs = []
+            for i in range(4):
+                try:
+                    offset = nti(buf[pos:pos + 12])
+                    numbytes = nti(buf[pos + 12:pos + 24])
+                except ValueError:
+                    break
+                structs.append((offset, numbytes))
+                pos += 24
+            isextended = bool(buf[482])
+            origsize = nti(buf[483:495])
+            obj._sparse_structs = (structs, isextended, origsize)
+
+        # Remove redundant slashes from directories.
+        if obj.isdir():
+            obj.name = obj.name.rstrip("/")
+
+        # Reconstruct a ustar longname.
+        if prefix and obj.type not in GNU_TYPES:
+            obj.name = prefix + "/" + obj.name
+        return obj
+
+    @classmethod
+    def fromtarfile(cls, tarfile):
+        """Return the next TarInfo object from TarFile object
+           tarfile.
+        """
+        buf = tarfile.fileobj.read(BLOCKSIZE)
+        obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
+        obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
+        return obj._proc_member(tarfile)
+
+    #--------------------------------------------------------------------------
+    # The following are methods that are called depending on the type of a
+    # member. The entry point is _proc_member() which can be overridden in a
+    # subclass to add custom _proc_*() methods. A _proc_*() method MUST
+    # implement the following
+    # operations:
+    # 1. Set self.offset_data to the position where the data blocks begin,
+    #    if there is data that follows.
+    # 2. Set tarfile.offset to the position where the next member's header will
+    #    begin.
+    # 3. Return self or another valid TarInfo object.
+    def _proc_member(self, tarfile):
+        """Choose the right processing method depending on
+           the type and call it.
+        """
+        if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
+            return self._proc_gnulong(tarfile)
+        elif self.type == GNUTYPE_SPARSE:
+            return self._proc_sparse(tarfile)
+        elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
+            return self._proc_pax(tarfile)
+        else:
+            return self._proc_builtin(tarfile)
+
+    def _proc_builtin(self, tarfile):
+        """Process a builtin type or an unknown type which
+           will be treated as a regular file.
+        """
+        self.offset_data = tarfile.fileobj.tell()
+        offset = self.offset_data
+        if self.isreg() or self.type not in SUPPORTED_TYPES:
+            # Skip the following data blocks.
+            offset += self._block(self.size)
+        tarfile.offset = offset
+
+        # Patch the TarInfo object with saved global
+        # header information.
+        self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
+
+        # Remove redundant slashes from directories. This is to be consistent
+        # with frombuf().
+        if self.isdir():
+            self.name = self.name.rstrip("/")
+
+        return self
+
+    def _proc_gnulong(self, tarfile):
+        """Process the blocks that hold a GNU longname
+           or longlink member.
+        """
+        buf = tarfile.fileobj.read(self._block(self.size))
+
+        # Fetch the next header and process it.
+        try:
+            next = self.fromtarfile(tarfile)
+        except HeaderError as e:
+            raise SubsequentHeaderError(str(e)) from None
+
+        # Patch the TarInfo object from the next header with
+        # the longname information.
+        next.offset = self.offset
+        if self.type == GNUTYPE_LONGNAME:
+            next.name = nts(buf, tarfile.encoding, tarfile.errors)
+        elif self.type == GNUTYPE_LONGLINK:
+            next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
+
+        # Remove redundant slashes from directories. This is to be consistent
+        # with frombuf().
+        if next.isdir():
+            next.name = removesuffix(next.name, "/")
+
+        return next
+
+    def _proc_sparse(self, tarfile):
+        """Process a GNU sparse header plus extra headers.
+        """
+        # We already collected some sparse structures in frombuf().
+        structs, isextended, origsize = self._sparse_structs
+        del self._sparse_structs
+
+        # Collect sparse structures from extended header blocks.
+        while isextended:
+            buf = tarfile.fileobj.read(BLOCKSIZE)
+            pos = 0
+            for i in range(21):
+                try:
+                    offset = nti(buf[pos:pos + 12])
+                    numbytes = nti(buf[pos + 12:pos + 24])
+                except ValueError:
+                    break
+                if offset and numbytes:
+                    structs.append((offset, numbytes))
+                pos += 24
+            isextended = bool(buf[504])
+        self.sparse = structs
+
+        self.offset_data = tarfile.fileobj.tell()
+        tarfile.offset = self.offset_data + self._block(self.size)
+        self.size = origsize
+        return self
+
+    def _proc_pax(self, tarfile):
+        """Process an extended or global header as described in
+           POSIX.1-2008.
+        """
+        # Read the header information.
+        buf = tarfile.fileobj.read(self._block(self.size))
+
+        # A pax header stores supplemental information for either
+        # the following file (extended) or all following files
+        # (global).
+        if self.type == XGLTYPE:
+            pax_headers = tarfile.pax_headers
+        else:
+            pax_headers = tarfile.pax_headers.copy()
+
+        # Check if the pax header contains a hdrcharset field. This tells us
+        # the encoding of the path, linkpath, uname and gname fields. Normally,
+        # these fields are UTF-8 encoded but since POSIX.1-2008 tar
+        # implementations are allowed to store them as raw binary strings if
+        # the translation to UTF-8 fails.
+        match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
+        if match is not None:
+            pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
+
+        # For the time being, we don't care about anything other than "BINARY".
+        # The only other value that is currently allowed by the standard is
+        # "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
+        hdrcharset = pax_headers.get("hdrcharset")
+        if hdrcharset == "BINARY":
+            encoding = tarfile.encoding
+        else:
+            encoding = "utf-8"
+
+        # Parse pax header information. A record looks like that:
+        # "%d %s=%s\n" % (length, keyword, value). length is the size
+        # of the complete record including the length field itself and
+        # the newline. keyword and value are both UTF-8 encoded strings.
+        regex = re.compile(br"(\d+) ([^=]+)=")
+        pos = 0
+        while match := regex.match(buf, pos):
+            length, keyword = match.groups()
+            length = int(length)
+            if length == 0:
+                raise InvalidHeaderError("invalid header")
+            value = buf[match.end(2) + 1:match.start(1) + length - 1]
+
+            # Normally, we could just use "utf-8" as the encoding and "strict"
+            # as the error handler, but we better not take the risk. For
+            # example, GNU tar <= 1.23 is known to store filenames it cannot
+            # translate to UTF-8 as raw strings (unfortunately without a
+            # hdrcharset=BINARY header).
+            # We first try the strict standard encoding, and if that fails we
+            # fall back on the user's encoding and error handler.
+            keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
+                    tarfile.errors)
+            if keyword in PAX_NAME_FIELDS:
+                value = self._decode_pax_field(value, encoding, tarfile.encoding,
+                        tarfile.errors)
+            else:
+                value = self._decode_pax_field(value, "utf-8", "utf-8",
+                        tarfile.errors)
+
+            pax_headers[keyword] = value
+            pos += length
+
+        # Fetch the next header.
+        try:
+            next = self.fromtarfile(tarfile)
+        except HeaderError as e:
+            raise SubsequentHeaderError(str(e)) from None
+
+        # Process GNU sparse information.
+        if "GNU.sparse.map" in pax_headers:
+            # GNU extended sparse format version 0.1.
+            self._proc_gnusparse_01(next, pax_headers)
+
+        elif "GNU.sparse.size" in pax_headers:
+            # GNU extended sparse format version 0.0.
+            self._proc_gnusparse_00(next, pax_headers, buf)
+
+        elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
+            # GNU extended sparse format version 1.0.
+            self._proc_gnusparse_10(next, pax_headers, tarfile)
+
+        if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
+            # Patch the TarInfo object with the extended header info.
+            next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
+            next.offset = self.offset
+
+            if "size" in pax_headers:
+                # If the extended header replaces the size field,
+                # we need to recalculate the offset where the next
+                # header starts.
+                offset = next.offset_data
+                if next.isreg() or next.type not in SUPPORTED_TYPES:
+                    offset += next._block(next.size)
+                tarfile.offset = offset
+
+        return next
+
+    def _proc_gnusparse_00(self, next, pax_headers, buf):
+        """Process a GNU tar extended sparse header, version 0.0.
+        """
+        offsets = []
+        for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
+            offsets.append(int(match.group(1)))
+        numbytes = []
+        for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
+            numbytes.append(int(match.group(1)))
+        next.sparse = list(zip(offsets, numbytes))
+
+    def _proc_gnusparse_01(self, next, pax_headers):
+        """Process a GNU tar extended sparse header, version 0.1.
+        """
+        sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
+        next.sparse = list(zip(sparse[::2], sparse[1::2]))
+
+    def _proc_gnusparse_10(self, next, pax_headers, tarfile):
+        """Process a GNU tar extended sparse header, version 1.0.
+        """
+        fields = None
+        sparse = []
+        buf = tarfile.fileobj.read(BLOCKSIZE)
+        fields, buf = buf.split(b"\n", 1)
+        fields = int(fields)
+        while len(sparse) < fields * 2:
+            if b"\n" not in buf:
+                buf += tarfile.fileobj.read(BLOCKSIZE)
+            number, buf = buf.split(b"\n", 1)
+            sparse.append(int(number))
+        next.offset_data = tarfile.fileobj.tell()
+        next.sparse = list(zip(sparse[::2], sparse[1::2]))
+
+    def _apply_pax_info(self, pax_headers, encoding, errors):
+        """Replace fields with supplemental information from a previous
+           pax extended or global header.
+        """
+        for keyword, value in pax_headers.items():
+            if keyword == "GNU.sparse.name":
+                setattr(self, "path", value)
+            elif keyword == "GNU.sparse.size":
+                setattr(self, "size", int(value))
+            elif keyword == "GNU.sparse.realsize":
+                setattr(self, "size", int(value))
+            elif keyword in PAX_FIELDS:
+                if keyword in PAX_NUMBER_FIELDS:
+                    try:
+                        value = PAX_NUMBER_FIELDS[keyword](value)
+                    except ValueError:
+                        value = 0
+                if keyword == "path":
+                    value = value.rstrip("/")
+                setattr(self, keyword, value)
+
+        self.pax_headers = pax_headers.copy()
+
+    def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
+        """Decode a single field from a pax record.
+        """
+        try:
+            return value.decode(encoding, "strict")
+        except UnicodeDecodeError:
+            return value.decode(fallback_encoding, fallback_errors)
+
+    def _block(self, count):
+        """Round up a byte count by BLOCKSIZE and return it,
+           e.g. _block(834) => 1024.
+        """
+        blocks, remainder = divmod(count, BLOCKSIZE)
+        if remainder:
+            blocks += 1
+        return blocks * BLOCKSIZE
+
+    def isreg(self):
+        'Return True if the Tarinfo object is a regular file.'
+        return self.type in REGULAR_TYPES
+
+    def isfile(self):
+        'Return True if the Tarinfo object is a regular file.'
+        return self.isreg()
+
+    def isdir(self):
+        'Return True if it is a directory.'
+        return self.type == DIRTYPE
+
+    def issym(self):
+        'Return True if it is a symbolic link.'
+        return self.type == SYMTYPE
+
+    def islnk(self):
+        'Return True if it is a hard link.'
+        return self.type == LNKTYPE
+
+    def ischr(self):
+        'Return True if it is a character device.'
+        return self.type == CHRTYPE
+
+    def isblk(self):
+        'Return True if it is a block device.'
+        return self.type == BLKTYPE
+
+    def isfifo(self):
+        'Return True if it is a FIFO.'
+        return self.type == FIFOTYPE
+
+    def issparse(self):
+        return self.sparse is not None
+
+    def isdev(self):
+        'Return True if it is one of character device, block device or FIFO.'
+        return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
+# class TarInfo
+
+class TarFile(object):
+    """The TarFile Class provides an interface to tar archives.
+    """
+
+    debug = 0                   # May be set from 0 (no msgs) to 3 (all msgs)
+
+    dereference = False         # If true, add content of linked file to the
+                                # tar file, else the link.
+
+    ignore_zeros = False        # If true, skips empty or invalid blocks and
+                                # continues processing.
+
+    errorlevel = 1              # If 0, fatal errors only appear in debug
+                                # messages (if debug >= 0). If > 0, errors
+                                # are passed to the caller as exceptions.
+
+    format = DEFAULT_FORMAT     # The format to use when creating an archive.
+
+    encoding = ENCODING         # Encoding for 8-bit character strings.
+
+    errors = None               # Error handler for unicode conversion.
+
+    tarinfo = TarInfo           # The default TarInfo class to use.
+
+    fileobject = ExFileObject   # The file-object for extractfile().
+
+    extraction_filter = None    # The default filter for extraction.
+
+    def __init__(self, name=None, mode="r", fileobj=None, format=None,
+            tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
+            errors="surrogateescape", pax_headers=None, debug=None,
+            errorlevel=None, copybufsize=None, stream=False):
+        """Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to
+           read from an existing archive, 'a' to append data to an existing
+           file or 'w' to create a new file overwriting an existing one. 'mode'
+           defaults to 'r'.
+           If 'fileobj' is given, it is used for reading or writing data. If it
+           can be determined, 'mode' is overridden by 'fileobj's mode.
+           'fileobj' is not closed, when TarFile is closed.
+        """
+        modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
+        if mode not in modes:
+            raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
+        self.mode = mode
+        self._mode = modes[mode]
+
+        if not fileobj:
+            if self.mode == "a" and not os.path.exists(name):
+                # Create nonexistent files in append mode.
+                self.mode = "w"
+                self._mode = "wb"
+            fileobj = bltn_open(name, self._mode)
+            self._extfileobj = False
+        else:
+            if (name is None and hasattr(fileobj, "name") and
+                isinstance(fileobj.name, (str, bytes))):
+                name = fileobj.name
+            if hasattr(fileobj, "mode"):
+                self._mode = fileobj.mode
+            self._extfileobj = True
+        self.name = os.path.abspath(name) if name else None
+        self.fileobj = fileobj
+
+        self.stream = stream
+
+        # Init attributes.
+        if format is not None:
+            self.format = format
+        if tarinfo is not None:
+            self.tarinfo = tarinfo
+        if dereference is not None:
+            self.dereference = dereference
+        if ignore_zeros is not None:
+            self.ignore_zeros = ignore_zeros
+        if encoding is not None:
+            self.encoding = encoding
+        self.errors = errors
+
+        if pax_headers is not None and self.format == PAX_FORMAT:
+            self.pax_headers = pax_headers
+        else:
+            self.pax_headers = {}
+
+        if debug is not None:
+            self.debug = debug
+        if errorlevel is not None:
+            self.errorlevel = errorlevel
+
+        # Init datastructures.
+        self.copybufsize = copybufsize
+        self.closed = False
+        self.members = []       # list of members as TarInfo objects
+        self._loaded = False    # flag if all members have been read
+        self.offset = self.fileobj.tell()
+                                # current position in the archive file
+        self.inodes = {}        # dictionary caching the inodes of
+                                # archive members already added
+
+        try:
+            if self.mode == "r":
+                self.firstmember = None
+                self.firstmember = self.next()
+
+            if self.mode == "a":
+                # Move to the end of the archive,
+                # before the first empty block.
+                while True:
+                    self.fileobj.seek(self.offset)
+                    try:
+                        tarinfo = self.tarinfo.fromtarfile(self)
+                        self.members.append(tarinfo)
+                    except EOFHeaderError:
+                        self.fileobj.seek(self.offset)
+                        break
+                    except HeaderError as e:
+                        raise ReadError(str(e)) from None
+
+            if self.mode in ("a", "w", "x"):
+                self._loaded = True
+
+                if self.pax_headers:
+                    buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
+                    self.fileobj.write(buf)
+                    self.offset += len(buf)
+        except:
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+            raise
+
+    #--------------------------------------------------------------------------
+    # Below are the classmethods which act as alternate constructors to the
+    # TarFile class. The open() method is the only one that is needed for
+    # public use; it is the "super"-constructor and is able to select an
+    # adequate "sub"-constructor for a particular compression using the mapping
+    # from OPEN_METH.
+    #
+    # This concept allows one to subclass TarFile without losing the comfort of
+    # the super-constructor. A sub-constructor is registered and made available
+    # by adding it to the mapping in OPEN_METH.
+
+    @classmethod
+    def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
+        r"""Open a tar archive for reading, writing or appending. Return
+           an appropriate TarFile class.
+
+           mode:
+           'r' or 'r:\*' open for reading with transparent compression
+           'r:'         open for reading exclusively uncompressed
+           'r:gz'       open for reading with gzip compression
+           'r:bz2'      open for reading with bzip2 compression
+           'r:xz'       open for reading with lzma compression
+           'a' or 'a:'  open for appending, creating the file if necessary
+           'w' or 'w:'  open for writing without compression
+           'w:gz'       open for writing with gzip compression
+           'w:bz2'      open for writing with bzip2 compression
+           'w:xz'       open for writing with lzma compression
+
+           'x' or 'x:'  create a tarfile exclusively without compression, raise
+                        an exception if the file is already created
+           'x:gz'       create a gzip compressed tarfile, raise an exception
+                        if the file is already created
+           'x:bz2'      create a bzip2 compressed tarfile, raise an exception
+                        if the file is already created
+           'x:xz'       create an lzma compressed tarfile, raise an exception
+                        if the file is already created
+
+           'r|\*'        open a stream of tar blocks with transparent compression
+           'r|'         open an uncompressed stream of tar blocks for reading
+           'r|gz'       open a gzip compressed stream of tar blocks
+           'r|bz2'      open a bzip2 compressed stream of tar blocks
+           'r|xz'       open an lzma compressed stream of tar blocks
+           'w|'         open an uncompressed stream for writing
+           'w|gz'       open a gzip compressed stream for writing
+           'w|bz2'      open a bzip2 compressed stream for writing
+           'w|xz'       open an lzma compressed stream for writing
+        """
+
+        if not name and not fileobj:
+            raise ValueError("nothing to open")
+
+        if mode in ("r", "r:*"):
+            # Find out which *open() is appropriate for opening the file.
+            def not_compressed(comptype):
+                return cls.OPEN_METH[comptype] == 'taropen'
+            error_msgs = []
+            for comptype in sorted(cls.OPEN_METH, key=not_compressed):
+                func = getattr(cls, cls.OPEN_METH[comptype])
+                if fileobj is not None:
+                    saved_pos = fileobj.tell()
+                try:
+                    return func(name, "r", fileobj, **kwargs)
+                except (ReadError, CompressionError) as e:
+                    error_msgs.append(f'- method {comptype}: {e!r}')
+                    if fileobj is not None:
+                        fileobj.seek(saved_pos)
+                    continue
+            error_msgs_summary = '\n'.join(error_msgs)
+            raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}")
+
+        elif ":" in mode:
+            filemode, comptype = mode.split(":", 1)
+            filemode = filemode or "r"
+            comptype = comptype or "tar"
+
+            # Select the *open() function according to
+            # given compression.
+            if comptype in cls.OPEN_METH:
+                func = getattr(cls, cls.OPEN_METH[comptype])
+            else:
+                raise CompressionError("unknown compression type %r" % comptype)
+            return func(name, filemode, fileobj, **kwargs)
+
+        elif "|" in mode:
+            filemode, comptype = mode.split("|", 1)
+            filemode = filemode or "r"
+            comptype = comptype or "tar"
+
+            if filemode not in ("r", "w"):
+                raise ValueError("mode must be 'r' or 'w'")
+
+            compresslevel = kwargs.pop("compresslevel", 9)
+            stream = _Stream(name, filemode, comptype, fileobj, bufsize,
+                             compresslevel)
+            try:
+                t = cls(name, filemode, stream, **kwargs)
+            except:
+                stream.close()
+                raise
+            t._extfileobj = False
+            return t
+
+        elif mode in ("a", "w", "x"):
+            return cls.taropen(name, mode, fileobj, **kwargs)
+
+        raise ValueError("undiscernible mode")
+
+    @classmethod
+    def taropen(cls, name, mode="r", fileobj=None, **kwargs):
+        """Open uncompressed tar archive name for reading or writing.
+        """
+        if mode not in ("r", "a", "w", "x"):
+            raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
+        return cls(name, mode, fileobj, **kwargs)
+
+    @classmethod
+    def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
+        """Open gzip compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from gzip import GzipFile
+        except ImportError:
+            raise CompressionError("gzip module is not available") from None
+
+        try:
+            fileobj = GzipFile(name, mode + "b", compresslevel, fileobj)
+        except OSError as e:
+            if fileobj is not None and mode == 'r':
+                raise ReadError("not a gzip file") from e
+            raise
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except OSError as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not a gzip file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    @classmethod
+    def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
+        """Open bzip2 compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from bz2 import BZ2File
+        except ImportError:
+            raise CompressionError("bz2 module is not available") from None
+
+        fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel)
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except (OSError, EOFError) as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not a bzip2 file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    @classmethod
+    def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
+        """Open lzma compressed tar archive name for reading or writing.
+           Appending is not allowed.
+        """
+        if mode not in ("r", "w", "x"):
+            raise ValueError("mode must be 'r', 'w' or 'x'")
+
+        try:
+            from lzma import LZMAFile, LZMAError
+        except ImportError:
+            raise CompressionError("lzma module is not available") from None
+
+        fileobj = LZMAFile(fileobj or name, mode, preset=preset)
+
+        try:
+            t = cls.taropen(name, mode, fileobj, **kwargs)
+        except (LZMAError, EOFError) as e:
+            fileobj.close()
+            if mode == 'r':
+                raise ReadError("not an lzma file") from e
+            raise
+        except:
+            fileobj.close()
+            raise
+        t._extfileobj = False
+        return t
+
+    # All *open() methods are registered here.
+    OPEN_METH = {
+        "tar": "taropen",   # uncompressed tar
+        "gz":  "gzopen",    # gzip compressed tar
+        "bz2": "bz2open",   # bzip2 compressed tar
+        "xz":  "xzopen"     # lzma compressed tar
+    }
+
+    #--------------------------------------------------------------------------
+    # The public methods which TarFile provides:
+
+    def close(self):
+        """Close the TarFile. In write-mode, two finishing zero blocks are
+           appended to the archive.
+        """
+        if self.closed:
+            return
+
+        self.closed = True
+        try:
+            if self.mode in ("a", "w", "x"):
+                self.fileobj.write(NUL * (BLOCKSIZE * 2))
+                self.offset += (BLOCKSIZE * 2)
+                # fill up the end with zero-blocks
+                # (like option -b20 for tar does)
+                blocks, remainder = divmod(self.offset, RECORDSIZE)
+                if remainder > 0:
+                    self.fileobj.write(NUL * (RECORDSIZE - remainder))
+        finally:
+            if not self._extfileobj:
+                self.fileobj.close()
+
+    def getmember(self, name):
+        """Return a TarInfo object for member 'name'. If 'name' can not be
+           found in the archive, KeyError is raised. If a member occurs more
+           than once in the archive, its last occurrence is assumed to be the
+           most up-to-date version.
+        """
+        tarinfo = self._getmember(name.rstrip('/'))
+        if tarinfo is None:
+            raise KeyError("filename %r not found" % name)
+        return tarinfo
+
+    def getmembers(self):
+        """Return the members of the archive as a list of TarInfo objects. The
+           list has the same order as the members in the archive.
+        """
+        self._check()
+        if not self._loaded:    # if we want to obtain a list of
+            self._load()        # all members, we first have to
+                                # scan the whole archive.
+        return self.members
+
+    def getnames(self):
+        """Return the members of the archive as a list of their names. It has
+           the same order as the list returned by getmembers().
+        """
+        return [tarinfo.name for tarinfo in self.getmembers()]
+
+    def gettarinfo(self, name=None, arcname=None, fileobj=None):
+        """Create a TarInfo object from the result of os.stat or equivalent
+           on an existing file. The file is either named by 'name', or
+           specified as a file object 'fileobj' with a file descriptor. If
+           given, 'arcname' specifies an alternative name for the file in the
+           archive, otherwise, the name is taken from the 'name' attribute of
+           'fileobj', or the 'name' argument. The name should be a text
+           string.
+        """
+        self._check("awx")
+
+        # When fileobj is given, replace name by
+        # fileobj's real name.
+        if fileobj is not None:
+            name = fileobj.name
+
+        # Building the name of the member in the archive.
+        # Backward slashes are converted to forward slashes,
+        # Absolute paths are turned to relative paths.
+        if arcname is None:
+            arcname = name
+        drv, arcname = os.path.splitdrive(arcname)
+        arcname = arcname.replace(os.sep, "/")
+        arcname = arcname.lstrip("/")
+
+        # Now, fill the TarInfo object with
+        # information specific for the file.
+        tarinfo = self.tarinfo()
+        tarinfo._tarfile = self  # To be removed in 3.16.
+
+        # Use os.stat or os.lstat, depending on if symlinks shall be resolved.
+        if fileobj is None:
+            if not self.dereference:
+                statres = os.lstat(name)
+            else:
+                statres = os.stat(name)
+        else:
+            statres = os.fstat(fileobj.fileno())
+        linkname = ""
+
+        stmd = statres.st_mode
+        if stat.S_ISREG(stmd):
+            inode = (statres.st_ino, statres.st_dev)
+            if not self.dereference and statres.st_nlink > 1 and \
+                    inode in self.inodes and arcname != self.inodes[inode]:
+                # Is it a hardlink to an already
+                # archived file?
+                type = LNKTYPE
+                linkname = self.inodes[inode]
+            else:
+                # The inode is added only if its valid.
+                # For win32 it is always 0.
+                type = REGTYPE
+                if inode[0]:
+                    self.inodes[inode] = arcname
+        elif stat.S_ISDIR(stmd):
+            type = DIRTYPE
+        elif stat.S_ISFIFO(stmd):
+            type = FIFOTYPE
+        elif stat.S_ISLNK(stmd):
+            type = SYMTYPE
+            linkname = os.readlink(name)
+        elif stat.S_ISCHR(stmd):
+            type = CHRTYPE
+        elif stat.S_ISBLK(stmd):
+            type = BLKTYPE
+        else:
+            return None
+
+        # Fill the TarInfo object with all
+        # information we can get.
+        tarinfo.name = arcname
+        tarinfo.mode = stmd
+        tarinfo.uid = statres.st_uid
+        tarinfo.gid = statres.st_gid
+        if type == REGTYPE:
+            tarinfo.size = statres.st_size
+        else:
+            tarinfo.size = 0
+        tarinfo.mtime = statres.st_mtime
+        tarinfo.type = type
+        tarinfo.linkname = linkname
+        if pwd:
+            try:
+                tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
+            except KeyError:
+                pass
+        if grp:
+            try:
+                tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
+            except KeyError:
+                pass
+
+        if type in (CHRTYPE, BLKTYPE):
+            if hasattr(os, "major") and hasattr(os, "minor"):
+                tarinfo.devmajor = os.major(statres.st_rdev)
+                tarinfo.devminor = os.minor(statres.st_rdev)
+        return tarinfo
+
+    def list(self, verbose=True, *, members=None):
+        """Print a table of contents to sys.stdout. If 'verbose' is False, only
+           the names of the members are printed. If it is True, an 'ls -l'-like
+           output is produced. 'members' is optional and must be a subset of the
+           list returned by getmembers().
+        """
+        # Convert tarinfo type to stat type.
+        type2mode = {REGTYPE: stat.S_IFREG, SYMTYPE: stat.S_IFLNK,
+                     FIFOTYPE: stat.S_IFIFO, CHRTYPE: stat.S_IFCHR,
+                     DIRTYPE: stat.S_IFDIR, BLKTYPE: stat.S_IFBLK}
+        self._check()
+
+        if members is None:
+            members = self
+        for tarinfo in members:
+            if verbose:
+                if tarinfo.mode is None:
+                    _safe_print("??????????")
+                else:
+                    modetype = type2mode.get(tarinfo.type, 0)
+                    _safe_print(stat.filemode(modetype | tarinfo.mode))
+                _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
+                                       tarinfo.gname or tarinfo.gid))
+                if tarinfo.ischr() or tarinfo.isblk():
+                    _safe_print("%10s" %
+                            ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
+                else:
+                    _safe_print("%10d" % tarinfo.size)
+                if tarinfo.mtime is None:
+                    _safe_print("????-??-?? ??:??:??")
+                else:
+                    _safe_print("%d-%02d-%02d %02d:%02d:%02d" \
+                                % time.localtime(tarinfo.mtime)[:6])
+
+            _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
+
+            if verbose:
+                if tarinfo.issym():
+                    _safe_print("-> " + tarinfo.linkname)
+                if tarinfo.islnk():
+                    _safe_print("link to " + tarinfo.linkname)
+            print()
+
+    def add(self, name, arcname=None, recursive=True, *, filter=None):
+        """Add the file 'name' to the archive. 'name' may be any type of file
+           (directory, fifo, symbolic link, etc.). If given, 'arcname'
+           specifies an alternative name for the file in the archive.
+           Directories are added recursively by default. This can be avoided by
+           setting 'recursive' to False. 'filter' is a function
+           that expects a TarInfo object argument and returns the changed
+           TarInfo object, if it returns None the TarInfo object will be
+           excluded from the archive.
+        """
+        self._check("awx")
+
+        if arcname is None:
+            arcname = name
+
+        # Skip if somebody tries to archive the archive...
+        if self.name is not None and os.path.abspath(name) == self.name:
+            self._dbg(2, "tarfile: Skipped %r" % name)
+            return
+
+        self._dbg(1, name)
+
+        # Create a TarInfo object from the file.
+        tarinfo = self.gettarinfo(name, arcname)
+
+        if tarinfo is None:
+            self._dbg(1, "tarfile: Unsupported type %r" % name)
+            return
+
+        # Change or exclude the TarInfo object.
+        if filter is not None:
+            tarinfo = filter(tarinfo)
+            if tarinfo is None:
+                self._dbg(2, "tarfile: Excluded %r" % name)
+                return
+
+        # Append the tar header and data to the archive.
+        if tarinfo.isreg():
+            with bltn_open(name, "rb") as f:
+                self.addfile(tarinfo, f)
+
+        elif tarinfo.isdir():
+            self.addfile(tarinfo)
+            if recursive:
+                for f in sorted(os.listdir(name)):
+                    self.add(os.path.join(name, f), os.path.join(arcname, f),
+                            recursive, filter=filter)
+
+        else:
+            self.addfile(tarinfo)
+
+    def addfile(self, tarinfo, fileobj=None):
+        """Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents
+           a non zero-size regular file, the 'fileobj' argument should be a binary file,
+           and tarinfo.size bytes are read from it and added to the archive.
+           You can create TarInfo objects directly, or by using gettarinfo().
+        """
+        self._check("awx")
+
+        if fileobj is None and tarinfo.isreg() and tarinfo.size != 0:
+            raise ValueError("fileobj not provided for non zero-size regular file")
+
+        tarinfo = copy.copy(tarinfo)
+
+        buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
+        self.fileobj.write(buf)
+        self.offset += len(buf)
+        bufsize=self.copybufsize
+        # If there's data to follow, append it.
+        if fileobj is not None:
+            copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize)
+            blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
+            if remainder > 0:
+                self.fileobj.write(NUL * (BLOCKSIZE - remainder))
+                blocks += 1
+            self.offset += blocks * BLOCKSIZE
+
+        self.members.append(tarinfo)
+
+    def _get_filter_function(self, filter):
+        if filter is None:
+            filter = self.extraction_filter
+            if filter is None:
+                import warnings
+                warnings.warn(
+                    'Python 3.14 will, by default, filter extracted tar '
+                    + 'archives and reject files or modify their metadata. '
+                    + 'Use the filter argument to control this behavior.',
+                    DeprecationWarning, stacklevel=3)
+                return fully_trusted_filter
+            if isinstance(filter, str):
+                raise TypeError(
+                    'String names are not supported for '
+                    + 'TarFile.extraction_filter. Use a function such as '
+                    + 'tarfile.data_filter directly.')
+            return filter
+        if callable(filter):
+            return filter
+        try:
+            return _NAMED_FILTERS[filter]
+        except KeyError:
+            raise ValueError(f"filter {filter!r} not found") from None
+
+    def extractall(self, path=".", members=None, *, numeric_owner=False,
+                   filter=None):
+        """Extract all members from the archive to the current working
+           directory and set owner, modification time and permissions on
+           directories afterwards. 'path' specifies a different directory
+           to extract to. 'members' is optional and must be a subset of the
+           list returned by getmembers(). If 'numeric_owner' is True, only
+           the numbers for user/group names are used and not the names.
+
+           The 'filter' function will be called on each member just
+           before extraction.
+           It can return a changed TarInfo or None to skip the member.
+           String names of common filters are accepted.
+        """
+        directories = []
+
+        filter_function = self._get_filter_function(filter)
+        if members is None:
+            members = self
+
+        for member in members:
+            tarinfo = self._get_extract_tarinfo(member, filter_function, path)
+            if tarinfo is None:
+                continue
+            if tarinfo.isdir():
+                # For directories, delay setting attributes until later,
+                # since permissions can interfere with extraction and
+                # extracting contents can reset mtime.
+                directories.append(tarinfo)
+            self._extract_one(tarinfo, path, set_attrs=not tarinfo.isdir(),
+                              numeric_owner=numeric_owner)
+
+        # Reverse sort directories.
+        directories.sort(key=lambda a: a.name, reverse=True)
+
+        # Set correct owner, mtime and filemode on directories.
+        for tarinfo in directories:
+            dirpath = os.path.join(path, tarinfo.name)
+            try:
+                self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
+                self.utime(tarinfo, dirpath)
+                self.chmod(tarinfo, dirpath)
+            except ExtractError as e:
+                self._handle_nonfatal_error(e)
+
+    def extract(self, member, path="", set_attrs=True, *, numeric_owner=False,
+                filter=None):
+        """Extract a member from the archive to the current working directory,
+           using its full name. Its file information is extracted as accurately
+           as possible. 'member' may be a filename or a TarInfo object. You can
+           specify a different directory using 'path'. File attributes (owner,
+           mtime, mode) are set unless 'set_attrs' is False. If 'numeric_owner'
+           is True, only the numbers for user/group names are used and not
+           the names.
+
+           The 'filter' function will be called before extraction.
+           It can return a changed TarInfo or None to skip the member.
+           String names of common filters are accepted.
+        """
+        filter_function = self._get_filter_function(filter)
+        tarinfo = self._get_extract_tarinfo(member, filter_function, path)
+        if tarinfo is not None:
+            self._extract_one(tarinfo, path, set_attrs, numeric_owner)
+
+    def _get_extract_tarinfo(self, member, filter_function, path):
+        """Get filtered TarInfo (or None) from member, which might be a str"""
+        if isinstance(member, str):
+            tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
+
+        unfiltered = tarinfo
+        try:
+            tarinfo = filter_function(tarinfo, path)
+        except (OSError, FilterError) as e:
+            self._handle_fatal_error(e)
+        except ExtractError as e:
+            self._handle_nonfatal_error(e)
+        if tarinfo is None:
+            self._dbg(2, "tarfile: Excluded %r" % unfiltered.name)
+            return None
+        # Prepare the link target for makelink().
+        if tarinfo.islnk():
+            tarinfo = copy.copy(tarinfo)
+            tarinfo._link_target = os.path.join(path, tarinfo.linkname)
+        return tarinfo
+
+    def _extract_one(self, tarinfo, path, set_attrs, numeric_owner):
+        """Extract from filtered tarinfo to disk"""
+        self._check("r")
+
+        try:
+            self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
+                                 set_attrs=set_attrs,
+                                 numeric_owner=numeric_owner)
+        except OSError as e:
+            self._handle_fatal_error(e)
+        except ExtractError as e:
+            self._handle_nonfatal_error(e)
+
+    def _handle_nonfatal_error(self, e):
+        """Handle non-fatal error (ExtractError) according to errorlevel"""
+        if self.errorlevel > 1:
+            raise
+        else:
+            self._dbg(1, "tarfile: %s" % e)
+
+    def _handle_fatal_error(self, e):
+        """Handle "fatal" error according to self.errorlevel"""
+        if self.errorlevel > 0:
+            raise
+        elif isinstance(e, OSError):
+            if e.filename is None:
+                self._dbg(1, "tarfile: %s" % e.strerror)
+            else:
+                self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
+        else:
+            self._dbg(1, "tarfile: %s %s" % (type(e).__name__, e))
+
+    def extractfile(self, member):
+        """Extract a member from the archive as a file object. 'member' may be
+           a filename or a TarInfo object. If 'member' is a regular file or
+           a link, an io.BufferedReader object is returned. For all other
+           existing members, None is returned. If 'member' does not appear
+           in the archive, KeyError is raised.
+        """
+        self._check("r")
+
+        if isinstance(member, str):
+            tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
+
+        if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
+            # Members with unknown types are treated as regular files.
+            return self.fileobject(self, tarinfo)
+
+        elif tarinfo.islnk() or tarinfo.issym():
+            if isinstance(self.fileobj, _Stream):
+                # A small but ugly workaround for the case that someone tries
+                # to extract a (sym)link as a file-object from a non-seekable
+                # stream of tar blocks.
+                raise StreamError("cannot extract (sym)link as file object")
+            else:
+                # A (sym)link's file object is its target's file object.
+                return self.extractfile(self._find_link_target(tarinfo))
+        else:
+            # If there's no data associated with the member (directory, chrdev,
+            # blkdev, etc.), return None instead of a file object.
+            return None
+
+    def _extract_member(self, tarinfo, targetpath, set_attrs=True,
+                        numeric_owner=False):
+        """Extract the TarInfo object tarinfo to a physical
+           file called targetpath.
+        """
+        # Fetch the TarInfo object for the given name
+        # and build the destination pathname, replacing
+        # forward slashes to platform specific separators.
+        targetpath = targetpath.rstrip("/")
+        targetpath = targetpath.replace("/", os.sep)
+
+        # Create all upper directories.
+        upperdirs = os.path.dirname(targetpath)
+        if upperdirs and not os.path.exists(upperdirs):
+            # Create directories that are not part of the archive with
+            # default permissions.
+            os.makedirs(upperdirs, exist_ok=True)
+
+        if tarinfo.islnk() or tarinfo.issym():
+            self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
+        else:
+            self._dbg(1, tarinfo.name)
+
+        if tarinfo.isreg():
+            self.makefile(tarinfo, targetpath)
+        elif tarinfo.isdir():
+            self.makedir(tarinfo, targetpath)
+        elif tarinfo.isfifo():
+            self.makefifo(tarinfo, targetpath)
+        elif tarinfo.ischr() or tarinfo.isblk():
+            self.makedev(tarinfo, targetpath)
+        elif tarinfo.islnk() or tarinfo.issym():
+            self.makelink(tarinfo, targetpath)
+        elif tarinfo.type not in SUPPORTED_TYPES:
+            self.makeunknown(tarinfo, targetpath)
+        else:
+            self.makefile(tarinfo, targetpath)
+
+        if set_attrs:
+            self.chown(tarinfo, targetpath, numeric_owner)
+            if not tarinfo.issym():
+                self.chmod(tarinfo, targetpath)
+                self.utime(tarinfo, targetpath)
+
+    #--------------------------------------------------------------------------
+    # Below are the different file methods. They are called via
+    # _extract_member() when extract() is called. They can be replaced in a
+    # subclass to implement other functionality.
+
+    def makedir(self, tarinfo, targetpath):
+        """Make a directory called targetpath.
+        """
+        try:
+            if tarinfo.mode is None:
+                # Use the system's default mode
+                os.mkdir(targetpath)
+            else:
+                # Use a safe mode for the directory, the real mode is set
+                # later in _extract_member().
+                os.mkdir(targetpath, 0o700)
+        except FileExistsError:
+            if not os.path.isdir(targetpath):
+                raise
+
+    def makefile(self, tarinfo, targetpath):
+        """Make a file called targetpath.
+        """
+        source = self.fileobj
+        source.seek(tarinfo.offset_data)
+        bufsize = self.copybufsize
+        with bltn_open(targetpath, "wb") as target:
+            if tarinfo.sparse is not None:
+                for offset, size in tarinfo.sparse:
+                    target.seek(offset)
+                    copyfileobj(source, target, size, ReadError, bufsize)
+                target.seek(tarinfo.size)
+                target.truncate()
+            else:
+                copyfileobj(source, target, tarinfo.size, ReadError, bufsize)
+
+    def makeunknown(self, tarinfo, targetpath):
+        """Make a file from a TarInfo object with an unknown type
+           at targetpath.
+        """
+        self.makefile(tarinfo, targetpath)
+        self._dbg(1, "tarfile: Unknown file type %r, " \
+                     "extracted as regular file." % tarinfo.type)
+
+    def makefifo(self, tarinfo, targetpath):
+        """Make a fifo called targetpath.
+        """
+        if hasattr(os, "mkfifo"):
+            os.mkfifo(targetpath)
+        else:
+            raise ExtractError("fifo not supported by system")
+
+    def makedev(self, tarinfo, targetpath):
+        """Make a character or block device called targetpath.
+        """
+        if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
+            raise ExtractError("special devices not supported by system")
+
+        mode = tarinfo.mode
+        if mode is None:
+            # Use mknod's default
+            mode = 0o600
+        if tarinfo.isblk():
+            mode |= stat.S_IFBLK
+        else:
+            mode |= stat.S_IFCHR
+
+        os.mknod(targetpath, mode,
+                 os.makedev(tarinfo.devmajor, tarinfo.devminor))
+
+    def makelink(self, tarinfo, targetpath):
+        """Make a (symbolic) link called targetpath. If it cannot be created
+          (platform limitation), we try to make a copy of the referenced file
+          instead of a link.
+        """
+        try:
+            # For systems that support symbolic and hard links.
+            if tarinfo.issym():
+                if os.path.lexists(targetpath):
+                    # Avoid FileExistsError on following os.symlink.
+                    os.unlink(targetpath)
+                os.symlink(tarinfo.linkname, targetpath)
+            else:
+                if os.path.exists(tarinfo._link_target):
+                    os.link(tarinfo._link_target, targetpath)
+                else:
+                    self._extract_member(self._find_link_target(tarinfo),
+                                         targetpath)
+        except symlink_exception:
+            try:
+                self._extract_member(self._find_link_target(tarinfo),
+                                     targetpath)
+            except KeyError:
+                raise ExtractError("unable to resolve link inside archive") from None
+
+    def chown(self, tarinfo, targetpath, numeric_owner):
+        """Set owner of targetpath according to tarinfo. If numeric_owner
+           is True, use .gid/.uid instead of .gname/.uname. If numeric_owner
+           is False, fall back to .gid/.uid when the search based on name
+           fails.
+        """
+        if hasattr(os, "geteuid") and os.geteuid() == 0:
+            # We have to be root to do so.
+            g = tarinfo.gid
+            u = tarinfo.uid
+            if not numeric_owner:
+                try:
+                    if grp and tarinfo.gname:
+                        g = grp.getgrnam(tarinfo.gname)[2]
+                except KeyError:
+                    pass
+                try:
+                    if pwd and tarinfo.uname:
+                        u = pwd.getpwnam(tarinfo.uname)[2]
+                except KeyError:
+                    pass
+            if g is None:
+                g = -1
+            if u is None:
+                u = -1
+            try:
+                if tarinfo.issym() and hasattr(os, "lchown"):
+                    os.lchown(targetpath, u, g)
+                else:
+                    os.chown(targetpath, u, g)
+            except (OSError, OverflowError) as e:
+                # OverflowError can be raised if an ID doesn't fit in 'id_t'
+                raise ExtractError("could not change owner") from e
+
+    def chmod(self, tarinfo, targetpath):
+        """Set file permissions of targetpath according to tarinfo.
+        """
+        if tarinfo.mode is None:
+            return
+        try:
+            os.chmod(targetpath, tarinfo.mode)
+        except OSError as e:
+            raise ExtractError("could not change mode") from e
+
+    def utime(self, tarinfo, targetpath):
+        """Set modification time of targetpath according to tarinfo.
+        """
+        mtime = tarinfo.mtime
+        if mtime is None:
+            return
+        if not hasattr(os, 'utime'):
+            return
+        try:
+            os.utime(targetpath, (mtime, mtime))
+        except OSError as e:
+            raise ExtractError("could not change modification time") from e
+
+    #--------------------------------------------------------------------------
+    def next(self):
+        """Return the next member of the archive as a TarInfo object, when
+           TarFile is opened for reading. Return None if there is no more
+           available.
+        """
+        self._check("ra")
+        if self.firstmember is not None:
+            m = self.firstmember
+            self.firstmember = None
+            return m
+
+        # Advance the file pointer.
+        if self.offset != self.fileobj.tell():
+            if self.offset == 0:
+                return None
+            self.fileobj.seek(self.offset - 1)
+            if not self.fileobj.read(1):
+                raise ReadError("unexpected end of data")
+
+        # Read the next block.
+        tarinfo = None
+        while True:
+            try:
+                tarinfo = self.tarinfo.fromtarfile(self)
+            except EOFHeaderError as e:
+                if self.ignore_zeros:
+                    self._dbg(2, "0x%X: %s" % (self.offset, e))
+                    self.offset += BLOCKSIZE
+                    continue
+            except InvalidHeaderError as e:
+                if self.ignore_zeros:
+                    self._dbg(2, "0x%X: %s" % (self.offset, e))
+                    self.offset += BLOCKSIZE
+                    continue
+                elif self.offset == 0:
+                    raise ReadError(str(e)) from None
+            except EmptyHeaderError:
+                if self.offset == 0:
+                    raise ReadError("empty file") from None
+            except TruncatedHeaderError as e:
+                if self.offset == 0:
+                    raise ReadError(str(e)) from None
+            except SubsequentHeaderError as e:
+                raise ReadError(str(e)) from None
+            except Exception as e:
+                try:
+                    import zlib
+                    if isinstance(e, zlib.error):
+                        raise ReadError(f'zlib error: {e}') from None
+                    else:
+                        raise e
+                except ImportError:
+                    raise e
+            break
+
+        if tarinfo is not None:
+            # if streaming the file we do not want to cache the tarinfo
+            if not self.stream:
+                self.members.append(tarinfo)
+        else:
+            self._loaded = True
+
+        return tarinfo
+
+    #--------------------------------------------------------------------------
+    # Little helper methods:
+
+    def _getmember(self, name, tarinfo=None, normalize=False):
+        """Find an archive member by name from bottom to top.
+           If tarinfo is given, it is used as the starting point.
+        """
+        # Ensure that all members have been loaded.
+        members = self.getmembers()
+
+        # Limit the member search list up to tarinfo.
+        skipping = False
+        if tarinfo is not None:
+            try:
+                index = members.index(tarinfo)
+            except ValueError:
+                # The given starting point might be a (modified) copy.
+                # We'll later skip members until we find an equivalent.
+                skipping = True
+            else:
+                # Happy fast path
+                members = members[:index]
+
+        if normalize:
+            name = os.path.normpath(name)
+
+        for member in reversed(members):
+            if skipping:
+                if tarinfo.offset == member.offset:
+                    skipping = False
+                continue
+            if normalize:
+                member_name = os.path.normpath(member.name)
+            else:
+                member_name = member.name
+
+            if name == member_name:
+                return member
+
+        if skipping:
+            # Starting point was not found
+            raise ValueError(tarinfo)
+
+    def _load(self):
+        """Read through the entire archive file and look for readable
+           members. This should not run if the file is set to stream.
+        """
+        if not self.stream:
+            while self.next() is not None:
+                pass
+            self._loaded = True
+
+    def _check(self, mode=None):
+        """Check if TarFile is still open, and if the operation's mode
+           corresponds to TarFile's mode.
+        """
+        if self.closed:
+            raise OSError("%s is closed" % self.__class__.__name__)
+        if mode is not None and self.mode not in mode:
+            raise OSError("bad operation for mode %r" % self.mode)
+
+    def _find_link_target(self, tarinfo):
+        """Find the target member of a symlink or hardlink member in the
+           archive.
+        """
+        if tarinfo.issym():
+            # Always search the entire archive.
+            linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
+            limit = None
+        else:
+            # Search the archive before the link, because a hard link is
+            # just a reference to an already archived file.
+            linkname = tarinfo.linkname
+            limit = tarinfo
+
+        member = self._getmember(linkname, tarinfo=limit, normalize=True)
+        if member is None:
+            raise KeyError("linkname %r not found" % linkname)
+        return member
+
+    def __iter__(self):
+        """Provide an iterator object.
+        """
+        if self._loaded:
+            yield from self.members
+            return
+
+        # Yield items using TarFile's next() method.
+        # When all members have been read, set TarFile as _loaded.
+        index = 0
+        # Fix for SF #1100429: Under rare circumstances it can
+        # happen that getmembers() is called during iteration,
+        # which will have already exhausted the next() method.
+        if self.firstmember is not None:
+            tarinfo = self.next()
+            index += 1
+            yield tarinfo
+
+        while True:
+            if index < len(self.members):
+                tarinfo = self.members[index]
+            elif not self._loaded:
+                tarinfo = self.next()
+                if not tarinfo:
+                    self._loaded = True
+                    return
+            else:
+                return
+            index += 1
+            yield tarinfo
+
+    def _dbg(self, level, msg):
+        """Write debugging output to sys.stderr.
+        """
+        if level <= self.debug:
+            print(msg, file=sys.stderr)
+
+    def __enter__(self):
+        self._check()
+        return self
+
+    def __exit__(self, type, value, traceback):
+        if type is None:
+            self.close()
+        else:
+            # An exception occurred. We must not call close() because
+            # it would try to write end-of-archive blocks and padding.
+            if not self._extfileobj:
+                self.fileobj.close()
+            self.closed = True
+
+#--------------------
+# exported functions
+#--------------------
+
+def is_tarfile(name):
+    """Return True if name points to a tar archive that we
+       are able to handle, else return False.
+
+       'name' should be a string, file, or file-like object.
+    """
+    try:
+        if hasattr(name, "read"):
+            pos = name.tell()
+            t = open(fileobj=name)
+            name.seek(pos)
+        else:
+            t = open(name)
+        t.close()
+        return True
+    except TarError:
+        return False
+
+open = TarFile.open
+
+
+def main():
+    import argparse
+
+    description = 'A simple command-line interface for tarfile module.'
+    parser = argparse.ArgumentParser(description=description)
+    parser.add_argument('-v', '--verbose', action='store_true', default=False,
+                        help='Verbose output')
+    parser.add_argument('--filter', metavar='',
+                        choices=_NAMED_FILTERS,
+                        help='Filter for extraction')
+
+    group = parser.add_mutually_exclusive_group(required=True)
+    group.add_argument('-l', '--list', metavar='',
+                       help='Show listing of a tarfile')
+    group.add_argument('-e', '--extract', nargs='+',
+                       metavar=('', ''),
+                       help='Extract tarfile into target dir')
+    group.add_argument('-c', '--create', nargs='+',
+                       metavar=('', ''),
+                       help='Create tarfile from sources')
+    group.add_argument('-t', '--test', metavar='',
+                       help='Test if a tarfile is valid')
+
+    args = parser.parse_args()
+
+    if args.filter and args.extract is None:
+        parser.exit(1, '--filter is only valid for extraction\n')
+
+    if args.test is not None:
+        src = args.test
+        if is_tarfile(src):
+            with open(src, 'r') as tar:
+                tar.getmembers()
+                print(tar.getmembers(), file=sys.stderr)
+            if args.verbose:
+                print('{!r} is a tar archive.'.format(src))
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.list is not None:
+        src = args.list
+        if is_tarfile(src):
+            with TarFile.open(src, 'r:*') as tf:
+                tf.list(verbose=args.verbose)
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.extract is not None:
+        if len(args.extract) == 1:
+            src = args.extract[0]
+            curdir = os.curdir
+        elif len(args.extract) == 2:
+            src, curdir = args.extract
+        else:
+            parser.exit(1, parser.format_help())
+
+        if is_tarfile(src):
+            with TarFile.open(src, 'r:*') as tf:
+                tf.extractall(path=curdir, filter=args.filter)
+            if args.verbose:
+                if curdir == '.':
+                    msg = '{!r} file is extracted.'.format(src)
+                else:
+                    msg = ('{!r} file is extracted '
+                           'into {!r} directory.').format(src, curdir)
+                print(msg)
+        else:
+            parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
+
+    elif args.create is not None:
+        tar_name = args.create.pop(0)
+        _, ext = os.path.splitext(tar_name)
+        compressions = {
+            # gz
+            '.gz': 'gz',
+            '.tgz': 'gz',
+            # xz
+            '.xz': 'xz',
+            '.txz': 'xz',
+            # bz2
+            '.bz2': 'bz2',
+            '.tbz': 'bz2',
+            '.tbz2': 'bz2',
+            '.tb2': 'bz2',
+        }
+        tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
+        tar_files = args.create
+
+        with TarFile.open(tar_name, tar_mode) as tf:
+            for file_name in tar_files:
+                tf.add(file_name)
+
+        if args.verbose:
+            print('{!r} file created.'.format(tar_name))
+
+if __name__ == '__main__':
+    main()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__main__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..daf55090862ae43283b6552073549ac3ab2ad50a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/__main__.py
@@ -0,0 +1,5 @@
+from . import main
+
+
+if __name__ == '__main__':
+    main()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py
new file mode 100644
index 0000000000000000000000000000000000000000..20fbbfc1c095baf9f8c72902b24296b50ad3ab9d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py
@@ -0,0 +1,24 @@
+import sys
+
+
+if sys.version_info < (3, 9):
+
+    def removesuffix(self, suffix):
+        # suffix='' should not call self[:-0].
+        if suffix and self.endswith(suffix):
+            return self[: -len(suffix)]
+        else:
+            return self[:]
+
+    def removeprefix(self, prefix):
+        if self.startswith(prefix):
+            return self[len(prefix) :]
+        else:
+            return self[:]
+else:
+
+    def removesuffix(self, suffix):
+        return self.removesuffix(suffix)
+
+    def removeprefix(self, prefix):
+        return self.removeprefix(prefix)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..85513e8a9f651c99f4a1fa372ba7768255bfa1c9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/METADATA
@@ -0,0 +1,129 @@
+Metadata-Version: 2.1
+Name: importlib_metadata
+Version: 8.0.0
+Summary: Read metadata from Python packages
+Author-email: "Jason R. Coombs" 
+Project-URL: Source, https://github.com/python/importlib_metadata
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: zipp >=0.5
+Requires-Dist: typing-extensions >=3.6.4 ; python_version < "3.8"
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: perf
+Requires-Dist: ipython ; extra == 'perf'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test'
+Requires-Dist: packaging ; extra == 'test'
+Requires-Dist: pyfakefs ; extra == 'test'
+Requires-Dist: flufl.flake8 ; extra == 'test'
+Requires-Dist: pytest-perf >=0.9.2 ; extra == 'test'
+Requires-Dist: jaraco.test >=5.4 ; extra == 'test'
+Requires-Dist: importlib-resources >=1.3 ; (python_version < "3.9") and extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/importlib_metadata.svg
+   :target: https://pypi.org/project/importlib_metadata
+
+.. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg
+
+.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest
+   :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/importlib-metadata
+   :target: https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=readme
+
+Library to access the metadata for a Python package.
+
+This package supplies third-party access to the functionality of
+`importlib.metadata `_
+including improvements added to subsequent Python versions.
+
+
+Compatibility
+=============
+
+New features are introduced in this third-party library and later merged
+into CPython. The following table indicates which versions of this library
+were contributed to different versions in the standard library:
+
+.. list-table::
+   :header-rows: 1
+
+   * - importlib_metadata
+     - stdlib
+   * - 7.0
+     - 3.13
+   * - 6.5
+     - 3.12
+   * - 4.13
+     - 3.11
+   * - 4.6
+     - 3.10
+   * - 1.4
+     - 3.8
+
+
+Usage
+=====
+
+See the `online documentation `_
+for usage details.
+
+`Finder authors
+`_ can
+also add support for custom package installers.  See the above documentation
+for details.
+
+
+Caveats
+=======
+
+This project primarily supports third-party packages installed by PyPA
+tools (or other conforming packages). It does not support:
+
+- Packages in the stdlib.
+- Packages installed without metadata.
+
+Project details
+===============
+
+ * Project home: https://github.com/python/importlib_metadata
+ * Report bugs at: https://github.com/python/importlib_metadata/issues
+ * Code hosting: https://github.com/python/importlib_metadata
+ * Documentation: https://importlib-metadata.readthedocs.io/
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..07b7dc51dbf8da033f8cd0eb05a52ecfe26dcbeb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/RECORD
@@ -0,0 +1,32 @@
+importlib_metadata-8.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+importlib_metadata-8.0.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
+importlib_metadata-8.0.0.dist-info/METADATA,sha256=anuQ7_7h4J1bSEzfcjIBakPi2cyVQ7y7jklLHsBeH1k,4648
+importlib_metadata-8.0.0.dist-info/RECORD,,
+importlib_metadata-8.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+importlib_metadata-8.0.0.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91
+importlib_metadata-8.0.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19
+importlib_metadata/__init__.py,sha256=tZNB-23h8Bixi9uCrQqj9Yf0aeC--Josdy3IZRIQeB0,33798
+importlib_metadata/__pycache__/__init__.cpython-312.pyc,,
+importlib_metadata/__pycache__/_adapters.cpython-312.pyc,,
+importlib_metadata/__pycache__/_collections.cpython-312.pyc,,
+importlib_metadata/__pycache__/_compat.cpython-312.pyc,,
+importlib_metadata/__pycache__/_functools.cpython-312.pyc,,
+importlib_metadata/__pycache__/_itertools.cpython-312.pyc,,
+importlib_metadata/__pycache__/_meta.cpython-312.pyc,,
+importlib_metadata/__pycache__/_text.cpython-312.pyc,,
+importlib_metadata/__pycache__/diagnose.cpython-312.pyc,,
+importlib_metadata/_adapters.py,sha256=rIhWTwBvYA1bV7i-5FfVX38qEXDTXFeS5cb5xJtP3ks,2317
+importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743
+importlib_metadata/_compat.py,sha256=73QKrN9KNoaZzhbX5yPCCZa-FaALwXe8TPlDR72JgBU,1314
+importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895
+importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068
+importlib_metadata/_meta.py,sha256=nxZ7C8GVlcBFAKWyVOn_dn7ot_twBcbm1NmvjIetBHI,1801
+importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166
+importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc,,
+importlib_metadata/compat/__pycache__/py311.cpython-312.pyc,,
+importlib_metadata/compat/__pycache__/py39.cpython-312.pyc,,
+importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608
+importlib_metadata/compat/py39.py,sha256=cPkMv6-0ilK-0Jw_Tkn0xYbOKJZc4WJKQHow0c2T44w,1102
+importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379
+importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..edf4ec7c70d7dbfc16600ff1b368daf1097c5dc7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (70.1.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bbb07547a19c30031d13c45cf01cba61dc434e47
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata-8.0.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+importlib_metadata
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed4813551ac238bfb9b5a48f4476463355415d27
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/__init__.py
@@ -0,0 +1,1083 @@
+from __future__ import annotations
+
+import os
+import re
+import abc
+import sys
+import json
+import zipp
+import email
+import types
+import inspect
+import pathlib
+import operator
+import textwrap
+import functools
+import itertools
+import posixpath
+import collections
+
+from . import _meta
+from .compat import py39, py311
+from ._collections import FreezableDefaultDict, Pair
+from ._compat import (
+    NullFinder,
+    install,
+)
+from ._functools import method_cache, pass_none
+from ._itertools import always_iterable, unique_everseen
+from ._meta import PackageMetadata, SimplePath
+
+from contextlib import suppress
+from importlib import import_module
+from importlib.abc import MetaPathFinder
+from itertools import starmap
+from typing import Any, Iterable, List, Mapping, Match, Optional, Set, cast
+
+__all__ = [
+    'Distribution',
+    'DistributionFinder',
+    'PackageMetadata',
+    'PackageNotFoundError',
+    'distribution',
+    'distributions',
+    'entry_points',
+    'files',
+    'metadata',
+    'packages_distributions',
+    'requires',
+    'version',
+]
+
+
+class PackageNotFoundError(ModuleNotFoundError):
+    """The package was not found."""
+
+    def __str__(self) -> str:
+        return f"No package metadata was found for {self.name}"
+
+    @property
+    def name(self) -> str:  # type: ignore[override]
+        (name,) = self.args
+        return name
+
+
+class Sectioned:
+    """
+    A simple entry point config parser for performance
+
+    >>> for item in Sectioned.read(Sectioned._sample):
+    ...     print(item)
+    Pair(name='sec1', value='# comments ignored')
+    Pair(name='sec1', value='a = 1')
+    Pair(name='sec1', value='b = 2')
+    Pair(name='sec2', value='a = 2')
+
+    >>> res = Sectioned.section_pairs(Sectioned._sample)
+    >>> item = next(res)
+    >>> item.name
+    'sec1'
+    >>> item.value
+    Pair(name='a', value='1')
+    >>> item = next(res)
+    >>> item.value
+    Pair(name='b', value='2')
+    >>> item = next(res)
+    >>> item.name
+    'sec2'
+    >>> item.value
+    Pair(name='a', value='2')
+    >>> list(res)
+    []
+    """
+
+    _sample = textwrap.dedent(
+        """
+        [sec1]
+        # comments ignored
+        a = 1
+        b = 2
+
+        [sec2]
+        a = 2
+        """
+    ).lstrip()
+
+    @classmethod
+    def section_pairs(cls, text):
+        return (
+            section._replace(value=Pair.parse(section.value))
+            for section in cls.read(text, filter_=cls.valid)
+            if section.name is not None
+        )
+
+    @staticmethod
+    def read(text, filter_=None):
+        lines = filter(filter_, map(str.strip, text.splitlines()))
+        name = None
+        for value in lines:
+            section_match = value.startswith('[') and value.endswith(']')
+            if section_match:
+                name = value.strip('[]')
+                continue
+            yield Pair(name, value)
+
+    @staticmethod
+    def valid(line: str):
+        return line and not line.startswith('#')
+
+
+class EntryPoint:
+    """An entry point as defined by Python packaging conventions.
+
+    See `the packaging docs on entry points
+    `_
+    for more information.
+
+    >>> ep = EntryPoint(
+    ...     name=None, group=None, value='package.module:attr [extra1, extra2]')
+    >>> ep.module
+    'package.module'
+    >>> ep.attr
+    'attr'
+    >>> ep.extras
+    ['extra1', 'extra2']
+    """
+
+    pattern = re.compile(
+        r'(?P[\w.]+)\s*'
+        r'(:\s*(?P[\w.]+)\s*)?'
+        r'((?P\[.*\])\s*)?$'
+    )
+    """
+    A regular expression describing the syntax for an entry point,
+    which might look like:
+
+        - module
+        - package.module
+        - package.module:attribute
+        - package.module:object.attribute
+        - package.module:attr [extra1, extra2]
+
+    Other combinations are possible as well.
+
+    The expression is lenient about whitespace around the ':',
+    following the attr, and following any extras.
+    """
+
+    name: str
+    value: str
+    group: str
+
+    dist: Optional[Distribution] = None
+
+    def __init__(self, name: str, value: str, group: str) -> None:
+        vars(self).update(name=name, value=value, group=group)
+
+    def load(self) -> Any:
+        """Load the entry point from its definition. If only a module
+        is indicated by the value, return that module. Otherwise,
+        return the named object.
+        """
+        match = cast(Match, self.pattern.match(self.value))
+        module = import_module(match.group('module'))
+        attrs = filter(None, (match.group('attr') or '').split('.'))
+        return functools.reduce(getattr, attrs, module)
+
+    @property
+    def module(self) -> str:
+        match = self.pattern.match(self.value)
+        assert match is not None
+        return match.group('module')
+
+    @property
+    def attr(self) -> str:
+        match = self.pattern.match(self.value)
+        assert match is not None
+        return match.group('attr')
+
+    @property
+    def extras(self) -> List[str]:
+        match = self.pattern.match(self.value)
+        assert match is not None
+        return re.findall(r'\w+', match.group('extras') or '')
+
+    def _for(self, dist):
+        vars(self).update(dist=dist)
+        return self
+
+    def matches(self, **params):
+        """
+        EntryPoint matches the given parameters.
+
+        >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
+        >>> ep.matches(group='foo')
+        True
+        >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
+        True
+        >>> ep.matches(group='foo', name='other')
+        False
+        >>> ep.matches()
+        True
+        >>> ep.matches(extras=['extra1', 'extra2'])
+        True
+        >>> ep.matches(module='bing')
+        True
+        >>> ep.matches(attr='bong')
+        True
+        """
+        attrs = (getattr(self, param) for param in params)
+        return all(map(operator.eq, params.values(), attrs))
+
+    def _key(self):
+        return self.name, self.value, self.group
+
+    def __lt__(self, other):
+        return self._key() < other._key()
+
+    def __eq__(self, other):
+        return self._key() == other._key()
+
+    def __setattr__(self, name, value):
+        raise AttributeError("EntryPoint objects are immutable.")
+
+    def __repr__(self):
+        return (
+            f'EntryPoint(name={self.name!r}, value={self.value!r}, '
+            f'group={self.group!r})'
+        )
+
+    def __hash__(self) -> int:
+        return hash(self._key())
+
+
+class EntryPoints(tuple):
+    """
+    An immutable collection of selectable EntryPoint objects.
+    """
+
+    __slots__ = ()
+
+    def __getitem__(self, name: str) -> EntryPoint:  # type: ignore[override]
+        """
+        Get the EntryPoint in self matching name.
+        """
+        try:
+            return next(iter(self.select(name=name)))
+        except StopIteration:
+            raise KeyError(name)
+
+    def __repr__(self):
+        """
+        Repr with classname and tuple constructor to
+        signal that we deviate from regular tuple behavior.
+        """
+        return '%s(%r)' % (self.__class__.__name__, tuple(self))
+
+    def select(self, **params) -> EntryPoints:
+        """
+        Select entry points from self that match the
+        given parameters (typically group and/or name).
+        """
+        return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params))
+
+    @property
+    def names(self) -> Set[str]:
+        """
+        Return the set of all names of all entry points.
+        """
+        return {ep.name for ep in self}
+
+    @property
+    def groups(self) -> Set[str]:
+        """
+        Return the set of all groups of all entry points.
+        """
+        return {ep.group for ep in self}
+
+    @classmethod
+    def _from_text_for(cls, text, dist):
+        return cls(ep._for(dist) for ep in cls._from_text(text))
+
+    @staticmethod
+    def _from_text(text):
+        return (
+            EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
+            for item in Sectioned.section_pairs(text or '')
+        )
+
+
+class PackagePath(pathlib.PurePosixPath):
+    """A reference to a path in a package"""
+
+    hash: Optional[FileHash]
+    size: int
+    dist: Distribution
+
+    def read_text(self, encoding: str = 'utf-8') -> str:  # type: ignore[override]
+        return self.locate().read_text(encoding=encoding)
+
+    def read_binary(self) -> bytes:
+        return self.locate().read_bytes()
+
+    def locate(self) -> SimplePath:
+        """Return a path-like object for this path"""
+        return self.dist.locate_file(self)
+
+
+class FileHash:
+    def __init__(self, spec: str) -> None:
+        self.mode, _, self.value = spec.partition('=')
+
+    def __repr__(self) -> str:
+        return f''
+
+
+class Distribution(metaclass=abc.ABCMeta):
+    """
+    An abstract Python distribution package.
+
+    Custom providers may derive from this class and define
+    the abstract methods to provide a concrete implementation
+    for their environment. Some providers may opt to override
+    the default implementation of some properties to bypass
+    the file-reading mechanism.
+    """
+
+    @abc.abstractmethod
+    def read_text(self, filename) -> Optional[str]:
+        """Attempt to load metadata file given by the name.
+
+        Python distribution metadata is organized by blobs of text
+        typically represented as "files" in the metadata directory
+        (e.g. package-1.0.dist-info). These files include things
+        like:
+
+        - METADATA: The distribution metadata including fields
+          like Name and Version and Description.
+        - entry_points.txt: A series of entry points as defined in
+          `the entry points spec `_.
+        - RECORD: A record of files according to
+          `this recording spec `_.
+
+        A package may provide any set of files, including those
+        not listed here or none at all.
+
+        :param filename: The name of the file in the distribution info.
+        :return: The text if found, otherwise None.
+        """
+
+    @abc.abstractmethod
+    def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
+        """
+        Given a path to a file in this distribution, return a SimplePath
+        to it.
+        """
+
+    @classmethod
+    def from_name(cls, name: str) -> Distribution:
+        """Return the Distribution for the given package name.
+
+        :param name: The name of the distribution package to search for.
+        :return: The Distribution instance (or subclass thereof) for the named
+            package, if found.
+        :raises PackageNotFoundError: When the named package's distribution
+            metadata cannot be found.
+        :raises ValueError: When an invalid value is supplied for name.
+        """
+        if not name:
+            raise ValueError("A distribution name is required.")
+        try:
+            return next(iter(cls.discover(name=name)))
+        except StopIteration:
+            raise PackageNotFoundError(name)
+
+    @classmethod
+    def discover(
+        cls, *, context: Optional[DistributionFinder.Context] = None, **kwargs
+    ) -> Iterable[Distribution]:
+        """Return an iterable of Distribution objects for all packages.
+
+        Pass a ``context`` or pass keyword arguments for constructing
+        a context.
+
+        :context: A ``DistributionFinder.Context`` object.
+        :return: Iterable of Distribution objects for packages matching
+          the context.
+        """
+        if context and kwargs:
+            raise ValueError("cannot accept context and kwargs")
+        context = context or DistributionFinder.Context(**kwargs)
+        return itertools.chain.from_iterable(
+            resolver(context) for resolver in cls._discover_resolvers()
+        )
+
+    @staticmethod
+    def at(path: str | os.PathLike[str]) -> Distribution:
+        """Return a Distribution for the indicated metadata path.
+
+        :param path: a string or path-like object
+        :return: a concrete Distribution instance for the path
+        """
+        return PathDistribution(pathlib.Path(path))
+
+    @staticmethod
+    def _discover_resolvers():
+        """Search the meta_path for resolvers (MetadataPathFinders)."""
+        declared = (
+            getattr(finder, 'find_distributions', None) for finder in sys.meta_path
+        )
+        return filter(None, declared)
+
+    @property
+    def metadata(self) -> _meta.PackageMetadata:
+        """Return the parsed metadata for this Distribution.
+
+        The returned object will have keys that name the various bits of
+        metadata per the
+        `Core metadata specifications `_.
+
+        Custom providers may provide the METADATA file or override this
+        property.
+        """
+        # deferred for performance (python/cpython#109829)
+        from . import _adapters
+
+        opt_text = (
+            self.read_text('METADATA')
+            or self.read_text('PKG-INFO')
+            # This last clause is here to support old egg-info files.  Its
+            # effect is to just end up using the PathDistribution's self._path
+            # (which points to the egg-info file) attribute unchanged.
+            or self.read_text('')
+        )
+        text = cast(str, opt_text)
+        return _adapters.Message(email.message_from_string(text))
+
+    @property
+    def name(self) -> str:
+        """Return the 'Name' metadata for the distribution package."""
+        return self.metadata['Name']
+
+    @property
+    def _normalized_name(self):
+        """Return a normalized version of the name."""
+        return Prepared.normalize(self.name)
+
+    @property
+    def version(self) -> str:
+        """Return the 'Version' metadata for the distribution package."""
+        return self.metadata['Version']
+
+    @property
+    def entry_points(self) -> EntryPoints:
+        """
+        Return EntryPoints for this distribution.
+
+        Custom providers may provide the ``entry_points.txt`` file
+        or override this property.
+        """
+        return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
+
+    @property
+    def files(self) -> Optional[List[PackagePath]]:
+        """Files in this distribution.
+
+        :return: List of PackagePath for this distribution or None
+
+        Result is `None` if the metadata file that enumerates files
+        (i.e. RECORD for dist-info, or installed-files.txt or
+        SOURCES.txt for egg-info) is missing.
+        Result may be empty if the metadata exists but is empty.
+
+        Custom providers are recommended to provide a "RECORD" file (in
+        ``read_text``) or override this property to allow for callers to be
+        able to resolve filenames provided by the package.
+        """
+
+        def make_file(name, hash=None, size_str=None):
+            result = PackagePath(name)
+            result.hash = FileHash(hash) if hash else None
+            result.size = int(size_str) if size_str else None
+            result.dist = self
+            return result
+
+        @pass_none
+        def make_files(lines):
+            # Delay csv import, since Distribution.files is not as widely used
+            # as other parts of importlib.metadata
+            import csv
+
+            return starmap(make_file, csv.reader(lines))
+
+        @pass_none
+        def skip_missing_files(package_paths):
+            return list(filter(lambda path: path.locate().exists(), package_paths))
+
+        return skip_missing_files(
+            make_files(
+                self._read_files_distinfo()
+                or self._read_files_egginfo_installed()
+                or self._read_files_egginfo_sources()
+            )
+        )
+
+    def _read_files_distinfo(self):
+        """
+        Read the lines of RECORD.
+        """
+        text = self.read_text('RECORD')
+        return text and text.splitlines()
+
+    def _read_files_egginfo_installed(self):
+        """
+        Read installed-files.txt and return lines in a similar
+        CSV-parsable format as RECORD: each file must be placed
+        relative to the site-packages directory and must also be
+        quoted (since file names can contain literal commas).
+
+        This file is written when the package is installed by pip,
+        but it might not be written for other installation methods.
+        Assume the file is accurate if it exists.
+        """
+        text = self.read_text('installed-files.txt')
+        # Prepend the .egg-info/ subdir to the lines in this file.
+        # But this subdir is only available from PathDistribution's
+        # self._path.
+        subdir = getattr(self, '_path', None)
+        if not text or not subdir:
+            return
+
+        paths = (
+            py311.relative_fix((subdir / name).resolve())
+            .relative_to(self.locate_file('').resolve(), walk_up=True)
+            .as_posix()
+            for name in text.splitlines()
+        )
+        return map('"{}"'.format, paths)
+
+    def _read_files_egginfo_sources(self):
+        """
+        Read SOURCES.txt and return lines in a similar CSV-parsable
+        format as RECORD: each file name must be quoted (since it
+        might contain literal commas).
+
+        Note that SOURCES.txt is not a reliable source for what
+        files are installed by a package. This file is generated
+        for a source archive, and the files that are present
+        there (e.g. setup.py) may not correctly reflect the files
+        that are present after the package has been installed.
+        """
+        text = self.read_text('SOURCES.txt')
+        return text and map('"{}"'.format, text.splitlines())
+
+    @property
+    def requires(self) -> Optional[List[str]]:
+        """Generated requirements specified for this Distribution"""
+        reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
+        return reqs and list(reqs)
+
+    def _read_dist_info_reqs(self):
+        return self.metadata.get_all('Requires-Dist')
+
+    def _read_egg_info_reqs(self):
+        source = self.read_text('requires.txt')
+        return pass_none(self._deps_from_requires_text)(source)
+
+    @classmethod
+    def _deps_from_requires_text(cls, source):
+        return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
+
+    @staticmethod
+    def _convert_egg_info_reqs_to_simple_reqs(sections):
+        """
+        Historically, setuptools would solicit and store 'extra'
+        requirements, including those with environment markers,
+        in separate sections. More modern tools expect each
+        dependency to be defined separately, with any relevant
+        extras and environment markers attached directly to that
+        requirement. This method converts the former to the
+        latter. See _test_deps_from_requires_text for an example.
+        """
+
+        def make_condition(name):
+            return name and f'extra == "{name}"'
+
+        def quoted_marker(section):
+            section = section or ''
+            extra, sep, markers = section.partition(':')
+            if extra and markers:
+                markers = f'({markers})'
+            conditions = list(filter(None, [markers, make_condition(extra)]))
+            return '; ' + ' and '.join(conditions) if conditions else ''
+
+        def url_req_space(req):
+            """
+            PEP 508 requires a space between the url_spec and the quoted_marker.
+            Ref python/importlib_metadata#357.
+            """
+            # '@' is uniquely indicative of a url_req.
+            return ' ' * ('@' in req)
+
+        for section in sections:
+            space = url_req_space(section.value)
+            yield section.value + space + quoted_marker(section.name)
+
+    @property
+    def origin(self):
+        return self._load_json('direct_url.json')
+
+    def _load_json(self, filename):
+        return pass_none(json.loads)(
+            self.read_text(filename),
+            object_hook=lambda data: types.SimpleNamespace(**data),
+        )
+
+
+class DistributionFinder(MetaPathFinder):
+    """
+    A MetaPathFinder capable of discovering installed distributions.
+
+    Custom providers should implement this interface in order to
+    supply metadata.
+    """
+
+    class Context:
+        """
+        Keyword arguments presented by the caller to
+        ``distributions()`` or ``Distribution.discover()``
+        to narrow the scope of a search for distributions
+        in all DistributionFinders.
+
+        Each DistributionFinder may expect any parameters
+        and should attempt to honor the canonical
+        parameters defined below when appropriate.
+
+        This mechanism gives a custom provider a means to
+        solicit additional details from the caller beyond
+        "name" and "path" when searching distributions.
+        For example, imagine a provider that exposes suites
+        of packages in either a "public" or "private" ``realm``.
+        A caller may wish to query only for distributions in
+        a particular realm and could call
+        ``distributions(realm="private")`` to signal to the
+        custom provider to only include distributions from that
+        realm.
+        """
+
+        name = None
+        """
+        Specific name for which a distribution finder should match.
+        A name of ``None`` matches all distributions.
+        """
+
+        def __init__(self, **kwargs):
+            vars(self).update(kwargs)
+
+        @property
+        def path(self) -> List[str]:
+            """
+            The sequence of directory path that a distribution finder
+            should search.
+
+            Typically refers to Python installed package paths such as
+            "site-packages" directories and defaults to ``sys.path``.
+            """
+            return vars(self).get('path', sys.path)
+
+    @abc.abstractmethod
+    def find_distributions(self, context=Context()) -> Iterable[Distribution]:
+        """
+        Find distributions.
+
+        Return an iterable of all Distribution instances capable of
+        loading the metadata for packages matching the ``context``,
+        a DistributionFinder.Context instance.
+        """
+
+
+class FastPath:
+    """
+    Micro-optimized class for searching a root for children.
+
+    Root is a path on the file system that may contain metadata
+    directories either as natural directories or within a zip file.
+
+    >>> FastPath('').children()
+    ['...']
+
+    FastPath objects are cached and recycled for any given root.
+
+    >>> FastPath('foobar') is FastPath('foobar')
+    True
+    """
+
+    @functools.lru_cache()  # type: ignore
+    def __new__(cls, root):
+        return super().__new__(cls)
+
+    def __init__(self, root):
+        self.root = root
+
+    def joinpath(self, child):
+        return pathlib.Path(self.root, child)
+
+    def children(self):
+        with suppress(Exception):
+            return os.listdir(self.root or '.')
+        with suppress(Exception):
+            return self.zip_children()
+        return []
+
+    def zip_children(self):
+        zip_path = zipp.Path(self.root)
+        names = zip_path.root.namelist()
+        self.joinpath = zip_path.joinpath
+
+        return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
+
+    def search(self, name):
+        return self.lookup(self.mtime).search(name)
+
+    @property
+    def mtime(self):
+        with suppress(OSError):
+            return os.stat(self.root).st_mtime
+        self.lookup.cache_clear()
+
+    @method_cache
+    def lookup(self, mtime):
+        return Lookup(self)
+
+
+class Lookup:
+    """
+    A micro-optimized class for searching a (fast) path for metadata.
+    """
+
+    def __init__(self, path: FastPath):
+        """
+        Calculate all of the children representing metadata.
+
+        From the children in the path, calculate early all of the
+        children that appear to represent metadata (infos) or legacy
+        metadata (eggs).
+        """
+
+        base = os.path.basename(path.root).lower()
+        base_is_egg = base.endswith(".egg")
+        self.infos = FreezableDefaultDict(list)
+        self.eggs = FreezableDefaultDict(list)
+
+        for child in path.children():
+            low = child.lower()
+            if low.endswith((".dist-info", ".egg-info")):
+                # rpartition is faster than splitext and suitable for this purpose.
+                name = low.rpartition(".")[0].partition("-")[0]
+                normalized = Prepared.normalize(name)
+                self.infos[normalized].append(path.joinpath(child))
+            elif base_is_egg and low == "egg-info":
+                name = base.rpartition(".")[0].partition("-")[0]
+                legacy_normalized = Prepared.legacy_normalize(name)
+                self.eggs[legacy_normalized].append(path.joinpath(child))
+
+        self.infos.freeze()
+        self.eggs.freeze()
+
+    def search(self, prepared: Prepared):
+        """
+        Yield all infos and eggs matching the Prepared query.
+        """
+        infos = (
+            self.infos[prepared.normalized]
+            if prepared
+            else itertools.chain.from_iterable(self.infos.values())
+        )
+        eggs = (
+            self.eggs[prepared.legacy_normalized]
+            if prepared
+            else itertools.chain.from_iterable(self.eggs.values())
+        )
+        return itertools.chain(infos, eggs)
+
+
+class Prepared:
+    """
+    A prepared search query for metadata on a possibly-named package.
+
+    Pre-calculates the normalization to prevent repeated operations.
+
+    >>> none = Prepared(None)
+    >>> none.normalized
+    >>> none.legacy_normalized
+    >>> bool(none)
+    False
+    >>> sample = Prepared('Sample__Pkg-name.foo')
+    >>> sample.normalized
+    'sample_pkg_name_foo'
+    >>> sample.legacy_normalized
+    'sample__pkg_name.foo'
+    >>> bool(sample)
+    True
+    """
+
+    normalized = None
+    legacy_normalized = None
+
+    def __init__(self, name: Optional[str]):
+        self.name = name
+        if name is None:
+            return
+        self.normalized = self.normalize(name)
+        self.legacy_normalized = self.legacy_normalize(name)
+
+    @staticmethod
+    def normalize(name):
+        """
+        PEP 503 normalization plus dashes as underscores.
+        """
+        return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
+
+    @staticmethod
+    def legacy_normalize(name):
+        """
+        Normalize the package name as found in the convention in
+        older packaging tools versions and specs.
+        """
+        return name.lower().replace('-', '_')
+
+    def __bool__(self):
+        return bool(self.name)
+
+
+@install
+class MetadataPathFinder(NullFinder, DistributionFinder):
+    """A degenerate finder for distribution packages on the file system.
+
+    This finder supplies only a find_distributions() method for versions
+    of Python that do not have a PathFinder find_distributions().
+    """
+
+    @classmethod
+    def find_distributions(
+        cls, context=DistributionFinder.Context()
+    ) -> Iterable[PathDistribution]:
+        """
+        Find distributions.
+
+        Return an iterable of all Distribution instances capable of
+        loading the metadata for packages matching ``context.name``
+        (or all names if ``None`` indicated) along the paths in the list
+        of directories ``context.path``.
+        """
+        found = cls._search_paths(context.name, context.path)
+        return map(PathDistribution, found)
+
+    @classmethod
+    def _search_paths(cls, name, paths):
+        """Find metadata directories in paths heuristically."""
+        prepared = Prepared(name)
+        return itertools.chain.from_iterable(
+            path.search(prepared) for path in map(FastPath, paths)
+        )
+
+    @classmethod
+    def invalidate_caches(cls) -> None:
+        FastPath.__new__.cache_clear()
+
+
+class PathDistribution(Distribution):
+    def __init__(self, path: SimplePath) -> None:
+        """Construct a distribution.
+
+        :param path: SimplePath indicating the metadata directory.
+        """
+        self._path = path
+
+    def read_text(self, filename: str | os.PathLike[str]) -> Optional[str]:
+        with suppress(
+            FileNotFoundError,
+            IsADirectoryError,
+            KeyError,
+            NotADirectoryError,
+            PermissionError,
+        ):
+            return self._path.joinpath(filename).read_text(encoding='utf-8')
+
+        return None
+
+    read_text.__doc__ = Distribution.read_text.__doc__
+
+    def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
+        return self._path.parent / path
+
+    @property
+    def _normalized_name(self):
+        """
+        Performance optimization: where possible, resolve the
+        normalized name from the file system path.
+        """
+        stem = os.path.basename(str(self._path))
+        return (
+            pass_none(Prepared.normalize)(self._name_from_stem(stem))
+            or super()._normalized_name
+        )
+
+    @staticmethod
+    def _name_from_stem(stem):
+        """
+        >>> PathDistribution._name_from_stem('foo-3.0.egg-info')
+        'foo'
+        >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info')
+        'CherryPy'
+        >>> PathDistribution._name_from_stem('face.egg-info')
+        'face'
+        >>> PathDistribution._name_from_stem('foo.bar')
+        """
+        filename, ext = os.path.splitext(stem)
+        if ext not in ('.dist-info', '.egg-info'):
+            return
+        name, sep, rest = filename.partition('-')
+        return name
+
+
+def distribution(distribution_name: str) -> Distribution:
+    """Get the ``Distribution`` instance for the named package.
+
+    :param distribution_name: The name of the distribution package as a string.
+    :return: A ``Distribution`` instance (or subclass thereof).
+    """
+    return Distribution.from_name(distribution_name)
+
+
+def distributions(**kwargs) -> Iterable[Distribution]:
+    """Get all ``Distribution`` instances in the current environment.
+
+    :return: An iterable of ``Distribution`` instances.
+    """
+    return Distribution.discover(**kwargs)
+
+
+def metadata(distribution_name: str) -> _meta.PackageMetadata:
+    """Get the metadata for the named package.
+
+    :param distribution_name: The name of the distribution package to query.
+    :return: A PackageMetadata containing the parsed metadata.
+    """
+    return Distribution.from_name(distribution_name).metadata
+
+
+def version(distribution_name: str) -> str:
+    """Get the version string for the named package.
+
+    :param distribution_name: The name of the distribution package to query.
+    :return: The version string for the package as defined in the package's
+        "Version" metadata key.
+    """
+    return distribution(distribution_name).version
+
+
+_unique = functools.partial(
+    unique_everseen,
+    key=py39.normalized_name,
+)
+"""
+Wrapper for ``distributions`` to return unique distributions by name.
+"""
+
+
+def entry_points(**params) -> EntryPoints:
+    """Return EntryPoint objects for all installed packages.
+
+    Pass selection parameters (group or name) to filter the
+    result to entry points matching those properties (see
+    EntryPoints.select()).
+
+    :return: EntryPoints for all installed packages.
+    """
+    eps = itertools.chain.from_iterable(
+        dist.entry_points for dist in _unique(distributions())
+    )
+    return EntryPoints(eps).select(**params)
+
+
+def files(distribution_name: str) -> Optional[List[PackagePath]]:
+    """Return a list of files for the named package.
+
+    :param distribution_name: The name of the distribution package to query.
+    :return: List of files composing the distribution.
+    """
+    return distribution(distribution_name).files
+
+
+def requires(distribution_name: str) -> Optional[List[str]]:
+    """
+    Return a list of requirements for the named package.
+
+    :return: An iterable of requirements, suitable for
+        packaging.requirement.Requirement.
+    """
+    return distribution(distribution_name).requires
+
+
+def packages_distributions() -> Mapping[str, List[str]]:
+    """
+    Return a mapping of top-level packages to their
+    distributions.
+
+    >>> import collections.abc
+    >>> pkgs = packages_distributions()
+    >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
+    True
+    """
+    pkg_to_dist = collections.defaultdict(list)
+    for dist in distributions():
+        for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
+            pkg_to_dist[pkg].append(dist.metadata['Name'])
+    return dict(pkg_to_dist)
+
+
+def _top_level_declared(dist):
+    return (dist.read_text('top_level.txt') or '').split()
+
+
+def _topmost(name: PackagePath) -> Optional[str]:
+    """
+    Return the top-most parent as long as there is a parent.
+    """
+    top, *rest = name.parts
+    return top if rest else None
+
+
+def _get_toplevel_name(name: PackagePath) -> str:
+    """
+    Infer a possibly importable module name from a name presumed on
+    sys.path.
+
+    >>> _get_toplevel_name(PackagePath('foo.py'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo.pyc'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo/__init__.py'))
+    'foo'
+    >>> _get_toplevel_name(PackagePath('foo.pth'))
+    'foo.pth'
+    >>> _get_toplevel_name(PackagePath('foo.dist-info'))
+    'foo.dist-info'
+    """
+    return _topmost(name) or (
+        # python/typeshed#10328
+        inspect.getmodulename(name)  # type: ignore
+        or str(name)
+    )
+
+
+def _top_level_inferred(dist):
+    opt_names = set(map(_get_toplevel_name, always_iterable(dist.files)))
+
+    def importable_name(name):
+        return '.' not in name
+
+    return filter(importable_name, opt_names)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py
new file mode 100644
index 0000000000000000000000000000000000000000..6223263ed53f22fc25c09de06789718d2cd3b6ea
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py
@@ -0,0 +1,83 @@
+import re
+import textwrap
+import email.message
+
+from ._text import FoldedCase
+
+
+class Message(email.message.Message):
+    multiple_use_keys = set(
+        map(
+            FoldedCase,
+            [
+                'Classifier',
+                'Obsoletes-Dist',
+                'Platform',
+                'Project-URL',
+                'Provides-Dist',
+                'Provides-Extra',
+                'Requires-Dist',
+                'Requires-External',
+                'Supported-Platform',
+                'Dynamic',
+            ],
+        )
+    )
+    """
+    Keys that may be indicated multiple times per PEP 566.
+    """
+
+    def __new__(cls, orig: email.message.Message):
+        res = super().__new__(cls)
+        vars(res).update(vars(orig))
+        return res
+
+    def __init__(self, *args, **kwargs):
+        self._headers = self._repair_headers()
+
+    # suppress spurious error from mypy
+    def __iter__(self):
+        return super().__iter__()
+
+    def __getitem__(self, item):
+        """
+        Override parent behavior to typical dict behavior.
+
+        ``email.message.Message`` will emit None values for missing
+        keys. Typical mappings, including this ``Message``, will raise
+        a key error for missing keys.
+
+        Ref python/importlib_metadata#371.
+        """
+        res = super().__getitem__(item)
+        if res is None:
+            raise KeyError(item)
+        return res
+
+    def _repair_headers(self):
+        def redent(value):
+            "Correct for RFC822 indentation"
+            if not value or '\n' not in value:
+                return value
+            return textwrap.dedent(' ' * 8 + value)
+
+        headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
+        if self._payload:
+            headers.append(('Description', self.get_payload()))
+        return headers
+
+    @property
+    def json(self):
+        """
+        Convert PackageMetadata to a JSON-compatible format
+        per PEP 0566.
+        """
+
+        def transform(key):
+            value = self.get_all(key) if key in self.multiple_use_keys else self[key]
+            if key == 'Keywords':
+                value = re.split(r'\s+', value)
+            tk = key.lower().replace('-', '_')
+            return tk, value
+
+        return dict(map(transform, map(FoldedCase, self)))
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_collections.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf0954e1a30546d781bf25781ec716ef92a77e32
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_collections.py
@@ -0,0 +1,30 @@
+import collections
+
+
+# from jaraco.collections 3.3
+class FreezableDefaultDict(collections.defaultdict):
+    """
+    Often it is desirable to prevent the mutation of
+    a default dict after its initial construction, such
+    as to prevent mutation during iteration.
+
+    >>> dd = FreezableDefaultDict(list)
+    >>> dd[0].append('1')
+    >>> dd.freeze()
+    >>> dd[1]
+    []
+    >>> len(dd)
+    1
+    """
+
+    def __missing__(self, key):
+        return getattr(self, '_frozen', super().__missing__)(key)
+
+    def freeze(self):
+        self._frozen = lambda key: self.default_factory()
+
+
+class Pair(collections.namedtuple('Pair', 'name value')):
+    @classmethod
+    def parse(cls, text):
+        return cls(*map(str.strip, text.split("=", 1)))
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_compat.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..df312b1cbbf18a337278df0e618fb9e8c862e5f6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_compat.py
@@ -0,0 +1,57 @@
+import sys
+import platform
+
+
+__all__ = ['install', 'NullFinder']
+
+
+def install(cls):
+    """
+    Class decorator for installation on sys.meta_path.
+
+    Adds the backport DistributionFinder to sys.meta_path and
+    attempts to disable the finder functionality of the stdlib
+    DistributionFinder.
+    """
+    sys.meta_path.append(cls())
+    disable_stdlib_finder()
+    return cls
+
+
+def disable_stdlib_finder():
+    """
+    Give the backport primacy for discovering path-based distributions
+    by monkey-patching the stdlib O_O.
+
+    See #91 for more background for rationale on this sketchy
+    behavior.
+    """
+
+    def matches(finder):
+        return getattr(
+            finder, '__module__', None
+        ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions')
+
+    for finder in filter(matches, sys.meta_path):  # pragma: nocover
+        del finder.find_distributions
+
+
+class NullFinder:
+    """
+    A "Finder" (aka "MetaPathFinder") that never finds any modules,
+    but may find distributions.
+    """
+
+    @staticmethod
+    def find_spec(*args, **kwargs):
+        return None
+
+
+def pypy_partial(val):
+    """
+    Adjust for variable stacklevel on partial under PyPy.
+
+    Workaround for #327.
+    """
+    is_pypy = platform.python_implementation() == 'PyPy'
+    return val + is_pypy
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_functools.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_functools.py
new file mode 100644
index 0000000000000000000000000000000000000000..71f66bd03cb713a2190853bdf7170c4ea80d2425
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_functools.py
@@ -0,0 +1,104 @@
+import types
+import functools
+
+
+# from jaraco.functools 3.3
+def method_cache(method, cache_wrapper=None):
+    """
+    Wrap lru_cache to support storing the cache data in the object instances.
+
+    Abstracts the common paradigm where the method explicitly saves an
+    underscore-prefixed protected property on first call and returns that
+    subsequently.
+
+    >>> class MyClass:
+    ...     calls = 0
+    ...
+    ...     @method_cache
+    ...     def method(self, value):
+    ...         self.calls += 1
+    ...         return value
+
+    >>> a = MyClass()
+    >>> a.method(3)
+    3
+    >>> for x in range(75):
+    ...     res = a.method(x)
+    >>> a.calls
+    75
+
+    Note that the apparent behavior will be exactly like that of lru_cache
+    except that the cache is stored on each instance, so values in one
+    instance will not flush values from another, and when an instance is
+    deleted, so are the cached values for that instance.
+
+    >>> b = MyClass()
+    >>> for x in range(35):
+    ...     res = b.method(x)
+    >>> b.calls
+    35
+    >>> a.method(0)
+    0
+    >>> a.calls
+    75
+
+    Note that if method had been decorated with ``functools.lru_cache()``,
+    a.calls would have been 76 (due to the cached value of 0 having been
+    flushed by the 'b' instance).
+
+    Clear the cache with ``.cache_clear()``
+
+    >>> a.method.cache_clear()
+
+    Same for a method that hasn't yet been called.
+
+    >>> c = MyClass()
+    >>> c.method.cache_clear()
+
+    Another cache wrapper may be supplied:
+
+    >>> cache = functools.lru_cache(maxsize=2)
+    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
+    >>> a = MyClass()
+    >>> a.method2()
+    3
+
+    Caution - do not subsequently wrap the method with another decorator, such
+    as ``@property``, which changes the semantics of the function.
+
+    See also
+    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
+    for another implementation and additional justification.
+    """
+    cache_wrapper = cache_wrapper or functools.lru_cache()
+
+    def wrapper(self, *args, **kwargs):
+        # it's the first call, replace the method with a cached, bound method
+        bound_method = types.MethodType(method, self)
+        cached_method = cache_wrapper(bound_method)
+        setattr(self, method.__name__, cached_method)
+        return cached_method(*args, **kwargs)
+
+    # Support cache clear even before cache has been created.
+    wrapper.cache_clear = lambda: None
+
+    return wrapper
+
+
+# From jaraco.functools 3.3
+def pass_none(func):
+    """
+    Wrap func so it's not called if its first param is None
+
+    >>> print_text = pass_none(print)
+    >>> print_text('text')
+    text
+    >>> print_text(None)
+    """
+
+    @functools.wraps(func)
+    def wrapper(param, *args, **kwargs):
+        if param is not None:
+            return func(param, *args, **kwargs)
+
+    return wrapper
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ca9b9140e3f085b36609bb8dfdaea79c78e144
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py
@@ -0,0 +1,73 @@
+from itertools import filterfalse
+
+
+def unique_everseen(iterable, key=None):
+    "List unique elements, preserving order. Remember all elements ever seen."
+    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
+    # unique_everseen('ABBCcAD', str.lower) --> A B C D
+    seen = set()
+    seen_add = seen.add
+    if key is None:
+        for element in filterfalse(seen.__contains__, iterable):
+            seen_add(element)
+            yield element
+    else:
+        for element in iterable:
+            k = key(element)
+            if k not in seen:
+                seen_add(k)
+                yield element
+
+
+# copied from more_itertools 8.8
+def always_iterable(obj, base_type=(str, bytes)):
+    """If *obj* is iterable, return an iterator over its items::
+
+        >>> obj = (1, 2, 3)
+        >>> list(always_iterable(obj))
+        [1, 2, 3]
+
+    If *obj* is not iterable, return a one-item iterable containing *obj*::
+
+        >>> obj = 1
+        >>> list(always_iterable(obj))
+        [1]
+
+    If *obj* is ``None``, return an empty iterable:
+
+        >>> obj = None
+        >>> list(always_iterable(None))
+        []
+
+    By default, binary and text strings are not considered iterable::
+
+        >>> obj = 'foo'
+        >>> list(always_iterable(obj))
+        ['foo']
+
+    If *base_type* is set, objects for which ``isinstance(obj, base_type)``
+    returns ``True`` won't be considered iterable.
+
+        >>> obj = {'a': 1}
+        >>> list(always_iterable(obj))  # Iterate over the dict's keys
+        ['a']
+        >>> list(always_iterable(obj, base_type=dict))  # Treat dicts as a unit
+        [{'a': 1}]
+
+    Set *base_type* to ``None`` to avoid any special handling and treat objects
+    Python considers iterable as iterable:
+
+        >>> obj = 'foo'
+        >>> list(always_iterable(obj, base_type=None))
+        ['f', 'o', 'o']
+    """
+    if obj is None:
+        return iter(())
+
+    if (base_type is not None) and isinstance(obj, base_type):
+        return iter((obj,))
+
+    try:
+        return iter(obj)
+    except TypeError:
+        return iter((obj,))
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_meta.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..1927d0f624d82f2fa12f81c80cce91279f039e84
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_meta.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import os
+from typing import Protocol
+from typing import Any, Dict, Iterator, List, Optional, TypeVar, Union, overload
+
+
+_T = TypeVar("_T")
+
+
+class PackageMetadata(Protocol):
+    def __len__(self) -> int: ...  # pragma: no cover
+
+    def __contains__(self, item: str) -> bool: ...  # pragma: no cover
+
+    def __getitem__(self, key: str) -> str: ...  # pragma: no cover
+
+    def __iter__(self) -> Iterator[str]: ...  # pragma: no cover
+
+    @overload
+    def get(
+        self, name: str, failobj: None = None
+    ) -> Optional[str]: ...  # pragma: no cover
+
+    @overload
+    def get(self, name: str, failobj: _T) -> Union[str, _T]: ...  # pragma: no cover
+
+    # overload per python/importlib_metadata#435
+    @overload
+    def get_all(
+        self, name: str, failobj: None = None
+    ) -> Optional[List[Any]]: ...  # pragma: no cover
+
+    @overload
+    def get_all(self, name: str, failobj: _T) -> Union[List[Any], _T]:
+        """
+        Return all values associated with a possibly multi-valued key.
+        """
+
+    @property
+    def json(self) -> Dict[str, Union[str, List[str]]]:
+        """
+        A JSON-compatible form of the metadata.
+        """
+
+
+class SimplePath(Protocol):
+    """
+    A minimal subset of pathlib.Path required by Distribution.
+    """
+
+    def joinpath(
+        self, other: Union[str, os.PathLike[str]]
+    ) -> SimplePath: ...  # pragma: no cover
+
+    def __truediv__(
+        self, other: Union[str, os.PathLike[str]]
+    ) -> SimplePath: ...  # pragma: no cover
+
+    @property
+    def parent(self) -> SimplePath: ...  # pragma: no cover
+
+    def read_text(self, encoding=None) -> str: ...  # pragma: no cover
+
+    def read_bytes(self) -> bytes: ...  # pragma: no cover
+
+    def exists(self) -> bool: ...  # pragma: no cover
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_text.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/_text.py
@@ -0,0 +1,99 @@
+import re
+
+from ._functools import method_cache
+
+
+# from jaraco.text 3.5
+class FoldedCase(str):
+    """
+    A case insensitive string class; behaves just like str
+    except compares equal when the only variation is case.
+
+    >>> s = FoldedCase('hello world')
+
+    >>> s == 'Hello World'
+    True
+
+    >>> 'Hello World' == s
+    True
+
+    >>> s != 'Hello World'
+    False
+
+    >>> s.index('O')
+    4
+
+    >>> s.split('O')
+    ['hell', ' w', 'rld']
+
+    >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))
+    ['alpha', 'Beta', 'GAMMA']
+
+    Sequence membership is straightforward.
+
+    >>> "Hello World" in [s]
+    True
+    >>> s in ["Hello World"]
+    True
+
+    You may test for set inclusion, but candidate and elements
+    must both be folded.
+
+    >>> FoldedCase("Hello World") in {s}
+    True
+    >>> s in {FoldedCase("Hello World")}
+    True
+
+    String inclusion works as long as the FoldedCase object
+    is on the right.
+
+    >>> "hello" in FoldedCase("Hello World")
+    True
+
+    But not if the FoldedCase object is on the left:
+
+    >>> FoldedCase('hello') in 'Hello World'
+    False
+
+    In that case, use in_:
+
+    >>> FoldedCase('hello').in_('Hello World')
+    True
+
+    >>> FoldedCase('hello') > FoldedCase('Hello')
+    False
+    """
+
+    def __lt__(self, other):
+        return self.lower() < other.lower()
+
+    def __gt__(self, other):
+        return self.lower() > other.lower()
+
+    def __eq__(self, other):
+        return self.lower() == other.lower()
+
+    def __ne__(self, other):
+        return self.lower() != other.lower()
+
+    def __hash__(self):
+        return hash(self.lower())
+
+    def __contains__(self, other):
+        return super().lower().__contains__(other.lower())
+
+    def in_(self, other):
+        "Does self appear in other?"
+        return self in FoldedCase(other)
+
+    # cache lower since it's likely to be called frequently.
+    @method_cache
+    def lower(self):
+        return super().lower()
+
+    def index(self, sub):
+        return self.lower().index(sub.lower())
+
+    def split(self, splitter=' ', maxsplit=0):
+        pattern = re.compile(re.escape(splitter), re.I)
+        return pattern.split(self, maxsplit)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a5327436f9b1d9eae371e321c491a270634b3cf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py
@@ -0,0 +1,22 @@
+import os
+import pathlib
+import sys
+import types
+
+
+def wrap(path):  # pragma: no cover
+    """
+    Workaround for https://github.com/python/cpython/issues/84538
+    to add backward compatibility for walk_up=True.
+    An example affected package is dask-labextension, which uses
+    jupyter-packaging to install JupyterLab javascript files outside
+    of site-packages.
+    """
+
+    def relative_to(root, *, walk_up=False):
+        return pathlib.Path(os.path.relpath(path, root))
+
+    return types.SimpleNamespace(relative_to=relative_to)
+
+
+relative_fix = wrap if sys.version_info < (3, 12) else lambda x: x
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f15bd97e6aa028d3e86734dd08c0eb5c06d79bc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py
@@ -0,0 +1,36 @@
+"""
+Compatibility layer with Python 3.8/3.9
+"""
+
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:  # pragma: no cover
+    # Prevent circular imports on runtime.
+    from .. import Distribution, EntryPoint
+else:
+    Distribution = EntryPoint = Any
+
+
+def normalized_name(dist: Distribution) -> Optional[str]:
+    """
+    Honor name normalization for distributions that don't provide ``_normalized_name``.
+    """
+    try:
+        return dist._normalized_name
+    except AttributeError:
+        from .. import Prepared  # -> delay to prevent circular imports.
+
+        return Prepared.normalize(getattr(dist, "name", None) or dist.metadata['Name'])
+
+
+def ep_matches(ep: EntryPoint, **params) -> bool:
+    """
+    Workaround for ``EntryPoint`` objects without the ``matches`` method.
+    """
+    try:
+        return ep.matches(**params)
+    except AttributeError:
+        from .. import EntryPoint  # -> delay to prevent circular imports.
+
+        # Reconstruct the EntryPoint object to make sure it is compatible.
+        return EntryPoint(ep.name, ep.value, ep.group).matches(**params)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py
new file mode 100644
index 0000000000000000000000000000000000000000..e405471ac4d94371b1ee9b1622227ff76b337180
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py
@@ -0,0 +1,21 @@
+import sys
+
+from . import Distribution
+
+
+def inspect(path):
+    print("Inspecting", path)
+    dists = list(Distribution.discover(path=[path]))
+    if not dists:
+        return
+    print("Found", len(dists), "packages:", end=' ')
+    print(', '.join(dist.name for dist in dists))
+
+
+def run():
+    for path in sys.path:
+        inspect(path)
+
+
+if __name__ == '__main__':
+    run()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/importlib_metadata/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..9a2097a54aaaf21e7f46235a3ccf362213032ca9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/METADATA
@@ -0,0 +1,591 @@
+Metadata-Version: 2.1
+Name: inflect
+Version: 7.3.1
+Summary: Correctly generate plurals, singular nouns, ordinals, indefinite articles
+Author-email: Paul Dyson 
+Maintainer-email: "Jason R. Coombs" 
+Project-URL: Source, https://github.com/jaraco/inflect
+Keywords: plural,inflect,participle
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Natural Language :: English
+Classifier: Operating System :: OS Independent
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing :: Linguistic
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: more-itertools >=8.5.0
+Requires-Dist: typeguard >=4.0.1
+Requires-Dist: typing-extensions ; python_version < "3.9"
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test'
+Requires-Dist: pygments ; extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/inflect.svg
+   :target: https://pypi.org/project/inflect
+
+.. image:: https://img.shields.io/pypi/pyversions/inflect.svg
+
+.. image:: https://github.com/jaraco/inflect/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/inflect/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/inflect/badge/?version=latest
+   :target: https://inflect.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/inflect
+   :target: https://tidelift.com/subscription/pkg/pypi-inflect?utm_source=pypi-inflect&utm_medium=readme
+
+NAME
+====
+
+inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.
+
+SYNOPSIS
+========
+
+.. code-block:: python
+
+    import inflect
+
+    p = inflect.engine()
+
+    # METHODS:
+
+    # plural plural_noun plural_verb plural_adj singular_noun no num
+    # compare compare_nouns compare_nouns compare_adjs
+    # a an
+    # present_participle
+    # ordinal number_to_words
+    # join
+    # inflect classical gender
+    # defnoun defverb defadj defa defan
+
+
+    # UNCONDITIONALLY FORM THE PLURAL
+
+    print("The plural of ", word, " is ", p.plural(word))
+
+
+    # CONDITIONALLY FORM THE PLURAL
+
+    print("I saw", cat_count, p.plural("cat", cat_count))
+
+
+    # FORM PLURALS FOR SPECIFIC PARTS OF SPEECH
+
+    print(
+        p.plural_noun("I", N1),
+        p.plural_verb("saw", N1),
+        p.plural_adj("my", N2),
+        p.plural_noun("saw", N2),
+    )
+
+
+    # FORM THE SINGULAR OF PLURAL NOUNS
+
+    print("The singular of ", word, " is ", p.singular_noun(word))
+
+    # SELECT THE GENDER OF SINGULAR PRONOUNS
+
+    print(p.singular_noun("they"))  # 'it'
+    p.gender("feminine")
+    print(p.singular_noun("they"))  # 'she'
+
+
+    # DEAL WITH "0/1/N" -> "no/1/N" TRANSLATION:
+
+    print("There ", p.plural_verb("was", errors), p.no(" error", errors))
+
+
+    # USE DEFAULT COUNTS:
+
+    print(
+        p.num(N1, ""),
+        p.plural("I"),
+        p.plural_verb(" saw"),
+        p.num(N2),
+        p.plural_noun(" saw"),
+    )
+    print("There ", p.num(errors, ""), p.plural_verb("was"), p.no(" error"))
+
+
+    # COMPARE TWO WORDS "NUMBER-INSENSITIVELY":
+
+    if p.compare(word1, word2):
+        print("same")
+    if p.compare_nouns(word1, word2):
+        print("same noun")
+    if p.compare_verbs(word1, word2):
+        print("same verb")
+    if p.compare_adjs(word1, word2):
+        print("same adj.")
+
+
+    # ADD CORRECT "a" OR "an" FOR A GIVEN WORD:
+
+    print("Did you want ", p.a(thing), " or ", p.an(idea))
+
+
+    # CONVERT NUMERALS INTO ORDINALS (i.e. 1->1st, 2->2nd, 3->3rd, etc.)
+
+    print("It was", p.ordinal(position), " from the left\n")
+
+    # CONVERT NUMERALS TO WORDS (i.e. 1->"one", 101->"one hundred and one", etc.)
+    # RETURNS A SINGLE STRING...
+
+    words = p.number_to_words(1234)
+    # "one thousand, two hundred and thirty-four"
+    words = p.number_to_words(p.ordinal(1234))
+    # "one thousand, two hundred and thirty-fourth"
+
+
+    # GET BACK A LIST OF STRINGS, ONE FOR EACH "CHUNK"...
+
+    words = p.number_to_words(1234, wantlist=True)
+    # ("one thousand","two hundred and thirty-four")
+
+
+    # OPTIONAL PARAMETERS CHANGE TRANSLATION:
+
+    words = p.number_to_words(12345, group=1)
+    # "one, two, three, four, five"
+
+    words = p.number_to_words(12345, group=2)
+    # "twelve, thirty-four, five"
+
+    words = p.number_to_words(12345, group=3)
+    # "one twenty-three, forty-five"
+
+    words = p.number_to_words(1234, andword="")
+    # "one thousand, two hundred thirty-four"
+
+    words = p.number_to_words(1234, andword=", plus")
+    # "one thousand, two hundred, plus thirty-four"
+    # TODO: I get no comma before plus: check perl
+
+    words = p.number_to_words(555_1202, group=1, zero="oh")
+    # "five, five, five, one, two, oh, two"
+
+    words = p.number_to_words(555_1202, group=1, one="unity")
+    # "five, five, five, unity, two, oh, two"
+
+    words = p.number_to_words(123.456, group=1, decimal="mark")
+    # "one two three mark four five six"
+    # TODO: DOCBUG: perl gives commas here as do I
+
+    # LITERAL STYLE ONLY NAMES NUMBERS LESS THAN A CERTAIN THRESHOLD...
+
+    words = p.number_to_words(9, threshold=10)  # "nine"
+    words = p.number_to_words(10, threshold=10)  # "ten"
+    words = p.number_to_words(11, threshold=10)  # "11"
+    words = p.number_to_words(1000, threshold=10)  # "1,000"
+
+    # JOIN WORDS INTO A LIST:
+
+    mylist = p.join(("apple", "banana", "carrot"))
+    # "apple, banana, and carrot"
+
+    mylist = p.join(("apple", "banana"))
+    # "apple and banana"
+
+    mylist = p.join(("apple", "banana", "carrot"), final_sep="")
+    # "apple, banana and carrot"
+
+
+    # REQUIRE "CLASSICAL" PLURALS (EG: "focus"->"foci", "cherub"->"cherubim")
+
+    p.classical()  # USE ALL CLASSICAL PLURALS
+
+    p.classical(all=True)  # USE ALL CLASSICAL PLURALS
+    p.classical(all=False)  # SWITCH OFF CLASSICAL MODE
+
+    p.classical(zero=True)  #  "no error" INSTEAD OF "no errors"
+    p.classical(zero=False)  #  "no errors" INSTEAD OF "no error"
+
+    p.classical(herd=True)  #  "2 buffalo" INSTEAD OF "2 buffalos"
+    p.classical(herd=False)  #  "2 buffalos" INSTEAD OF "2 buffalo"
+
+    p.classical(persons=True)  # "2 chairpersons" INSTEAD OF "2 chairpeople"
+    p.classical(persons=False)  # "2 chairpeople" INSTEAD OF "2 chairpersons"
+
+    p.classical(ancient=True)  # "2 formulae" INSTEAD OF "2 formulas"
+    p.classical(ancient=False)  # "2 formulas" INSTEAD OF "2 formulae"
+
+
+    # INTERPOLATE "plural()", "plural_noun()", "plural_verb()", "plural_adj()", "singular_noun()",
+    # a()", "an()", "num()" AND "ordinal()" WITHIN STRINGS:
+
+    print(p.inflect("The plural of {0} is plural('{0}')".format(word)))
+    print(p.inflect("The singular of {0} is singular_noun('{0}')".format(word)))
+    print(p.inflect("I saw {0} plural('cat',{0})".format(cat_count)))
+    print(
+        p.inflect(
+            "plural('I',{0}) "
+            "plural_verb('saw',{0}) "
+            "plural('a',{1}) "
+            "plural_noun('saw',{1})".format(N1, N2)
+        )
+    )
+    print(
+        p.inflect(
+            "num({0}, False)plural('I') "
+            "plural_verb('saw') "
+            "num({1}, False)plural('a') "
+            "plural_noun('saw')".format(N1, N2)
+        )
+    )
+    print(p.inflect("I saw num({0}) plural('cat')\nnum()".format(cat_count)))
+    print(p.inflect("There plural_verb('was',{0}) no('error',{0})".format(errors)))
+    print(p.inflect("There num({0}, False)plural_verb('was') no('error')".format(errors)))
+    print(p.inflect("Did you want a('{0}') or an('{1}')".format(thing, idea)))
+    print(p.inflect("It was ordinal('{0}') from the left".format(position)))
+
+
+    # ADD USER-DEFINED INFLECTIONS (OVERRIDING INBUILT RULES):
+
+    p.defnoun("VAX", "VAXen")  # SINGULAR => PLURAL
+
+    p.defverb(
+        "will",  # 1ST PERSON SINGULAR
+        "shall",  # 1ST PERSON PLURAL
+        "will",  # 2ND PERSON SINGULAR
+        "will",  # 2ND PERSON PLURAL
+        "will",  # 3RD PERSON SINGULAR
+        "will",  # 3RD PERSON PLURAL
+    )
+
+    p.defadj("hir", "their")  # SINGULAR => PLURAL
+
+    p.defa("h")  # "AY HALWAYS SEZ 'HAITCH'!"
+
+    p.defan("horrendous.*")  # "AN HORRENDOUS AFFECTATION"
+
+
+DESCRIPTION
+===========
+
+The methods of the class ``engine`` in module ``inflect.py`` provide plural
+inflections, singular noun inflections, "a"/"an" selection for English words,
+and manipulation of numbers as words.
+
+Plural forms of all nouns, most verbs, and some adjectives are
+provided. Where appropriate, "classical" variants (for example: "brother" ->
+"brethren", "dogma" -> "dogmata", etc.) are also provided.
+
+Single forms of nouns are also provided. The gender of singular pronouns
+can be chosen (for example "they" -> "it" or "she" or "he" or "they").
+
+Pronunciation-based "a"/"an" selection is provided for all English
+words, and most initialisms.
+
+It is also possible to inflect numerals (1,2,3) to ordinals (1st, 2nd, 3rd)
+and to English words ("one", "two", "three").
+
+In generating these inflections, ``inflect.py`` follows the Oxford
+English Dictionary and the guidelines in Fowler's Modern English
+Usage, preferring the former where the two disagree.
+
+The module is built around standard British spelling, but is designed
+to cope with common American variants as well. Slang, jargon, and
+other English dialects are *not* explicitly catered for.
+
+Where two or more inflected forms exist for a single word (typically a
+"classical" form and a "modern" form), ``inflect.py`` prefers the
+more common form (typically the "modern" one), unless "classical"
+processing has been specified
+(see `MODERN VS CLASSICAL INFLECTIONS`).
+
+FORMING PLURALS AND SINGULARS
+=============================
+
+Inflecting Plurals and Singulars
+--------------------------------
+
+All of the ``plural...`` plural inflection methods take the word to be
+inflected as their first argument and return the corresponding inflection.
+Note that all such methods expect the *singular* form of the word. The
+results of passing a plural form are undefined (and unlikely to be correct).
+Similarly, the ``si...`` singular inflection method expects the *plural*
+form of the word.
+
+The ``plural...`` methods also take an optional second argument,
+which indicates the grammatical "number" of the word (or of another word
+with which the word being inflected must agree). If the "number" argument is
+supplied and is not ``1`` (or ``"one"`` or ``"a"``, or some other adjective that
+implies the singular), the plural form of the word is returned. If the
+"number" argument *does* indicate singularity, the (uninflected) word
+itself is returned. If the number argument is omitted, the plural form
+is returned unconditionally.
+
+The ``si...`` method takes a second argument in a similar fashion. If it is
+some form of the number ``1``, or is omitted, the singular form is returned.
+Otherwise the plural is returned unaltered.
+
+
+The various methods of ``inflect.engine`` are:
+
+
+
+``plural_noun(word, count=None)``
+
+ The method ``plural_noun()`` takes a *singular* English noun or
+ pronoun and returns its plural. Pronouns in the nominative ("I" ->
+ "we") and accusative ("me" -> "us") cases are handled, as are
+ possessive pronouns ("mine" -> "ours").
+
+
+``plural_verb(word, count=None)``
+
+ The method ``plural_verb()`` takes the *singular* form of a
+ conjugated verb (that is, one which is already in the correct "person"
+ and "mood") and returns the corresponding plural conjugation.
+
+
+``plural_adj(word, count=None)``
+
+ The method ``plural_adj()`` takes the *singular* form of
+ certain types of adjectives and returns the corresponding plural form.
+ Adjectives that are correctly handled include: "numerical" adjectives
+ ("a" -> "some"), demonstrative adjectives ("this" -> "these", "that" ->
+ "those"), and possessives ("my" -> "our", "cat's" -> "cats'", "child's"
+ -> "childrens'", etc.)
+
+
+``plural(word, count=None)``
+
+ The method ``plural()`` takes a *singular* English noun,
+ pronoun, verb, or adjective and returns its plural form. Where a word
+ has more than one inflection depending on its part of speech (for
+ example, the noun "thought" inflects to "thoughts", the verb "thought"
+ to "thought"), the (singular) noun sense is preferred to the (singular)
+ verb sense.
+
+ Hence ``plural("knife")`` will return "knives" ("knife" having been treated
+ as a singular noun), whereas ``plural("knifes")`` will return "knife"
+ ("knifes" having been treated as a 3rd person singular verb).
+
+ The inherent ambiguity of such cases suggests that,
+ where the part of speech is known, ``plural_noun``, ``plural_verb``, and
+ ``plural_adj`` should be used in preference to ``plural``.
+
+
+``singular_noun(word, count=None)``
+
+ The method ``singular_noun()`` takes a *plural* English noun or
+ pronoun and returns its singular. Pronouns in the nominative ("we" ->
+ "I") and accusative ("us" -> "me") cases are handled, as are
+ possessive pronouns ("ours" -> "mine"). When third person
+ singular pronouns are returned they take the neuter gender by default
+ ("they" -> "it"), not ("they"-> "she") nor ("they" -> "he"). This can be
+ changed with ``gender()``.
+
+Note that all these methods ignore any whitespace surrounding the
+word being inflected, but preserve that whitespace when the result is
+returned. For example, ``plural(" cat  ")`` returns " cats  ".
+
+
+``gender(genderletter)``
+
+ The third person plural pronoun takes the same form for the female, male and
+ neuter (e.g. "they"). The singular however, depends upon gender (e.g. "she",
+ "he", "it" and "they" -- "they" being the gender neutral form.) By default
+ ``singular_noun`` returns the neuter form, however, the gender can be selected with
+ the ``gender`` method. Pass the first letter of the gender to
+ ``gender`` to return the f(eminine), m(asculine), n(euter) or t(hey)
+ form of the singular. e.g.
+ gender('f') followed by singular_noun('themselves') returns 'herself'.
+
+Numbered plurals
+----------------
+
+The ``plural...`` methods return only the inflected word, not the count that
+was used to inflect it. Thus, in order to produce "I saw 3 ducks", it
+is necessary to use:
+
+.. code-block:: python
+
+    print("I saw", N, p.plural_noun(animal, N))
+
+Since the usual purpose of producing a plural is to make it agree with
+a preceding count, inflect.py provides a method
+(``no(word, count)``) which, given a word and a(n optional) count, returns the
+count followed by the correctly inflected word. Hence the previous
+example can be rewritten:
+
+.. code-block:: python
+
+    print("I saw ", p.no(animal, N))
+
+In addition, if the count is zero (or some other term which implies
+zero, such as ``"zero"``, ``"nil"``, etc.) the count is replaced by the
+word "no". Hence, if ``N`` had the value zero, the previous example
+would print (the somewhat more elegant)::
+
+    I saw no animals
+
+rather than::
+
+    I saw 0 animals
+
+Note that the name of the method is a pun: the method
+returns either a number (a *No.*) or a ``"no"``, in front of the
+inflected word.
+
+
+Reducing the number of counts required
+--------------------------------------
+
+In some contexts, the need to supply an explicit count to the various
+``plural...`` methods makes for tiresome repetition. For example:
+
+.. code-block:: python
+
+    print(
+        plural_adj("This", errors),
+        plural_noun(" error", errors),
+        plural_verb(" was", errors),
+        " fatal.",
+    )
+
+inflect.py therefore provides a method
+(``num(count=None, show=None)``) which may be used to set a persistent "default number"
+value. If such a value is set, it is subsequently used whenever an
+optional second "number" argument is omitted. The default value thus set
+can subsequently be removed by calling ``num()`` with no arguments.
+Hence we could rewrite the previous example:
+
+.. code-block:: python
+
+    p.num(errors)
+    print(p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal.")
+    p.num()
+
+Normally, ``num()`` returns its first argument, so that it may also
+be "inlined" in contexts like:
+
+.. code-block:: python
+
+    print(p.num(errors), p.plural_noun(" error"), p.plural_verb(" was"), " detected.")
+    if severity > 1:
+        print(
+            p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal."
+        )
+
+However, in certain contexts (see `INTERPOLATING INFLECTIONS IN STRINGS`)
+it is preferable that ``num()`` return an empty string. Hence ``num()``
+provides an optional second argument. If that argument is supplied (that is, if
+it is defined) and evaluates to false, ``num`` returns an empty string
+instead of its first argument. For example:
+
+.. code-block:: python
+
+    print(p.num(errors, 0), p.no("error"), p.plural_verb(" was"), " detected.")
+    if severity > 1:
+        print(
+            p.plural_adj("This"), p.plural_noun(" error"), p.plural_verb(" was"), "fatal."
+        )
+
+
+
+Number-insensitive equality
+---------------------------
+
+inflect.py also provides a solution to the problem
+of comparing words of differing plurality through the methods
+``compare(word1, word2)``, ``compare_nouns(word1, word2)``,
+``compare_verbs(word1, word2)``, and ``compare_adjs(word1, word2)``.
+Each  of these methods takes two strings, and  compares them
+using the corresponding plural-inflection method (``plural()``, ``plural_noun()``,
+``plural_verb()``, and ``plural_adj()`` respectively).
+
+The comparison returns true if:
+
+- the strings are equal, or
+- one string is equal to a plural form of the other, or
+- the strings are two different plural forms of the one word.
+
+
+Hence all of the following return true:
+
+.. code-block:: python
+
+    p.compare("index", "index")  # RETURNS "eq"
+    p.compare("index", "indexes")  # RETURNS "s:p"
+    p.compare("index", "indices")  # RETURNS "s:p"
+    p.compare("indexes", "index")  # RETURNS "p:s"
+    p.compare("indices", "index")  # RETURNS "p:s"
+    p.compare("indices", "indexes")  # RETURNS "p:p"
+    p.compare("indexes", "indices")  # RETURNS "p:p"
+    p.compare("indices", "indices")  # RETURNS "eq"
+
+As indicated by the comments in the previous example, the actual value
+returned by the various ``compare`` methods encodes which of the
+three equality rules succeeded: "eq" is returned if the strings were
+identical, "s:p" if the strings were singular and plural respectively,
+"p:s" for plural and singular, and "p:p" for two distinct plurals.
+Inequality is indicated by returning an empty string.
+
+It should be noted that two distinct singular words which happen to take
+the same plural form are *not* considered equal, nor are cases where
+one (singular) word's plural is the other (plural) word's singular.
+Hence all of the following return false:
+
+.. code-block:: python
+
+    p.compare("base", "basis")  # ALTHOUGH BOTH -> "bases"
+    p.compare("syrinx", "syringe")  # ALTHOUGH BOTH -> "syringes"
+    p.compare("she", "he")  # ALTHOUGH BOTH -> "they"
+
+    p.compare("opus", "operas")  # ALTHOUGH "opus" -> "opera" -> "operas"
+    p.compare("taxi", "taxes")  # ALTHOUGH "taxi" -> "taxis" -> "taxes"
+
+Note too that, although the comparison is "number-insensitive" it is *not*
+case-insensitive (that is, ``plural("time","Times")`` returns false. To obtain
+both number and case insensitivity, use the ``lower()`` method on both strings
+(that is, ``plural("time".lower(), "Times".lower())`` returns true).
+
+Related Functionality
+=====================
+
+Shout out to these libraries that provide related functionality:
+
+* `WordSet `_
+  parses identifiers like variable names into sets of words suitable for re-assembling
+  in another form.
+
+* `word2number `_ converts words to
+  a number.
+
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..73ff576be5f4bf4cc1caa75633e475150b69cf2f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/RECORD
@@ -0,0 +1,13 @@
+inflect-7.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+inflect-7.3.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+inflect-7.3.1.dist-info/METADATA,sha256=ZgMNY0WAZRs-U8wZiV2SMfjSKqBrMngXyDMs_CAwMwg,21079
+inflect-7.3.1.dist-info/RECORD,,
+inflect-7.3.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91
+inflect-7.3.1.dist-info/top_level.txt,sha256=m52ujdp10CqT6jh1XQxZT6kEntcnv-7Tl7UiGNTzWZA,8
+inflect/__init__.py,sha256=Jxy1HJXZiZ85kHeLAhkmvz6EMTdFqBe-duvt34R6IOc,103796
+inflect/__pycache__/__init__.cpython-312.pyc,,
+inflect/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+inflect/compat/__pycache__/__init__.cpython-312.pyc,,
+inflect/compat/__pycache__/py38.cpython-312.pyc,,
+inflect/compat/py38.py,sha256=oObVfVnWX9_OpnOuEJn1mFbJxVhwyR5epbiTNXDDaso,160
+inflect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..564c6724e4bdf48d3dc10e804a73f100414c6533
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (70.2.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0fd75fab3e9e94881f61ee5eb66aef862e637a36
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect-7.3.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+inflect
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3eec27f4c67f24db167393895a6eaf0a9aa16d35
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/__init__.py
@@ -0,0 +1,3986 @@
+"""
+inflect: english language inflection
+ - correctly generate plurals, ordinals, indefinite articles
+ - convert numbers to words
+
+Copyright (C) 2010 Paul Dyson
+
+Based upon the Perl module
+`Lingua::EN::Inflect `_.
+
+methods:
+    classical inflect
+    plural plural_noun plural_verb plural_adj singular_noun no num a an
+    compare compare_nouns compare_verbs compare_adjs
+    present_participle
+    ordinal
+    number_to_words
+    join
+    defnoun defverb defadj defa defan
+
+INFLECTIONS:
+    classical inflect
+    plural plural_noun plural_verb plural_adj singular_noun compare
+    no num a an present_participle
+
+PLURALS:
+    classical inflect
+    plural plural_noun plural_verb plural_adj singular_noun no num
+    compare compare_nouns compare_verbs compare_adjs
+
+COMPARISONS:
+    classical
+    compare compare_nouns compare_verbs compare_adjs
+
+ARTICLES:
+    classical inflect num a an
+
+NUMERICAL:
+    ordinal number_to_words
+
+USER_DEFINED:
+    defnoun defverb defadj defa defan
+
+Exceptions:
+ UnknownClassicalModeError
+ BadNumValueError
+ BadChunkingOptionError
+ NumOutOfRangeError
+ BadUserDefinedPatternError
+ BadRcFileError
+ BadGenderError
+
+"""
+
+from __future__ import annotations
+
+import ast
+import collections
+import contextlib
+import functools
+import itertools
+import re
+from numbers import Number
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Callable,
+    Dict,
+    Iterable,
+    List,
+    Literal,
+    Match,
+    Optional,
+    Sequence,
+    Tuple,
+    Union,
+    cast,
+)
+
+from more_itertools import windowed_complete
+from typeguard import typechecked
+
+from .compat.py38 import Annotated
+
+
+class UnknownClassicalModeError(Exception):
+    pass
+
+
+class BadNumValueError(Exception):
+    pass
+
+
+class BadChunkingOptionError(Exception):
+    pass
+
+
+class NumOutOfRangeError(Exception):
+    pass
+
+
+class BadUserDefinedPatternError(Exception):
+    pass
+
+
+class BadRcFileError(Exception):
+    pass
+
+
+class BadGenderError(Exception):
+    pass
+
+
+def enclose(s: str) -> str:
+    return f"(?:{s})"
+
+
+def joinstem(cutpoint: Optional[int] = 0, words: Optional[Iterable[str]] = None) -> str:
+    """
+    Join stem of each word in words into a string for regex.
+
+    Each word is truncated at cutpoint.
+
+    Cutpoint is usually negative indicating the number of letters to remove
+    from the end of each word.
+
+    >>> joinstem(-2, ["ephemeris", "iris", ".*itis"])
+    '(?:ephemer|ir|.*it)'
+
+    >>> joinstem(None, ["ephemeris"])
+    '(?:ephemeris)'
+
+    >>> joinstem(5, None)
+    '(?:)'
+    """
+    return enclose("|".join(w[:cutpoint] for w in words or []))
+
+
+def bysize(words: Iterable[str]) -> Dict[int, set]:
+    """
+    From a list of words, return a dict of sets sorted by word length.
+
+    >>> words = ['ant', 'cat', 'dog', 'pig', 'frog', 'goat', 'horse', 'elephant']
+    >>> ret = bysize(words)
+    >>> sorted(ret[3])
+    ['ant', 'cat', 'dog', 'pig']
+    >>> ret[5]
+    {'horse'}
+    """
+    res: Dict[int, set] = collections.defaultdict(set)
+    for w in words:
+        res[len(w)].add(w)
+    return res
+
+
+def make_pl_si_lists(
+    lst: Iterable[str],
+    plending: str,
+    siendingsize: Optional[int],
+    dojoinstem: bool = True,
+):
+    """
+    given a list of singular words: lst
+
+    an ending to append to make the plural: plending
+
+    the number of characters to remove from the singular
+    before appending plending: siendingsize
+
+    a flag whether to create a joinstem: dojoinstem
+
+    return:
+    a list of pluralised words: si_list (called si because this is what you need to
+    look for to make the singular)
+
+    the pluralised words as a dict of sets sorted by word length: si_bysize
+    the singular words as a dict of sets sorted by word length: pl_bysize
+    if dojoinstem is True: a regular expression that matches any of the stems: stem
+    """
+    if siendingsize is not None:
+        siendingsize = -siendingsize
+    si_list = [w[:siendingsize] + plending for w in lst]
+    pl_bysize = bysize(lst)
+    si_bysize = bysize(si_list)
+    if dojoinstem:
+        stem = joinstem(siendingsize, lst)
+        return si_list, si_bysize, pl_bysize, stem
+    else:
+        return si_list, si_bysize, pl_bysize
+
+
+# 1. PLURALS
+
+pl_sb_irregular_s = {
+    "corpus": "corpuses|corpora",
+    "opus": "opuses|opera",
+    "genus": "genera",
+    "mythos": "mythoi",
+    "penis": "penises|penes",
+    "testis": "testes",
+    "atlas": "atlases|atlantes",
+    "yes": "yeses",
+}
+
+pl_sb_irregular = {
+    "child": "children",
+    "chili": "chilis|chilies",
+    "brother": "brothers|brethren",
+    "infinity": "infinities|infinity",
+    "loaf": "loaves",
+    "lore": "lores|lore",
+    "hoof": "hoofs|hooves",
+    "beef": "beefs|beeves",
+    "thief": "thiefs|thieves",
+    "money": "monies",
+    "mongoose": "mongooses",
+    "ox": "oxen",
+    "cow": "cows|kine",
+    "graffito": "graffiti",
+    "octopus": "octopuses|octopodes",
+    "genie": "genies|genii",
+    "ganglion": "ganglions|ganglia",
+    "trilby": "trilbys",
+    "turf": "turfs|turves",
+    "numen": "numina",
+    "atman": "atmas",
+    "occiput": "occiputs|occipita",
+    "sabretooth": "sabretooths",
+    "sabertooth": "sabertooths",
+    "lowlife": "lowlifes",
+    "flatfoot": "flatfoots",
+    "tenderfoot": "tenderfoots",
+    "romany": "romanies",
+    "jerry": "jerries",
+    "mary": "maries",
+    "talouse": "talouses",
+    "rom": "roma",
+    "carmen": "carmina",
+}
+
+pl_sb_irregular.update(pl_sb_irregular_s)
+# pl_sb_irregular_keys = enclose('|'.join(pl_sb_irregular.keys()))
+
+pl_sb_irregular_caps = {
+    "Romany": "Romanies",
+    "Jerry": "Jerrys",
+    "Mary": "Marys",
+    "Rom": "Roma",
+}
+
+pl_sb_irregular_compound = {"prima donna": "prima donnas|prime donne"}
+
+si_sb_irregular = {v: k for (k, v) in pl_sb_irregular.items()}
+for k in list(si_sb_irregular):
+    if "|" in k:
+        k1, k2 = k.split("|")
+        si_sb_irregular[k1] = si_sb_irregular[k2] = si_sb_irregular[k]
+        del si_sb_irregular[k]
+si_sb_irregular_caps = {v: k for (k, v) in pl_sb_irregular_caps.items()}
+si_sb_irregular_compound = {v: k for (k, v) in pl_sb_irregular_compound.items()}
+for k in list(si_sb_irregular_compound):
+    if "|" in k:
+        k1, k2 = k.split("|")
+        si_sb_irregular_compound[k1] = si_sb_irregular_compound[k2] = (
+            si_sb_irregular_compound[k]
+        )
+        del si_sb_irregular_compound[k]
+
+# si_sb_irregular_keys = enclose('|'.join(si_sb_irregular.keys()))
+
+# Z's that don't double
+
+pl_sb_z_zes_list = ("quartz", "topaz")
+pl_sb_z_zes_bysize = bysize(pl_sb_z_zes_list)
+
+pl_sb_ze_zes_list = ("snooze",)
+pl_sb_ze_zes_bysize = bysize(pl_sb_ze_zes_list)
+
+
+# CLASSICAL "..is" -> "..ides"
+
+pl_sb_C_is_ides_complete = [
+    # GENERAL WORDS...
+    "ephemeris",
+    "iris",
+    "clitoris",
+    "chrysalis",
+    "epididymis",
+]
+
+pl_sb_C_is_ides_endings = [
+    # INFLAMATIONS...
+    "itis"
+]
+
+pl_sb_C_is_ides = joinstem(
+    -2, pl_sb_C_is_ides_complete + [f".*{w}" for w in pl_sb_C_is_ides_endings]
+)
+
+pl_sb_C_is_ides_list = pl_sb_C_is_ides_complete + pl_sb_C_is_ides_endings
+
+(
+    si_sb_C_is_ides_list,
+    si_sb_C_is_ides_bysize,
+    pl_sb_C_is_ides_bysize,
+) = make_pl_si_lists(pl_sb_C_is_ides_list, "ides", 2, dojoinstem=False)
+
+
+# CLASSICAL "..a" -> "..ata"
+
+pl_sb_C_a_ata_list = (
+    "anathema",
+    "bema",
+    "carcinoma",
+    "charisma",
+    "diploma",
+    "dogma",
+    "drama",
+    "edema",
+    "enema",
+    "enigma",
+    "lemma",
+    "lymphoma",
+    "magma",
+    "melisma",
+    "miasma",
+    "oedema",
+    "sarcoma",
+    "schema",
+    "soma",
+    "stigma",
+    "stoma",
+    "trauma",
+    "gumma",
+    "pragma",
+)
+
+(
+    si_sb_C_a_ata_list,
+    si_sb_C_a_ata_bysize,
+    pl_sb_C_a_ata_bysize,
+    pl_sb_C_a_ata,
+) = make_pl_si_lists(pl_sb_C_a_ata_list, "ata", 1)
+
+# UNCONDITIONAL "..a" -> "..ae"
+
+pl_sb_U_a_ae_list = (
+    "alumna",
+    "alga",
+    "vertebra",
+    "persona",
+    "vita",
+)
+(
+    si_sb_U_a_ae_list,
+    si_sb_U_a_ae_bysize,
+    pl_sb_U_a_ae_bysize,
+    pl_sb_U_a_ae,
+) = make_pl_si_lists(pl_sb_U_a_ae_list, "e", None)
+
+# CLASSICAL "..a" -> "..ae"
+
+pl_sb_C_a_ae_list = (
+    "amoeba",
+    "antenna",
+    "formula",
+    "hyperbola",
+    "medusa",
+    "nebula",
+    "parabola",
+    "abscissa",
+    "hydra",
+    "nova",
+    "lacuna",
+    "aurora",
+    "umbra",
+    "flora",
+    "fauna",
+)
+(
+    si_sb_C_a_ae_list,
+    si_sb_C_a_ae_bysize,
+    pl_sb_C_a_ae_bysize,
+    pl_sb_C_a_ae,
+) = make_pl_si_lists(pl_sb_C_a_ae_list, "e", None)
+
+
+# CLASSICAL "..en" -> "..ina"
+
+pl_sb_C_en_ina_list = ("stamen", "foramen", "lumen")
+
+(
+    si_sb_C_en_ina_list,
+    si_sb_C_en_ina_bysize,
+    pl_sb_C_en_ina_bysize,
+    pl_sb_C_en_ina,
+) = make_pl_si_lists(pl_sb_C_en_ina_list, "ina", 2)
+
+
+# UNCONDITIONAL "..um" -> "..a"
+
+pl_sb_U_um_a_list = (
+    "bacterium",
+    "agendum",
+    "desideratum",
+    "erratum",
+    "stratum",
+    "datum",
+    "ovum",
+    "extremum",
+    "candelabrum",
+)
+(
+    si_sb_U_um_a_list,
+    si_sb_U_um_a_bysize,
+    pl_sb_U_um_a_bysize,
+    pl_sb_U_um_a,
+) = make_pl_si_lists(pl_sb_U_um_a_list, "a", 2)
+
+# CLASSICAL "..um" -> "..a"
+
+pl_sb_C_um_a_list = (
+    "maximum",
+    "minimum",
+    "momentum",
+    "optimum",
+    "quantum",
+    "cranium",
+    "curriculum",
+    "dictum",
+    "phylum",
+    "aquarium",
+    "compendium",
+    "emporium",
+    "encomium",
+    "gymnasium",
+    "honorarium",
+    "interregnum",
+    "lustrum",
+    "memorandum",
+    "millennium",
+    "rostrum",
+    "spectrum",
+    "speculum",
+    "stadium",
+    "trapezium",
+    "ultimatum",
+    "medium",
+    "vacuum",
+    "velum",
+    "consortium",
+    "arboretum",
+)
+
+(
+    si_sb_C_um_a_list,
+    si_sb_C_um_a_bysize,
+    pl_sb_C_um_a_bysize,
+    pl_sb_C_um_a,
+) = make_pl_si_lists(pl_sb_C_um_a_list, "a", 2)
+
+
+# UNCONDITIONAL "..us" -> "i"
+
+pl_sb_U_us_i_list = (
+    "alumnus",
+    "alveolus",
+    "bacillus",
+    "bronchus",
+    "locus",
+    "nucleus",
+    "stimulus",
+    "meniscus",
+    "sarcophagus",
+)
+(
+    si_sb_U_us_i_list,
+    si_sb_U_us_i_bysize,
+    pl_sb_U_us_i_bysize,
+    pl_sb_U_us_i,
+) = make_pl_si_lists(pl_sb_U_us_i_list, "i", 2)
+
+# CLASSICAL "..us" -> "..i"
+
+pl_sb_C_us_i_list = (
+    "focus",
+    "radius",
+    "genius",
+    "incubus",
+    "succubus",
+    "nimbus",
+    "fungus",
+    "nucleolus",
+    "stylus",
+    "torus",
+    "umbilicus",
+    "uterus",
+    "hippopotamus",
+    "cactus",
+)
+
+(
+    si_sb_C_us_i_list,
+    si_sb_C_us_i_bysize,
+    pl_sb_C_us_i_bysize,
+    pl_sb_C_us_i,
+) = make_pl_si_lists(pl_sb_C_us_i_list, "i", 2)
+
+
+# CLASSICAL "..us" -> "..us"  (ASSIMILATED 4TH DECLENSION LATIN NOUNS)
+
+pl_sb_C_us_us = (
+    "status",
+    "apparatus",
+    "prospectus",
+    "sinus",
+    "hiatus",
+    "impetus",
+    "plexus",
+)
+pl_sb_C_us_us_bysize = bysize(pl_sb_C_us_us)
+
+# UNCONDITIONAL "..on" -> "a"
+
+pl_sb_U_on_a_list = (
+    "criterion",
+    "perihelion",
+    "aphelion",
+    "phenomenon",
+    "prolegomenon",
+    "noumenon",
+    "organon",
+    "asyndeton",
+    "hyperbaton",
+)
+(
+    si_sb_U_on_a_list,
+    si_sb_U_on_a_bysize,
+    pl_sb_U_on_a_bysize,
+    pl_sb_U_on_a,
+) = make_pl_si_lists(pl_sb_U_on_a_list, "a", 2)
+
+# CLASSICAL "..on" -> "..a"
+
+pl_sb_C_on_a_list = ("oxymoron",)
+
+(
+    si_sb_C_on_a_list,
+    si_sb_C_on_a_bysize,
+    pl_sb_C_on_a_bysize,
+    pl_sb_C_on_a,
+) = make_pl_si_lists(pl_sb_C_on_a_list, "a", 2)
+
+
+# CLASSICAL "..o" -> "..i"  (BUT NORMALLY -> "..os")
+
+pl_sb_C_o_i = [
+    "solo",
+    "soprano",
+    "basso",
+    "alto",
+    "contralto",
+    "tempo",
+    "piano",
+    "virtuoso",
+]  # list not tuple so can concat for pl_sb_U_o_os
+
+pl_sb_C_o_i_bysize = bysize(pl_sb_C_o_i)
+si_sb_C_o_i_bysize = bysize([f"{w[:-1]}i" for w in pl_sb_C_o_i])
+
+pl_sb_C_o_i_stems = joinstem(-1, pl_sb_C_o_i)
+
+# ALWAYS "..o" -> "..os"
+
+pl_sb_U_o_os_complete = {"ado", "ISO", "NATO", "NCO", "NGO", "oto"}
+si_sb_U_o_os_complete = {f"{w}s" for w in pl_sb_U_o_os_complete}
+
+
+pl_sb_U_o_os_endings = [
+    "aficionado",
+    "aggro",
+    "albino",
+    "allegro",
+    "ammo",
+    "Antananarivo",
+    "archipelago",
+    "armadillo",
+    "auto",
+    "avocado",
+    "Bamako",
+    "Barquisimeto",
+    "bimbo",
+    "bingo",
+    "Biro",
+    "bolero",
+    "Bolzano",
+    "bongo",
+    "Boto",
+    "burro",
+    "Cairo",
+    "canto",
+    "cappuccino",
+    "casino",
+    "cello",
+    "Chicago",
+    "Chimango",
+    "cilantro",
+    "cochito",
+    "coco",
+    "Colombo",
+    "Colorado",
+    "commando",
+    "concertino",
+    "contango",
+    "credo",
+    "crescendo",
+    "cyano",
+    "demo",
+    "ditto",
+    "Draco",
+    "dynamo",
+    "embryo",
+    "Esperanto",
+    "espresso",
+    "euro",
+    "falsetto",
+    "Faro",
+    "fiasco",
+    "Filipino",
+    "flamenco",
+    "furioso",
+    "generalissimo",
+    "Gestapo",
+    "ghetto",
+    "gigolo",
+    "gizmo",
+    "Greensboro",
+    "gringo",
+    "Guaiabero",
+    "guano",
+    "gumbo",
+    "gyro",
+    "hairdo",
+    "hippo",
+    "Idaho",
+    "impetigo",
+    "inferno",
+    "info",
+    "intermezzo",
+    "intertrigo",
+    "Iquico",
+    "jumbo",
+    "junto",
+    "Kakapo",
+    "kilo",
+    "Kinkimavo",
+    "Kokako",
+    "Kosovo",
+    "Lesotho",
+    "libero",
+    "libido",
+    "libretto",
+    "lido",
+    "Lilo",
+    "limbo",
+    "limo",
+    "lineno",
+    "lingo",
+    "lino",
+    "livedo",
+    "loco",
+    "logo",
+    "lumbago",
+    "macho",
+    "macro",
+    "mafioso",
+    "magneto",
+    "magnifico",
+    "Majuro",
+    "Malabo",
+    "manifesto",
+    "Maputo",
+    "Maracaibo",
+    "medico",
+    "memo",
+    "metro",
+    "Mexico",
+    "micro",
+    "Milano",
+    "Monaco",
+    "mono",
+    "Montenegro",
+    "Morocco",
+    "Muqdisho",
+    "myo",
+    "neutrino",
+    "Ningbo",
+    "octavo",
+    "oregano",
+    "Orinoco",
+    "Orlando",
+    "Oslo",
+    "panto",
+    "Paramaribo",
+    "Pardusco",
+    "pedalo",
+    "photo",
+    "pimento",
+    "pinto",
+    "pleco",
+    "Pluto",
+    "pogo",
+    "polo",
+    "poncho",
+    "Porto-Novo",
+    "Porto",
+    "pro",
+    "psycho",
+    "pueblo",
+    "quarto",
+    "Quito",
+    "repo",
+    "rhino",
+    "risotto",
+    "rococo",
+    "rondo",
+    "Sacramento",
+    "saddo",
+    "sago",
+    "salvo",
+    "Santiago",
+    "Sapporo",
+    "Sarajevo",
+    "scherzando",
+    "scherzo",
+    "silo",
+    "sirocco",
+    "sombrero",
+    "staccato",
+    "sterno",
+    "stucco",
+    "stylo",
+    "sumo",
+    "Taiko",
+    "techno",
+    "terrazzo",
+    "testudo",
+    "timpano",
+    "tiro",
+    "tobacco",
+    "Togo",
+    "Tokyo",
+    "torero",
+    "Torino",
+    "Toronto",
+    "torso",
+    "tremolo",
+    "typo",
+    "tyro",
+    "ufo",
+    "UNESCO",
+    "vaquero",
+    "vermicello",
+    "verso",
+    "vibrato",
+    "violoncello",
+    "Virgo",
+    "weirdo",
+    "WHO",
+    "WTO",
+    "Yamoussoukro",
+    "yo-yo",
+    "zero",
+    "Zibo",
+] + pl_sb_C_o_i
+
+pl_sb_U_o_os_bysize = bysize(pl_sb_U_o_os_endings)
+si_sb_U_o_os_bysize = bysize([f"{w}s" for w in pl_sb_U_o_os_endings])
+
+
+# UNCONDITIONAL "..ch" -> "..chs"
+
+pl_sb_U_ch_chs_list = ("czech", "eunuch", "stomach")
+
+(
+    si_sb_U_ch_chs_list,
+    si_sb_U_ch_chs_bysize,
+    pl_sb_U_ch_chs_bysize,
+    pl_sb_U_ch_chs,
+) = make_pl_si_lists(pl_sb_U_ch_chs_list, "s", None)
+
+
+# UNCONDITIONAL "..[ei]x" -> "..ices"
+
+pl_sb_U_ex_ices_list = ("codex", "murex", "silex")
+(
+    si_sb_U_ex_ices_list,
+    si_sb_U_ex_ices_bysize,
+    pl_sb_U_ex_ices_bysize,
+    pl_sb_U_ex_ices,
+) = make_pl_si_lists(pl_sb_U_ex_ices_list, "ices", 2)
+
+pl_sb_U_ix_ices_list = ("radix", "helix")
+(
+    si_sb_U_ix_ices_list,
+    si_sb_U_ix_ices_bysize,
+    pl_sb_U_ix_ices_bysize,
+    pl_sb_U_ix_ices,
+) = make_pl_si_lists(pl_sb_U_ix_ices_list, "ices", 2)
+
+# CLASSICAL "..[ei]x" -> "..ices"
+
+pl_sb_C_ex_ices_list = (
+    "vortex",
+    "vertex",
+    "cortex",
+    "latex",
+    "pontifex",
+    "apex",
+    "index",
+    "simplex",
+)
+
+(
+    si_sb_C_ex_ices_list,
+    si_sb_C_ex_ices_bysize,
+    pl_sb_C_ex_ices_bysize,
+    pl_sb_C_ex_ices,
+) = make_pl_si_lists(pl_sb_C_ex_ices_list, "ices", 2)
+
+
+pl_sb_C_ix_ices_list = ("appendix",)
+
+(
+    si_sb_C_ix_ices_list,
+    si_sb_C_ix_ices_bysize,
+    pl_sb_C_ix_ices_bysize,
+    pl_sb_C_ix_ices,
+) = make_pl_si_lists(pl_sb_C_ix_ices_list, "ices", 2)
+
+
+# ARABIC: ".." -> "..i"
+
+pl_sb_C_i_list = ("afrit", "afreet", "efreet")
+
+(si_sb_C_i_list, si_sb_C_i_bysize, pl_sb_C_i_bysize, pl_sb_C_i) = make_pl_si_lists(
+    pl_sb_C_i_list, "i", None
+)
+
+
+# HEBREW: ".." -> "..im"
+
+pl_sb_C_im_list = ("goy", "seraph", "cherub")
+
+(si_sb_C_im_list, si_sb_C_im_bysize, pl_sb_C_im_bysize, pl_sb_C_im) = make_pl_si_lists(
+    pl_sb_C_im_list, "im", None
+)
+
+
+# UNCONDITIONAL "..man" -> "..mans"
+
+pl_sb_U_man_mans_list = """
+    ataman caiman cayman ceriman
+    desman dolman farman harman hetman
+    human leman ottoman shaman talisman
+""".split()
+pl_sb_U_man_mans_caps_list = """
+    Alabaman Bahaman Burman German
+    Hiroshiman Liman Nakayaman Norman Oklahoman
+    Panaman Roman Selman Sonaman Tacoman Yakiman
+    Yokohaman Yuman
+""".split()
+
+(
+    si_sb_U_man_mans_list,
+    si_sb_U_man_mans_bysize,
+    pl_sb_U_man_mans_bysize,
+) = make_pl_si_lists(pl_sb_U_man_mans_list, "s", None, dojoinstem=False)
+(
+    si_sb_U_man_mans_caps_list,
+    si_sb_U_man_mans_caps_bysize,
+    pl_sb_U_man_mans_caps_bysize,
+) = make_pl_si_lists(pl_sb_U_man_mans_caps_list, "s", None, dojoinstem=False)
+
+# UNCONDITIONAL "..louse" -> "..lice"
+pl_sb_U_louse_lice_list = ("booklouse", "grapelouse", "louse", "woodlouse")
+
+(
+    si_sb_U_louse_lice_list,
+    si_sb_U_louse_lice_bysize,
+    pl_sb_U_louse_lice_bysize,
+) = make_pl_si_lists(pl_sb_U_louse_lice_list, "lice", 5, dojoinstem=False)
+
+pl_sb_uninflected_s_complete = [
+    # PAIRS OR GROUPS SUBSUMED TO A SINGULAR...
+    "breeches",
+    "britches",
+    "pajamas",
+    "pyjamas",
+    "clippers",
+    "gallows",
+    "hijinks",
+    "headquarters",
+    "pliers",
+    "scissors",
+    "testes",
+    "herpes",
+    "pincers",
+    "shears",
+    "proceedings",
+    "trousers",
+    # UNASSIMILATED LATIN 4th DECLENSION
+    "cantus",
+    "coitus",
+    "nexus",
+    # RECENT IMPORTS...
+    "contretemps",
+    "corps",
+    "debris",
+    "siemens",
+    # DISEASES
+    "mumps",
+    # MISCELLANEOUS OTHERS...
+    "diabetes",
+    "jackanapes",
+    "series",
+    "species",
+    "subspecies",
+    "rabies",
+    "chassis",
+    "innings",
+    "news",
+    "mews",
+    "haggis",
+]
+
+pl_sb_uninflected_s_endings = [
+    # RECENT IMPORTS...
+    "ois",
+    # DISEASES
+    "measles",
+]
+
+pl_sb_uninflected_s = pl_sb_uninflected_s_complete + [
+    f".*{w}" for w in pl_sb_uninflected_s_endings
+]
+
+pl_sb_uninflected_herd = (
+    # DON'T INFLECT IN CLASSICAL MODE, OTHERWISE NORMAL INFLECTION
+    "wildebeest",
+    "swine",
+    "eland",
+    "bison",
+    "buffalo",
+    "cattle",
+    "elk",
+    "rhinoceros",
+    "zucchini",
+    "caribou",
+    "dace",
+    "grouse",
+    "guinea fowl",
+    "guinea-fowl",
+    "haddock",
+    "hake",
+    "halibut",
+    "herring",
+    "mackerel",
+    "pickerel",
+    "pike",
+    "roe",
+    "seed",
+    "shad",
+    "snipe",
+    "teal",
+    "turbot",
+    "water fowl",
+    "water-fowl",
+)
+
+pl_sb_uninflected_complete = [
+    # SOME FISH AND HERD ANIMALS
+    "tuna",
+    "salmon",
+    "mackerel",
+    "trout",
+    "bream",
+    "sea-bass",
+    "sea bass",
+    "carp",
+    "cod",
+    "flounder",
+    "whiting",
+    "moose",
+    # OTHER ODDITIES
+    "graffiti",
+    "djinn",
+    "samuri",
+    "offspring",
+    "pence",
+    "quid",
+    "hertz",
+] + pl_sb_uninflected_s_complete
+# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE)
+
+pl_sb_uninflected_caps = [
+    # ALL NATIONALS ENDING IN -ese
+    "Portuguese",
+    "Amoyese",
+    "Borghese",
+    "Congoese",
+    "Faroese",
+    "Foochowese",
+    "Genevese",
+    "Genoese",
+    "Gilbertese",
+    "Hottentotese",
+    "Kiplingese",
+    "Kongoese",
+    "Lucchese",
+    "Maltese",
+    "Nankingese",
+    "Niasese",
+    "Pekingese",
+    "Piedmontese",
+    "Pistoiese",
+    "Sarawakese",
+    "Shavese",
+    "Vermontese",
+    "Wenchowese",
+    "Yengeese",
+]
+
+
+pl_sb_uninflected_endings = [
+    # UNCOUNTABLE NOUNS
+    "butter",
+    "cash",
+    "furniture",
+    "information",
+    # SOME FISH AND HERD ANIMALS
+    "fish",
+    "deer",
+    "sheep",
+    # ALL NATIONALS ENDING IN -ese
+    "nese",
+    "rese",
+    "lese",
+    "mese",
+    # DISEASES
+    "pox",
+    # OTHER ODDITIES
+    "craft",
+] + pl_sb_uninflected_s_endings
+# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE)
+
+
+pl_sb_uninflected_bysize = bysize(pl_sb_uninflected_endings)
+
+
+# SINGULAR WORDS ENDING IN ...s (ALL INFLECT WITH ...es)
+
+pl_sb_singular_s_complete = [
+    "acropolis",
+    "aegis",
+    "alias",
+    "asbestos",
+    "bathos",
+    "bias",
+    "bronchitis",
+    "bursitis",
+    "caddis",
+    "cannabis",
+    "canvas",
+    "chaos",
+    "cosmos",
+    "dais",
+    "digitalis",
+    "epidermis",
+    "ethos",
+    "eyas",
+    "gas",
+    "glottis",
+    "hubris",
+    "ibis",
+    "lens",
+    "mantis",
+    "marquis",
+    "metropolis",
+    "pathos",
+    "pelvis",
+    "polis",
+    "rhinoceros",
+    "sassafras",
+    "trellis",
+] + pl_sb_C_is_ides_complete
+
+
+pl_sb_singular_s_endings = ["ss", "us"] + pl_sb_C_is_ides_endings
+
+pl_sb_singular_s_bysize = bysize(pl_sb_singular_s_endings)
+
+si_sb_singular_s_complete = [f"{w}es" for w in pl_sb_singular_s_complete]
+si_sb_singular_s_endings = [f"{w}es" for w in pl_sb_singular_s_endings]
+si_sb_singular_s_bysize = bysize(si_sb_singular_s_endings)
+
+pl_sb_singular_s_es = ["[A-Z].*es"]
+
+pl_sb_singular_s = enclose(
+    "|".join(
+        pl_sb_singular_s_complete
+        + [f".*{w}" for w in pl_sb_singular_s_endings]
+        + pl_sb_singular_s_es
+    )
+)
+
+
+# PLURALS ENDING IN uses -> use
+
+
+si_sb_ois_oi_case = ("Bolshois", "Hanois")
+
+si_sb_uses_use_case = ("Betelgeuses", "Duses", "Meuses", "Syracuses", "Toulouses")
+
+si_sb_uses_use = (
+    "abuses",
+    "applauses",
+    "blouses",
+    "carouses",
+    "causes",
+    "chartreuses",
+    "clauses",
+    "contuses",
+    "douses",
+    "excuses",
+    "fuses",
+    "grouses",
+    "hypotenuses",
+    "masseuses",
+    "menopauses",
+    "misuses",
+    "muses",
+    "overuses",
+    "pauses",
+    "peruses",
+    "profuses",
+    "recluses",
+    "reuses",
+    "ruses",
+    "souses",
+    "spouses",
+    "suffuses",
+    "transfuses",
+    "uses",
+)
+
+si_sb_ies_ie_case = (
+    "Addies",
+    "Aggies",
+    "Allies",
+    "Amies",
+    "Angies",
+    "Annies",
+    "Annmaries",
+    "Archies",
+    "Arties",
+    "Aussies",
+    "Barbies",
+    "Barries",
+    "Basies",
+    "Bennies",
+    "Bernies",
+    "Berties",
+    "Bessies",
+    "Betties",
+    "Billies",
+    "Blondies",
+    "Bobbies",
+    "Bonnies",
+    "Bowies",
+    "Brandies",
+    "Bries",
+    "Brownies",
+    "Callies",
+    "Carnegies",
+    "Carries",
+    "Cassies",
+    "Charlies",
+    "Cheries",
+    "Christies",
+    "Connies",
+    "Curies",
+    "Dannies",
+    "Debbies",
+    "Dixies",
+    "Dollies",
+    "Donnies",
+    "Drambuies",
+    "Eddies",
+    "Effies",
+    "Ellies",
+    "Elsies",
+    "Eries",
+    "Ernies",
+    "Essies",
+    "Eugenies",
+    "Fannies",
+    "Flossies",
+    "Frankies",
+    "Freddies",
+    "Gillespies",
+    "Goldies",
+    "Gracies",
+    "Guthries",
+    "Hallies",
+    "Hatties",
+    "Hetties",
+    "Hollies",
+    "Jackies",
+    "Jamies",
+    "Janies",
+    "Jannies",
+    "Jeanies",
+    "Jeannies",
+    "Jennies",
+    "Jessies",
+    "Jimmies",
+    "Jodies",
+    "Johnies",
+    "Johnnies",
+    "Josies",
+    "Julies",
+    "Kalgoorlies",
+    "Kathies",
+    "Katies",
+    "Kellies",
+    "Kewpies",
+    "Kristies",
+    "Laramies",
+    "Lassies",
+    "Lauries",
+    "Leslies",
+    "Lessies",
+    "Lillies",
+    "Lizzies",
+    "Lonnies",
+    "Lories",
+    "Lorries",
+    "Lotties",
+    "Louies",
+    "Mackenzies",
+    "Maggies",
+    "Maisies",
+    "Mamies",
+    "Marcies",
+    "Margies",
+    "Maries",
+    "Marjories",
+    "Matties",
+    "McKenzies",
+    "Melanies",
+    "Mickies",
+    "Millies",
+    "Minnies",
+    "Mollies",
+    "Mounties",
+    "Nannies",
+    "Natalies",
+    "Nellies",
+    "Netties",
+    "Ollies",
+    "Ozzies",
+    "Pearlies",
+    "Pottawatomies",
+    "Reggies",
+    "Richies",
+    "Rickies",
+    "Robbies",
+    "Ronnies",
+    "Rosalies",
+    "Rosemaries",
+    "Rosies",
+    "Roxies",
+    "Rushdies",
+    "Ruthies",
+    "Sadies",
+    "Sallies",
+    "Sammies",
+    "Scotties",
+    "Selassies",
+    "Sherries",
+    "Sophies",
+    "Stacies",
+    "Stefanies",
+    "Stephanies",
+    "Stevies",
+    "Susies",
+    "Sylvies",
+    "Tammies",
+    "Terries",
+    "Tessies",
+    "Tommies",
+    "Tracies",
+    "Trekkies",
+    "Valaries",
+    "Valeries",
+    "Valkyries",
+    "Vickies",
+    "Virgies",
+    "Willies",
+    "Winnies",
+    "Wylies",
+    "Yorkies",
+)
+
+si_sb_ies_ie = (
+    "aeries",
+    "baggies",
+    "belies",
+    "biggies",
+    "birdies",
+    "bogies",
+    "bonnies",
+    "boogies",
+    "bookies",
+    "bourgeoisies",
+    "brownies",
+    "budgies",
+    "caddies",
+    "calories",
+    "camaraderies",
+    "cockamamies",
+    "collies",
+    "cookies",
+    "coolies",
+    "cooties",
+    "coteries",
+    "crappies",
+    "curies",
+    "cutesies",
+    "dogies",
+    "eyries",
+    "floozies",
+    "footsies",
+    "freebies",
+    "genies",
+    "goalies",
+    "groupies",
+    "hies",
+    "jalousies",
+    "junkies",
+    "kiddies",
+    "laddies",
+    "lassies",
+    "lies",
+    "lingeries",
+    "magpies",
+    "menageries",
+    "mommies",
+    "movies",
+    "neckties",
+    "newbies",
+    "nighties",
+    "oldies",
+    "organdies",
+    "overlies",
+    "pies",
+    "pinkies",
+    "pixies",
+    "potpies",
+    "prairies",
+    "quickies",
+    "reveries",
+    "rookies",
+    "rotisseries",
+    "softies",
+    "sorties",
+    "species",
+    "stymies",
+    "sweeties",
+    "ties",
+    "underlies",
+    "unties",
+    "veggies",
+    "vies",
+    "yuppies",
+    "zombies",
+)
+
+
+si_sb_oes_oe_case = (
+    "Chloes",
+    "Crusoes",
+    "Defoes",
+    "Faeroes",
+    "Ivanhoes",
+    "Joes",
+    "McEnroes",
+    "Moes",
+    "Monroes",
+    "Noes",
+    "Poes",
+    "Roscoes",
+    "Tahoes",
+    "Tippecanoes",
+    "Zoes",
+)
+
+si_sb_oes_oe = (
+    "aloes",
+    "backhoes",
+    "canoes",
+    "does",
+    "floes",
+    "foes",
+    "hoes",
+    "mistletoes",
+    "oboes",
+    "pekoes",
+    "roes",
+    "sloes",
+    "throes",
+    "tiptoes",
+    "toes",
+    "woes",
+)
+
+si_sb_z_zes = ("quartzes", "topazes")
+
+si_sb_zzes_zz = ("buzzes", "fizzes", "frizzes", "razzes")
+
+si_sb_ches_che_case = (
+    "Andromaches",
+    "Apaches",
+    "Blanches",
+    "Comanches",
+    "Nietzsches",
+    "Porsches",
+    "Roches",
+)
+
+si_sb_ches_che = (
+    "aches",
+    "avalanches",
+    "backaches",
+    "bellyaches",
+    "caches",
+    "cloches",
+    "creches",
+    "douches",
+    "earaches",
+    "fiches",
+    "headaches",
+    "heartaches",
+    "microfiches",
+    "niches",
+    "pastiches",
+    "psyches",
+    "quiches",
+    "stomachaches",
+    "toothaches",
+    "tranches",
+)
+
+si_sb_xes_xe = ("annexes", "axes", "deluxes", "pickaxes")
+
+si_sb_sses_sse_case = ("Hesses", "Jesses", "Larousses", "Matisses")
+si_sb_sses_sse = (
+    "bouillabaisses",
+    "crevasses",
+    "demitasses",
+    "impasses",
+    "mousses",
+    "posses",
+)
+
+si_sb_ves_ve_case = (
+    # *[nwl]ives -> [nwl]live
+    "Clives",
+    "Palmolives",
+)
+si_sb_ves_ve = (
+    # *[^d]eaves -> eave
+    "interweaves",
+    "weaves",
+    # *[nwl]ives -> [nwl]live
+    "olives",
+    # *[eoa]lves -> [eoa]lve
+    "bivalves",
+    "dissolves",
+    "resolves",
+    "salves",
+    "twelves",
+    "valves",
+)
+
+
+plverb_special_s = enclose(
+    "|".join(
+        [pl_sb_singular_s]
+        + pl_sb_uninflected_s
+        + list(pl_sb_irregular_s)
+        + ["(.*[csx])is", "(.*)ceps", "[A-Z].*s"]
+    )
+)
+
+_pl_sb_postfix_adj_defn = (
+    ("general", enclose(r"(?!major|lieutenant|brigadier|adjutant|.*star)\S+")),
+    ("martial", enclose("court")),
+    ("force", enclose("pound")),
+)
+
+pl_sb_postfix_adj: Iterable[str] = (
+    enclose(val + f"(?=(?:-|\\s+){key})") for key, val in _pl_sb_postfix_adj_defn
+)
+
+pl_sb_postfix_adj_stems = f"({'|'.join(pl_sb_postfix_adj)})(.*)"
+
+
+# PLURAL WORDS ENDING IS es GO TO SINGULAR is
+
+si_sb_es_is = (
+    "amanuenses",
+    "amniocenteses",
+    "analyses",
+    "antitheses",
+    "apotheoses",
+    "arterioscleroses",
+    "atheroscleroses",
+    "axes",
+    # 'bases', # bases -> basis
+    "catalyses",
+    "catharses",
+    "chasses",
+    "cirrhoses",
+    "cocces",
+    "crises",
+    "diagnoses",
+    "dialyses",
+    "diereses",
+    "electrolyses",
+    "emphases",
+    "exegeses",
+    "geneses",
+    "halitoses",
+    "hydrolyses",
+    "hypnoses",
+    "hypotheses",
+    "hystereses",
+    "metamorphoses",
+    "metastases",
+    "misdiagnoses",
+    "mitoses",
+    "mononucleoses",
+    "narcoses",
+    "necroses",
+    "nemeses",
+    "neuroses",
+    "oases",
+    "osmoses",
+    "osteoporoses",
+    "paralyses",
+    "parentheses",
+    "parthenogeneses",
+    "periphrases",
+    "photosyntheses",
+    "probosces",
+    "prognoses",
+    "prophylaxes",
+    "prostheses",
+    "preces",
+    "psoriases",
+    "psychoanalyses",
+    "psychokineses",
+    "psychoses",
+    "scleroses",
+    "scolioses",
+    "sepses",
+    "silicoses",
+    "symbioses",
+    "synopses",
+    "syntheses",
+    "taxes",
+    "telekineses",
+    "theses",
+    "thromboses",
+    "tuberculoses",
+    "urinalyses",
+)
+
+pl_prep_list = """
+    about above across after among around at athwart before behind
+    below beneath beside besides between betwixt beyond but by
+    during except for from in into near of off on onto out over
+    since till to under until unto upon with""".split()
+
+pl_prep_list_da = pl_prep_list + ["de", "du", "da"]
+
+pl_prep_bysize = bysize(pl_prep_list_da)
+
+pl_prep = enclose("|".join(pl_prep_list_da))
+
+pl_sb_prep_dual_compound = rf"(.*?)((?:-|\s+)(?:{pl_prep})(?:-|\s+))a(?:-|\s+)(.*)"
+
+
+singular_pronoun_genders = {
+    "neuter",
+    "feminine",
+    "masculine",
+    "gender-neutral",
+    "feminine or masculine",
+    "masculine or feminine",
+}
+
+pl_pron_nom = {
+    # NOMINATIVE    REFLEXIVE
+    "i": "we",
+    "myself": "ourselves",
+    "you": "you",
+    "yourself": "yourselves",
+    "she": "they",
+    "herself": "themselves",
+    "he": "they",
+    "himself": "themselves",
+    "it": "they",
+    "itself": "themselves",
+    "they": "they",
+    "themself": "themselves",
+    #   POSSESSIVE
+    "mine": "ours",
+    "yours": "yours",
+    "hers": "theirs",
+    "his": "theirs",
+    "its": "theirs",
+    "theirs": "theirs",
+}
+
+si_pron: Dict[str, Dict[str, Union[str, Dict[str, str]]]] = {
+    "nom": {v: k for (k, v) in pl_pron_nom.items()}
+}
+si_pron["nom"]["we"] = "I"
+
+
+pl_pron_acc = {
+    # ACCUSATIVE    REFLEXIVE
+    "me": "us",
+    "myself": "ourselves",
+    "you": "you",
+    "yourself": "yourselves",
+    "her": "them",
+    "herself": "themselves",
+    "him": "them",
+    "himself": "themselves",
+    "it": "them",
+    "itself": "themselves",
+    "them": "them",
+    "themself": "themselves",
+}
+
+pl_pron_acc_keys = enclose("|".join(pl_pron_acc))
+pl_pron_acc_keys_bysize = bysize(pl_pron_acc)
+
+si_pron["acc"] = {v: k for (k, v) in pl_pron_acc.items()}
+
+for _thecase, _plur, _gend, _sing in (
+    ("nom", "they", "neuter", "it"),
+    ("nom", "they", "feminine", "she"),
+    ("nom", "they", "masculine", "he"),
+    ("nom", "they", "gender-neutral", "they"),
+    ("nom", "they", "feminine or masculine", "she or he"),
+    ("nom", "they", "masculine or feminine", "he or she"),
+    ("nom", "themselves", "neuter", "itself"),
+    ("nom", "themselves", "feminine", "herself"),
+    ("nom", "themselves", "masculine", "himself"),
+    ("nom", "themselves", "gender-neutral", "themself"),
+    ("nom", "themselves", "feminine or masculine", "herself or himself"),
+    ("nom", "themselves", "masculine or feminine", "himself or herself"),
+    ("nom", "theirs", "neuter", "its"),
+    ("nom", "theirs", "feminine", "hers"),
+    ("nom", "theirs", "masculine", "his"),
+    ("nom", "theirs", "gender-neutral", "theirs"),
+    ("nom", "theirs", "feminine or masculine", "hers or his"),
+    ("nom", "theirs", "masculine or feminine", "his or hers"),
+    ("acc", "them", "neuter", "it"),
+    ("acc", "them", "feminine", "her"),
+    ("acc", "them", "masculine", "him"),
+    ("acc", "them", "gender-neutral", "them"),
+    ("acc", "them", "feminine or masculine", "her or him"),
+    ("acc", "them", "masculine or feminine", "him or her"),
+    ("acc", "themselves", "neuter", "itself"),
+    ("acc", "themselves", "feminine", "herself"),
+    ("acc", "themselves", "masculine", "himself"),
+    ("acc", "themselves", "gender-neutral", "themself"),
+    ("acc", "themselves", "feminine or masculine", "herself or himself"),
+    ("acc", "themselves", "masculine or feminine", "himself or herself"),
+):
+    try:
+        si_pron[_thecase][_plur][_gend] = _sing  # type: ignore
+    except TypeError:
+        si_pron[_thecase][_plur] = {}
+        si_pron[_thecase][_plur][_gend] = _sing  # type: ignore
+
+
+si_pron_acc_keys = enclose("|".join(si_pron["acc"]))
+si_pron_acc_keys_bysize = bysize(si_pron["acc"])
+
+
+def get_si_pron(thecase, word, gender) -> str:
+    try:
+        sing = si_pron[thecase][word]
+    except KeyError:
+        raise  # not a pronoun
+    try:
+        return sing[gender]  # has several types due to gender
+    except TypeError:
+        return cast(str, sing)  # answer independent of gender
+
+
+# These dictionaries group verbs by first, second and third person
+# conjugations.
+
+plverb_irregular_pres = {
+    "am": "are",
+    "are": "are",
+    "is": "are",
+    "was": "were",
+    "were": "were",
+    "have": "have",
+    "has": "have",
+    "do": "do",
+    "does": "do",
+}
+
+plverb_ambiguous_pres = {
+    "act": "act",
+    "acts": "act",
+    "blame": "blame",
+    "blames": "blame",
+    "can": "can",
+    "must": "must",
+    "fly": "fly",
+    "flies": "fly",
+    "copy": "copy",
+    "copies": "copy",
+    "drink": "drink",
+    "drinks": "drink",
+    "fight": "fight",
+    "fights": "fight",
+    "fire": "fire",
+    "fires": "fire",
+    "like": "like",
+    "likes": "like",
+    "look": "look",
+    "looks": "look",
+    "make": "make",
+    "makes": "make",
+    "reach": "reach",
+    "reaches": "reach",
+    "run": "run",
+    "runs": "run",
+    "sink": "sink",
+    "sinks": "sink",
+    "sleep": "sleep",
+    "sleeps": "sleep",
+    "view": "view",
+    "views": "view",
+}
+
+plverb_ambiguous_pres_keys = re.compile(
+    rf"^({enclose('|'.join(plverb_ambiguous_pres))})((\s.*)?)$", re.IGNORECASE
+)
+
+
+plverb_irregular_non_pres = (
+    "did",
+    "had",
+    "ate",
+    "made",
+    "put",
+    "spent",
+    "fought",
+    "sank",
+    "gave",
+    "sought",
+    "shall",
+    "could",
+    "ought",
+    "should",
+)
+
+plverb_ambiguous_non_pres = re.compile(
+    r"^((?:thought|saw|bent|will|might|cut))((\s.*)?)$", re.IGNORECASE
+)
+
+# "..oes" -> "..oe" (the rest are "..oes" -> "o")
+
+pl_v_oes_oe = ("canoes", "floes", "oboes", "roes", "throes", "woes")
+pl_v_oes_oe_endings_size4 = ("hoes", "toes")
+pl_v_oes_oe_endings_size5 = ("shoes",)
+
+
+pl_count_zero = ("0", "no", "zero", "nil")
+
+
+pl_count_one = ("1", "a", "an", "one", "each", "every", "this", "that")
+
+pl_adj_special = {"a": "some", "an": "some", "this": "these", "that": "those"}
+
+pl_adj_special_keys = re.compile(
+    rf"^({enclose('|'.join(pl_adj_special))})$", re.IGNORECASE
+)
+
+pl_adj_poss = {
+    "my": "our",
+    "your": "your",
+    "its": "their",
+    "her": "their",
+    "his": "their",
+    "their": "their",
+}
+
+pl_adj_poss_keys = re.compile(rf"^({enclose('|'.join(pl_adj_poss))})$", re.IGNORECASE)
+
+
+# 2. INDEFINITE ARTICLES
+
+# THIS PATTERN MATCHES STRINGS OF CAPITALS STARTING WITH A "VOWEL-SOUND"
+# CONSONANT FOLLOWED BY ANOTHER CONSONANT, AND WHICH ARE NOT LIKELY
+# TO BE REAL WORDS (OH, ALL RIGHT THEN, IT'S JUST MAGIC!)
+
+A_abbrev = re.compile(
+    r"""
+^(?! FJO | [HLMNS]Y.  | RY[EO] | SQU
+  | ( F[LR]? | [HL] | MN? | N | RH? | S[CHKLMNPTVW]? | X(YL)?) [AEIOU])
+[FHLMNRSX][A-Z]
+""",
+    re.VERBOSE,
+)
+
+# THIS PATTERN CODES THE BEGINNINGS OF ALL ENGLISH WORDS BEGINING WITH A
+# 'y' FOLLOWED BY A CONSONANT. ANY OTHER Y-CONSONANT PREFIX THEREFORE
+# IMPLIES AN ABBREVIATION.
+
+A_y_cons = re.compile(r"^(y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt))", re.IGNORECASE)
+
+# EXCEPTIONS TO EXCEPTIONS
+
+A_explicit_a = re.compile(r"^((?:unabomber|unanimous|US))", re.IGNORECASE)
+
+A_explicit_an = re.compile(
+    r"^((?:euler|hour(?!i)|heir|honest|hono[ur]|mpeg))", re.IGNORECASE
+)
+
+A_ordinal_an = re.compile(r"^([aefhilmnorsx]-?th)", re.IGNORECASE)
+
+A_ordinal_a = re.compile(r"^([bcdgjkpqtuvwyz]-?th)", re.IGNORECASE)
+
+
+# NUMERICAL INFLECTIONS
+
+nth = {
+    0: "th",
+    1: "st",
+    2: "nd",
+    3: "rd",
+    4: "th",
+    5: "th",
+    6: "th",
+    7: "th",
+    8: "th",
+    9: "th",
+    11: "th",
+    12: "th",
+    13: "th",
+}
+nth_suff = set(nth.values())
+
+ordinal = dict(
+    ty="tieth",
+    one="first",
+    two="second",
+    three="third",
+    five="fifth",
+    eight="eighth",
+    nine="ninth",
+    twelve="twelfth",
+)
+
+ordinal_suff = re.compile(rf"({'|'.join(ordinal)})\Z")
+
+
+# NUMBERS
+
+unit = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
+teen = [
+    "ten",
+    "eleven",
+    "twelve",
+    "thirteen",
+    "fourteen",
+    "fifteen",
+    "sixteen",
+    "seventeen",
+    "eighteen",
+    "nineteen",
+]
+ten = [
+    "",
+    "",
+    "twenty",
+    "thirty",
+    "forty",
+    "fifty",
+    "sixty",
+    "seventy",
+    "eighty",
+    "ninety",
+]
+mill = [
+    " ",
+    " thousand",
+    " million",
+    " billion",
+    " trillion",
+    " quadrillion",
+    " quintillion",
+    " sextillion",
+    " septillion",
+    " octillion",
+    " nonillion",
+    " decillion",
+]
+
+
+# SUPPORT CLASSICAL PLURALIZATIONS
+
+def_classical = dict(
+    all=False, zero=False, herd=False, names=True, persons=False, ancient=False
+)
+
+all_classical = {k: True for k in def_classical}
+no_classical = {k: False for k in def_classical}
+
+
+# Maps strings to built-in constant types
+string_to_constant = {"True": True, "False": False, "None": None}
+
+
+# Pre-compiled regular expression objects
+DOLLAR_DIGITS = re.compile(r"\$(\d+)")
+FUNCTION_CALL = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE)
+PARTITION_WORD = re.compile(r"\A(\s*)(.+?)(\s*)\Z")
+PL_SB_POSTFIX_ADJ_STEMS_RE = re.compile(
+    rf"^(?:{pl_sb_postfix_adj_stems})$", re.IGNORECASE
+)
+PL_SB_PREP_DUAL_COMPOUND_RE = re.compile(
+    rf"^(?:{pl_sb_prep_dual_compound})$", re.IGNORECASE
+)
+DENOMINATOR = re.compile(r"(?P.+)( (per|a) .+)")
+PLVERB_SPECIAL_S_RE = re.compile(rf"^({plverb_special_s})$")
+WHITESPACE = re.compile(r"\s")
+ENDS_WITH_S = re.compile(r"^(.*[^s])s$", re.IGNORECASE)
+ENDS_WITH_APOSTROPHE_S = re.compile(r"^(.*)'s?$")
+INDEFINITE_ARTICLE_TEST = re.compile(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", re.IGNORECASE)
+SPECIAL_AN = re.compile(r"^[aefhilmnorsx]$", re.IGNORECASE)
+SPECIAL_A = re.compile(r"^[bcdgjkpqtuvwyz]$", re.IGNORECASE)
+SPECIAL_ABBREV_AN = re.compile(r"^[aefhilmnorsx][.-]", re.IGNORECASE)
+SPECIAL_ABBREV_A = re.compile(r"^[a-z][.-]", re.IGNORECASE)
+CONSONANTS = re.compile(r"^[^aeiouy]", re.IGNORECASE)
+ARTICLE_SPECIAL_EU = re.compile(r"^e[uw]", re.IGNORECASE)
+ARTICLE_SPECIAL_ONCE = re.compile(r"^onc?e\b", re.IGNORECASE)
+ARTICLE_SPECIAL_ONETIME = re.compile(r"^onetime\b", re.IGNORECASE)
+ARTICLE_SPECIAL_UNIT = re.compile(r"^uni([^nmd]|mo)", re.IGNORECASE)
+ARTICLE_SPECIAL_UBA = re.compile(r"^u[bcfghjkqrst][aeiou]", re.IGNORECASE)
+ARTICLE_SPECIAL_UKR = re.compile(r"^ukr", re.IGNORECASE)
+SPECIAL_CAPITALS = re.compile(r"^U[NK][AIEO]?")
+VOWELS = re.compile(r"^[aeiou]", re.IGNORECASE)
+
+DIGIT_GROUP = re.compile(r"(\d)")
+TWO_DIGITS = re.compile(r"(\d)(\d)")
+THREE_DIGITS = re.compile(r"(\d)(\d)(\d)")
+THREE_DIGITS_WORD = re.compile(r"(\d)(\d)(\d)(?=\D*\Z)")
+TWO_DIGITS_WORD = re.compile(r"(\d)(\d)(?=\D*\Z)")
+ONE_DIGIT_WORD = re.compile(r"(\d)(?=\D*\Z)")
+
+FOUR_DIGIT_COMMA = re.compile(r"(\d)(\d{3}(?:,|\Z))")
+NON_DIGIT = re.compile(r"\D")
+WHITESPACES_COMMA = re.compile(r"\s+,")
+COMMA_WORD = re.compile(r", (\S+)\s+\Z")
+WHITESPACES = re.compile(r"\s+")
+
+
+PRESENT_PARTICIPLE_REPLACEMENTS = (
+    (re.compile(r"ie$"), r"y"),
+    (
+        re.compile(r"ue$"),
+        r"u",
+    ),  # TODO: isn't ue$ -> u encompassed in the following rule?
+    (re.compile(r"([auy])e$"), r"\g<1>"),
+    (re.compile(r"ski$"), r"ski"),
+    (re.compile(r"[^b]i$"), r""),
+    (re.compile(r"^(are|were)$"), r"be"),
+    (re.compile(r"^(had)$"), r"hav"),
+    (re.compile(r"^(hoe)$"), r"\g<1>"),
+    (re.compile(r"([^e])e$"), r"\g<1>"),
+    (re.compile(r"er$"), r"er"),
+    (re.compile(r"([^aeiou][aeiouy]([bdgmnprst]))$"), r"\g<1>\g<2>"),
+)
+
+DIGIT = re.compile(r"\d")
+
+
+class Words(str):
+    lowered: str
+    split_: List[str]
+    first: str
+    last: str
+
+    def __init__(self, orig) -> None:
+        self.lowered = self.lower()
+        self.split_ = self.split()
+        self.first = self.split_[0]
+        self.last = self.split_[-1]
+
+
+Falsish = Any  # ideally, falsish would only validate on bool(value) is False
+
+
+_STATIC_TYPE_CHECKING = TYPE_CHECKING
+# ^-- Workaround for typeguard AST manipulation:
+#     https://github.com/agronholm/typeguard/issues/353#issuecomment-1556306554
+
+if _STATIC_TYPE_CHECKING:  # pragma: no cover
+    Word = Annotated[str, "String with at least 1 character"]
+else:
+
+    class _WordMeta(type):  # Too dynamic to be supported by mypy...
+        def __instancecheck__(self, instance: Any) -> bool:
+            return isinstance(instance, str) and len(instance) >= 1
+
+    class Word(metaclass=_WordMeta):  # type: ignore[no-redef]
+        """String with at least 1 character"""
+
+
+class engine:
+    def __init__(self) -> None:
+        self.classical_dict = def_classical.copy()
+        self.persistent_count: Optional[int] = None
+        self.mill_count = 0
+        self.pl_sb_user_defined: List[Optional[Word]] = []
+        self.pl_v_user_defined: List[Optional[Word]] = []
+        self.pl_adj_user_defined: List[Optional[Word]] = []
+        self.si_sb_user_defined: List[Optional[Word]] = []
+        self.A_a_user_defined: List[Optional[Word]] = []
+        self.thegender = "neuter"
+        self.__number_args: Optional[Dict[str, str]] = None
+
+    @property
+    def _number_args(self):
+        return cast(Dict[str, str], self.__number_args)
+
+    @_number_args.setter
+    def _number_args(self, val):
+        self.__number_args = val
+
+    @typechecked
+    def defnoun(self, singular: Optional[Word], plural: Optional[Word]) -> int:
+        """
+        Set the noun plural of singular to plural.
+
+        """
+        self.checkpat(singular)
+        self.checkpatplural(plural)
+        self.pl_sb_user_defined.extend((singular, plural))
+        self.si_sb_user_defined.extend((plural, singular))
+        return 1
+
+    @typechecked
+    def defverb(
+        self,
+        s1: Optional[Word],
+        p1: Optional[Word],
+        s2: Optional[Word],
+        p2: Optional[Word],
+        s3: Optional[Word],
+        p3: Optional[Word],
+    ) -> int:
+        """
+        Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively.
+
+        Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb.
+
+        """
+        self.checkpat(s1)
+        self.checkpat(s2)
+        self.checkpat(s3)
+        self.checkpatplural(p1)
+        self.checkpatplural(p2)
+        self.checkpatplural(p3)
+        self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3))
+        return 1
+
+    @typechecked
+    def defadj(self, singular: Optional[Word], plural: Optional[Word]) -> int:
+        """
+        Set the adjective plural of singular to plural.
+
+        """
+        self.checkpat(singular)
+        self.checkpatplural(plural)
+        self.pl_adj_user_defined.extend((singular, plural))
+        return 1
+
+    @typechecked
+    def defa(self, pattern: Optional[Word]) -> int:
+        """
+        Define the indefinite article as 'a' for words matching pattern.
+
+        """
+        self.checkpat(pattern)
+        self.A_a_user_defined.extend((pattern, "a"))
+        return 1
+
+    @typechecked
+    def defan(self, pattern: Optional[Word]) -> int:
+        """
+        Define the indefinite article as 'an' for words matching pattern.
+
+        """
+        self.checkpat(pattern)
+        self.A_a_user_defined.extend((pattern, "an"))
+        return 1
+
+    def checkpat(self, pattern: Optional[Word]) -> None:
+        """
+        check for errors in a regex pattern
+        """
+        if pattern is None:
+            return
+        try:
+            re.match(pattern, "")
+        except re.error as err:
+            raise BadUserDefinedPatternError(pattern) from err
+
+    def checkpatplural(self, pattern: Optional[Word]) -> None:
+        """
+        check for errors in a regex replace pattern
+        """
+        return
+
+    @typechecked
+    def ud_match(self, word: Word, wordlist: Sequence[Optional[Word]]) -> Optional[str]:
+        for i in range(len(wordlist) - 2, -2, -2):  # backwards through even elements
+            mo = re.search(rf"^{wordlist[i]}$", word, re.IGNORECASE)
+            if mo:
+                if wordlist[i + 1] is None:
+                    return None
+                pl = DOLLAR_DIGITS.sub(
+                    r"\\1", cast(Word, wordlist[i + 1])
+                )  # change $n to \n for expand
+                return mo.expand(pl)
+        return None
+
+    def classical(self, **kwargs) -> None:
+        """
+        turn classical mode on and off for various categories
+
+        turn on all classical modes:
+        classical()
+        classical(all=True)
+
+        turn on or off specific claassical modes:
+        e.g.
+        classical(herd=True)
+        classical(names=False)
+
+        By default all classical modes are off except names.
+
+        unknown value in args or key in kwargs raises
+        exception: UnknownClasicalModeError
+
+        """
+        if not kwargs:
+            self.classical_dict = all_classical.copy()
+            return
+        if "all" in kwargs:
+            if kwargs["all"]:
+                self.classical_dict = all_classical.copy()
+            else:
+                self.classical_dict = no_classical.copy()
+
+        for k, v in kwargs.items():
+            if k in def_classical:
+                self.classical_dict[k] = v
+            else:
+                raise UnknownClassicalModeError
+
+    def num(
+        self, count: Optional[int] = None, show: Optional[int] = None
+    ) -> str:  # (;$count,$show)
+        """
+        Set the number to be used in other method calls.
+
+        Returns count.
+
+        Set show to False to return '' instead.
+
+        """
+        if count is not None:
+            try:
+                self.persistent_count = int(count)
+            except ValueError as err:
+                raise BadNumValueError from err
+            if (show is None) or show:
+                return str(count)
+        else:
+            self.persistent_count = None
+        return ""
+
+    def gender(self, gender: str) -> None:
+        """
+        set the gender for the singular of plural pronouns
+
+        can be one of:
+        'neuter'                ('they' -> 'it')
+        'feminine'              ('they' -> 'she')
+        'masculine'             ('they' -> 'he')
+        'gender-neutral'        ('they' -> 'they')
+        'feminine or masculine' ('they' -> 'she or he')
+        'masculine or feminine' ('they' -> 'he or she')
+        """
+        if gender in singular_pronoun_genders:
+            self.thegender = gender
+        else:
+            raise BadGenderError
+
+    def _get_value_from_ast(self, obj):
+        """
+        Return the value of the ast object.
+        """
+        if isinstance(obj, ast.Num):
+            return obj.n
+        elif isinstance(obj, ast.Str):
+            return obj.s
+        elif isinstance(obj, ast.List):
+            return [self._get_value_from_ast(e) for e in obj.elts]
+        elif isinstance(obj, ast.Tuple):
+            return tuple([self._get_value_from_ast(e) for e in obj.elts])
+
+        # None, True and False are NameConstants in Py3.4 and above.
+        elif isinstance(obj, ast.NameConstant):
+            return obj.value
+
+        # Probably passed a variable name.
+        # Or passed a single word without wrapping it in quotes as an argument
+        # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
+        raise NameError(f"name '{obj.id}' is not defined")
+
+    def _string_to_substitute(
+        self, mo: Match, methods_dict: Dict[str, Callable]
+    ) -> str:
+        """
+        Return the string to be substituted for the match.
+        """
+        matched_text, f_name = mo.groups()
+        # matched_text is the complete match string. e.g. plural_noun(cat)
+        # f_name is the function name. e.g. plural_noun
+
+        # Return matched_text if function name is not in methods_dict
+        if f_name not in methods_dict:
+            return matched_text
+
+        # Parse the matched text
+        a_tree = ast.parse(matched_text)
+
+        # get the args and kwargs from ast objects
+        args_list = [
+            self._get_value_from_ast(a)
+            for a in a_tree.body[0].value.args  # type: ignore[attr-defined]
+        ]
+        kwargs_list = {
+            kw.arg: self._get_value_from_ast(kw.value)
+            for kw in a_tree.body[0].value.keywords  # type: ignore[attr-defined]
+        }
+
+        # Call the corresponding function
+        return methods_dict[f_name](*args_list, **kwargs_list)
+
+    # 0. PERFORM GENERAL INFLECTIONS IN A STRING
+
+    @typechecked
+    def inflect(self, text: Word) -> str:
+        """
+        Perform inflections in a string.
+
+        e.g. inflect('The plural of cat is plural(cat)') returns
+        'The plural of cat is cats'
+
+        can use plural, plural_noun, plural_verb, plural_adj,
+        singular_noun, a, an, no, ordinal, number_to_words,
+        and prespart
+
+        """
+        save_persistent_count = self.persistent_count
+
+        # Dictionary of allowed methods
+        methods_dict: Dict[str, Callable] = {
+            "plural": self.plural,
+            "plural_adj": self.plural_adj,
+            "plural_noun": self.plural_noun,
+            "plural_verb": self.plural_verb,
+            "singular_noun": self.singular_noun,
+            "a": self.a,
+            "an": self.a,
+            "no": self.no,
+            "ordinal": self.ordinal,
+            "number_to_words": self.number_to_words,
+            "present_participle": self.present_participle,
+            "num": self.num,
+        }
+
+        # Regular expression to find Python's function call syntax
+        output = FUNCTION_CALL.sub(
+            lambda mo: self._string_to_substitute(mo, methods_dict), text
+        )
+        self.persistent_count = save_persistent_count
+        return output
+
+    # ## PLURAL SUBROUTINES
+
+    def postprocess(self, orig: str, inflected) -> str:
+        inflected = str(inflected)
+        if "|" in inflected:
+            word_options = inflected.split("|")
+            # When two parts of a noun need to be pluralized
+            if len(word_options[0].split(" ")) == len(word_options[1].split(" ")):
+                result = inflected.split("|")[self.classical_dict["all"]].split(" ")
+            # When only the last part of the noun needs to be pluralized
+            else:
+                result = inflected.split(" ")
+                for index, word in enumerate(result):
+                    if "|" in word:
+                        result[index] = word.split("|")[self.classical_dict["all"]]
+        else:
+            result = inflected.split(" ")
+
+        # Try to fix word wise capitalization
+        for index, word in enumerate(orig.split(" ")):
+            if word == "I":
+                # Is this the only word for exceptions like this
+                # Where the original is fully capitalized
+                # without 'meaning' capitalization?
+                # Also this fails to handle a capitalizaion in context
+                continue
+            if word.capitalize() == word:
+                result[index] = result[index].capitalize()
+            if word == word.upper():
+                result[index] = result[index].upper()
+        return " ".join(result)
+
+    def partition_word(self, text: str) -> Tuple[str, str, str]:
+        mo = PARTITION_WORD.search(text)
+        if mo:
+            return mo.group(1), mo.group(2), mo.group(3)
+        else:
+            return "", "", ""
+
+    @typechecked
+    def plural(self, text: Word, count: Optional[Union[str, int, Any]] = None) -> str:
+        """
+        Return the plural of text.
+
+        If count supplied, then return text if count is one of:
+            1, a, an, one, each, every, this, that
+
+        otherwise return the plural.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        pre, word, post = self.partition_word(text)
+        if not word:
+            return text
+        plural = self.postprocess(
+            word,
+            self._pl_special_adjective(word, count)
+            or self._pl_special_verb(word, count)
+            or self._plnoun(word, count),
+        )
+        return f"{pre}{plural}{post}"
+
+    @typechecked
+    def plural_noun(
+        self, text: Word, count: Optional[Union[str, int, Any]] = None
+    ) -> str:
+        """
+        Return the plural of text, where text is a noun.
+
+        If count supplied, then return text if count is one of:
+            1, a, an, one, each, every, this, that
+
+        otherwise return the plural.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        pre, word, post = self.partition_word(text)
+        if not word:
+            return text
+        plural = self.postprocess(word, self._plnoun(word, count))
+        return f"{pre}{plural}{post}"
+
+    @typechecked
+    def plural_verb(
+        self, text: Word, count: Optional[Union[str, int, Any]] = None
+    ) -> str:
+        """
+        Return the plural of text, where text is a verb.
+
+        If count supplied, then return text if count is one of:
+            1, a, an, one, each, every, this, that
+
+        otherwise return the plural.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        pre, word, post = self.partition_word(text)
+        if not word:
+            return text
+        plural = self.postprocess(
+            word,
+            self._pl_special_verb(word, count) or self._pl_general_verb(word, count),
+        )
+        return f"{pre}{plural}{post}"
+
+    @typechecked
+    def plural_adj(
+        self, text: Word, count: Optional[Union[str, int, Any]] = None
+    ) -> str:
+        """
+        Return the plural of text, where text is an adjective.
+
+        If count supplied, then return text if count is one of:
+            1, a, an, one, each, every, this, that
+
+        otherwise return the plural.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        pre, word, post = self.partition_word(text)
+        if not word:
+            return text
+        plural = self.postprocess(word, self._pl_special_adjective(word, count) or word)
+        return f"{pre}{plural}{post}"
+
+    @typechecked
+    def compare(self, word1: Word, word2: Word) -> Union[str, bool]:
+        """
+        compare word1 and word2 for equality regardless of plurality
+
+        return values:
+        eq - the strings are equal
+        p:s - word1 is the plural of word2
+        s:p - word2 is the plural of word1
+        p:p - word1 and word2 are two different plural forms of the one word
+        False - otherwise
+
+        >>> compare = engine().compare
+        >>> compare("egg", "eggs")
+        's:p'
+        >>> compare('egg', 'egg')
+        'eq'
+
+        Words should not be empty.
+
+        >>> compare('egg', '')
+        Traceback (most recent call last):
+        ...
+        typeguard.TypeCheckError:...is not an instance of inflect.Word
+        """
+        norms = self.plural_noun, self.plural_verb, self.plural_adj
+        results = (self._plequal(word1, word2, norm) for norm in norms)
+        return next(filter(None, results), False)
+
+    @typechecked
+    def compare_nouns(self, word1: Word, word2: Word) -> Union[str, bool]:
+        """
+        compare word1 and word2 for equality regardless of plurality
+        word1 and word2 are to be treated as nouns
+
+        return values:
+        eq - the strings are equal
+        p:s - word1 is the plural of word2
+        s:p - word2 is the plural of word1
+        p:p - word1 and word2 are two different plural forms of the one word
+        False - otherwise
+
+        """
+        return self._plequal(word1, word2, self.plural_noun)
+
+    @typechecked
+    def compare_verbs(self, word1: Word, word2: Word) -> Union[str, bool]:
+        """
+        compare word1 and word2 for equality regardless of plurality
+        word1 and word2 are to be treated as verbs
+
+        return values:
+        eq - the strings are equal
+        p:s - word1 is the plural of word2
+        s:p - word2 is the plural of word1
+        p:p - word1 and word2 are two different plural forms of the one word
+        False - otherwise
+
+        """
+        return self._plequal(word1, word2, self.plural_verb)
+
+    @typechecked
+    def compare_adjs(self, word1: Word, word2: Word) -> Union[str, bool]:
+        """
+        compare word1 and word2 for equality regardless of plurality
+        word1 and word2 are to be treated as adjectives
+
+        return values:
+        eq - the strings are equal
+        p:s - word1 is the plural of word2
+        s:p - word2 is the plural of word1
+        p:p - word1 and word2 are two different plural forms of the one word
+        False - otherwise
+
+        """
+        return self._plequal(word1, word2, self.plural_adj)
+
+    @typechecked
+    def singular_noun(
+        self,
+        text: Word,
+        count: Optional[Union[int, str, Any]] = None,
+        gender: Optional[str] = None,
+    ) -> Union[str, Literal[False]]:
+        """
+        Return the singular of text, where text is a plural noun.
+
+        If count supplied, then return the singular if count is one of:
+            1, a, an, one, each, every, this, that or if count is None
+
+        otherwise return text unchanged.
+
+        Whitespace at the start and end is preserved.
+
+        >>> p = engine()
+        >>> p.singular_noun('horses')
+        'horse'
+        >>> p.singular_noun('knights')
+        'knight'
+
+        Returns False when a singular noun is passed.
+
+        >>> p.singular_noun('horse')
+        False
+        >>> p.singular_noun('knight')
+        False
+        >>> p.singular_noun('soldier')
+        False
+
+        """
+        pre, word, post = self.partition_word(text)
+        if not word:
+            return text
+        sing = self._sinoun(word, count=count, gender=gender)
+        if sing is not False:
+            plural = self.postprocess(word, sing)
+            return f"{pre}{plural}{post}"
+        return False
+
+    def _plequal(self, word1: str, word2: str, pl) -> Union[str, bool]:  # noqa: C901
+        classval = self.classical_dict.copy()
+        self.classical_dict = all_classical.copy()
+        if word1 == word2:
+            return "eq"
+        if word1 == pl(word2):
+            return "p:s"
+        if pl(word1) == word2:
+            return "s:p"
+        self.classical_dict = no_classical.copy()
+        if word1 == pl(word2):
+            return "p:s"
+        if pl(word1) == word2:
+            return "s:p"
+        self.classical_dict = classval.copy()
+
+        if pl == self.plural or pl == self.plural_noun:
+            if self._pl_check_plurals_N(word1, word2):
+                return "p:p"
+            if self._pl_check_plurals_N(word2, word1):
+                return "p:p"
+        if pl == self.plural or pl == self.plural_adj:
+            if self._pl_check_plurals_adj(word1, word2):
+                return "p:p"
+        return False
+
+    def _pl_reg_plurals(self, pair: str, stems: str, end1: str, end2: str) -> bool:
+        pattern = rf"({stems})({end1}\|\1{end2}|{end2}\|\1{end1})"
+        return bool(re.search(pattern, pair))
+
+    def _pl_check_plurals_N(self, word1: str, word2: str) -> bool:
+        stem_endings = (
+            (pl_sb_C_a_ata, "as", "ata"),
+            (pl_sb_C_is_ides, "is", "ides"),
+            (pl_sb_C_a_ae, "s", "e"),
+            (pl_sb_C_en_ina, "ens", "ina"),
+            (pl_sb_C_um_a, "ums", "a"),
+            (pl_sb_C_us_i, "uses", "i"),
+            (pl_sb_C_on_a, "ons", "a"),
+            (pl_sb_C_o_i_stems, "os", "i"),
+            (pl_sb_C_ex_ices, "exes", "ices"),
+            (pl_sb_C_ix_ices, "ixes", "ices"),
+            (pl_sb_C_i, "s", "i"),
+            (pl_sb_C_im, "s", "im"),
+            (".*eau", "s", "x"),
+            (".*ieu", "s", "x"),
+            (".*tri", "xes", "ces"),
+            (".{2,}[yia]n", "xes", "ges"),
+        )
+
+        words = map(Words, (word1, word2))
+        pair = "|".join(word.last for word in words)
+
+        return (
+            pair in pl_sb_irregular_s.values()
+            or pair in pl_sb_irregular.values()
+            or pair in pl_sb_irregular_caps.values()
+            or any(
+                self._pl_reg_plurals(pair, stems, end1, end2)
+                for stems, end1, end2 in stem_endings
+            )
+        )
+
+    def _pl_check_plurals_adj(self, word1: str, word2: str) -> bool:
+        word1a = word1[: word1.rfind("'")] if word1.endswith(("'s", "'")) else ""
+        word2a = word2[: word2.rfind("'")] if word2.endswith(("'s", "'")) else ""
+
+        return (
+            bool(word1a)
+            and bool(word2a)
+            and (
+                self._pl_check_plurals_N(word1a, word2a)
+                or self._pl_check_plurals_N(word2a, word1a)
+            )
+        )
+
+    def get_count(self, count: Optional[Union[str, int]] = None) -> Union[str, int]:
+        if count is None and self.persistent_count is not None:
+            count = self.persistent_count
+
+        if count is not None:
+            count = (
+                1
+                if (
+                    (str(count) in pl_count_one)
+                    or (
+                        self.classical_dict["zero"]
+                        and str(count).lower() in pl_count_zero
+                    )
+                )
+                else 2
+            )
+        else:
+            count = ""
+        return count
+
+    # @profile
+    def _plnoun(  # noqa: C901
+        self, word: str, count: Optional[Union[str, int]] = None
+    ) -> str:
+        count = self.get_count(count)
+
+        # DEFAULT TO PLURAL
+
+        if count == 1:
+            return word
+
+        # HANDLE USER-DEFINED NOUNS
+
+        value = self.ud_match(word, self.pl_sb_user_defined)
+        if value is not None:
+            return value
+
+        # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS
+
+        if word == "":
+            return word
+
+        word = Words(word)
+
+        if word.last.lower() in pl_sb_uninflected_complete:
+            if len(word.split_) >= 3:
+                return self._handle_long_compounds(word, count=2) or word
+            return word
+
+        if word in pl_sb_uninflected_caps:
+            return word
+
+        for k, v in pl_sb_uninflected_bysize.items():
+            if word.lowered[-k:] in v:
+                return word
+
+        if self.classical_dict["herd"] and word.last.lower() in pl_sb_uninflected_herd:
+            return word
+
+        # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.)
+
+        mo = PL_SB_POSTFIX_ADJ_STEMS_RE.search(word)
+        if mo and mo.group(2) != "":
+            return f"{self._plnoun(mo.group(1), 2)}{mo.group(2)}"
+
+        if " a " in word.lowered or "-a-" in word.lowered:
+            mo = PL_SB_PREP_DUAL_COMPOUND_RE.search(word)
+            if mo and mo.group(2) != "" and mo.group(3) != "":
+                return (
+                    f"{self._plnoun(mo.group(1), 2)}"
+                    f"{mo.group(2)}"
+                    f"{self._plnoun(mo.group(3))}"
+                )
+
+        if len(word.split_) >= 3:
+            handled_words = self._handle_long_compounds(word, count=2)
+            if handled_words is not None:
+                return handled_words
+
+        # only pluralize denominators in units
+        mo = DENOMINATOR.search(word.lowered)
+        if mo:
+            index = len(mo.group("denominator"))
+            return f"{self._plnoun(word[:index])}{word[index:]}"
+
+        # handle units given in degrees (only accept if
+        # there is no more than one word following)
+        # degree Celsius => degrees Celsius but degree
+        # fahrenheit hour => degree fahrenheit hours
+        if len(word.split_) >= 2 and word.split_[-2] == "degree":
+            return " ".join([self._plnoun(word.first)] + word.split_[1:])
+
+        with contextlib.suppress(ValueError):
+            return self._handle_prepositional_phrase(
+                word.lowered,
+                functools.partial(self._plnoun, count=2),
+                '-',
+            )
+
+        # HANDLE PRONOUNS
+
+        for k, v in pl_pron_acc_keys_bysize.items():
+            if word.lowered[-k:] in v:  # ends with accusative pronoun
+                for pk, pv in pl_prep_bysize.items():
+                    if word.lowered[:pk] in pv:  # starts with a prep
+                        if word.lowered.split() == [
+                            word.lowered[:pk],
+                            word.lowered[-k:],
+                        ]:
+                            # only whitespace in between
+                            return word.lowered[:-k] + pl_pron_acc[word.lowered[-k:]]
+
+        try:
+            return pl_pron_nom[word.lowered]
+        except KeyError:
+            pass
+
+        try:
+            return pl_pron_acc[word.lowered]
+        except KeyError:
+            pass
+
+        # HANDLE ISOLATED IRREGULAR PLURALS
+
+        if word.last in pl_sb_irregular_caps:
+            llen = len(word.last)
+            return f"{word[:-llen]}{pl_sb_irregular_caps[word.last]}"
+
+        lowered_last = word.last.lower()
+        if lowered_last in pl_sb_irregular:
+            llen = len(lowered_last)
+            return f"{word[:-llen]}{pl_sb_irregular[lowered_last]}"
+
+        dash_split = word.lowered.split('-')
+        if (" ".join(dash_split[-2:])).lower() in pl_sb_irregular_compound:
+            llen = len(
+                " ".join(dash_split[-2:])
+            )  # TODO: what if 2 spaces between these words?
+            return (
+                f"{word[:-llen]}"
+                f"{pl_sb_irregular_compound[(' '.join(dash_split[-2:])).lower()]}"
+            )
+
+        if word.lowered[-3:] == "quy":
+            return f"{word[:-1]}ies"
+
+        if word.lowered[-6:] == "person":
+            if self.classical_dict["persons"]:
+                return f"{word}s"
+            else:
+                return f"{word[:-4]}ople"
+
+        # HANDLE FAMILIES OF IRREGULAR PLURALS
+
+        if word.lowered[-3:] == "man":
+            for k, v in pl_sb_U_man_mans_bysize.items():
+                if word.lowered[-k:] in v:
+                    return f"{word}s"
+            for k, v in pl_sb_U_man_mans_caps_bysize.items():
+                if word[-k:] in v:
+                    return f"{word}s"
+            return f"{word[:-3]}men"
+        if word.lowered[-5:] == "mouse":
+            return f"{word[:-5]}mice"
+        if word.lowered[-5:] == "louse":
+            v = pl_sb_U_louse_lice_bysize.get(len(word))
+            if v and word.lowered in v:
+                return f"{word[:-5]}lice"
+            return f"{word}s"
+        if word.lowered[-5:] == "goose":
+            return f"{word[:-5]}geese"
+        if word.lowered[-5:] == "tooth":
+            return f"{word[:-5]}teeth"
+        if word.lowered[-4:] == "foot":
+            return f"{word[:-4]}feet"
+        if word.lowered[-4:] == "taco":
+            return f"{word[:-5]}tacos"
+
+        if word.lowered == "die":
+            return "dice"
+
+        # HANDLE UNASSIMILATED IMPORTS
+
+        if word.lowered[-4:] == "ceps":
+            return word
+        if word.lowered[-4:] == "zoon":
+            return f"{word[:-2]}a"
+        if word.lowered[-3:] in ("cis", "sis", "xis"):
+            return f"{word[:-2]}es"
+
+        for lastlet, d, numend, post in (
+            ("h", pl_sb_U_ch_chs_bysize, None, "s"),
+            ("x", pl_sb_U_ex_ices_bysize, -2, "ices"),
+            ("x", pl_sb_U_ix_ices_bysize, -2, "ices"),
+            ("m", pl_sb_U_um_a_bysize, -2, "a"),
+            ("s", pl_sb_U_us_i_bysize, -2, "i"),
+            ("n", pl_sb_U_on_a_bysize, -2, "a"),
+            ("a", pl_sb_U_a_ae_bysize, None, "e"),
+        ):
+            if word.lowered[-1] == lastlet:  # this test to add speed
+                for k, v in d.items():
+                    if word.lowered[-k:] in v:
+                        return word[:numend] + post
+
+        # HANDLE INCOMPLETELY ASSIMILATED IMPORTS
+
+        if self.classical_dict["ancient"]:
+            if word.lowered[-4:] == "trix":
+                return f"{word[:-1]}ces"
+            if word.lowered[-3:] in ("eau", "ieu"):
+                return f"{word}x"
+            if word.lowered[-3:] in ("ynx", "inx", "anx") and len(word) > 4:
+                return f"{word[:-1]}ges"
+
+            for lastlet, d, numend, post in (
+                ("n", pl_sb_C_en_ina_bysize, -2, "ina"),
+                ("x", pl_sb_C_ex_ices_bysize, -2, "ices"),
+                ("x", pl_sb_C_ix_ices_bysize, -2, "ices"),
+                ("m", pl_sb_C_um_a_bysize, -2, "a"),
+                ("s", pl_sb_C_us_i_bysize, -2, "i"),
+                ("s", pl_sb_C_us_us_bysize, None, ""),
+                ("a", pl_sb_C_a_ae_bysize, None, "e"),
+                ("a", pl_sb_C_a_ata_bysize, None, "ta"),
+                ("s", pl_sb_C_is_ides_bysize, -1, "des"),
+                ("o", pl_sb_C_o_i_bysize, -1, "i"),
+                ("n", pl_sb_C_on_a_bysize, -2, "a"),
+            ):
+                if word.lowered[-1] == lastlet:  # this test to add speed
+                    for k, v in d.items():
+                        if word.lowered[-k:] in v:
+                            return word[:numend] + post
+
+            for d, numend, post in (
+                (pl_sb_C_i_bysize, None, "i"),
+                (pl_sb_C_im_bysize, None, "im"),
+            ):
+                for k, v in d.items():
+                    if word.lowered[-k:] in v:
+                        return word[:numend] + post
+
+        # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS
+
+        if lowered_last in pl_sb_singular_s_complete:
+            return f"{word}es"
+
+        for k, v in pl_sb_singular_s_bysize.items():
+            if word.lowered[-k:] in v:
+                return f"{word}es"
+
+        if word.lowered[-2:] == "es" and word[0] == word[0].upper():
+            return f"{word}es"
+
+        if word.lowered[-1] == "z":
+            for k, v in pl_sb_z_zes_bysize.items():
+                if word.lowered[-k:] in v:
+                    return f"{word}es"
+
+            if word.lowered[-2:-1] != "z":
+                return f"{word}zes"
+
+        if word.lowered[-2:] == "ze":
+            for k, v in pl_sb_ze_zes_bysize.items():
+                if word.lowered[-k:] in v:
+                    return f"{word}s"
+
+        if word.lowered[-2:] in ("ch", "sh", "zz", "ss") or word.lowered[-1] == "x":
+            return f"{word}es"
+
+        # HANDLE ...f -> ...ves
+
+        if word.lowered[-3:] in ("elf", "alf", "olf"):
+            return f"{word[:-1]}ves"
+        if word.lowered[-3:] == "eaf" and word.lowered[-4:-3] != "d":
+            return f"{word[:-1]}ves"
+        if word.lowered[-4:] in ("nife", "life", "wife"):
+            return f"{word[:-2]}ves"
+        if word.lowered[-3:] == "arf":
+            return f"{word[:-1]}ves"
+
+        # HANDLE ...y
+
+        if word.lowered[-1] == "y":
+            if word.lowered[-2:-1] in "aeiou" or len(word) == 1:
+                return f"{word}s"
+
+            if self.classical_dict["names"]:
+                if word.lowered[-1] == "y" and word[0] == word[0].upper():
+                    return f"{word}s"
+
+            return f"{word[:-1]}ies"
+
+        # HANDLE ...o
+
+        if lowered_last in pl_sb_U_o_os_complete:
+            return f"{word}s"
+
+        for k, v in pl_sb_U_o_os_bysize.items():
+            if word.lowered[-k:] in v:
+                return f"{word}s"
+
+        if word.lowered[-2:] in ("ao", "eo", "io", "oo", "uo"):
+            return f"{word}s"
+
+        if word.lowered[-1] == "o":
+            return f"{word}es"
+
+        # OTHERWISE JUST ADD ...s
+
+        return f"{word}s"
+
+    @classmethod
+    def _handle_prepositional_phrase(cls, phrase, transform, sep):
+        """
+        Given a word or phrase possibly separated by sep, parse out
+        the prepositional phrase and apply the transform to the word
+        preceding the prepositional phrase.
+
+        Raise ValueError if the pivot is not found or if at least two
+        separators are not found.
+
+        >>> engine._handle_prepositional_phrase("man-of-war", str.upper, '-')
+        'MAN-of-war'
+        >>> engine._handle_prepositional_phrase("man of war", str.upper, ' ')
+        'MAN of war'
+        """
+        parts = phrase.split(sep)
+        if len(parts) < 3:
+            raise ValueError("Cannot handle words with fewer than two separators")
+
+        pivot = cls._find_pivot(parts, pl_prep_list_da)
+
+        transformed = transform(parts[pivot - 1]) or parts[pivot - 1]
+        return " ".join(
+            parts[: pivot - 1] + [sep.join([transformed, parts[pivot], ''])]
+        ) + " ".join(parts[(pivot + 1) :])
+
+    def _handle_long_compounds(self, word: Words, count: int) -> Union[str, None]:
+        """
+        Handles the plural and singular for compound `Words` that
+        have three or more words, based on the given count.
+
+        >>> engine()._handle_long_compounds(Words("pair of scissors"), 2)
+        'pairs of scissors'
+        >>> engine()._handle_long_compounds(Words("men beyond hills"), 1)
+        'man beyond hills'
+        """
+        inflection = self._sinoun if count == 1 else self._plnoun
+        solutions = (  # type: ignore
+            " ".join(
+                itertools.chain(
+                    leader,
+                    [inflection(cand, count), prep],  # type: ignore
+                    trailer,
+                )
+            )
+            for leader, (cand, prep), trailer in windowed_complete(word.split_, 2)
+            if prep in pl_prep_list_da  # type: ignore
+        )
+        return next(solutions, None)
+
+    @staticmethod
+    def _find_pivot(words, candidates):
+        pivots = (
+            index for index in range(1, len(words) - 1) if words[index] in candidates
+        )
+        try:
+            return next(pivots)
+        except StopIteration:
+            raise ValueError("No pivot found") from None
+
+    def _pl_special_verb(  # noqa: C901
+        self, word: str, count: Optional[Union[str, int]] = None
+    ) -> Union[str, bool]:
+        if self.classical_dict["zero"] and str(count).lower() in pl_count_zero:
+            return False
+        count = self.get_count(count)
+
+        if count == 1:
+            return word
+
+        # HANDLE USER-DEFINED VERBS
+
+        value = self.ud_match(word, self.pl_v_user_defined)
+        if value is not None:
+            return value
+
+        # HANDLE IRREGULAR PRESENT TENSE (SIMPLE AND COMPOUND)
+
+        try:
+            words = Words(word)
+        except IndexError:
+            return False  # word is ''
+
+        if words.first in plverb_irregular_pres:
+            return f"{plverb_irregular_pres[words.first]}{words[len(words.first) :]}"
+
+        # HANDLE IRREGULAR FUTURE, PRETERITE AND PERFECT TENSES
+
+        if words.first in plverb_irregular_non_pres:
+            return word
+
+        # HANDLE PRESENT NEGATIONS (SIMPLE AND COMPOUND)
+
+        if words.first.endswith("n't") and words.first[:-3] in plverb_irregular_pres:
+            return (
+                f"{plverb_irregular_pres[words.first[:-3]]}n't"
+                f"{words[len(words.first) :]}"
+            )
+
+        if words.first.endswith("n't"):
+            return word
+
+        # HANDLE SPECIAL CASES
+
+        mo = PLVERB_SPECIAL_S_RE.search(word)
+        if mo:
+            return False
+        if WHITESPACE.search(word):
+            return False
+
+        if words.lowered == "quizzes":
+            return "quiz"
+
+        # HANDLE STANDARD 3RD PERSON (CHOP THE ...(e)s OFF SINGLE WORDS)
+
+        if (
+            words.lowered[-4:] in ("ches", "shes", "zzes", "sses")
+            or words.lowered[-3:] == "xes"
+        ):
+            return words[:-2]
+
+        if words.lowered[-3:] == "ies" and len(words) > 3:
+            return words.lowered[:-3] + "y"
+
+        if (
+            words.last.lower() in pl_v_oes_oe
+            or words.lowered[-4:] in pl_v_oes_oe_endings_size4
+            or words.lowered[-5:] in pl_v_oes_oe_endings_size5
+        ):
+            return words[:-1]
+
+        if words.lowered.endswith("oes") and len(words) > 3:
+            return words.lowered[:-2]
+
+        mo = ENDS_WITH_S.search(words)
+        if mo:
+            return mo.group(1)
+
+        # OTHERWISE, A REGULAR VERB (HANDLE ELSEWHERE)
+
+        return False
+
+    def _pl_general_verb(
+        self, word: str, count: Optional[Union[str, int]] = None
+    ) -> str:
+        count = self.get_count(count)
+
+        if count == 1:
+            return word
+
+        # HANDLE AMBIGUOUS PRESENT TENSES  (SIMPLE AND COMPOUND)
+
+        mo = plverb_ambiguous_pres_keys.search(word)
+        if mo:
+            return f"{plverb_ambiguous_pres[mo.group(1).lower()]}{mo.group(2)}"
+
+        # HANDLE AMBIGUOUS PRETERITE AND PERFECT TENSES
+
+        mo = plverb_ambiguous_non_pres.search(word)
+        if mo:
+            return word
+
+        # OTHERWISE, 1st OR 2ND PERSON IS UNINFLECTED
+
+        return word
+
+    def _pl_special_adjective(
+        self, word: str, count: Optional[Union[str, int]] = None
+    ) -> Union[str, bool]:
+        count = self.get_count(count)
+
+        if count == 1:
+            return word
+
+        # HANDLE USER-DEFINED ADJECTIVES
+
+        value = self.ud_match(word, self.pl_adj_user_defined)
+        if value is not None:
+            return value
+
+        # HANDLE KNOWN CASES
+
+        mo = pl_adj_special_keys.search(word)
+        if mo:
+            return pl_adj_special[mo.group(1).lower()]
+
+        # HANDLE POSSESSIVES
+
+        mo = pl_adj_poss_keys.search(word)
+        if mo:
+            return pl_adj_poss[mo.group(1).lower()]
+
+        mo = ENDS_WITH_APOSTROPHE_S.search(word)
+        if mo:
+            pl = self.plural_noun(mo.group(1))
+            trailing_s = "" if pl[-1] == "s" else "s"
+            return f"{pl}'{trailing_s}"
+
+        # OTHERWISE, NO IDEA
+
+        return False
+
+    # @profile
+    def _sinoun(  # noqa: C901
+        self,
+        word: str,
+        count: Optional[Union[str, int]] = None,
+        gender: Optional[str] = None,
+    ) -> Union[str, bool]:
+        count = self.get_count(count)
+
+        # DEFAULT TO PLURAL
+
+        if count == 2:
+            return word
+
+        # SET THE GENDER
+
+        try:
+            if gender is None:
+                gender = self.thegender
+            elif gender not in singular_pronoun_genders:
+                raise BadGenderError
+        except (TypeError, IndexError) as err:
+            raise BadGenderError from err
+
+        # HANDLE USER-DEFINED NOUNS
+
+        value = self.ud_match(word, self.si_sb_user_defined)
+        if value is not None:
+            return value
+
+        # HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS
+
+        if word == "":
+            return word
+
+        if word in si_sb_ois_oi_case:
+            return word[:-1]
+
+        words = Words(word)
+
+        if words.last.lower() in pl_sb_uninflected_complete:
+            if len(words.split_) >= 3:
+                return self._handle_long_compounds(words, count=1) or word
+            return word
+
+        if word in pl_sb_uninflected_caps:
+            return word
+
+        for k, v in pl_sb_uninflected_bysize.items():
+            if words.lowered[-k:] in v:
+                return word
+
+        if self.classical_dict["herd"] and words.last.lower() in pl_sb_uninflected_herd:
+            return word
+
+        if words.last.lower() in pl_sb_C_us_us:
+            return word if self.classical_dict["ancient"] else False
+
+        # HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.)
+
+        mo = PL_SB_POSTFIX_ADJ_STEMS_RE.search(word)
+        if mo and mo.group(2) != "":
+            return f"{self._sinoun(mo.group(1), 1, gender=gender)}{mo.group(2)}"
+
+        with contextlib.suppress(ValueError):
+            return self._handle_prepositional_phrase(
+                words.lowered,
+                functools.partial(self._sinoun, count=1, gender=gender),
+                ' ',
+            )
+
+        with contextlib.suppress(ValueError):
+            return self._handle_prepositional_phrase(
+                words.lowered,
+                functools.partial(self._sinoun, count=1, gender=gender),
+                '-',
+            )
+
+        # HANDLE PRONOUNS
+
+        for k, v in si_pron_acc_keys_bysize.items():
+            if words.lowered[-k:] in v:  # ends with accusative pronoun
+                for pk, pv in pl_prep_bysize.items():
+                    if words.lowered[:pk] in pv:  # starts with a prep
+                        if words.lowered.split() == [
+                            words.lowered[:pk],
+                            words.lowered[-k:],
+                        ]:
+                            # only whitespace in between
+                            return words.lowered[:-k] + get_si_pron(
+                                "acc", words.lowered[-k:], gender
+                            )
+
+        try:
+            return get_si_pron("nom", words.lowered, gender)
+        except KeyError:
+            pass
+
+        try:
+            return get_si_pron("acc", words.lowered, gender)
+        except KeyError:
+            pass
+
+        # HANDLE ISOLATED IRREGULAR PLURALS
+
+        if words.last in si_sb_irregular_caps:
+            llen = len(words.last)
+            return f"{word[:-llen]}{si_sb_irregular_caps[words.last]}"
+
+        if words.last.lower() in si_sb_irregular:
+            llen = len(words.last.lower())
+            return f"{word[:-llen]}{si_sb_irregular[words.last.lower()]}"
+
+        dash_split = words.lowered.split("-")
+        if (" ".join(dash_split[-2:])).lower() in si_sb_irregular_compound:
+            llen = len(
+                " ".join(dash_split[-2:])
+            )  # TODO: what if 2 spaces between these words?
+            return "{}{}".format(
+                word[:-llen],
+                si_sb_irregular_compound[(" ".join(dash_split[-2:])).lower()],
+            )
+
+        if words.lowered[-5:] == "quies":
+            return word[:-3] + "y"
+
+        if words.lowered[-7:] == "persons":
+            return word[:-1]
+        if words.lowered[-6:] == "people":
+            return word[:-4] + "rson"
+
+        # HANDLE FAMILIES OF IRREGULAR PLURALS
+
+        if words.lowered[-4:] == "mans":
+            for k, v in si_sb_U_man_mans_bysize.items():
+                if words.lowered[-k:] in v:
+                    return word[:-1]
+            for k, v in si_sb_U_man_mans_caps_bysize.items():
+                if word[-k:] in v:
+                    return word[:-1]
+        if words.lowered[-3:] == "men":
+            return word[:-3] + "man"
+        if words.lowered[-4:] == "mice":
+            return word[:-4] + "mouse"
+        if words.lowered[-4:] == "lice":
+            v = si_sb_U_louse_lice_bysize.get(len(word))
+            if v and words.lowered in v:
+                return word[:-4] + "louse"
+        if words.lowered[-5:] == "geese":
+            return word[:-5] + "goose"
+        if words.lowered[-5:] == "teeth":
+            return word[:-5] + "tooth"
+        if words.lowered[-4:] == "feet":
+            return word[:-4] + "foot"
+
+        if words.lowered == "dice":
+            return "die"
+
+        # HANDLE UNASSIMILATED IMPORTS
+
+        if words.lowered[-4:] == "ceps":
+            return word
+        if words.lowered[-3:] == "zoa":
+            return word[:-1] + "on"
+
+        for lastlet, d, unass_numend, post in (
+            ("s", si_sb_U_ch_chs_bysize, -1, ""),
+            ("s", si_sb_U_ex_ices_bysize, -4, "ex"),
+            ("s", si_sb_U_ix_ices_bysize, -4, "ix"),
+            ("a", si_sb_U_um_a_bysize, -1, "um"),
+            ("i", si_sb_U_us_i_bysize, -1, "us"),
+            ("a", si_sb_U_on_a_bysize, -1, "on"),
+            ("e", si_sb_U_a_ae_bysize, -1, ""),
+        ):
+            if words.lowered[-1] == lastlet:  # this test to add speed
+                for k, v in d.items():
+                    if words.lowered[-k:] in v:
+                        return word[:unass_numend] + post
+
+        # HANDLE INCOMPLETELY ASSIMILATED IMPORTS
+
+        if self.classical_dict["ancient"]:
+            if words.lowered[-6:] == "trices":
+                return word[:-3] + "x"
+            if words.lowered[-4:] in ("eaux", "ieux"):
+                return word[:-1]
+            if words.lowered[-5:] in ("ynges", "inges", "anges") and len(word) > 6:
+                return word[:-3] + "x"
+
+            for lastlet, d, class_numend, post in (
+                ("a", si_sb_C_en_ina_bysize, -3, "en"),
+                ("s", si_sb_C_ex_ices_bysize, -4, "ex"),
+                ("s", si_sb_C_ix_ices_bysize, -4, "ix"),
+                ("a", si_sb_C_um_a_bysize, -1, "um"),
+                ("i", si_sb_C_us_i_bysize, -1, "us"),
+                ("s", pl_sb_C_us_us_bysize, None, ""),
+                ("e", si_sb_C_a_ae_bysize, -1, ""),
+                ("a", si_sb_C_a_ata_bysize, -2, ""),
+                ("s", si_sb_C_is_ides_bysize, -3, "s"),
+                ("i", si_sb_C_o_i_bysize, -1, "o"),
+                ("a", si_sb_C_on_a_bysize, -1, "on"),
+                ("m", si_sb_C_im_bysize, -2, ""),
+                ("i", si_sb_C_i_bysize, -1, ""),
+            ):
+                if words.lowered[-1] == lastlet:  # this test to add speed
+                    for k, v in d.items():
+                        if words.lowered[-k:] in v:
+                            return word[:class_numend] + post
+
+        # HANDLE PLURLS ENDING IN uses -> use
+
+        if (
+            words.lowered[-6:] == "houses"
+            or word in si_sb_uses_use_case
+            or words.last.lower() in si_sb_uses_use
+        ):
+            return word[:-1]
+
+        # HANDLE PLURLS ENDING IN ies -> ie
+
+        if word in si_sb_ies_ie_case or words.last.lower() in si_sb_ies_ie:
+            return word[:-1]
+
+        # HANDLE PLURLS ENDING IN oes -> oe
+
+        if (
+            words.lowered[-5:] == "shoes"
+            or word in si_sb_oes_oe_case
+            or words.last.lower() in si_sb_oes_oe
+        ):
+            return word[:-1]
+
+        # HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS
+
+        if word in si_sb_sses_sse_case or words.last.lower() in si_sb_sses_sse:
+            return word[:-1]
+
+        if words.last.lower() in si_sb_singular_s_complete:
+            return word[:-2]
+
+        for k, v in si_sb_singular_s_bysize.items():
+            if words.lowered[-k:] in v:
+                return word[:-2]
+
+        if words.lowered[-4:] == "eses" and word[0] == word[0].upper():
+            return word[:-2]
+
+        if words.last.lower() in si_sb_z_zes:
+            return word[:-2]
+
+        if words.last.lower() in si_sb_zzes_zz:
+            return word[:-2]
+
+        if words.lowered[-4:] == "zzes":
+            return word[:-3]
+
+        if word in si_sb_ches_che_case or words.last.lower() in si_sb_ches_che:
+            return word[:-1]
+
+        if words.lowered[-4:] in ("ches", "shes"):
+            return word[:-2]
+
+        if words.last.lower() in si_sb_xes_xe:
+            return word[:-1]
+
+        if words.lowered[-3:] == "xes":
+            return word[:-2]
+
+        # HANDLE ...f -> ...ves
+
+        if word in si_sb_ves_ve_case or words.last.lower() in si_sb_ves_ve:
+            return word[:-1]
+
+        if words.lowered[-3:] == "ves":
+            if words.lowered[-5:-3] in ("el", "al", "ol"):
+                return word[:-3] + "f"
+            if words.lowered[-5:-3] == "ea" and word[-6:-5] != "d":
+                return word[:-3] + "f"
+            if words.lowered[-5:-3] in ("ni", "li", "wi"):
+                return word[:-3] + "fe"
+            if words.lowered[-5:-3] == "ar":
+                return word[:-3] + "f"
+
+        # HANDLE ...y
+
+        if words.lowered[-2:] == "ys":
+            if len(words.lowered) > 2 and words.lowered[-3] in "aeiou":
+                return word[:-1]
+
+            if self.classical_dict["names"]:
+                if words.lowered[-2:] == "ys" and word[0] == word[0].upper():
+                    return word[:-1]
+
+        if words.lowered[-3:] == "ies":
+            return word[:-3] + "y"
+
+        # HANDLE ...o
+
+        if words.lowered[-2:] == "os":
+            if words.last.lower() in si_sb_U_o_os_complete:
+                return word[:-1]
+
+            for k, v in si_sb_U_o_os_bysize.items():
+                if words.lowered[-k:] in v:
+                    return word[:-1]
+
+            if words.lowered[-3:] in ("aos", "eos", "ios", "oos", "uos"):
+                return word[:-1]
+
+        if words.lowered[-3:] == "oes":
+            return word[:-2]
+
+        # UNASSIMILATED IMPORTS FINAL RULE
+
+        if word in si_sb_es_is:
+            return word[:-2] + "is"
+
+        # OTHERWISE JUST REMOVE ...s
+
+        if words.lowered[-1] == "s":
+            return word[:-1]
+
+        # COULD NOT FIND SINGULAR
+
+        return False
+
+    # ADJECTIVES
+
+    @typechecked
+    def a(self, text: Word, count: Optional[Union[int, str, Any]] = 1) -> str:
+        """
+        Return the appropriate indefinite article followed by text.
+
+        The indefinite article is either 'a' or 'an'.
+
+        If count is not one, then return count followed by text
+        instead of 'a' or 'an'.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        mo = INDEFINITE_ARTICLE_TEST.search(text)
+        if mo:
+            word = mo.group(2)
+            if not word:
+                return text
+            pre = mo.group(1)
+            post = mo.group(3)
+            result = self._indef_article(word, count)
+            return f"{pre}{result}{post}"
+        return ""
+
+    an = a
+
+    _indef_article_cases = (
+        # HANDLE ORDINAL FORMS
+        (A_ordinal_a, "a"),
+        (A_ordinal_an, "an"),
+        # HANDLE SPECIAL CASES
+        (A_explicit_an, "an"),
+        (SPECIAL_AN, "an"),
+        (SPECIAL_A, "a"),
+        # HANDLE ABBREVIATIONS
+        (A_abbrev, "an"),
+        (SPECIAL_ABBREV_AN, "an"),
+        (SPECIAL_ABBREV_A, "a"),
+        # HANDLE CONSONANTS
+        (CONSONANTS, "a"),
+        # HANDLE SPECIAL VOWEL-FORMS
+        (ARTICLE_SPECIAL_EU, "a"),
+        (ARTICLE_SPECIAL_ONCE, "a"),
+        (ARTICLE_SPECIAL_ONETIME, "a"),
+        (ARTICLE_SPECIAL_UNIT, "a"),
+        (ARTICLE_SPECIAL_UBA, "a"),
+        (ARTICLE_SPECIAL_UKR, "a"),
+        (A_explicit_a, "a"),
+        # HANDLE SPECIAL CAPITALS
+        (SPECIAL_CAPITALS, "a"),
+        # HANDLE VOWELS
+        (VOWELS, "an"),
+        # HANDLE y...
+        # (BEFORE CERTAIN CONSONANTS IMPLIES (UNNATURALIZED) "i.." SOUND)
+        (A_y_cons, "an"),
+    )
+
+    def _indef_article(self, word: str, count: Union[int, str, Any]) -> str:
+        mycount = self.get_count(count)
+
+        if mycount != 1:
+            return f"{count} {word}"
+
+        # HANDLE USER-DEFINED VARIANTS
+
+        value = self.ud_match(word, self.A_a_user_defined)
+        if value is not None:
+            return f"{value} {word}"
+
+        matches = (
+            f'{article} {word}'
+            for regexen, article in self._indef_article_cases
+            if regexen.search(word)
+        )
+
+        # OTHERWISE, GUESS "a"
+        fallback = f'a {word}'
+        return next(matches, fallback)
+
+    # 2. TRANSLATE ZERO-QUANTIFIED $word TO "no plural($word)"
+
+    @typechecked
+    def no(self, text: Word, count: Optional[Union[int, str]] = None) -> str:
+        """
+        If count is 0, no, zero or nil, return 'no' followed by the plural
+        of text.
+
+        If count is one of:
+            1, a, an, one, each, every, this, that
+            return count followed by text.
+
+        Otherwise return count follow by the plural of text.
+
+        In the return value count is always followed by a space.
+
+        Whitespace at the start and end is preserved.
+
+        """
+        if count is None and self.persistent_count is not None:
+            count = self.persistent_count
+
+        if count is None:
+            count = 0
+        mo = PARTITION_WORD.search(text)
+        if mo:
+            pre = mo.group(1)
+            word = mo.group(2)
+            post = mo.group(3)
+        else:
+            pre = ""
+            word = ""
+            post = ""
+
+        if str(count).lower() in pl_count_zero:
+            count = 'no'
+        return f"{pre}{count} {self.plural(word, count)}{post}"
+
+    # PARTICIPLES
+
+    @typechecked
+    def present_participle(self, word: Word) -> str:
+        """
+        Return the present participle for word.
+
+        word is the 3rd person singular verb.
+
+        """
+        plv = self.plural_verb(word, 2)
+        ans = plv
+
+        for regexen, repl in PRESENT_PARTICIPLE_REPLACEMENTS:
+            ans, num = regexen.subn(repl, plv)
+            if num:
+                return f"{ans}ing"
+        return f"{ans}ing"
+
+    # NUMERICAL INFLECTIONS
+
+    @typechecked
+    def ordinal(self, num: Union[Number, Word]) -> str:
+        """
+        Return the ordinal of num.
+
+        >>> ordinal = engine().ordinal
+        >>> ordinal(1)
+        '1st'
+        >>> ordinal('one')
+        'first'
+        """
+        if DIGIT.match(str(num)):
+            if isinstance(num, (float, int)) and int(num) == num:
+                n = int(num)
+            else:
+                if "." in str(num):
+                    try:
+                        # numbers after decimal,
+                        # so only need last one for ordinal
+                        n = int(str(num)[-1])
+
+                    except ValueError:  # ends with '.', so need to use whole string
+                        n = int(str(num)[:-1])
+                else:
+                    n = int(num)  # type: ignore
+            try:
+                post = nth[n % 100]
+            except KeyError:
+                post = nth[n % 10]
+            return f"{num}{post}"
+        else:
+            return self._sub_ord(num)
+
+    def millfn(self, ind: int = 0) -> str:
+        if ind > len(mill) - 1:
+            raise NumOutOfRangeError
+        return mill[ind]
+
+    def unitfn(self, units: int, mindex: int = 0) -> str:
+        return f"{unit[units]}{self.millfn(mindex)}"
+
+    def tenfn(self, tens, units, mindex=0) -> str:
+        if tens != 1:
+            tens_part = ten[tens]
+            if tens and units:
+                hyphen = "-"
+            else:
+                hyphen = ""
+            unit_part = unit[units]
+            mill_part = self.millfn(mindex)
+            return f"{tens_part}{hyphen}{unit_part}{mill_part}"
+        return f"{teen[units]}{mill[mindex]}"
+
+    def hundfn(self, hundreds: int, tens: int, units: int, mindex: int) -> str:
+        if hundreds:
+            andword = f" {self._number_args['andword']} " if tens or units else ""
+            # use unit not unitfn as simpler
+            return (
+                f"{unit[hundreds]} hundred{andword}"
+                f"{self.tenfn(tens, units)}{self.millfn(mindex)}, "
+            )
+        if tens or units:
+            return f"{self.tenfn(tens, units)}{self.millfn(mindex)}, "
+        return ""
+
+    def group1sub(self, mo: Match) -> str:
+        units = int(mo.group(1))
+        if units == 1:
+            return f" {self._number_args['one']}, "
+        elif units:
+            return f"{unit[units]}, "
+        else:
+            return f" {self._number_args['zero']}, "
+
+    def group1bsub(self, mo: Match) -> str:
+        units = int(mo.group(1))
+        if units:
+            return f"{unit[units]}, "
+        else:
+            return f" {self._number_args['zero']}, "
+
+    def group2sub(self, mo: Match) -> str:
+        tens = int(mo.group(1))
+        units = int(mo.group(2))
+        if tens:
+            return f"{self.tenfn(tens, units)}, "
+        if units:
+            return f" {self._number_args['zero']} {unit[units]}, "
+        return f" {self._number_args['zero']} {self._number_args['zero']}, "
+
+    def group3sub(self, mo: Match) -> str:
+        hundreds = int(mo.group(1))
+        tens = int(mo.group(2))
+        units = int(mo.group(3))
+        if hundreds == 1:
+            hunword = f" {self._number_args['one']}"
+        elif hundreds:
+            hunword = str(unit[hundreds])
+        else:
+            hunword = f" {self._number_args['zero']}"
+        if tens:
+            tenword = self.tenfn(tens, units)
+        elif units:
+            tenword = f" {self._number_args['zero']} {unit[units]}"
+        else:
+            tenword = f" {self._number_args['zero']} {self._number_args['zero']}"
+        return f"{hunword} {tenword}, "
+
+    def hundsub(self, mo: Match) -> str:
+        ret = self.hundfn(
+            int(mo.group(1)), int(mo.group(2)), int(mo.group(3)), self.mill_count
+        )
+        self.mill_count += 1
+        return ret
+
+    def tensub(self, mo: Match) -> str:
+        return f"{self.tenfn(int(mo.group(1)), int(mo.group(2)), self.mill_count)}, "
+
+    def unitsub(self, mo: Match) -> str:
+        return f"{self.unitfn(int(mo.group(1)), self.mill_count)}, "
+
+    def enword(self, num: str, group: int) -> str:
+        # import pdb
+        # pdb.set_trace()
+
+        if group == 1:
+            num = DIGIT_GROUP.sub(self.group1sub, num)
+        elif group == 2:
+            num = TWO_DIGITS.sub(self.group2sub, num)
+            num = DIGIT_GROUP.sub(self.group1bsub, num, 1)
+        elif group == 3:
+            num = THREE_DIGITS.sub(self.group3sub, num)
+            num = TWO_DIGITS.sub(self.group2sub, num, 1)
+            num = DIGIT_GROUP.sub(self.group1sub, num, 1)
+        elif int(num) == 0:
+            num = self._number_args["zero"]
+        elif int(num) == 1:
+            num = self._number_args["one"]
+        else:
+            num = num.lstrip().lstrip("0")
+            self.mill_count = 0
+            # surely there's a better way to do the next bit
+            mo = THREE_DIGITS_WORD.search(num)
+            while mo:
+                num = THREE_DIGITS_WORD.sub(self.hundsub, num, 1)
+                mo = THREE_DIGITS_WORD.search(num)
+            num = TWO_DIGITS_WORD.sub(self.tensub, num, 1)
+            num = ONE_DIGIT_WORD.sub(self.unitsub, num, 1)
+        return num
+
+    @staticmethod
+    def _sub_ord(val):
+        new = ordinal_suff.sub(lambda match: ordinal[match.group(1)], val)
+        return new + "th" * (new == val)
+
+    @classmethod
+    def _chunk_num(cls, num, decimal, group):
+        if decimal:
+            max_split = -1 if group != 0 else 1
+            chunks = num.split(".", max_split)
+        else:
+            chunks = [num]
+        return cls._remove_last_blank(chunks)
+
+    @staticmethod
+    def _remove_last_blank(chunks):
+        """
+        Remove the last item from chunks if it's a blank string.
+
+        Return the resultant chunks and whether the last item was removed.
+        """
+        removed = chunks[-1] == ""
+        result = chunks[:-1] if removed else chunks
+        return result, removed
+
+    @staticmethod
+    def _get_sign(num):
+        return {'+': 'plus', '-': 'minus'}.get(num.lstrip()[0], '')
+
+    @typechecked
+    def number_to_words(  # noqa: C901
+        self,
+        num: Union[Number, Word],
+        wantlist: bool = False,
+        group: int = 0,
+        comma: Union[Falsish, str] = ",",
+        andword: str = "and",
+        zero: str = "zero",
+        one: str = "one",
+        decimal: Union[Falsish, str] = "point",
+        threshold: Optional[int] = None,
+    ) -> Union[str, List[str]]:
+        """
+        Return a number in words.
+
+        group = 1, 2 or 3 to group numbers before turning into words
+        comma: define comma
+
+        andword:
+            word for 'and'. Can be set to ''.
+            e.g. "one hundred and one" vs "one hundred one"
+
+        zero: word for '0'
+        one: word for '1'
+        decimal: word for decimal point
+        threshold: numbers above threshold not turned into words
+
+        parameters not remembered from last call. Departure from Perl version.
+        """
+        self._number_args = {"andword": andword, "zero": zero, "one": one}
+        num = str(num)
+
+        # Handle "stylistic" conversions (up to a given threshold)...
+        if threshold is not None and float(num) > threshold:
+            spnum = num.split(".", 1)
+            while comma:
+                (spnum[0], n) = FOUR_DIGIT_COMMA.subn(r"\1,\2", spnum[0])
+                if n == 0:
+                    break
+            try:
+                return f"{spnum[0]}.{spnum[1]}"
+            except IndexError:
+                return str(spnum[0])
+
+        if group < 0 or group > 3:
+            raise BadChunkingOptionError
+
+        sign = self._get_sign(num)
+
+        if num in nth_suff:
+            num = zero
+
+        myord = num[-2:] in nth_suff
+        if myord:
+            num = num[:-2]
+
+        chunks, finalpoint = self._chunk_num(num, decimal, group)
+
+        loopstart = chunks[0] == ""
+        first: bool | None = not loopstart
+
+        def _handle_chunk(chunk):
+            nonlocal first
+
+            # remove all non numeric \D
+            chunk = NON_DIGIT.sub("", chunk)
+            if chunk == "":
+                chunk = "0"
+
+            if group == 0 and not first:
+                chunk = self.enword(chunk, 1)
+            else:
+                chunk = self.enword(chunk, group)
+
+            if chunk[-2:] == ", ":
+                chunk = chunk[:-2]
+            chunk = WHITESPACES_COMMA.sub(",", chunk)
+
+            if group == 0 and first:
+                chunk = COMMA_WORD.sub(f" {andword} \\1", chunk)
+            chunk = WHITESPACES.sub(" ", chunk)
+            # chunk = re.sub(r"(\A\s|\s\Z)", self.blankfn, chunk)
+            chunk = chunk.strip()
+            if first:
+                first = None
+            return chunk
+
+        chunks[loopstart:] = map(_handle_chunk, chunks[loopstart:])
+
+        numchunks = []
+        if first != 0:
+            numchunks = chunks[0].split(f"{comma} ")
+
+        if myord and numchunks:
+            numchunks[-1] = self._sub_ord(numchunks[-1])
+
+        for chunk in chunks[1:]:
+            numchunks.append(decimal)
+            numchunks.extend(chunk.split(f"{comma} "))
+
+        if finalpoint:
+            numchunks.append(decimal)
+
+        if wantlist:
+            return [sign] * bool(sign) + numchunks
+
+        signout = f"{sign} " if sign else ""
+        valout = (
+            ', '.join(numchunks)
+            if group
+            else ''.join(self._render(numchunks, decimal, comma))
+        )
+        return signout + valout
+
+    @staticmethod
+    def _render(chunks, decimal, comma):
+        first_item = chunks.pop(0)
+        yield first_item
+        first = decimal is None or not first_item.endswith(decimal)
+        for nc in chunks:
+            if nc == decimal:
+                first = False
+            elif first:
+                yield comma
+            yield f" {nc}"
+
+    @typechecked
+    def join(
+        self,
+        words: Optional[Sequence[Word]],
+        sep: Optional[str] = None,
+        sep_spaced: bool = True,
+        final_sep: Optional[str] = None,
+        conj: str = "and",
+        conj_spaced: bool = True,
+    ) -> str:
+        """
+        Join words into a list.
+
+        e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
+
+        options:
+        conj: replacement for 'and'
+        sep: separator. default ',', unless ',' is in the list then ';'
+        final_sep: final separator. default ',', unless ',' is in the list then ';'
+        conj_spaced: boolean. Should conj have spaces around it
+
+        """
+        if not words:
+            return ""
+        if len(words) == 1:
+            return words[0]
+
+        if conj_spaced:
+            if conj == "":
+                conj = " "
+            else:
+                conj = f" {conj} "
+
+        if len(words) == 2:
+            return f"{words[0]}{conj}{words[1]}"
+
+        if sep is None:
+            if "," in "".join(words):
+                sep = ";"
+            else:
+                sep = ","
+        if final_sep is None:
+            final_sep = sep
+
+        final_sep = f"{final_sep}{conj}"
+
+        if sep_spaced:
+            sep += " "
+
+        return f"{sep.join(words[0:-1])}{final_sep}{words[-1]}"
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/compat/py38.py b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/compat/py38.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2d01bd98f4ae3d9236d0e6ec3b89faa9ca706ae
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/compat/py38.py
@@ -0,0 +1,7 @@
+import sys
+
+
+if sys.version_info > (3, 9):
+    from typing import Annotated
+else:  # pragma: no cover
+    from typing_extensions import Annotated  # noqa: F401
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/inflect/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..fe6ca5ad880ff2a77c81a94ed84ee60c742e298f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/METADATA
@@ -0,0 +1,85 @@
+Metadata-Version: 2.1
+Name: jaraco.collections
+Version: 5.1.0
+Summary: Collection objects similar to those in stdlib by jaraco
+Author-email: "Jason R. Coombs" 
+Project-URL: Source, https://github.com/jaraco/jaraco.collections
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: jaraco.text
+Provides-Extra: check
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'check'
+Requires-Dist: pytest-ruff >=0.2.1 ; (sys_platform != "cygwin") and extra == 'check'
+Provides-Extra: cover
+Requires-Dist: pytest-cov ; extra == 'cover'
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: enabler
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'enabler'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Provides-Extra: type
+Requires-Dist: pytest-mypy ; extra == 'type'
+
+.. image:: https://img.shields.io/pypi/v/jaraco.collections.svg
+   :target: https://pypi.org/project/jaraco.collections
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.collections.svg
+
+.. image:: https://github.com/jaraco/jaraco.collections/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.collections/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracocollections/badge/?version=latest
+   :target: https://jaracocollections.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.collections
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.collections?utm_source=pypi-jaraco.collections&utm_medium=readme
+
+Models and classes to supplement the stdlib 'collections' module.
+
+See the docs, linked above, for descriptions and usage examples.
+
+Highlights include:
+
+- RangeMap: A mapping that accepts a range of values for keys.
+- Projection: A subset over an existing mapping.
+- KeyTransformingDict: Generalized mapping with keys transformed by a function.
+- FoldedCaseKeyedDict: A dict whose string keys are case-insensitive.
+- BijectiveMap: A map where keys map to values and values back to their keys.
+- ItemsAsAttributes: A mapping mix-in exposing items as attributes.
+- IdentityOverrideMap: A map whose keys map by default to themselves unless overridden.
+- FrozenDict: A hashable, immutable map.
+- Enumeration: An object whose keys are enumerated.
+- Everything: A container that contains all things.
+- Least, Greatest: Objects that are always less than or greater than any other.
+- pop_all: Return all items from the mutable sequence and remove them from that sequence.
+- DictStack: A stack of dicts, great for sharing scopes.
+- WeightedLookup: A specialized RangeMap for selecting an item by weights.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..48b957ec88588e68cf23d25ebf6f5f6b1cfcf43b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/RECORD
@@ -0,0 +1,10 @@
+jaraco.collections-5.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+jaraco.collections-5.1.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+jaraco.collections-5.1.0.dist-info/METADATA,sha256=IMUaliNsA5X1Ox9MXUWOagch5R4Wwb_3M7erp29dBtg,3933
+jaraco.collections-5.1.0.dist-info/RECORD,,
+jaraco.collections-5.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco.collections-5.1.0.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91
+jaraco.collections-5.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
+jaraco/collections/__init__.py,sha256=Pc1-SqjWm81ad1P0-GttpkwO_LWlnaY6gUq8gcKh2v0,26640
+jaraco/collections/__pycache__/__init__.cpython-312.pyc,,
+jaraco/collections/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..50e1e84e4a3fa44387f2798f8f465963bc3fc406
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (73.0.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.collections-5.1.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+jaraco
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..a36f7c5e82d796eadf667ad461fae3bb5cea0b4a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/METADATA
@@ -0,0 +1,75 @@
+Metadata-Version: 2.1
+Name: jaraco.context
+Version: 5.3.0
+Summary: Useful decorators and context managers
+Home-page: https://github.com/jaraco/jaraco.context
+Author: Jason R. Coombs
+Author-email: jaraco@jaraco.com
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+License-File: LICENSE
+Requires-Dist: backports.tarfile ; python_version < "3.12"
+Provides-Extra: docs
+Requires-Dist: sphinx >=3.5 ; extra == 'docs'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs'
+Requires-Dist: rst.linker >=1.9 ; extra == 'docs'
+Requires-Dist: furo ; extra == 'docs'
+Requires-Dist: sphinx-lint ; extra == 'docs'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'docs'
+Provides-Extra: testing
+Requires-Dist: pytest !=8.1.1,>=6 ; extra == 'testing'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing'
+Requires-Dist: pytest-cov ; extra == 'testing'
+Requires-Dist: pytest-mypy ; extra == 'testing'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'testing'
+Requires-Dist: portend ; extra == 'testing'
+
+.. image:: https://img.shields.io/pypi/v/jaraco.context.svg
+   :target: https://pypi.org/project/jaraco.context
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg
+
+.. image:: https://github.com/jaraco/jaraco.context/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest
+   :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.context
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme
+
+
+Highlights
+==========
+
+See the docs linked from the badge above for the full details, but here are some features that may be of interest.
+
+- ``ExceptionTrap`` provides a general-purpose wrapper for trapping exceptions and then acting on the outcome. Includes ``passes`` and ``raises`` decorators to replace the result of a wrapped function by a boolean indicating the outcome of the exception trap. See `this keyring commit `_ for an example of it in production.
+- ``suppress`` simply enables ``contextlib.suppress`` as a decorator.
+- ``on_interrupt`` is a decorator used by CLI entry points to affect the handling of a ``KeyboardInterrupt``. Inspired by `Lucretiel/autocommand#18 `_.
+- ``pushd`` is similar to pytest's ``monkeypatch.chdir`` or path's `default context `_, changes the current working directory for the duration of the context.
+- ``tarball`` will download a tarball, extract it, change directory, yield, then clean up after. Convenient when working with web assets.
+- ``null`` is there for those times when one code branch needs a context and the other doesn't; this null context provides symmetry across those branches.
+
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..09d191f214a1b83403df2ba891b21f5be94134dc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/RECORD
@@ -0,0 +1,8 @@
+jaraco.context-5.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+jaraco.context-5.3.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+jaraco.context-5.3.0.dist-info/METADATA,sha256=xDtguJej0tN9iEXCUvxEJh2a7xceIRVBEakBLSr__tY,4020
+jaraco.context-5.3.0.dist-info/RECORD,,
+jaraco.context-5.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+jaraco.context-5.3.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
+jaraco/__pycache__/context.cpython-312.pyc,,
+jaraco/context.py,sha256=REoLIxDkO5MfEYowt_WoupNCRoxBS5v7YX2PbW8lIcs,9552
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.context-5.3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+jaraco
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..c865140ab2971d078e8605fa22d8e4a27c2fecff
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/METADATA
@@ -0,0 +1,64 @@
+Metadata-Version: 2.1
+Name: jaraco.functools
+Version: 4.0.1
+Summary: Functools like those found in stdlib
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/jaraco.functools
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: more-itertools
+Provides-Extra: docs
+Requires-Dist: sphinx >=3.5 ; extra == 'docs'
+Requires-Dist: sphinx <7.2.5 ; extra == 'docs'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'docs'
+Requires-Dist: rst.linker >=1.9 ; extra == 'docs'
+Requires-Dist: furo ; extra == 'docs'
+Requires-Dist: sphinx-lint ; extra == 'docs'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'docs'
+Provides-Extra: testing
+Requires-Dist: pytest >=6 ; extra == 'testing'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'testing'
+Requires-Dist: pytest-cov ; extra == 'testing'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'testing'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'testing'
+Requires-Dist: jaraco.classes ; extra == 'testing'
+Requires-Dist: pytest-mypy ; (platform_python_implementation != "PyPy") and extra == 'testing'
+
+.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg
+   :target: https://pypi.org/project/jaraco.functools
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg
+
+.. image:: https://github.com/jaraco/jaraco.functools/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest
+   :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.functools
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.functools?utm_source=pypi-jaraco.functools&utm_medium=readme
+
+Additional functools in the spirit of stdlib's functools.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..ef3bc21e929e6881fc560bdef1505ed44bf838e1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/RECORD
@@ -0,0 +1,10 @@
+jaraco.functools-4.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+jaraco.functools-4.0.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+jaraco.functools-4.0.1.dist-info/METADATA,sha256=i4aUaQDX-jjdEQK5wevhegyx8JyLfin2HyvaSk3FHso,2891
+jaraco.functools-4.0.1.dist-info/RECORD,,
+jaraco.functools-4.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+jaraco.functools-4.0.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
+jaraco/functools/__init__.py,sha256=hEAJaS2uSZRuF_JY4CxCHIYh79ZpxaPp9OiHyr9EJ1w,16642
+jaraco/functools/__init__.pyi,sha256=gk3dsgHzo5F_U74HzAvpNivFAPCkPJ1b2-yCd62dfnw,3878
+jaraco/functools/__pycache__/__init__.cpython-312.pyc,,
+jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.functools-4.0.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+jaraco
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..0258a380f4acb6abb3b9e8d1bea70836b69a2559
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/METADATA
@@ -0,0 +1,95 @@
+Metadata-Version: 2.1
+Name: jaraco.text
+Version: 3.12.1
+Summary: Module for text manipulation
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/jaraco.text
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: jaraco.functools
+Requires-Dist: jaraco.context >=4.1
+Requires-Dist: autocommand
+Requires-Dist: inflect
+Requires-Dist: more-itertools
+Requires-Dist: importlib-resources ; python_version < "3.9"
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test'
+Requires-Dist: pathlib2 ; (python_version < "3.10") and extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/jaraco.text.svg
+   :target: https://pypi.org/project/jaraco.text
+
+.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg
+
+.. image:: https://github.com/jaraco/jaraco.text/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest
+   :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/jaraco.text
+   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=readme
+
+
+This package provides handy routines for dealing with text, such as
+wrapping, substitution, trimming, stripping, prefix and suffix removal,
+line continuation, indentation, comment processing, identifier processing,
+values parsing, case insensitive comparison, and more. See the docs
+(linked in the badge above) for the detailed documentation and examples.
+
+Layouts
+=======
+
+One of the features of this package is the layouts module, which
+provides a simple example of translating keystrokes from one keyboard
+layout to another::
+
+    echo qwerty | python -m jaraco.text.to-dvorak
+    ',.pyf
+    echo  "',.pyf" | python -m jaraco.text.to-qwerty
+    qwerty
+
+Newline Reporting
+=================
+
+Need to know what newlines appear in a file?
+
+::
+
+    $ python -m jaraco.text.show-newlines README.rst
+    newline is '\n'
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..19e2d8402af9356a13a1335ef2b71222b0aadeec
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/RECORD
@@ -0,0 +1,20 @@
+jaraco.text-3.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+jaraco.text-3.12.1.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+jaraco.text-3.12.1.dist-info/METADATA,sha256=AzWdm6ViMfDOPoQMfLWn2zgBQSGJScyqeN29TcuWXVI,3658
+jaraco.text-3.12.1.dist-info/RECORD,,
+jaraco.text-3.12.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jaraco.text-3.12.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+jaraco.text-3.12.1.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
+jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335
+jaraco/text/__init__.py,sha256=Y2YUqXR_orUoDaY4SkPRe6ZZhb5HUHB_Ah9RCNsVyho,16250
+jaraco/text/__pycache__/__init__.cpython-312.pyc,,
+jaraco/text/__pycache__/layouts.cpython-312.pyc,,
+jaraco/text/__pycache__/show-newlines.cpython-312.pyc,,
+jaraco/text/__pycache__/strip-prefix.cpython-312.pyc,,
+jaraco/text/__pycache__/to-dvorak.cpython-312.pyc,,
+jaraco/text/__pycache__/to-qwerty.cpython-312.pyc,,
+jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643
+jaraco/text/show-newlines.py,sha256=WGQa65e8lyhb92LUOLqVn6KaCtoeVgVws6WtSRmLk6w,904
+jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412
+jaraco/text/to-dvorak.py,sha256=1SNcbSsvISpXXg-LnybIHHY-RUFOQr36zcHkY1pWFqw,119
+jaraco/text/to-qwerty.py,sha256=s4UMQUnPwFn_dB5uZC27BurHOQcYondBfzIpVL5pEzw,119
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco.text-3.12.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+jaraco
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/collections/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/collections/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d501cf9e9cef5859f3c1bf844bc7280ce1e7aaa
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/collections/__init__.py
@@ -0,0 +1,1091 @@
+from __future__ import annotations
+
+import collections.abc
+import copy
+import functools
+import itertools
+import operator
+import random
+import re
+from collections.abc import Container, Iterable, Mapping
+from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar, Union, overload
+
+import jaraco.text
+
+if TYPE_CHECKING:
+    from _operator import _SupportsComparison
+
+    from _typeshed import SupportsKeysAndGetItem
+    from typing_extensions import Self
+
+    _RangeMapKT = TypeVar('_RangeMapKT', bound=_SupportsComparison)
+else:
+    # _SupportsComparison doesn't exist at runtime,
+    # but _RangeMapKT is used in RangeMap's superclass' type parameters
+    _RangeMapKT = TypeVar('_RangeMapKT')
+
+_T = TypeVar('_T')
+_VT = TypeVar('_VT')
+
+_Matchable = Union[Callable, Container, Iterable, re.Pattern]
+
+
+def _dispatch(obj: _Matchable) -> Callable:
+    # can't rely on singledispatch for Union[Container, Iterable]
+    # due to ambiguity
+    # (https://peps.python.org/pep-0443/#abstract-base-classes).
+    if isinstance(obj, re.Pattern):
+        return obj.fullmatch
+    # mypy issue: https://github.com/python/mypy/issues/11071
+    if not isinstance(obj, Callable):  # type: ignore[arg-type]
+        if not isinstance(obj, Container):
+            obj = set(obj)  # type: ignore[arg-type]
+        obj = obj.__contains__
+    return obj  # type: ignore[return-value]
+
+
+class Projection(collections.abc.Mapping):
+    """
+    Project a set of keys over a mapping
+
+    >>> sample = {'a': 1, 'b': 2, 'c': 3}
+    >>> prj = Projection(['a', 'c', 'd'], sample)
+    >>> dict(prj)
+    {'a': 1, 'c': 3}
+
+    Projection also accepts an iterable or callable or pattern.
+
+    >>> iter_prj = Projection(iter('acd'), sample)
+    >>> call_prj = Projection(lambda k: ord(k) in (97, 99, 100), sample)
+    >>> pat_prj = Projection(re.compile(r'[acd]'), sample)
+    >>> prj == iter_prj == call_prj == pat_prj
+    True
+
+    Keys should only appear if they were specified and exist in the space.
+    Order is retained.
+
+    >>> list(prj)
+    ['a', 'c']
+
+    Attempting to access a key not in the projection
+    results in a KeyError.
+
+    >>> prj['b']
+    Traceback (most recent call last):
+    ...
+    KeyError: 'b'
+
+    Use the projection to update another dict.
+
+    >>> target = {'a': 2, 'b': 2}
+    >>> target.update(prj)
+    >>> target
+    {'a': 1, 'b': 2, 'c': 3}
+
+    Projection keeps a reference to the original dict, so
+    modifying the original dict may modify the Projection.
+
+    >>> del sample['a']
+    >>> dict(prj)
+    {'c': 3}
+    """
+
+    def __init__(self, keys: _Matchable, space: Mapping):
+        self._match = _dispatch(keys)
+        self._space = space
+
+    def __getitem__(self, key):
+        if not self._match(key):
+            raise KeyError(key)
+        return self._space[key]
+
+    def _keys_resolved(self):
+        return filter(self._match, self._space)
+
+    def __iter__(self):
+        return self._keys_resolved()
+
+    def __len__(self):
+        return len(tuple(self._keys_resolved()))
+
+
+class Mask(Projection):
+    """
+    The inverse of a :class:`Projection`, masking out keys.
+
+    >>> sample = {'a': 1, 'b': 2, 'c': 3}
+    >>> msk = Mask(['a', 'c', 'd'], sample)
+    >>> dict(msk)
+    {'b': 2}
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        # self._match = compose(operator.not_, self._match)
+        self._match = lambda key, orig=self._match: not orig(key)
+
+
+def dict_map(function, dictionary):
+    """
+    Return a new dict with function applied to values of dictionary.
+
+    >>> dict_map(lambda x: x+1, dict(a=1, b=2))
+    {'a': 2, 'b': 3}
+    """
+    return dict((key, function(value)) for key, value in dictionary.items())
+
+
+class RangeMap(Dict[_RangeMapKT, _VT]):
+    """
+    A dictionary-like object that uses the keys as bounds for a range.
+    Inclusion of the value for that range is determined by the
+    key_match_comparator, which defaults to less-than-or-equal.
+    A value is returned for a key if it is the first key that matches in
+    the sorted list of keys.
+
+    One may supply keyword parameters to be passed to the sort function used
+    to sort keys (i.e. key, reverse) as sort_params.
+
+    Create a map that maps 1-3 -> 'a', 4-6 -> 'b'
+
+    >>> r = RangeMap({3: 'a', 6: 'b'})  # boy, that was easy
+    >>> r[1], r[2], r[3], r[4], r[5], r[6]
+    ('a', 'a', 'a', 'b', 'b', 'b')
+
+    Even float values should work so long as the comparison operator
+    supports it.
+
+    >>> r[4.5]
+    'b'
+
+    Notice that the way rangemap is defined, it must be open-ended
+    on one side.
+
+    >>> r[0]
+    'a'
+    >>> r[-1]
+    'a'
+
+    One can close the open-end of the RangeMap by using undefined_value
+
+    >>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
+    >>> r[0]
+    Traceback (most recent call last):
+    ...
+    KeyError: 0
+
+    One can get the first or last elements in the range by using RangeMap.Item
+
+    >>> last_item = RangeMap.Item(-1)
+    >>> r[last_item]
+    'b'
+
+    .last_item is a shortcut for Item(-1)
+
+    >>> r[RangeMap.last_item]
+    'b'
+
+    Sometimes it's useful to find the bounds for a RangeMap
+
+    >>> r.bounds()
+    (0, 6)
+
+    RangeMap supports .get(key, default)
+
+    >>> r.get(0, 'not found')
+    'not found'
+
+    >>> r.get(7, 'not found')
+    'not found'
+
+    One often wishes to define the ranges by their left-most values,
+    which requires use of sort params and a key_match_comparator.
+
+    >>> r = RangeMap({1: 'a', 4: 'b'},
+    ...     sort_params=dict(reverse=True),
+    ...     key_match_comparator=operator.ge)
+    >>> r[1], r[2], r[3], r[4], r[5], r[6]
+    ('a', 'a', 'a', 'b', 'b', 'b')
+
+    That wasn't nearly as easy as before, so an alternate constructor
+    is provided:
+
+    >>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value})
+    >>> r[1], r[2], r[3], r[4], r[5], r[6]
+    ('a', 'a', 'a', 'b', 'b', 'b')
+
+    """
+
+    def __init__(
+        self,
+        source: (
+            SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]
+        ),
+        sort_params: Mapping[str, Any] = {},
+        key_match_comparator: Callable[[_RangeMapKT, _RangeMapKT], bool] = operator.le,
+    ):
+        dict.__init__(self, source)
+        self.sort_params = sort_params
+        self.match = key_match_comparator
+
+    @classmethod
+    def left(
+        cls,
+        source: (
+            SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]
+        ),
+    ) -> Self:
+        return cls(
+            source, sort_params=dict(reverse=True), key_match_comparator=operator.ge
+        )
+
+    def __getitem__(self, item: _RangeMapKT) -> _VT:
+        sorted_keys = sorted(self.keys(), **self.sort_params)
+        if isinstance(item, RangeMap.Item):
+            result = self.__getitem__(sorted_keys[item])
+        else:
+            key = self._find_first_match_(sorted_keys, item)
+            result = dict.__getitem__(self, key)
+            if result is RangeMap.undefined_value:
+                raise KeyError(key)
+        return result
+
+    @overload  # type: ignore[override] # Signature simplified over dict and Mapping
+    def get(self, key: _RangeMapKT, default: _T) -> _VT | _T: ...
+    @overload
+    def get(self, key: _RangeMapKT, default: None = None) -> _VT | None: ...
+    def get(self, key: _RangeMapKT, default: _T | None = None) -> _VT | _T | None:
+        """
+        Return the value for key if key is in the dictionary, else default.
+        If default is not given, it defaults to None, so that this method
+        never raises a KeyError.
+        """
+        try:
+            return self[key]
+        except KeyError:
+            return default
+
+    def _find_first_match_(
+        self, keys: Iterable[_RangeMapKT], item: _RangeMapKT
+    ) -> _RangeMapKT:
+        is_match = functools.partial(self.match, item)
+        matches = filter(is_match, keys)
+        try:
+            return next(matches)
+        except StopIteration:
+            raise KeyError(item) from None
+
+    def bounds(self) -> tuple[_RangeMapKT, _RangeMapKT]:
+        sorted_keys = sorted(self.keys(), **self.sort_params)
+        return (sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item])
+
+    # some special values for the RangeMap
+    undefined_value = type('RangeValueUndefined', (), {})()
+
+    class Item(int):
+        """RangeMap Item"""
+
+    first_item = Item(0)
+    last_item = Item(-1)
+
+
+def __identity(x):
+    return x
+
+
+def sorted_items(d, key=__identity, reverse=False):
+    """
+    Return the items of the dictionary sorted by the keys.
+
+    >>> sample = dict(foo=20, bar=42, baz=10)
+    >>> tuple(sorted_items(sample))
+    (('bar', 42), ('baz', 10), ('foo', 20))
+
+    >>> reverse_string = lambda s: ''.join(reversed(s))
+    >>> tuple(sorted_items(sample, key=reverse_string))
+    (('foo', 20), ('bar', 42), ('baz', 10))
+
+    >>> tuple(sorted_items(sample, reverse=True))
+    (('foo', 20), ('baz', 10), ('bar', 42))
+    """
+
+    # wrap the key func so it operates on the first element of each item
+    def pairkey_key(item):
+        return key(item[0])
+
+    return sorted(d.items(), key=pairkey_key, reverse=reverse)
+
+
+class KeyTransformingDict(dict):
+    """
+    A dict subclass that transforms the keys before they're used.
+    Subclasses may override the default transform_key to customize behavior.
+    """
+
+    @staticmethod
+    def transform_key(key):  # pragma: nocover
+        return key
+
+    def __init__(self, *args, **kargs):
+        super().__init__()
+        # build a dictionary using the default constructs
+        d = dict(*args, **kargs)
+        # build this dictionary using transformed keys.
+        for item in d.items():
+            self.__setitem__(*item)
+
+    def __setitem__(self, key, val):
+        key = self.transform_key(key)
+        super().__setitem__(key, val)
+
+    def __getitem__(self, key):
+        key = self.transform_key(key)
+        return super().__getitem__(key)
+
+    def __contains__(self, key):
+        key = self.transform_key(key)
+        return super().__contains__(key)
+
+    def __delitem__(self, key):
+        key = self.transform_key(key)
+        return super().__delitem__(key)
+
+    def get(self, key, *args, **kwargs):
+        key = self.transform_key(key)
+        return super().get(key, *args, **kwargs)
+
+    def setdefault(self, key, *args, **kwargs):
+        key = self.transform_key(key)
+        return super().setdefault(key, *args, **kwargs)
+
+    def pop(self, key, *args, **kwargs):
+        key = self.transform_key(key)
+        return super().pop(key, *args, **kwargs)
+
+    def matching_key_for(self, key):
+        """
+        Given a key, return the actual key stored in self that matches.
+        Raise KeyError if the key isn't found.
+        """
+        try:
+            return next(e_key for e_key in self.keys() if e_key == key)
+        except StopIteration as err:
+            raise KeyError(key) from err
+
+
+class FoldedCaseKeyedDict(KeyTransformingDict):
+    """
+    A case-insensitive dictionary (keys are compared as insensitive
+    if they are strings).
+
+    >>> d = FoldedCaseKeyedDict()
+    >>> d['heLlo'] = 'world'
+    >>> list(d.keys()) == ['heLlo']
+    True
+    >>> list(d.values()) == ['world']
+    True
+    >>> d['hello'] == 'world'
+    True
+    >>> 'hello' in d
+    True
+    >>> 'HELLO' in d
+    True
+    >>> print(repr(FoldedCaseKeyedDict({'heLlo': 'world'})))
+    {'heLlo': 'world'}
+    >>> d = FoldedCaseKeyedDict({'heLlo': 'world'})
+    >>> print(d['hello'])
+    world
+    >>> print(d['Hello'])
+    world
+    >>> list(d.keys())
+    ['heLlo']
+    >>> d = FoldedCaseKeyedDict({'heLlo': 'world', 'Hello': 'world'})
+    >>> list(d.values())
+    ['world']
+    >>> key, = d.keys()
+    >>> key in ['heLlo', 'Hello']
+    True
+    >>> del d['HELLO']
+    >>> d
+    {}
+
+    get should work
+
+    >>> d['Sumthin'] = 'else'
+    >>> d.get('SUMTHIN')
+    'else'
+    >>> d.get('OTHER', 'thing')
+    'thing'
+    >>> del d['sumthin']
+
+    setdefault should also work
+
+    >>> d['This'] = 'that'
+    >>> print(d.setdefault('this', 'other'))
+    that
+    >>> len(d)
+    1
+    >>> print(d['this'])
+    that
+    >>> print(d.setdefault('That', 'other'))
+    other
+    >>> print(d['THAT'])
+    other
+
+    Make it pop!
+
+    >>> print(d.pop('THAT'))
+    other
+
+    To retrieve the key in its originally-supplied form, use matching_key_for
+
+    >>> print(d.matching_key_for('this'))
+    This
+
+    >>> d.matching_key_for('missing')
+    Traceback (most recent call last):
+    ...
+    KeyError: 'missing'
+    """
+
+    @staticmethod
+    def transform_key(key):
+        return jaraco.text.FoldedCase(key)
+
+
+class DictAdapter:
+    """
+    Provide a getitem interface for attributes of an object.
+
+    Let's say you want to get at the string.lowercase property in a formatted
+    string. It's easy with DictAdapter.
+
+    >>> import string
+    >>> print("lowercase is %(ascii_lowercase)s" % DictAdapter(string))
+    lowercase is abcdefghijklmnopqrstuvwxyz
+    """
+
+    def __init__(self, wrapped_ob):
+        self.object = wrapped_ob
+
+    def __getitem__(self, name):
+        return getattr(self.object, name)
+
+
+class ItemsAsAttributes:
+    """
+    Mix-in class to enable a mapping object to provide items as
+    attributes.
+
+    >>> C = type('C', (dict, ItemsAsAttributes), dict())
+    >>> i = C()
+    >>> i['foo'] = 'bar'
+    >>> i.foo
+    'bar'
+
+    Natural attribute access takes precedence
+
+    >>> i.foo = 'henry'
+    >>> i.foo
+    'henry'
+
+    But as you might expect, the mapping functionality is preserved.
+
+    >>> i['foo']
+    'bar'
+
+    A normal attribute error should be raised if an attribute is
+    requested that doesn't exist.
+
+    >>> i.missing
+    Traceback (most recent call last):
+    ...
+    AttributeError: 'C' object has no attribute 'missing'
+
+    It also works on dicts that customize __getitem__
+
+    >>> missing_func = lambda self, key: 'missing item'
+    >>> C = type(
+    ...     'C',
+    ...     (dict, ItemsAsAttributes),
+    ...     dict(__missing__ = missing_func),
+    ... )
+    >>> i = C()
+    >>> i.missing
+    'missing item'
+    >>> i.foo
+    'missing item'
+    """
+
+    def __getattr__(self, key):
+        try:
+            return getattr(super(), key)
+        except AttributeError as e:
+            # attempt to get the value from the mapping (return self[key])
+            #  but be careful not to lose the original exception context.
+            noval = object()
+
+            def _safe_getitem(cont, key, missing_result):
+                try:
+                    return cont[key]
+                except KeyError:
+                    return missing_result
+
+            result = _safe_getitem(self, key, noval)
+            if result is not noval:
+                return result
+            # raise the original exception, but use the original class
+            #  name, not 'super'.
+            (message,) = e.args
+            message = message.replace('super', self.__class__.__name__, 1)
+            e.args = (message,)
+            raise
+
+
+def invert_map(map):
+    """
+    Given a dictionary, return another dictionary with keys and values
+    switched. If any of the values resolve to the same key, raises
+    a ValueError.
+
+    >>> numbers = dict(a=1, b=2, c=3)
+    >>> letters = invert_map(numbers)
+    >>> letters[1]
+    'a'
+    >>> numbers['d'] = 3
+    >>> invert_map(numbers)
+    Traceback (most recent call last):
+    ...
+    ValueError: Key conflict in inverted mapping
+    """
+    res = dict((v, k) for k, v in map.items())
+    if not len(res) == len(map):
+        raise ValueError('Key conflict in inverted mapping')
+    return res
+
+
+class IdentityOverrideMap(dict):
+    """
+    A dictionary that by default maps each key to itself, but otherwise
+    acts like a normal dictionary.
+
+    >>> d = IdentityOverrideMap()
+    >>> d[42]
+    42
+    >>> d['speed'] = 'speedo'
+    >>> print(d['speed'])
+    speedo
+    """
+
+    def __missing__(self, key):
+        return key
+
+
+class DictStack(list, collections.abc.MutableMapping):
+    """
+    A stack of dictionaries that behaves as a view on those dictionaries,
+    giving preference to the last.
+
+    >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
+    >>> stack['a']
+    2
+    >>> stack['b']
+    2
+    >>> stack['c']
+    2
+    >>> len(stack)
+    3
+    >>> stack.push(dict(a=3))
+    >>> stack['a']
+    3
+    >>> stack['a'] = 4
+    >>> set(stack.keys()) == set(['a', 'b', 'c'])
+    True
+    >>> set(stack.items()) == set([('a', 4), ('b', 2), ('c', 2)])
+    True
+    >>> dict(**stack) == dict(stack) == dict(a=4, c=2, b=2)
+    True
+    >>> d = stack.pop()
+    >>> stack['a']
+    2
+    >>> d = stack.pop()
+    >>> stack['a']
+    1
+    >>> stack.get('b', None)
+    >>> 'c' in stack
+    True
+    >>> del stack['c']
+    >>> dict(stack)
+    {'a': 1}
+    """
+
+    def __iter__(self):
+        dicts = list.__iter__(self)
+        return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
+
+    def __getitem__(self, key):
+        for scope in reversed(tuple(list.__iter__(self))):
+            if key in scope:
+                return scope[key]
+        raise KeyError(key)
+
+    push = list.append
+
+    def __contains__(self, other):
+        return collections.abc.Mapping.__contains__(self, other)
+
+    def __len__(self):
+        return len(list(iter(self)))
+
+    def __setitem__(self, key, item):
+        last = list.__getitem__(self, -1)
+        return last.__setitem__(key, item)
+
+    def __delitem__(self, key):
+        last = list.__getitem__(self, -1)
+        return last.__delitem__(key)
+
+    # workaround for mypy confusion
+    def pop(self, *args, **kwargs):
+        return list.pop(self, *args, **kwargs)
+
+
+class BijectiveMap(dict):
+    """
+    A Bijective Map (two-way mapping).
+
+    Implemented as a simple dictionary of 2x the size, mapping values back
+    to keys.
+
+    Note, this implementation may be incomplete. If there's not a test for
+    your use case below, it's likely to fail, so please test and send pull
+    requests or patches for additional functionality needed.
+
+
+    >>> m = BijectiveMap()
+    >>> m['a'] = 'b'
+    >>> m == {'a': 'b', 'b': 'a'}
+    True
+    >>> print(m['b'])
+    a
+
+    >>> m['c'] = 'd'
+    >>> len(m)
+    2
+
+    Some weird things happen if you map an item to itself or overwrite a
+    single key of a pair, so it's disallowed.
+
+    >>> m['e'] = 'e'
+    Traceback (most recent call last):
+    ValueError: Key cannot map to itself
+
+    >>> m['d'] = 'e'
+    Traceback (most recent call last):
+    ValueError: Key/Value pairs may not overlap
+
+    >>> m['e'] = 'd'
+    Traceback (most recent call last):
+    ValueError: Key/Value pairs may not overlap
+
+    >>> print(m.pop('d'))
+    c
+
+    >>> 'c' in m
+    False
+
+    >>> m = BijectiveMap(dict(a='b'))
+    >>> len(m)
+    1
+    >>> print(m['b'])
+    a
+
+    >>> m = BijectiveMap()
+    >>> m.update(a='b')
+    >>> m['b']
+    'a'
+
+    >>> del m['b']
+    >>> len(m)
+    0
+    >>> 'a' in m
+    False
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__()
+        self.update(*args, **kwargs)
+
+    def __setitem__(self, item, value):
+        if item == value:
+            raise ValueError("Key cannot map to itself")
+        overlap = (
+            item in self
+            and self[item] != value
+            or value in self
+            and self[value] != item
+        )
+        if overlap:
+            raise ValueError("Key/Value pairs may not overlap")
+        super().__setitem__(item, value)
+        super().__setitem__(value, item)
+
+    def __delitem__(self, item):
+        self.pop(item)
+
+    def __len__(self):
+        return super().__len__() // 2
+
+    def pop(self, key, *args, **kwargs):
+        mirror = self[key]
+        super().__delitem__(mirror)
+        return super().pop(key, *args, **kwargs)
+
+    def update(self, *args, **kwargs):
+        # build a dictionary using the default constructs
+        d = dict(*args, **kwargs)
+        # build this dictionary using transformed keys.
+        for item in d.items():
+            self.__setitem__(*item)
+
+
+class FrozenDict(collections.abc.Mapping, collections.abc.Hashable):
+    """
+    An immutable mapping.
+
+    >>> a = FrozenDict(a=1, b=2)
+    >>> b = FrozenDict(a=1, b=2)
+    >>> a == b
+    True
+
+    >>> a == dict(a=1, b=2)
+    True
+    >>> dict(a=1, b=2) == a
+    True
+    >>> 'a' in a
+    True
+    >>> type(hash(a)) is type(0)
+    True
+    >>> set(iter(a)) == {'a', 'b'}
+    True
+    >>> len(a)
+    2
+    >>> a['a'] == a.get('a') == 1
+    True
+
+    >>> a['c'] = 3
+    Traceback (most recent call last):
+    ...
+    TypeError: 'FrozenDict' object does not support item assignment
+
+    >>> a.update(y=3)
+    Traceback (most recent call last):
+    ...
+    AttributeError: 'FrozenDict' object has no attribute 'update'
+
+    Copies should compare equal
+
+    >>> copy.copy(a) == a
+    True
+
+    Copies should be the same type
+
+    >>> isinstance(copy.copy(a), FrozenDict)
+    True
+
+    FrozenDict supplies .copy(), even though
+    collections.abc.Mapping doesn't demand it.
+
+    >>> a.copy() == a
+    True
+    >>> a.copy() is not a
+    True
+    """
+
+    __slots__ = ['__data']
+
+    def __new__(cls, *args, **kwargs):
+        self = super().__new__(cls)
+        self.__data = dict(*args, **kwargs)
+        return self
+
+    # Container
+    def __contains__(self, key):
+        return key in self.__data
+
+    # Hashable
+    def __hash__(self):
+        return hash(tuple(sorted(self.__data.items())))
+
+    # Mapping
+    def __iter__(self):
+        return iter(self.__data)
+
+    def __len__(self):
+        return len(self.__data)
+
+    def __getitem__(self, key):
+        return self.__data[key]
+
+    # override get for efficiency provided by dict
+    def get(self, *args, **kwargs):
+        return self.__data.get(*args, **kwargs)
+
+    # override eq to recognize underlying implementation
+    def __eq__(self, other):
+        if isinstance(other, FrozenDict):
+            other = other.__data
+        return self.__data.__eq__(other)
+
+    def copy(self):
+        "Return a shallow copy of self"
+        return copy.copy(self)
+
+
+class Enumeration(ItemsAsAttributes, BijectiveMap):
+    """
+    A convenient way to provide enumerated values
+
+    >>> e = Enumeration('a b c')
+    >>> e['a']
+    0
+
+    >>> e.a
+    0
+
+    >>> e[1]
+    'b'
+
+    >>> set(e.names) == set('abc')
+    True
+
+    >>> set(e.codes) == set(range(3))
+    True
+
+    >>> e.get('d') is None
+    True
+
+    Codes need not start with 0
+
+    >>> e = Enumeration('a b c', range(1, 4))
+    >>> e['a']
+    1
+
+    >>> e[3]
+    'c'
+    """
+
+    def __init__(self, names, codes=None):
+        if isinstance(names, str):
+            names = names.split()
+        if codes is None:
+            codes = itertools.count()
+        super().__init__(zip(names, codes))
+
+    @property
+    def names(self):
+        return (key for key in self if isinstance(key, str))
+
+    @property
+    def codes(self):
+        return (self[name] for name in self.names)
+
+
+class Everything:
+    """
+    A collection "containing" every possible thing.
+
+    >>> 'foo' in Everything()
+    True
+
+    >>> import random
+    >>> random.randint(1, 999) in Everything()
+    True
+
+    >>> random.choice([None, 'foo', 42, ('a', 'b', 'c')]) in Everything()
+    True
+    """
+
+    def __contains__(self, other):
+        return True
+
+
+class InstrumentedDict(collections.UserDict):
+    """
+    Instrument an existing dictionary with additional
+    functionality, but always reference and mutate
+    the original dictionary.
+
+    >>> orig = {'a': 1, 'b': 2}
+    >>> inst = InstrumentedDict(orig)
+    >>> inst['a']
+    1
+    >>> inst['c'] = 3
+    >>> orig['c']
+    3
+    >>> inst.keys() == orig.keys()
+    True
+    """
+
+    def __init__(self, data):
+        super().__init__()
+        self.data = data
+
+
+class Least:
+    """
+    A value that is always lesser than any other
+
+    >>> least = Least()
+    >>> 3 < least
+    False
+    >>> 3 > least
+    True
+    >>> least < 3
+    True
+    >>> least <= 3
+    True
+    >>> least > 3
+    False
+    >>> 'x' > least
+    True
+    >>> None > least
+    True
+    """
+
+    def __le__(self, other):
+        return True
+
+    __lt__ = __le__
+
+    def __ge__(self, other):
+        return False
+
+    __gt__ = __ge__
+
+
+class Greatest:
+    """
+    A value that is always greater than any other
+
+    >>> greatest = Greatest()
+    >>> 3 < greatest
+    True
+    >>> 3 > greatest
+    False
+    >>> greatest < 3
+    False
+    >>> greatest > 3
+    True
+    >>> greatest >= 3
+    True
+    >>> 'x' > greatest
+    False
+    >>> None > greatest
+    False
+    """
+
+    def __ge__(self, other):
+        return True
+
+    __gt__ = __ge__
+
+    def __le__(self, other):
+        return False
+
+    __lt__ = __le__
+
+
+def pop_all(items):
+    """
+    Clear items in place and return a copy of items.
+
+    >>> items = [1, 2, 3]
+    >>> popped = pop_all(items)
+    >>> popped is items
+    False
+    >>> popped
+    [1, 2, 3]
+    >>> items
+    []
+    """
+    result, items[:] = items[:], []
+    return result
+
+
+class FreezableDefaultDict(collections.defaultdict):
+    """
+    Often it is desirable to prevent the mutation of
+    a default dict after its initial construction, such
+    as to prevent mutation during iteration.
+
+    >>> dd = FreezableDefaultDict(list)
+    >>> dd[0].append('1')
+    >>> dd.freeze()
+    >>> dd[1]
+    []
+    >>> len(dd)
+    1
+    """
+
+    def __missing__(self, key):
+        return getattr(self, '_frozen', super().__missing__)(key)
+
+    def freeze(self):
+        self._frozen = lambda key: self.default_factory()
+
+
+class Accumulator:
+    def __init__(self, initial=0):
+        self.val = initial
+
+    def __call__(self, val):
+        self.val += val
+        return self.val
+
+
+class WeightedLookup(RangeMap):
+    """
+    Given parameters suitable for a dict representing keys
+    and a weighted proportion, return a RangeMap representing
+    spans of values proportial to the weights:
+
+    >>> even = WeightedLookup(a=1, b=1)
+
+    [0, 1) -> a
+    [1, 2) -> b
+
+    >>> lk = WeightedLookup(a=1, b=2)
+
+    [0, 1) -> a
+    [1, 3) -> b
+
+    >>> lk[.5]
+    'a'
+    >>> lk[1.5]
+    'b'
+
+    Adds ``.random()`` to select a random weighted value:
+
+    >>> lk.random() in ['a', 'b']
+    True
+
+    >>> choices = [lk.random() for x in range(1000)]
+
+    Statistically speaking, choices should be .5 a:b
+    >>> ratio = choices.count('a') / choices.count('b')
+    >>> .4 < ratio < .6
+    True
+    """
+
+    def __init__(self, *args, **kwargs):
+        raw = dict(*args, **kwargs)
+
+        # allocate keys by weight
+        indexes = map(Accumulator(), raw.values())
+        super().__init__(zip(indexes, raw.keys()), key_match_comparator=operator.lt)
+
+    def random(self):
+        lower, upper = self.bounds()
+        selector = random.random() * upper
+        return self[selector]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/collections/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/collections/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/context.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..61b27135df1fc5504622ad69875249c87947e453
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/context.py
@@ -0,0 +1,361 @@
+from __future__ import annotations
+
+import contextlib
+import functools
+import operator
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import urllib.request
+import warnings
+from typing import Iterator
+
+
+if sys.version_info < (3, 12):
+    from backports import tarfile
+else:
+    import tarfile
+
+
+@contextlib.contextmanager
+def pushd(dir: str | os.PathLike) -> Iterator[str | os.PathLike]:
+    """
+    >>> tmp_path = getfixture('tmp_path')
+    >>> with pushd(tmp_path):
+    ...     assert os.getcwd() == os.fspath(tmp_path)
+    >>> assert os.getcwd() != os.fspath(tmp_path)
+    """
+
+    orig = os.getcwd()
+    os.chdir(dir)
+    try:
+        yield dir
+    finally:
+        os.chdir(orig)
+
+
+@contextlib.contextmanager
+def tarball(
+    url, target_dir: str | os.PathLike | None = None
+) -> Iterator[str | os.PathLike]:
+    """
+    Get a tarball, extract it, yield, then clean up.
+
+    >>> import urllib.request
+    >>> url = getfixture('tarfile_served')
+    >>> target = getfixture('tmp_path') / 'out'
+    >>> tb = tarball(url, target_dir=target)
+    >>> import pathlib
+    >>> with tb as extracted:
+    ...     contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8')
+    >>> assert not os.path.exists(extracted)
+    """
+    if target_dir is None:
+        target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '')
+    # In the tar command, use --strip-components=1 to strip the first path and
+    #  then
+    #  use -C to cause the files to be extracted to {target_dir}. This ensures
+    #  that we always know where the files were extracted.
+    os.mkdir(target_dir)
+    try:
+        req = urllib.request.urlopen(url)
+        with tarfile.open(fileobj=req, mode='r|*') as tf:
+            tf.extractall(path=target_dir, filter=strip_first_component)
+        yield target_dir
+    finally:
+        shutil.rmtree(target_dir)
+
+
+def strip_first_component(
+    member: tarfile.TarInfo,
+    path,
+) -> tarfile.TarInfo:
+    _, member.name = member.name.split('/', 1)
+    return member
+
+
+def _compose(*cmgrs):
+    """
+    Compose any number of dependent context managers into a single one.
+
+    The last, innermost context manager may take arbitrary arguments, but
+    each successive context manager should accept the result from the
+    previous as a single parameter.
+
+    Like :func:`jaraco.functools.compose`, behavior works from right to
+    left, so the context manager should be indicated from outermost to
+    innermost.
+
+    Example, to create a context manager to change to a temporary
+    directory:
+
+    >>> temp_dir_as_cwd = _compose(pushd, temp_dir)
+    >>> with temp_dir_as_cwd() as dir:
+    ...     assert os.path.samefile(os.getcwd(), dir)
+    """
+
+    def compose_two(inner, outer):
+        def composed(*args, **kwargs):
+            with inner(*args, **kwargs) as saved, outer(saved) as res:
+                yield res
+
+        return contextlib.contextmanager(composed)
+
+    return functools.reduce(compose_two, reversed(cmgrs))
+
+
+tarball_cwd = _compose(pushd, tarball)
+
+
+@contextlib.contextmanager
+def tarball_context(*args, **kwargs):
+    warnings.warn(
+        "tarball_context is deprecated. Use tarball or tarball_cwd instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    pushd_ctx = kwargs.pop('pushd', pushd)
+    with tarball(*args, **kwargs) as tball, pushd_ctx(tball) as dir:
+        yield dir
+
+
+def infer_compression(url):
+    """
+    Given a URL or filename, infer the compression code for tar.
+
+    >>> infer_compression('http://foo/bar.tar.gz')
+    'z'
+    >>> infer_compression('http://foo/bar.tgz')
+    'z'
+    >>> infer_compression('file.bz')
+    'j'
+    >>> infer_compression('file.xz')
+    'J'
+    """
+    warnings.warn(
+        "infer_compression is deprecated with no replacement",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    # cheat and just assume it's the last two characters
+    compression_indicator = url[-2:]
+    mapping = dict(gz='z', bz='j', xz='J')
+    # Assume 'z' (gzip) if no match
+    return mapping.get(compression_indicator, 'z')
+
+
+@contextlib.contextmanager
+def temp_dir(remover=shutil.rmtree):
+    """
+    Create a temporary directory context. Pass a custom remover
+    to override the removal behavior.
+
+    >>> import pathlib
+    >>> with temp_dir() as the_dir:
+    ...     assert os.path.isdir(the_dir)
+    ...     _ = pathlib.Path(the_dir).joinpath('somefile').write_text('contents', encoding='utf-8')
+    >>> assert not os.path.exists(the_dir)
+    """
+    temp_dir = tempfile.mkdtemp()
+    try:
+        yield temp_dir
+    finally:
+        remover(temp_dir)
+
+
+@contextlib.contextmanager
+def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):
+    """
+    Check out the repo indicated by url.
+
+    If dest_ctx is supplied, it should be a context manager
+    to yield the target directory for the check out.
+    """
+    exe = 'git' if 'git' in url else 'hg'
+    with dest_ctx() as repo_dir:
+        cmd = [exe, 'clone', url, repo_dir]
+        if branch:
+            cmd.extend(['--branch', branch])
+        devnull = open(os.path.devnull, 'w')
+        stdout = devnull if quiet else None
+        subprocess.check_call(cmd, stdout=stdout)
+        yield repo_dir
+
+
+def null():
+    """
+    A null context suitable to stand in for a meaningful context.
+
+    >>> with null() as value:
+    ...     assert value is None
+
+    This context is most useful when dealing with two or more code
+    branches but only some need a context. Wrap the others in a null
+    context to provide symmetry across all options.
+    """
+    warnings.warn(
+        "null is deprecated. Use contextlib.nullcontext",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    return contextlib.nullcontext()
+
+
+class ExceptionTrap:
+    """
+    A context manager that will catch certain exceptions and provide an
+    indication they occurred.
+
+    >>> with ExceptionTrap() as trap:
+    ...     raise Exception()
+    >>> bool(trap)
+    True
+
+    >>> with ExceptionTrap() as trap:
+    ...     pass
+    >>> bool(trap)
+    False
+
+    >>> with ExceptionTrap(ValueError) as trap:
+    ...     raise ValueError("1 + 1 is not 3")
+    >>> bool(trap)
+    True
+    >>> trap.value
+    ValueError('1 + 1 is not 3')
+    >>> trap.tb
+    
+
+    >>> with ExceptionTrap(ValueError) as trap:
+    ...     raise Exception()
+    Traceback (most recent call last):
+    ...
+    Exception
+
+    >>> bool(trap)
+    False
+    """
+
+    exc_info = None, None, None
+
+    def __init__(self, exceptions=(Exception,)):
+        self.exceptions = exceptions
+
+    def __enter__(self):
+        return self
+
+    @property
+    def type(self):
+        return self.exc_info[0]
+
+    @property
+    def value(self):
+        return self.exc_info[1]
+
+    @property
+    def tb(self):
+        return self.exc_info[2]
+
+    def __exit__(self, *exc_info):
+        type = exc_info[0]
+        matches = type and issubclass(type, self.exceptions)
+        if matches:
+            self.exc_info = exc_info
+        return matches
+
+    def __bool__(self):
+        return bool(self.type)
+
+    def raises(self, func, *, _test=bool):
+        """
+        Wrap func and replace the result with the truth
+        value of the trap (True if an exception occurred).
+
+        First, give the decorator an alias to support Python 3.8
+        Syntax.
+
+        >>> raises = ExceptionTrap(ValueError).raises
+
+        Now decorate a function that always fails.
+
+        >>> @raises
+        ... def fail():
+        ...     raise ValueError('failed')
+        >>> fail()
+        True
+        """
+
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            with ExceptionTrap(self.exceptions) as trap:
+                func(*args, **kwargs)
+            return _test(trap)
+
+        return wrapper
+
+    def passes(self, func):
+        """
+        Wrap func and replace the result with the truth
+        value of the trap (True if no exception).
+
+        First, give the decorator an alias to support Python 3.8
+        Syntax.
+
+        >>> passes = ExceptionTrap(ValueError).passes
+
+        Now decorate a function that always fails.
+
+        >>> @passes
+        ... def fail():
+        ...     raise ValueError('failed')
+
+        >>> fail()
+        False
+        """
+        return self.raises(func, _test=operator.not_)
+
+
+class suppress(contextlib.suppress, contextlib.ContextDecorator):
+    """
+    A version of contextlib.suppress with decorator support.
+
+    >>> @suppress(KeyError)
+    ... def key_error():
+    ...     {}['']
+    >>> key_error()
+    """
+
+
+class on_interrupt(contextlib.ContextDecorator):
+    """
+    Replace a KeyboardInterrupt with SystemExit(1)
+
+    >>> def do_interrupt():
+    ...     raise KeyboardInterrupt()
+    >>> on_interrupt('error')(do_interrupt)()
+    Traceback (most recent call last):
+    ...
+    SystemExit: 1
+    >>> on_interrupt('error', code=255)(do_interrupt)()
+    Traceback (most recent call last):
+    ...
+    SystemExit: 255
+    >>> on_interrupt('suppress')(do_interrupt)()
+    >>> with __import__('pytest').raises(KeyboardInterrupt):
+    ...     on_interrupt('ignore')(do_interrupt)()
+    """
+
+    def __init__(self, action='error', /, code=1):
+        self.action = action
+        self.code = code
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exctype, excinst, exctb):
+        if exctype is not KeyboardInterrupt or self.action == 'ignore':
+            return
+        elif self.action == 'error':
+            raise SystemExit(self.code) from excinst
+        return self.action == 'suppress'
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca6c22fa9ba2777507118fbfa38bc29ac2d84964
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.py
@@ -0,0 +1,633 @@
+import collections.abc
+import functools
+import inspect
+import itertools
+import operator
+import time
+import types
+import warnings
+
+import more_itertools
+
+
+def compose(*funcs):
+    """
+    Compose any number of unary functions into a single unary function.
+
+    >>> import textwrap
+    >>> expected = str.strip(textwrap.dedent(compose.__doc__))
+    >>> strip_and_dedent = compose(str.strip, textwrap.dedent)
+    >>> strip_and_dedent(compose.__doc__) == expected
+    True
+
+    Compose also allows the innermost function to take arbitrary arguments.
+
+    >>> round_three = lambda x: round(x, ndigits=3)
+    >>> f = compose(round_three, int.__truediv__)
+    >>> [f(3*x, x+1) for x in range(1,10)]
+    [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]
+    """
+
+    def compose_two(f1, f2):
+        return lambda *args, **kwargs: f1(f2(*args, **kwargs))
+
+    return functools.reduce(compose_two, funcs)
+
+
+def once(func):
+    """
+    Decorate func so it's only ever called the first time.
+
+    This decorator can ensure that an expensive or non-idempotent function
+    will not be expensive on subsequent calls and is idempotent.
+
+    >>> add_three = once(lambda a: a+3)
+    >>> add_three(3)
+    6
+    >>> add_three(9)
+    6
+    >>> add_three('12')
+    6
+
+    To reset the stored value, simply clear the property ``saved_result``.
+
+    >>> del add_three.saved_result
+    >>> add_three(9)
+    12
+    >>> add_three(8)
+    12
+
+    Or invoke 'reset()' on it.
+
+    >>> add_three.reset()
+    >>> add_three(-3)
+    0
+    >>> add_three(0)
+    0
+    """
+
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        if not hasattr(wrapper, 'saved_result'):
+            wrapper.saved_result = func(*args, **kwargs)
+        return wrapper.saved_result
+
+    wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')
+    return wrapper
+
+
+def method_cache(method, cache_wrapper=functools.lru_cache()):
+    """
+    Wrap lru_cache to support storing the cache data in the object instances.
+
+    Abstracts the common paradigm where the method explicitly saves an
+    underscore-prefixed protected property on first call and returns that
+    subsequently.
+
+    >>> class MyClass:
+    ...     calls = 0
+    ...
+    ...     @method_cache
+    ...     def method(self, value):
+    ...         self.calls += 1
+    ...         return value
+
+    >>> a = MyClass()
+    >>> a.method(3)
+    3
+    >>> for x in range(75):
+    ...     res = a.method(x)
+    >>> a.calls
+    75
+
+    Note that the apparent behavior will be exactly like that of lru_cache
+    except that the cache is stored on each instance, so values in one
+    instance will not flush values from another, and when an instance is
+    deleted, so are the cached values for that instance.
+
+    >>> b = MyClass()
+    >>> for x in range(35):
+    ...     res = b.method(x)
+    >>> b.calls
+    35
+    >>> a.method(0)
+    0
+    >>> a.calls
+    75
+
+    Note that if method had been decorated with ``functools.lru_cache()``,
+    a.calls would have been 76 (due to the cached value of 0 having been
+    flushed by the 'b' instance).
+
+    Clear the cache with ``.cache_clear()``
+
+    >>> a.method.cache_clear()
+
+    Same for a method that hasn't yet been called.
+
+    >>> c = MyClass()
+    >>> c.method.cache_clear()
+
+    Another cache wrapper may be supplied:
+
+    >>> cache = functools.lru_cache(maxsize=2)
+    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
+    >>> a = MyClass()
+    >>> a.method2()
+    3
+
+    Caution - do not subsequently wrap the method with another decorator, such
+    as ``@property``, which changes the semantics of the function.
+
+    See also
+    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
+    for another implementation and additional justification.
+    """
+
+    def wrapper(self, *args, **kwargs):
+        # it's the first call, replace the method with a cached, bound method
+        bound_method = types.MethodType(method, self)
+        cached_method = cache_wrapper(bound_method)
+        setattr(self, method.__name__, cached_method)
+        return cached_method(*args, **kwargs)
+
+    # Support cache clear even before cache has been created.
+    wrapper.cache_clear = lambda: None
+
+    return _special_method_cache(method, cache_wrapper) or wrapper
+
+
+def _special_method_cache(method, cache_wrapper):
+    """
+    Because Python treats special methods differently, it's not
+    possible to use instance attributes to implement the cached
+    methods.
+
+    Instead, install the wrapper method under a different name
+    and return a simple proxy to that wrapper.
+
+    https://github.com/jaraco/jaraco.functools/issues/5
+    """
+    name = method.__name__
+    special_names = '__getattr__', '__getitem__'
+
+    if name not in special_names:
+        return None
+
+    wrapper_name = '__cached' + name
+
+    def proxy(self, /, *args, **kwargs):
+        if wrapper_name not in vars(self):
+            bound = types.MethodType(method, self)
+            cache = cache_wrapper(bound)
+            setattr(self, wrapper_name, cache)
+        else:
+            cache = getattr(self, wrapper_name)
+        return cache(*args, **kwargs)
+
+    return proxy
+
+
+def apply(transform):
+    """
+    Decorate a function with a transform function that is
+    invoked on results returned from the decorated function.
+
+    >>> @apply(reversed)
+    ... def get_numbers(start):
+    ...     "doc for get_numbers"
+    ...     return range(start, start+3)
+    >>> list(get_numbers(4))
+    [6, 5, 4]
+    >>> get_numbers.__doc__
+    'doc for get_numbers'
+    """
+
+    def wrap(func):
+        return functools.wraps(func)(compose(transform, func))
+
+    return wrap
+
+
+def result_invoke(action):
+    r"""
+    Decorate a function with an action function that is
+    invoked on the results returned from the decorated
+    function (for its side effect), then return the original
+    result.
+
+    >>> @result_invoke(print)
+    ... def add_two(a, b):
+    ...     return a + b
+    >>> x = add_two(2, 3)
+    5
+    >>> x
+    5
+    """
+
+    def wrap(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            result = func(*args, **kwargs)
+            action(result)
+            return result
+
+        return wrapper
+
+    return wrap
+
+
+def invoke(f, /, *args, **kwargs):
+    """
+    Call a function for its side effect after initialization.
+
+    The benefit of using the decorator instead of simply invoking a function
+    after defining it is that it makes explicit the author's intent for the
+    function to be called immediately. Whereas if one simply calls the
+    function immediately, it's less obvious if that was intentional or
+    incidental. It also avoids repeating the name - the two actions, defining
+    the function and calling it immediately are modeled separately, but linked
+    by the decorator construct.
+
+    The benefit of having a function construct (opposed to just invoking some
+    behavior inline) is to serve as a scope in which the behavior occurs. It
+    avoids polluting the global namespace with local variables, provides an
+    anchor on which to attach documentation (docstring), keeps the behavior
+    logically separated (instead of conceptually separated or not separated at
+    all), and provides potential to re-use the behavior for testing or other
+    purposes.
+
+    This function is named as a pithy way to communicate, "call this function
+    primarily for its side effect", or "while defining this function, also
+    take it aside and call it". It exists because there's no Python construct
+    for "define and call" (nor should there be, as decorators serve this need
+    just fine). The behavior happens immediately and synchronously.
+
+    >>> @invoke
+    ... def func(): print("called")
+    called
+    >>> func()
+    called
+
+    Use functools.partial to pass parameters to the initial call
+
+    >>> @functools.partial(invoke, name='bingo')
+    ... def func(name): print('called with', name)
+    called with bingo
+    """
+    f(*args, **kwargs)
+    return f
+
+
+class Throttler:
+    """Rate-limit a function (or other callable)."""
+
+    def __init__(self, func, max_rate=float('Inf')):
+        if isinstance(func, Throttler):
+            func = func.func
+        self.func = func
+        self.max_rate = max_rate
+        self.reset()
+
+    def reset(self):
+        self.last_called = 0
+
+    def __call__(self, *args, **kwargs):
+        self._wait()
+        return self.func(*args, **kwargs)
+
+    def _wait(self):
+        """Ensure at least 1/max_rate seconds from last call."""
+        elapsed = time.time() - self.last_called
+        must_wait = 1 / self.max_rate - elapsed
+        time.sleep(max(0, must_wait))
+        self.last_called = time.time()
+
+    def __get__(self, obj, owner=None):
+        return first_invoke(self._wait, functools.partial(self.func, obj))
+
+
+def first_invoke(func1, func2):
+    """
+    Return a function that when invoked will invoke func1 without
+    any parameters (for its side effect) and then invoke func2
+    with whatever parameters were passed, returning its result.
+    """
+
+    def wrapper(*args, **kwargs):
+        func1()
+        return func2(*args, **kwargs)
+
+    return wrapper
+
+
+method_caller = first_invoke(
+    lambda: warnings.warn(
+        '`jaraco.functools.method_caller` is deprecated, '
+        'use `operator.methodcaller` instead',
+        DeprecationWarning,
+        stacklevel=3,
+    ),
+    operator.methodcaller,
+)
+
+
+def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
+    """
+    Given a callable func, trap the indicated exceptions
+    for up to 'retries' times, invoking cleanup on the
+    exception. On the final attempt, allow any exceptions
+    to propagate.
+    """
+    attempts = itertools.count() if retries == float('inf') else range(retries)
+    for _ in attempts:
+        try:
+            return func()
+        except trap:
+            cleanup()
+
+    return func()
+
+
+def retry(*r_args, **r_kwargs):
+    """
+    Decorator wrapper for retry_call. Accepts arguments to retry_call
+    except func and then returns a decorator for the decorated function.
+
+    Ex:
+
+    >>> @retry(retries=3)
+    ... def my_func(a, b):
+    ...     "this is my funk"
+    ...     print(a, b)
+    >>> my_func.__doc__
+    'this is my funk'
+    """
+
+    def decorate(func):
+        @functools.wraps(func)
+        def wrapper(*f_args, **f_kwargs):
+            bound = functools.partial(func, *f_args, **f_kwargs)
+            return retry_call(bound, *r_args, **r_kwargs)
+
+        return wrapper
+
+    return decorate
+
+
+def print_yielded(func):
+    """
+    Convert a generator into a function that prints all yielded elements.
+
+    >>> @print_yielded
+    ... def x():
+    ...     yield 3; yield None
+    >>> x()
+    3
+    None
+    """
+    print_all = functools.partial(map, print)
+    print_results = compose(more_itertools.consume, print_all, func)
+    return functools.wraps(func)(print_results)
+
+
+def pass_none(func):
+    """
+    Wrap func so it's not called if its first param is None.
+
+    >>> print_text = pass_none(print)
+    >>> print_text('text')
+    text
+    >>> print_text(None)
+    """
+
+    @functools.wraps(func)
+    def wrapper(param, /, *args, **kwargs):
+        if param is not None:
+            return func(param, *args, **kwargs)
+        return None
+
+    return wrapper
+
+
+def assign_params(func, namespace):
+    """
+    Assign parameters from namespace where func solicits.
+
+    >>> def func(x, y=3):
+    ...     print(x, y)
+    >>> assigned = assign_params(func, dict(x=2, z=4))
+    >>> assigned()
+    2 3
+
+    The usual errors are raised if a function doesn't receive
+    its required parameters:
+
+    >>> assigned = assign_params(func, dict(y=3, z=4))
+    >>> assigned()
+    Traceback (most recent call last):
+    TypeError: func() ...argument...
+
+    It even works on methods:
+
+    >>> class Handler:
+    ...     def meth(self, arg):
+    ...         print(arg)
+    >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()
+    crystal
+    """
+    sig = inspect.signature(func)
+    params = sig.parameters.keys()
+    call_ns = {k: namespace[k] for k in params if k in namespace}
+    return functools.partial(func, **call_ns)
+
+
+def save_method_args(method):
+    """
+    Wrap a method such that when it is called, the args and kwargs are
+    saved on the method.
+
+    >>> class MyClass:
+    ...     @save_method_args
+    ...     def method(self, a, b):
+    ...         print(a, b)
+    >>> my_ob = MyClass()
+    >>> my_ob.method(1, 2)
+    1 2
+    >>> my_ob._saved_method.args
+    (1, 2)
+    >>> my_ob._saved_method.kwargs
+    {}
+    >>> my_ob.method(a=3, b='foo')
+    3 foo
+    >>> my_ob._saved_method.args
+    ()
+    >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
+    True
+
+    The arguments are stored on the instance, allowing for
+    different instance to save different args.
+
+    >>> your_ob = MyClass()
+    >>> your_ob.method({str('x'): 3}, b=[4])
+    {'x': 3} [4]
+    >>> your_ob._saved_method.args
+    ({'x': 3},)
+    >>> my_ob._saved_method.args
+    ()
+    """
+    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
+
+    @functools.wraps(method)
+    def wrapper(self, /, *args, **kwargs):
+        attr_name = '_saved_' + method.__name__
+        attr = args_and_kwargs(args, kwargs)
+        setattr(self, attr_name, attr)
+        return method(self, *args, **kwargs)
+
+    return wrapper
+
+
+def except_(*exceptions, replace=None, use=None):
+    """
+    Replace the indicated exceptions, if raised, with the indicated
+    literal replacement or evaluated expression (if present).
+
+    >>> safe_int = except_(ValueError)(int)
+    >>> safe_int('five')
+    >>> safe_int('5')
+    5
+
+    Specify a literal replacement with ``replace``.
+
+    >>> safe_int_r = except_(ValueError, replace=0)(int)
+    >>> safe_int_r('five')
+    0
+
+    Provide an expression to ``use`` to pass through particular parameters.
+
+    >>> safe_int_pt = except_(ValueError, use='args[0]')(int)
+    >>> safe_int_pt('five')
+    'five'
+
+    """
+
+    def decorate(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            try:
+                return func(*args, **kwargs)
+            except exceptions:
+                try:
+                    return eval(use)
+                except TypeError:
+                    return replace
+
+        return wrapper
+
+    return decorate
+
+
+def identity(x):
+    """
+    Return the argument.
+
+    >>> o = object()
+    >>> identity(o) is o
+    True
+    """
+    return x
+
+
+def bypass_when(check, *, _op=identity):
+    """
+    Decorate a function to return its parameter when ``check``.
+
+    >>> bypassed = []  # False
+
+    >>> @bypass_when(bypassed)
+    ... def double(x):
+    ...     return x * 2
+    >>> double(2)
+    4
+    >>> bypassed[:] = [object()]  # True
+    >>> double(2)
+    2
+    """
+
+    def decorate(func):
+        @functools.wraps(func)
+        def wrapper(param, /):
+            return param if _op(check) else func(param)
+
+        return wrapper
+
+    return decorate
+
+
+def bypass_unless(check):
+    """
+    Decorate a function to return its parameter unless ``check``.
+
+    >>> enabled = [object()]  # True
+
+    >>> @bypass_unless(enabled)
+    ... def double(x):
+    ...     return x * 2
+    >>> double(2)
+    4
+    >>> del enabled[:]  # False
+    >>> double(2)
+    2
+    """
+    return bypass_when(check, _op=operator.not_)
+
+
+@functools.singledispatch
+def _splat_inner(args, func):
+    """Splat args to func."""
+    return func(*args)
+
+
+@_splat_inner.register
+def _(args: collections.abc.Mapping, func):
+    """Splat kargs to func as kwargs."""
+    return func(**args)
+
+
+def splat(func):
+    """
+    Wrap func to expect its parameters to be passed positionally in a tuple.
+
+    Has a similar effect to that of ``itertools.starmap`` over
+    simple ``map``.
+
+    >>> pairs = [(-1, 1), (0, 2)]
+    >>> more_itertools.consume(itertools.starmap(print, pairs))
+    -1 1
+    0 2
+    >>> more_itertools.consume(map(splat(print), pairs))
+    -1 1
+    0 2
+
+    The approach generalizes to other iterators that don't have a "star"
+    equivalent, such as a "starfilter".
+
+    >>> list(filter(splat(operator.add), pairs))
+    [(0, 2)]
+
+    Splat also accepts a mapping argument.
+
+    >>> def is_nice(msg, code):
+    ...     return "smile" in msg or code == 0
+    >>> msgs = [
+    ...     dict(msg='smile!', code=20),
+    ...     dict(msg='error :(', code=1),
+    ...     dict(msg='unknown', code=0),
+    ... ]
+    >>> for msg in filter(splat(is_nice), msgs):
+    ...     print(msg)
+    {'msg': 'smile!', 'code': 20}
+    {'msg': 'unknown', 'code': 0}
+    """
+    return functools.wraps(func)(functools.partial(_splat_inner, func=func))
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..19191bf93eea22a55c8d47a57ec24de370caca27
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi
@@ -0,0 +1,125 @@
+from collections.abc import Callable, Hashable, Iterator
+from functools import partial
+from operator import methodcaller
+import sys
+from typing import (
+    Any,
+    Generic,
+    Protocol,
+    TypeVar,
+    overload,
+)
+
+if sys.version_info >= (3, 10):
+    from typing import Concatenate, ParamSpec
+else:
+    from typing_extensions import Concatenate, ParamSpec
+
+_P = ParamSpec('_P')
+_R = TypeVar('_R')
+_T = TypeVar('_T')
+_R1 = TypeVar('_R1')
+_R2 = TypeVar('_R2')
+_V = TypeVar('_V')
+_S = TypeVar('_S')
+_R_co = TypeVar('_R_co', covariant=True)
+
+class _OnceCallable(Protocol[_P, _R]):
+    saved_result: _R
+    reset: Callable[[], None]
+    def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...
+
+class _ProxyMethodCacheWrapper(Protocol[_R_co]):
+    cache_clear: Callable[[], None]
+    def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
+
+class _MethodCacheWrapper(Protocol[_R_co]):
+    def cache_clear(self) -> None: ...
+    def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
+
+# `compose()` overloads below will cover most use cases.
+
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[_P, _R],
+    /,
+) -> Callable[_P, _T]: ...
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[[_R1], _R],
+    __func3: Callable[_P, _R1],
+    /,
+) -> Callable[_P, _T]: ...
+@overload
+def compose(
+    __func1: Callable[[_R], _T],
+    __func2: Callable[[_R2], _R],
+    __func3: Callable[[_R1], _R2],
+    __func4: Callable[_P, _R1],
+    /,
+) -> Callable[_P, _T]: ...
+def once(func: Callable[_P, _R]) -> _OnceCallable[_P, _R]: ...
+def method_cache(
+    method: Callable[..., _R],
+    cache_wrapper: Callable[[Callable[..., _R]], _MethodCacheWrapper[_R]] = ...,
+) -> _MethodCacheWrapper[_R] | _ProxyMethodCacheWrapper[_R]: ...
+def apply(
+    transform: Callable[[_R], _T]
+) -> Callable[[Callable[_P, _R]], Callable[_P, _T]]: ...
+def result_invoke(
+    action: Callable[[_R], Any]
+) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
+def invoke(
+    f: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs
+) -> Callable[_P, _R]: ...
+
+class Throttler(Generic[_R]):
+    last_called: float
+    func: Callable[..., _R]
+    max_rate: float
+    def __init__(
+        self, func: Callable[..., _R] | Throttler[_R], max_rate: float = ...
+    ) -> None: ...
+    def reset(self) -> None: ...
+    def __call__(self, *args: Any, **kwargs: Any) -> _R: ...
+    def __get__(self, obj: Any, owner: type[Any] | None = ...) -> Callable[..., _R]: ...
+
+def first_invoke(
+    func1: Callable[..., Any], func2: Callable[_P, _R]
+) -> Callable[_P, _R]: ...
+
+method_caller: Callable[..., methodcaller]
+
+def retry_call(
+    func: Callable[..., _R],
+    cleanup: Callable[..., None] = ...,
+    retries: int | float = ...,
+    trap: type[BaseException] | tuple[type[BaseException], ...] = ...,
+) -> _R: ...
+def retry(
+    cleanup: Callable[..., None] = ...,
+    retries: int | float = ...,
+    trap: type[BaseException] | tuple[type[BaseException], ...] = ...,
+) -> Callable[[Callable[..., _R]], Callable[..., _R]]: ...
+def print_yielded(func: Callable[_P, Iterator[Any]]) -> Callable[_P, None]: ...
+def pass_none(
+    func: Callable[Concatenate[_T, _P], _R]
+) -> Callable[Concatenate[_T, _P], _R]: ...
+def assign_params(
+    func: Callable[..., _R], namespace: dict[str, Any]
+) -> partial[_R]: ...
+def save_method_args(
+    method: Callable[Concatenate[_S, _P], _R]
+) -> Callable[Concatenate[_S, _P], _R]: ...
+def except_(
+    *exceptions: type[BaseException], replace: Any = ..., use: Any = ...
+) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ...
+def identity(x: _T) -> _T: ...
+def bypass_when(
+    check: _V, *, _op: Callable[[_V], Any] = ...
+) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...
+def bypass_unless(
+    check: Any,
+) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/functools/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt
new file mode 100644
index 0000000000000000000000000000000000000000..986f944b60b9900c22464a0c027d713854cc204e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt	
@@ -0,0 +1,2 @@
+Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fabd0c3f036d47f2cd9b2a66828ba33a00ab7b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/__init__.py
@@ -0,0 +1,624 @@
+import re
+import itertools
+import textwrap
+import functools
+
+try:
+    from importlib.resources import files  # type: ignore
+except ImportError:  # pragma: nocover
+    from importlib_resources import files  # type: ignore
+
+from jaraco.functools import compose, method_cache
+from jaraco.context import ExceptionTrap
+
+
+def substitution(old, new):
+    """
+    Return a function that will perform a substitution on a string
+    """
+    return lambda s: s.replace(old, new)
+
+
+def multi_substitution(*substitutions):
+    """
+    Take a sequence of pairs specifying substitutions, and create
+    a function that performs those substitutions.
+
+    >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo')
+    'baz'
+    """
+    substitutions = itertools.starmap(substitution, substitutions)
+    # compose function applies last function first, so reverse the
+    #  substitutions to get the expected order.
+    substitutions = reversed(tuple(substitutions))
+    return compose(*substitutions)
+
+
+class FoldedCase(str):
+    """
+    A case insensitive string class; behaves just like str
+    except compares equal when the only variation is case.
+
+    >>> s = FoldedCase('hello world')
+
+    >>> s == 'Hello World'
+    True
+
+    >>> 'Hello World' == s
+    True
+
+    >>> s != 'Hello World'
+    False
+
+    >>> s.index('O')
+    4
+
+    >>> s.split('O')
+    ['hell', ' w', 'rld']
+
+    >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))
+    ['alpha', 'Beta', 'GAMMA']
+
+    Sequence membership is straightforward.
+
+    >>> "Hello World" in [s]
+    True
+    >>> s in ["Hello World"]
+    True
+
+    Allows testing for set inclusion, but candidate and elements
+    must both be folded.
+
+    >>> FoldedCase("Hello World") in {s}
+    True
+    >>> s in {FoldedCase("Hello World")}
+    True
+
+    String inclusion works as long as the FoldedCase object
+    is on the right.
+
+    >>> "hello" in FoldedCase("Hello World")
+    True
+
+    But not if the FoldedCase object is on the left:
+
+    >>> FoldedCase('hello') in 'Hello World'
+    False
+
+    In that case, use ``in_``:
+
+    >>> FoldedCase('hello').in_('Hello World')
+    True
+
+    >>> FoldedCase('hello') > FoldedCase('Hello')
+    False
+
+    >>> FoldedCase('ß') == FoldedCase('ss')
+    True
+    """
+
+    def __lt__(self, other):
+        return self.casefold() < other.casefold()
+
+    def __gt__(self, other):
+        return self.casefold() > other.casefold()
+
+    def __eq__(self, other):
+        return self.casefold() == other.casefold()
+
+    def __ne__(self, other):
+        return self.casefold() != other.casefold()
+
+    def __hash__(self):
+        return hash(self.casefold())
+
+    def __contains__(self, other):
+        return super().casefold().__contains__(other.casefold())
+
+    def in_(self, other):
+        "Does self appear in other?"
+        return self in FoldedCase(other)
+
+    # cache casefold since it's likely to be called frequently.
+    @method_cache
+    def casefold(self):
+        return super().casefold()
+
+    def index(self, sub):
+        return self.casefold().index(sub.casefold())
+
+    def split(self, splitter=' ', maxsplit=0):
+        pattern = re.compile(re.escape(splitter), re.I)
+        return pattern.split(self, maxsplit)
+
+
+# Python 3.8 compatibility
+_unicode_trap = ExceptionTrap(UnicodeDecodeError)
+
+
+@_unicode_trap.passes
+def is_decodable(value):
+    r"""
+    Return True if the supplied value is decodable (using the default
+    encoding).
+
+    >>> is_decodable(b'\xff')
+    False
+    >>> is_decodable(b'\x32')
+    True
+    """
+    value.decode()
+
+
+def is_binary(value):
+    r"""
+    Return True if the value appears to be binary (that is, it's a byte
+    string and isn't decodable).
+
+    >>> is_binary(b'\xff')
+    True
+    >>> is_binary('\xff')
+    False
+    """
+    return isinstance(value, bytes) and not is_decodable(value)
+
+
+def trim(s):
+    r"""
+    Trim something like a docstring to remove the whitespace that
+    is common due to indentation and formatting.
+
+    >>> trim("\n\tfoo = bar\n\t\tbar = baz\n")
+    'foo = bar\n\tbar = baz'
+    """
+    return textwrap.dedent(s).strip()
+
+
+def wrap(s):
+    """
+    Wrap lines of text, retaining existing newlines as
+    paragraph markers.
+
+    >>> print(wrap(lorem_ipsum))
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
+    eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
+    minim veniam, quis nostrud exercitation ullamco laboris nisi ut
+    aliquip ex ea commodo consequat. Duis aute irure dolor in
+    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
+    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
+    culpa qui officia deserunt mollit anim id est laborum.
+    
+    Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam
+    varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus
+    magna felis sollicitudin mauris. Integer in mauris eu nibh euismod
+    gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis
+    risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue,
+    eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas
+    fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla
+    a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis,
+    neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing
+    sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque
+    nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus
+    quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis,
+    molestie eu, feugiat in, orci. In hac habitasse platea dictumst.
+    """
+    paragraphs = s.splitlines()
+    wrapped = ('\n'.join(textwrap.wrap(para)) for para in paragraphs)
+    return '\n\n'.join(wrapped)
+
+
+def unwrap(s):
+    r"""
+    Given a multi-line string, return an unwrapped version.
+
+    >>> wrapped = wrap(lorem_ipsum)
+    >>> wrapped.count('\n')
+    20
+    >>> unwrapped = unwrap(wrapped)
+    >>> unwrapped.count('\n')
+    1
+    >>> print(unwrapped)
+    Lorem ipsum dolor sit amet, consectetur adipiscing ...
+    Curabitur pretium tincidunt lacus. Nulla gravida orci ...
+
+    """
+    paragraphs = re.split(r'\n\n+', s)
+    cleaned = (para.replace('\n', ' ') for para in paragraphs)
+    return '\n'.join(cleaned)
+
+
+lorem_ipsum: str = (
+    files(__name__).joinpath('Lorem ipsum.txt').read_text(encoding='utf-8')
+)
+
+
+class Splitter:
+    """object that will split a string with the given arguments for each call
+
+    >>> s = Splitter(',')
+    >>> s('hello, world, this is your, master calling')
+    ['hello', ' world', ' this is your', ' master calling']
+    """
+
+    def __init__(self, *args):
+        self.args = args
+
+    def __call__(self, s):
+        return s.split(*self.args)
+
+
+def indent(string, prefix=' ' * 4):
+    """
+    >>> indent('foo')
+    '    foo'
+    """
+    return prefix + string
+
+
+class WordSet(tuple):
+    """
+    Given an identifier, return the words that identifier represents,
+    whether in camel case, underscore-separated, etc.
+
+    >>> WordSet.parse("camelCase")
+    ('camel', 'Case')
+
+    >>> WordSet.parse("under_sep")
+    ('under', 'sep')
+
+    Acronyms should be retained
+
+    >>> WordSet.parse("firstSNL")
+    ('first', 'SNL')
+
+    >>> WordSet.parse("you_and_I")
+    ('you', 'and', 'I')
+
+    >>> WordSet.parse("A simple test")
+    ('A', 'simple', 'test')
+
+    Multiple caps should not interfere with the first cap of another word.
+
+    >>> WordSet.parse("myABCClass")
+    ('my', 'ABC', 'Class')
+
+    The result is a WordSet, providing access to other forms.
+
+    >>> WordSet.parse("myABCClass").underscore_separated()
+    'my_ABC_Class'
+
+    >>> WordSet.parse('a-command').camel_case()
+    'ACommand'
+
+    >>> WordSet.parse('someIdentifier').lowered().space_separated()
+    'some identifier'
+
+    Slices of the result should return another WordSet.
+
+    >>> WordSet.parse('taken-out-of-context')[1:].underscore_separated()
+    'out_of_context'
+
+    >>> WordSet.from_class_name(WordSet()).lowered().space_separated()
+    'word set'
+
+    >>> example = WordSet.parse('figured it out')
+    >>> example.headless_camel_case()
+    'figuredItOut'
+    >>> example.dash_separated()
+    'figured-it-out'
+
+    """
+
+    _pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))')
+
+    def capitalized(self):
+        return WordSet(word.capitalize() for word in self)
+
+    def lowered(self):
+        return WordSet(word.lower() for word in self)
+
+    def camel_case(self):
+        return ''.join(self.capitalized())
+
+    def headless_camel_case(self):
+        words = iter(self)
+        first = next(words).lower()
+        new_words = itertools.chain((first,), WordSet(words).camel_case())
+        return ''.join(new_words)
+
+    def underscore_separated(self):
+        return '_'.join(self)
+
+    def dash_separated(self):
+        return '-'.join(self)
+
+    def space_separated(self):
+        return ' '.join(self)
+
+    def trim_right(self, item):
+        """
+        Remove the item from the end of the set.
+
+        >>> WordSet.parse('foo bar').trim_right('foo')
+        ('foo', 'bar')
+        >>> WordSet.parse('foo bar').trim_right('bar')
+        ('foo',)
+        >>> WordSet.parse('').trim_right('bar')
+        ()
+        """
+        return self[:-1] if self and self[-1] == item else self
+
+    def trim_left(self, item):
+        """
+        Remove the item from the beginning of the set.
+
+        >>> WordSet.parse('foo bar').trim_left('foo')
+        ('bar',)
+        >>> WordSet.parse('foo bar').trim_left('bar')
+        ('foo', 'bar')
+        >>> WordSet.parse('').trim_left('bar')
+        ()
+        """
+        return self[1:] if self and self[0] == item else self
+
+    def trim(self, item):
+        """
+        >>> WordSet.parse('foo bar').trim('foo')
+        ('bar',)
+        """
+        return self.trim_left(item).trim_right(item)
+
+    def __getitem__(self, item):
+        result = super().__getitem__(item)
+        if isinstance(item, slice):
+            result = WordSet(result)
+        return result
+
+    @classmethod
+    def parse(cls, identifier):
+        matches = cls._pattern.finditer(identifier)
+        return WordSet(match.group(0) for match in matches)
+
+    @classmethod
+    def from_class_name(cls, subject):
+        return cls.parse(subject.__class__.__name__)
+
+
+# for backward compatibility
+words = WordSet.parse
+
+
+def simple_html_strip(s):
+    r"""
+    Remove HTML from the string `s`.
+
+    >>> str(simple_html_strip(''))
+    ''
+
+    >>> print(simple_html_strip('A stormy day in paradise'))
+    A stormy day in paradise
+
+    >>> print(simple_html_strip('Somebody  tell the truth.'))
+    Somebody  tell the truth.
+
+    >>> print(simple_html_strip('What about
\nmultiple lines?')) + What about + multiple lines? + """ + html_stripper = re.compile('()|(<[^>]*>)|([^<]+)', re.DOTALL) + texts = (match.group(3) or '' for match in html_stripper.finditer(s)) + return ''.join(texts) + + +class SeparatedValues(str): + """ + A string separated by a separator. Overrides __iter__ for getting + the values. + + >>> list(SeparatedValues('a,b,c')) + ['a', 'b', 'c'] + + Whitespace is stripped and empty values are discarded. + + >>> list(SeparatedValues(' a, b , c, ')) + ['a', 'b', 'c'] + """ + + separator = ',' + + def __iter__(self): + parts = self.split(self.separator) + return filter(None, (part.strip() for part in parts)) + + +class Stripper: + r""" + Given a series of lines, find the common prefix and strip it from them. + + >>> lines = [ + ... 'abcdefg\n', + ... 'abc\n', + ... 'abcde\n', + ... ] + >>> res = Stripper.strip_prefix(lines) + >>> res.prefix + 'abc' + >>> list(res.lines) + ['defg\n', '\n', 'de\n'] + + If no prefix is common, nothing should be stripped. + + >>> lines = [ + ... 'abcd\n', + ... '1234\n', + ... ] + >>> res = Stripper.strip_prefix(lines) + >>> res.prefix = '' + >>> list(res.lines) + ['abcd\n', '1234\n'] + """ + + def __init__(self, prefix, lines): + self.prefix = prefix + self.lines = map(self, lines) + + @classmethod + def strip_prefix(cls, lines): + prefix_lines, lines = itertools.tee(lines) + prefix = functools.reduce(cls.common_prefix, prefix_lines) + return cls(prefix, lines) + + def __call__(self, line): + if not self.prefix: + return line + null, prefix, rest = line.partition(self.prefix) + return rest + + @staticmethod + def common_prefix(s1, s2): + """ + Return the common prefix of two lines. + """ + index = min(len(s1), len(s2)) + while s1[:index] != s2[:index]: + index -= 1 + return s1[:index] + + +def remove_prefix(text, prefix): + """ + Remove the prefix from the text if it exists. + + >>> remove_prefix('underwhelming performance', 'underwhelming ') + 'performance' + + >>> remove_prefix('something special', 'sample') + 'something special' + """ + null, prefix, rest = text.rpartition(prefix) + return rest + + +def remove_suffix(text, suffix): + """ + Remove the suffix from the text if it exists. + + >>> remove_suffix('name.git', '.git') + 'name' + + >>> remove_suffix('something special', 'sample') + 'something special' + """ + rest, suffix, null = text.partition(suffix) + return rest + + +def normalize_newlines(text): + r""" + Replace alternate newlines with the canonical newline. + + >>> normalize_newlines('Lorem Ipsum\u2029') + 'Lorem Ipsum\n' + >>> normalize_newlines('Lorem Ipsum\r\n') + 'Lorem Ipsum\n' + >>> normalize_newlines('Lorem Ipsum\x85') + 'Lorem Ipsum\n' + """ + newlines = ['\r\n', '\r', '\n', '\u0085', '\u2028', '\u2029'] + pattern = '|'.join(newlines) + return re.sub(pattern, '\n', text) + + +def _nonblank(str): + return str and not str.startswith('#') + + +@functools.singledispatch +def yield_lines(iterable): + r""" + Yield valid lines of a string or iterable. + + >>> list(yield_lines('')) + [] + >>> list(yield_lines(['foo', 'bar'])) + ['foo', 'bar'] + >>> list(yield_lines('foo\nbar')) + ['foo', 'bar'] + >>> list(yield_lines('\nfoo\n#bar\nbaz #comment')) + ['foo', 'baz #comment'] + >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n'])) + ['foo', 'bar', 'baz', 'bing'] + """ + return itertools.chain.from_iterable(map(yield_lines, iterable)) + + +@yield_lines.register(str) +def _(text): + return filter(_nonblank, map(str.strip, text.splitlines())) + + +def drop_comment(line): + """ + Drop comments. + + >>> drop_comment('foo # bar') + 'foo' + + A hash without a space may be in a URL. + + >>> drop_comment('http://example.com/foo#bar') + 'http://example.com/foo#bar' + """ + return line.partition(' #')[0] + + +def join_continuation(lines): + r""" + Join lines continued by a trailing backslash. + + >>> list(join_continuation(['foo \\', 'bar', 'baz'])) + ['foobar', 'baz'] + >>> list(join_continuation(['foo \\', 'bar', 'baz'])) + ['foobar', 'baz'] + >>> list(join_continuation(['foo \\', 'bar \\', 'baz'])) + ['foobarbaz'] + + Not sure why, but... + The character preceding the backslash is also elided. + + >>> list(join_continuation(['goo\\', 'dly'])) + ['godly'] + + A terrible idea, but... + If no line is available to continue, suppress the lines. + + >>> list(join_continuation(['foo', 'bar\\', 'baz\\'])) + ['foo'] + """ + lines = iter(lines) + for item in lines: + while item.endswith('\\'): + try: + item = item[:-2].strip() + next(lines) + except StopIteration: + return + yield item + + +def read_newlines(filename, limit=1024): + r""" + >>> tmp_path = getfixture('tmp_path') + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\n', newline='', encoding='utf-8') + >>> read_newlines(filename) + '\n' + >>> _ = filename.write_text('foo\r\n', newline='', encoding='utf-8') + >>> read_newlines(filename) + '\r\n' + >>> _ = filename.write_text('foo\r\nbar\nbing\r', newline='', encoding='utf-8') + >>> read_newlines(filename) + ('\r', '\n', '\r\n') + """ + with open(filename, encoding='utf-8') as fp: + fp.read(limit) + return fp.newlines diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/layouts.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..9636f0f7b53cb4d1ea5842e1eb62c998ddb91070 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/layouts.py @@ -0,0 +1,25 @@ +qwerty = "-=qwertyuiop[]asdfghjkl;'zxcvbnm,./_+QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?" +dvorak = "[]',.pyfgcrl/=aoeuidhtns-;qjkxbmwvz{}\"<>PYFGCRL?+AOEUIDHTNS_:QJKXBMWVZ" + + +to_dvorak = str.maketrans(qwerty, dvorak) +to_qwerty = str.maketrans(dvorak, qwerty) + + +def translate(input, translation): + """ + >>> translate('dvorak', to_dvorak) + 'ekrpat' + >>> translate('qwerty', to_qwerty) + 'x,dokt' + """ + return input.translate(translation) + + +def _translate_stream(stream, translation): + """ + >>> import io + >>> _translate_stream(io.StringIO('foo'), to_dvorak) + urr + """ + print(translate(stream.read(), translation)) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py new file mode 100644 index 0000000000000000000000000000000000000000..e11d1ba4280e9a882ca788c27f56034e90987004 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py @@ -0,0 +1,33 @@ +import autocommand +import inflect + +from more_itertools import always_iterable + +import jaraco.text + + +def report_newlines(filename): + r""" + Report the newlines in the indicated file. + + >>> tmp_path = getfixture('tmp_path') + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\nbar\n', newline='', encoding='utf-8') + >>> report_newlines(filename) + newline is '\n' + >>> filename = tmp_path / 'out.txt' + >>> _ = filename.write_text('foo\nbar\r\n', newline='', encoding='utf-8') + >>> report_newlines(filename) + newlines are ('\n', '\r\n') + """ + newlines = jaraco.text.read_newlines(filename) + count = len(tuple(always_iterable(newlines))) + engine = inflect.engine() + print( + engine.plural_noun("newline", count), + engine.plural_verb("is", count), + repr(newlines), + ) + + +autocommand.autocommand(__name__)(report_newlines) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py new file mode 100644 index 0000000000000000000000000000000000000000..761717a9b9e1f837eeacf0e888822f6fad881361 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py @@ -0,0 +1,21 @@ +import sys + +import autocommand + +from jaraco.text import Stripper + + +def strip_prefix(): + r""" + Strip any common prefix from stdin. + + >>> import io, pytest + >>> getfixture('monkeypatch').setattr('sys.stdin', io.StringIO('abcdef\nabc123')) + >>> strip_prefix() + def + 123 + """ + sys.stdout.writelines(Stripper.strip_prefix(sys.stdin).lines) + + +autocommand.autocommand(__name__)(strip_prefix) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d5da80b3b565b956b523a5e0aaea7b6274cfcb --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py @@ -0,0 +1,6 @@ +import sys + +from . import layouts + + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_dvorak) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py new file mode 100644 index 0000000000000000000000000000000000000000..abe27286629cd3c1d95a984ad4a172957927af9b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py @@ -0,0 +1,6 @@ +import sys + +from . import layouts + + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_qwerty) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a523bece3e50519653c4d7a38399baa487fefa1 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Erik Rose + +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. diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fb41b0cfe69bd01a045de31597a3f6d176604d25 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/METADATA @@ -0,0 +1,266 @@ +Metadata-Version: 2.1 +Name: more-itertools +Version: 10.3.0 +Summary: More routines for operating on iterables, beyond itertools +Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked +Author-email: Erik Rose +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Project-URL: Homepage, https://github.com/more-itertools/more-itertools + +============== +More Itertools +============== + +.. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest + :target: https://more-itertools.readthedocs.io/en/stable/ + +Python's ``itertools`` library is a gem - you can compose elegant solutions +for a variety of problems with the functions it provides. In ``more-itertools`` +we collect additional building blocks, recipes, and routines for working with +Python iterables. + ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Grouping | `chunked `_, | +| | `ichunked `_, | +| | `chunked_even `_, | +| | `sliced `_, | +| | `constrained_batches `_, | +| | `distribute `_, | +| | `divide `_, | +| | `split_at `_, | +| | `split_before `_, | +| | `split_after `_, | +| | `split_into `_, | +| | `split_when `_, | +| | `bucket `_, | +| | `unzip `_, | +| | `batched `_, | +| | `grouper `_, | +| | `partition `_, | +| | `transpose `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Lookahead and lookback | `spy `_, | +| | `peekable `_, | +| | `seekable `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Windowing | `windowed `_, | +| | `substrings `_, | +| | `substrings_indexes `_, | +| | `stagger `_, | +| | `windowed_complete `_, | +| | `pairwise `_, | +| | `triplewise `_, | +| | `sliding_window `_, | +| | `subslices `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Augmenting | `count_cycle `_, | +| | `intersperse `_, | +| | `padded `_, | +| | `repeat_each `_, | +| | `mark_ends `_, | +| | `repeat_last `_, | +| | `adjacent `_, | +| | `groupby_transform `_, | +| | `pad_none `_, | +| | `ncycles `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Combining | `collapse `_, | +| | `sort_together `_, | +| | `interleave `_, | +| | `interleave_longest `_, | +| | `interleave_evenly `_, | +| | `zip_offset `_, | +| | `zip_equal `_, | +| | `zip_broadcast `_, | +| | `flatten `_, | +| | `roundrobin `_, | +| | `prepend `_, | +| | `value_chain `_, | +| | `partial_product `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Summarizing | `ilen `_, | +| | `unique_to_each `_, | +| | `sample `_, | +| | `consecutive_groups `_, | +| | `run_length `_, | +| | `map_reduce `_, | +| | `join_mappings `_, | +| | `exactly_n `_, | +| | `is_sorted `_, | +| | `all_equal `_, | +| | `all_unique `_, | +| | `minmax `_, | +| | `first_true `_, | +| | `quantify `_, | +| | `iequals `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Selecting | `islice_extended `_, | +| | `first `_, | +| | `last `_, | +| | `one `_, | +| | `only `_, | +| | `strictly_n `_, | +| | `strip `_, | +| | `lstrip `_, | +| | `rstrip `_, | +| | `filter_except `_, | +| | `map_except `_, | +| | `filter_map `_, | +| | `iter_suppress `_, | +| | `nth_or_last `_, | +| | `unique_in_window `_, | +| | `before_and_after `_, | +| | `nth `_, | +| | `take `_, | +| | `tail `_, | +| | `unique_everseen `_, | +| | `unique_justseen `_, | +| | `unique `_, | +| | `duplicates_everseen `_, | +| | `duplicates_justseen `_, | +| | `classify_unique `_, | +| | `longest_common_prefix `_, | +| | `takewhile_inclusive `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Math | `dft `_, | +| | `idft `_, | +| | `convolve `_, | +| | `dotproduct `_, | +| | `factor `_, | +| | `matmul `_, | +| | `polynomial_from_roots `_, | +| | `polynomial_derivative `_, | +| | `polynomial_eval `_, | +| | `sieve `_, | +| | `sum_of_squares `_, | +| | `totient `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Combinatorics | `distinct_permutations `_, | +| | `distinct_combinations `_, | +| | `circular_shifts `_, | +| | `partitions `_, | +| | `set_partitions `_, | +| | `product_index `_, | +| | `combination_index `_, | +| | `permutation_index `_, | +| | `combination_with_replacement_index `_, | +| | `gray_product `_, | +| | `outer_product `_, | +| | `powerset `_, | +| | `powerset_of_sets `_, | +| | `random_product `_, | +| | `random_permutation `_, | +| | `random_combination `_, | +| | `random_combination_with_replacement `_, | +| | `nth_product `_, | +| | `nth_permutation `_, | +| | `nth_combination `_, | +| | `nth_combination_with_replacement `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Wrapping | `always_iterable `_, | +| | `always_reversible `_, | +| | `countable `_, | +| | `consumer `_, | +| | `with_iter `_, | +| | `iter_except `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Others | `locate `_, | +| | `rlocate `_, | +| | `replace `_, | +| | `numeric_range `_, | +| | `side_effect `_, | +| | `iterate `_, | +| | `difference `_, | +| | `make_decorator `_, | +| | `SequenceView `_, | +| | `time_limited `_, | +| | `map_if `_, | +| | `iter_index `_, | +| | `consume `_, | +| | `tabulate `_, | +| | `repeatfunc `_, | +| | `reshape `_ | +| | `doublestarmap `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + + +Getting started +=============== + +To get started, install the library with `pip `_: + +.. code-block:: shell + + pip install more-itertools + +The recipes from the `itertools docs `_ +are included in the top-level package: + +.. code-block:: python + + >>> from more_itertools import flatten + >>> iterable = [(0, 1), (2, 3)] + >>> list(flatten(iterable)) + [0, 1, 2, 3] + +Several new recipes are available as well: + +.. code-block:: python + + >>> from more_itertools import chunked + >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8] + >>> list(chunked(iterable, 3)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + >>> from more_itertools import spy + >>> iterable = (x * x for x in range(1, 6)) + >>> head, iterable = spy(iterable, n=3) + >>> list(head) + [1, 4, 9] + >>> list(iterable) + [1, 4, 9, 16, 25] + + + +For the full listing of functions, see the `API documentation `_. + + +Links elsewhere +=============== + +Blog posts about ``more-itertools``: + +* `Yo, I heard you like decorators `__ +* `Tour of Python Itertools `__ (`Alternate `__) +* `Real-World Python More Itertools `_ + + +Development +=========== + +``more-itertools`` is maintained by `@erikrose `_ +and `@bbayles `_, with help from `many others `_. +If you have a problem or suggestion, please file a bug or pull request in this +repository. Thanks for contributing! + + +Version History +=============== + +The version history can be found in `documentation `_. + diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f15f3fcdc5c751048d3c9eac077a3d11c861df36 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/RECORD @@ -0,0 +1,16 @@ +more_itertools-10.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +more_itertools-10.3.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +more_itertools-10.3.0.dist-info/METADATA,sha256=BFO90O-fLNiVQMpj7oIS5ztzgJUUQZ3TA32P5HH3N-A,36293 +more_itertools-10.3.0.dist-info/RECORD,, +more_itertools-10.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools-10.3.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81 +more_itertools/__init__.py,sha256=dtAbGjTDmn_ghiU5YXfhyDy0phAlXVdt5klZA5fUa-Q,149 +more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +more_itertools/__pycache__/__init__.cpython-312.pyc,, +more_itertools/__pycache__/more.cpython-312.pyc,, +more_itertools/__pycache__/recipes.cpython-312.pyc,, +more_itertools/more.py,sha256=1E5kzFncRKTDw0cYv1yRXMgDdunstLQd1QStcnL6U90,148370 +more_itertools/more.pyi,sha256=iXXeqt48Nxe8VGmIWpkVXuKpR2FYNuu2DU8nQLWCCu0,21484 +more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools/recipes.py,sha256=WedhhfhGVgr6zii8fIbGJVmRTw0ZKRiLKnYBDGJv4nY,28591 +more_itertools/recipes.pyi,sha256=T_mdGpcFdfrP3JSWbwzYP9JyNV-Go-7RPfpxfftAWlA,4617 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..db4a255f3a271083b66f205eeaa81f74c97bb8ac --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools-10.3.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.8.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4662fc31a75cd576f6f110a345f5e2f3cb2958 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py @@ -0,0 +1,6 @@ +"""More routines for operating on iterables, beyond itertools""" + +from .more import * # noqa +from .recipes import * # noqa + +__version__ = '10.3.0' diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.pyi b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..96f6e36c7f4ac9ea0aebdcd9e11b8d1ff092d2ef --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.pyi @@ -0,0 +1,2 @@ +from .more import * +from .recipes import * diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.py b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.py new file mode 100644 index 0000000000000000000000000000000000000000..7b481907daee16c08b1e6fac8cec3b87ea4c8bd8 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.py @@ -0,0 +1,4806 @@ +import math +import warnings + +from collections import Counter, defaultdict, deque, abc +from collections.abc import Sequence +from functools import cached_property, partial, reduce, wraps +from heapq import heapify, heapreplace, heappop +from itertools import ( + chain, + combinations, + compress, + count, + cycle, + dropwhile, + groupby, + islice, + repeat, + starmap, + takewhile, + tee, + zip_longest, + product, +) +from math import comb, e, exp, factorial, floor, fsum, log, perm, tau +from queue import Empty, Queue +from random import random, randrange, uniform +from operator import itemgetter, mul, sub, gt, lt, ge, le +from sys import hexversion, maxsize +from time import monotonic + +from .recipes import ( + _marker, + _zip_equal, + UnequalIterablesError, + consume, + flatten, + pairwise, + powerset, + take, + unique_everseen, + all_equal, + batched, +) + +__all__ = [ + 'AbortThread', + 'SequenceView', + 'UnequalIterablesError', + 'adjacent', + 'all_unique', + 'always_iterable', + 'always_reversible', + 'bucket', + 'callback_iter', + 'chunked', + 'chunked_even', + 'circular_shifts', + 'collapse', + 'combination_index', + 'combination_with_replacement_index', + 'consecutive_groups', + 'constrained_batches', + 'consumer', + 'count_cycle', + 'countable', + 'dft', + 'difference', + 'distinct_combinations', + 'distinct_permutations', + 'distribute', + 'divide', + 'doublestarmap', + 'duplicates_everseen', + 'duplicates_justseen', + 'classify_unique', + 'exactly_n', + 'filter_except', + 'filter_map', + 'first', + 'gray_product', + 'groupby_transform', + 'ichunked', + 'iequals', + 'idft', + 'ilen', + 'interleave', + 'interleave_evenly', + 'interleave_longest', + 'intersperse', + 'is_sorted', + 'islice_extended', + 'iterate', + 'iter_suppress', + 'join_mappings', + 'last', + 'locate', + 'longest_common_prefix', + 'lstrip', + 'make_decorator', + 'map_except', + 'map_if', + 'map_reduce', + 'mark_ends', + 'minmax', + 'nth_or_last', + 'nth_permutation', + 'nth_product', + 'nth_combination_with_replacement', + 'numeric_range', + 'one', + 'only', + 'outer_product', + 'padded', + 'partial_product', + 'partitions', + 'peekable', + 'permutation_index', + 'powerset_of_sets', + 'product_index', + 'raise_', + 'repeat_each', + 'repeat_last', + 'replace', + 'rlocate', + 'rstrip', + 'run_length', + 'sample', + 'seekable', + 'set_partitions', + 'side_effect', + 'sliced', + 'sort_together', + 'split_after', + 'split_at', + 'split_before', + 'split_into', + 'split_when', + 'spy', + 'stagger', + 'strip', + 'strictly_n', + 'substrings', + 'substrings_indexes', + 'takewhile_inclusive', + 'time_limited', + 'unique_in_window', + 'unique_to_each', + 'unzip', + 'value_chain', + 'windowed', + 'windowed_complete', + 'with_iter', + 'zip_broadcast', + 'zip_equal', + 'zip_offset', +] + +# math.sumprod is available for Python 3.12+ +_fsumprod = getattr(math, 'sumprod', lambda x, y: fsum(map(mul, x, y))) + + +def chunked(iterable, n, strict=False): + """Break *iterable* into lists of length *n*: + + >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) + [[1, 2, 3], [4, 5, 6]] + + By the default, the last yielded list will have fewer than *n* elements + if the length of *iterable* is not divisible by *n*: + + >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) + [[1, 2, 3], [4, 5, 6], [7, 8]] + + To use a fill-in value instead, see the :func:`grouper` recipe. + + If the length of *iterable* is not divisible by *n* and *strict* is + ``True``, then ``ValueError`` will be raised before the last + list is yielded. + + """ + iterator = iter(partial(take, n, iter(iterable)), []) + if strict: + if n is None: + raise ValueError('n must not be None when using strict mode.') + + def ret(): + for chunk in iterator: + if len(chunk) != n: + raise ValueError('iterable is not divisible by n.') + yield chunk + + return iter(ret()) + else: + return iterator + + +def first(iterable, default=_marker): + """Return the first item of *iterable*, or *default* if *iterable* is + empty. + + >>> first([0, 1, 2, 3]) + 0 + >>> first([], 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + + :func:`first` is useful when you have a generator of expensive-to-retrieve + values and want any arbitrary one. It is marginally shorter than + ``next(iter(iterable), default)``. + + """ + for item in iterable: + return item + if default is _marker: + raise ValueError( + 'first() was called on an empty iterable, and no ' + 'default value was provided.' + ) + return default + + +def last(iterable, default=_marker): + """Return the last item of *iterable*, or *default* if *iterable* is + empty. + + >>> last([0, 1, 2, 3]) + 3 + >>> last([], 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + """ + try: + if isinstance(iterable, Sequence): + return iterable[-1] + # Work around https://bugs.python.org/issue38525 + elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0): + return next(reversed(iterable)) + else: + return deque(iterable, maxlen=1)[-1] + except (IndexError, TypeError, StopIteration): + if default is _marker: + raise ValueError( + 'last() was called on an empty iterable, and no default was ' + 'provided.' + ) + return default + + +def nth_or_last(iterable, n, default=_marker): + """Return the nth or the last item of *iterable*, + or *default* if *iterable* is empty. + + >>> nth_or_last([0, 1, 2, 3], 2) + 2 + >>> nth_or_last([0, 1], 2) + 1 + >>> nth_or_last([], 0, 'some default') + 'some default' + + If *default* is not provided and there are no items in the iterable, + raise ``ValueError``. + """ + return last(islice(iterable, n + 1), default=default) + + +class peekable: + """Wrap an iterator to allow lookahead and prepending elements. + + Call :meth:`peek` on the result to get the value that will be returned + by :func:`next`. This won't advance the iterator: + + >>> p = peekable(['a', 'b']) + >>> p.peek() + 'a' + >>> next(p) + 'a' + + Pass :meth:`peek` a default value to return that instead of raising + ``StopIteration`` when the iterator is exhausted. + + >>> p = peekable([]) + >>> p.peek('hi') + 'hi' + + peekables also offer a :meth:`prepend` method, which "inserts" items + at the head of the iterable: + + >>> p = peekable([1, 2, 3]) + >>> p.prepend(10, 11, 12) + >>> next(p) + 10 + >>> p.peek() + 11 + >>> list(p) + [11, 12, 1, 2, 3] + + peekables can be indexed. Index 0 is the item that will be returned by + :func:`next`, index 1 is the item after that, and so on: + The values up to the given index will be cached. + + >>> p = peekable(['a', 'b', 'c', 'd']) + >>> p[0] + 'a' + >>> p[1] + 'b' + >>> next(p) + 'a' + + Negative indexes are supported, but be aware that they will cache the + remaining items in the source iterator, which may require significant + storage. + + To check whether a peekable is exhausted, check its truth value: + + >>> p = peekable(['a', 'b']) + >>> if p: # peekable has items + ... list(p) + ['a', 'b'] + >>> if not p: # peekable is exhausted + ... list(p) + [] + + """ + + def __init__(self, iterable): + self._it = iter(iterable) + self._cache = deque() + + def __iter__(self): + return self + + def __bool__(self): + try: + self.peek() + except StopIteration: + return False + return True + + def peek(self, default=_marker): + """Return the item that will be next returned from ``next()``. + + Return ``default`` if there are no items left. If ``default`` is not + provided, raise ``StopIteration``. + + """ + if not self._cache: + try: + self._cache.append(next(self._it)) + except StopIteration: + if default is _marker: + raise + return default + return self._cache[0] + + def prepend(self, *items): + """Stack up items to be the next ones returned from ``next()`` or + ``self.peek()``. The items will be returned in + first in, first out order:: + + >>> p = peekable([1, 2, 3]) + >>> p.prepend(10, 11, 12) + >>> next(p) + 10 + >>> list(p) + [11, 12, 1, 2, 3] + + It is possible, by prepending items, to "resurrect" a peekable that + previously raised ``StopIteration``. + + >>> p = peekable([]) + >>> next(p) + Traceback (most recent call last): + ... + StopIteration + >>> p.prepend(1) + >>> next(p) + 1 + >>> next(p) + Traceback (most recent call last): + ... + StopIteration + + """ + self._cache.extendleft(reversed(items)) + + def __next__(self): + if self._cache: + return self._cache.popleft() + + return next(self._it) + + def _get_slice(self, index): + # Normalize the slice's arguments + step = 1 if (index.step is None) else index.step + if step > 0: + start = 0 if (index.start is None) else index.start + stop = maxsize if (index.stop is None) else index.stop + elif step < 0: + start = -1 if (index.start is None) else index.start + stop = (-maxsize - 1) if (index.stop is None) else index.stop + else: + raise ValueError('slice step cannot be zero') + + # If either the start or stop index is negative, we'll need to cache + # the rest of the iterable in order to slice from the right side. + if (start < 0) or (stop < 0): + self._cache.extend(self._it) + # Otherwise we'll need to find the rightmost index and cache to that + # point. + else: + n = min(max(start, stop) + 1, maxsize) + cache_len = len(self._cache) + if n >= cache_len: + self._cache.extend(islice(self._it, n - cache_len)) + + return list(self._cache)[index] + + def __getitem__(self, index): + if isinstance(index, slice): + return self._get_slice(index) + + cache_len = len(self._cache) + if index < 0: + self._cache.extend(self._it) + elif index >= cache_len: + self._cache.extend(islice(self._it, index + 1 - cache_len)) + + return self._cache[index] + + +def consumer(func): + """Decorator that automatically advances a PEP-342-style "reverse iterator" + to its first yield point so you don't have to call ``next()`` on it + manually. + + >>> @consumer + ... def tally(): + ... i = 0 + ... while True: + ... print('Thing number %s is %s.' % (i, (yield))) + ... i += 1 + ... + >>> t = tally() + >>> t.send('red') + Thing number 0 is red. + >>> t.send('fish') + Thing number 1 is fish. + + Without the decorator, you would have to call ``next(t)`` before + ``t.send()`` could be used. + + """ + + @wraps(func) + def wrapper(*args, **kwargs): + gen = func(*args, **kwargs) + next(gen) + return gen + + return wrapper + + +def ilen(iterable): + """Return the number of items in *iterable*. + + >>> ilen(x for x in range(1000000) if x % 3 == 0) + 333334 + + This consumes the iterable, so handle with care. + + """ + # This approach was selected because benchmarks showed it's likely the + # fastest of the known implementations at the time of writing. + # See GitHub tracker: #236, #230. + counter = count() + deque(zip(iterable, counter), maxlen=0) + return next(counter) + + +def iterate(func, start): + """Return ``start``, ``func(start)``, ``func(func(start))``, ... + + >>> from itertools import islice + >>> list(islice(iterate(lambda x: 2*x, 1), 10)) + [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + + """ + while True: + yield start + try: + start = func(start) + except StopIteration: + break + + +def with_iter(context_manager): + """Wrap an iterable in a ``with`` statement, so it closes once exhausted. + + For example, this will close the file when the iterator is exhausted:: + + upper_lines = (line.upper() for line in with_iter(open('foo'))) + + Any context manager which returns an iterable is a candidate for + ``with_iter``. + + """ + with context_manager as iterable: + yield from iterable + + +def one(iterable, too_short=None, too_long=None): + """Return the first item from *iterable*, which is expected to contain only + that item. Raise an exception if *iterable* is empty or has more than one + item. + + :func:`one` is useful for ensuring that an iterable contains only one item. + For example, it can be used to retrieve the result of a database query + that is expected to return a single row. + + If *iterable* is empty, ``ValueError`` will be raised. You may specify a + different exception with the *too_short* keyword: + + >>> it = [] + >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too many items in iterable (expected 1)' + >>> too_short = IndexError('too few items') + >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + IndexError: too few items + + Similarly, if *iterable* contains more than one item, ``ValueError`` will + be raised. You may specify a different exception with the *too_long* + keyword: + + >>> it = ['too', 'many'] + >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 'too', + 'many', and perhaps more. + >>> too_long = RuntimeError + >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + RuntimeError + + Note that :func:`one` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check iterable + contents less destructively. + + """ + it = iter(iterable) + + try: + first_value = next(it) + except StopIteration as exc: + raise ( + too_short or ValueError('too few items in iterable (expected 1)') + ) from exc + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value + + +def raise_(exception, *args): + raise exception(*args) + + +def strictly_n(iterable, n, too_short=None, too_long=None): + """Validate that *iterable* has exactly *n* items and return them if + it does. If it has fewer than *n* items, call function *too_short* + with those items. If it has more than *n* items, call function + *too_long* with the first ``n + 1`` items. + + >>> iterable = ['a', 'b', 'c', 'd'] + >>> n = 4 + >>> list(strictly_n(iterable, n)) + ['a', 'b', 'c', 'd'] + + Note that the returned iterable must be consumed in order for the check to + be made. + + By default, *too_short* and *too_long* are functions that raise + ``ValueError``. + + >>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too few items in iterable (got 2) + + >>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: too many items in iterable (got at least 3) + + You can instead supply functions that do something else. + *too_short* will be called with the number of items in *iterable*. + *too_long* will be called with `n + 1`. + + >>> def too_short(item_count): + ... raise RuntimeError + >>> it = strictly_n('abcd', 6, too_short=too_short) + >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + RuntimeError + + >>> def too_long(item_count): + ... print('The boss is going to hear about this') + >>> it = strictly_n('abcdef', 4, too_long=too_long) + >>> list(it) + The boss is going to hear about this + ['a', 'b', 'c', 'd'] + + """ + if too_short is None: + too_short = lambda item_count: raise_( + ValueError, + 'Too few items in iterable (got {})'.format(item_count), + ) + + if too_long is None: + too_long = lambda item_count: raise_( + ValueError, + 'Too many items in iterable (got at least {})'.format(item_count), + ) + + it = iter(iterable) + for i in range(n): + try: + item = next(it) + except StopIteration: + too_short(i) + return + else: + yield item + + try: + next(it) + except StopIteration: + pass + else: + too_long(n + 1) + + +def distinct_permutations(iterable, r=None): + """Yield successive distinct permutations of the elements in *iterable*. + + >>> sorted(distinct_permutations([1, 0, 1])) + [(0, 1, 1), (1, 0, 1), (1, 1, 0)] + + Equivalent to ``set(permutations(iterable))``, except duplicates are not + generated and thrown away. For larger input sequences this is much more + efficient. + + Duplicate permutations arise when there are duplicated elements in the + input iterable. The number of items returned is + `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of + items input, and each `x_i` is the count of a distinct item in the input + sequence. + + If *r* is given, only the *r*-length permutations are yielded. + + >>> sorted(distinct_permutations([1, 0, 1], r=2)) + [(0, 1), (1, 0), (1, 1)] + >>> sorted(distinct_permutations(range(3), r=2)) + [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] + + """ + + # Algorithm: https://w.wiki/Qai + def _full(A): + while True: + # Yield the permutation we have + yield tuple(A) + + # Find the largest index i such that A[i] < A[i + 1] + for i in range(size - 2, -1, -1): + if A[i] < A[i + 1]: + break + # If no such index exists, this permutation is the last one + else: + return + + # Find the largest index j greater than j such that A[i] < A[j] + for j in range(size - 1, i, -1): + if A[i] < A[j]: + break + + # Swap the value of A[i] with that of A[j], then reverse the + # sequence from A[i + 1] to form the new permutation + A[i], A[j] = A[j], A[i] + A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1] + + # Algorithm: modified from the above + def _partial(A, r): + # Split A into the first r items and the last r items + head, tail = A[:r], A[r:] + right_head_indexes = range(r - 1, -1, -1) + left_tail_indexes = range(len(tail)) + + while True: + # Yield the permutation we have + yield tuple(head) + + # Starting from the right, find the first index of the head with + # value smaller than the maximum value of the tail - call it i. + pivot = tail[-1] + for i in right_head_indexes: + if head[i] < pivot: + break + pivot = head[i] + else: + return + + # Starting from the left, find the first value of the tail + # with a value greater than head[i] and swap. + for j in left_tail_indexes: + if tail[j] > head[i]: + head[i], tail[j] = tail[j], head[i] + break + # If we didn't find one, start from the right and find the first + # index of the head with a value greater than head[i] and swap. + else: + for j in right_head_indexes: + if head[j] > head[i]: + head[i], head[j] = head[j], head[i] + break + + # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)] + tail += head[: i - r : -1] # head[i + 1:][::-1] + i += 1 + head[i:], tail[:] = tail[: r - i], tail[r - i :] + + items = sorted(iterable) + + size = len(items) + if r is None: + r = size + + if 0 < r <= size: + return _full(items) if (r == size) else _partial(items, r) + + return iter(() if r else ((),)) + + +def intersperse(e, iterable, n=1): + """Intersperse filler element *e* among the items in *iterable*, leaving + *n* items between each filler element. + + >>> list(intersperse('!', [1, 2, 3, 4, 5])) + [1, '!', 2, '!', 3, '!', 4, '!', 5] + + >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) + [1, 2, None, 3, 4, None, 5] + + """ + if n == 0: + raise ValueError('n must be > 0') + elif n == 1: + # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2... + # islice(..., 1, None) -> x_0, e, x_1, e, x_2... + return islice(interleave(repeat(e), iterable), 1, None) + else: + # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]... + # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]... + # flatten(...) -> x_0, x_1, e, x_2, x_3... + filler = repeat([e]) + chunks = chunked(iterable, n) + return flatten(islice(interleave(filler, chunks), 1, None)) + + +def unique_to_each(*iterables): + """Return the elements from each of the input iterables that aren't in the + other input iterables. + + For example, suppose you have a set of packages, each with a set of + dependencies:: + + {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}} + + If you remove one package, which dependencies can also be removed? + + If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not + associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for + ``pkg_2``, and ``D`` is only needed for ``pkg_3``:: + + >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'}) + [['A'], ['C'], ['D']] + + If there are duplicates in one input iterable that aren't in the others + they will be duplicated in the output. Input order is preserved:: + + >>> unique_to_each("mississippi", "missouri") + [['p', 'p'], ['o', 'u', 'r']] + + It is assumed that the elements of each iterable are hashable. + + """ + pool = [list(it) for it in iterables] + counts = Counter(chain.from_iterable(map(set, pool))) + uniques = {element for element in counts if counts[element] == 1} + return [list(filter(uniques.__contains__, it)) for it in pool] + + +def windowed(seq, n, fillvalue=None, step=1): + """Return a sliding window of width *n* over the given iterable. + + >>> all_windows = windowed([1, 2, 3, 4, 5], 3) + >>> list(all_windows) + [(1, 2, 3), (2, 3, 4), (3, 4, 5)] + + When the window is larger than the iterable, *fillvalue* is used in place + of missing values: + + >>> list(windowed([1, 2, 3], 4)) + [(1, 2, 3, None)] + + Each window will advance in increments of *step*: + + >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2)) + [(1, 2, 3), (3, 4, 5), (5, 6, '!')] + + To slide into the iterable's items, use :func:`chain` to add filler items + to the left: + + >>> iterable = [1, 2, 3, 4] + >>> n = 3 + >>> padding = [None] * (n - 1) + >>> list(windowed(chain(padding, iterable), 3)) + [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)] + """ + if n < 0: + raise ValueError('n must be >= 0') + if n == 0: + yield () + return + if step < 1: + raise ValueError('step must be >= 1') + + iterable = iter(seq) + + # Generate first window + window = deque(islice(iterable, n), maxlen=n) + + # Deal with the first window not being full + if not window: + return + if len(window) < n: + yield tuple(window) + ((fillvalue,) * (n - len(window))) + return + yield tuple(window) + + # Create the filler for the next windows. The padding ensures + # we have just enough elements to fill the last window. + padding = (fillvalue,) * (n - 1 if step >= n else step - 1) + filler = map(window.append, chain(iterable, padding)) + + # Generate the rest of the windows + for _ in islice(filler, step - 1, None, step): + yield tuple(window) + + +def substrings(iterable): + """Yield all of the substrings of *iterable*. + + >>> [''.join(s) for s in substrings('more')] + ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more'] + + Note that non-string iterables can also be subdivided. + + >>> list(substrings([0, 1, 2])) + [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)] + + """ + # The length-1 substrings + seq = [] + for item in iter(iterable): + seq.append(item) + yield (item,) + seq = tuple(seq) + item_count = len(seq) + + # And the rest + for n in range(2, item_count + 1): + for i in range(item_count - n + 1): + yield seq[i : i + n] + + +def substrings_indexes(seq, reverse=False): + """Yield all substrings and their positions in *seq* + + The items yielded will be a tuple of the form ``(substr, i, j)``, where + ``substr == seq[i:j]``. + + This function only works for iterables that support slicing, such as + ``str`` objects. + + >>> for item in substrings_indexes('more'): + ... print(item) + ('m', 0, 1) + ('o', 1, 2) + ('r', 2, 3) + ('e', 3, 4) + ('mo', 0, 2) + ('or', 1, 3) + ('re', 2, 4) + ('mor', 0, 3) + ('ore', 1, 4) + ('more', 0, 4) + + Set *reverse* to ``True`` to yield the same items in the opposite order. + + + """ + r = range(1, len(seq) + 1) + if reverse: + r = reversed(r) + return ( + (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1) + ) + + +class bucket: + """Wrap *iterable* and return an object that buckets the iterable into + child iterables based on a *key* function. + + >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] + >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character + >>> sorted(list(s)) # Get the keys + ['a', 'b', 'c'] + >>> a_iterable = s['a'] + >>> next(a_iterable) + 'a1' + >>> next(a_iterable) + 'a2' + >>> list(s['b']) + ['b1', 'b2', 'b3'] + + The original iterable will be advanced and its items will be cached until + they are used by the child iterables. This may require significant storage. + + By default, attempting to select a bucket to which no items belong will + exhaust the iterable and cache all values. + If you specify a *validator* function, selected buckets will instead be + checked against it. + + >>> from itertools import count + >>> it = count(1, 2) # Infinite sequence of odd numbers + >>> key = lambda x: x % 10 # Bucket by last digit + >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only + >>> s = bucket(it, key=key, validator=validator) + >>> 2 in s + False + >>> list(s[2]) + [] + + """ + + def __init__(self, iterable, key, validator=None): + self._it = iter(iterable) + self._key = key + self._cache = defaultdict(deque) + self._validator = validator or (lambda x: True) + + def __contains__(self, value): + if not self._validator(value): + return False + + try: + item = next(self[value]) + except StopIteration: + return False + else: + self._cache[value].appendleft(item) + + return True + + def _get_values(self, value): + """ + Helper to yield items from the parent iterator that match *value*. + Items that don't match are stored in the local cache as they + are encountered. + """ + while True: + # If we've cached some items that match the target value, emit + # the first one and evict it from the cache. + if self._cache[value]: + yield self._cache[value].popleft() + # Otherwise we need to advance the parent iterator to search for + # a matching item, caching the rest. + else: + while True: + try: + item = next(self._it) + except StopIteration: + return + item_value = self._key(item) + if item_value == value: + yield item + break + elif self._validator(item_value): + self._cache[item_value].append(item) + + def __iter__(self): + for item in self._it: + item_value = self._key(item) + if self._validator(item_value): + self._cache[item_value].append(item) + + yield from self._cache.keys() + + def __getitem__(self, value): + if not self._validator(value): + return iter(()) + + return self._get_values(value) + + +def spy(iterable, n=1): + """Return a 2-tuple with a list containing the first *n* elements of + *iterable*, and an iterator with the same items as *iterable*. + This allows you to "look ahead" at the items in the iterable without + advancing it. + + There is one item in the list by default: + + >>> iterable = 'abcdefg' + >>> head, iterable = spy(iterable) + >>> head + ['a'] + >>> list(iterable) + ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + + You may use unpacking to retrieve items instead of lists: + + >>> (head,), iterable = spy('abcdefg') + >>> head + 'a' + >>> (first, second), iterable = spy('abcdefg', 2) + >>> first + 'a' + >>> second + 'b' + + The number of items requested can be larger than the number of items in + the iterable: + + >>> iterable = [1, 2, 3, 4, 5] + >>> head, iterable = spy(iterable, 10) + >>> head + [1, 2, 3, 4, 5] + >>> list(iterable) + [1, 2, 3, 4, 5] + + """ + it = iter(iterable) + head = take(n, it) + + return head.copy(), chain(head, it) + + +def interleave(*iterables): + """Return a new iterable yielding from each iterable in turn, + until the shortest is exhausted. + + >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8])) + [1, 4, 6, 2, 5, 7] + + For a version that doesn't terminate after the shortest iterable is + exhausted, see :func:`interleave_longest`. + + """ + return chain.from_iterable(zip(*iterables)) + + +def interleave_longest(*iterables): + """Return a new iterable yielding from each iterable in turn, + skipping any that are exhausted. + + >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8])) + [1, 4, 6, 2, 5, 7, 3, 8] + + This function produces the same output as :func:`roundrobin`, but may + perform better for some inputs (in particular when the number of iterables + is large). + + """ + i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker)) + return (x for x in i if x is not _marker) + + +def interleave_evenly(iterables, lengths=None): + """ + Interleave multiple iterables so that their elements are evenly distributed + throughout the output sequence. + + >>> iterables = [1, 2, 3, 4, 5], ['a', 'b'] + >>> list(interleave_evenly(iterables)) + [1, 2, 'a', 3, 4, 'b', 5] + + >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]] + >>> list(interleave_evenly(iterables)) + [1, 6, 4, 2, 7, 3, 8, 5] + + This function requires iterables of known length. Iterables without + ``__len__()`` can be used by manually specifying lengths with *lengths*: + + >>> from itertools import combinations, repeat + >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']] + >>> lengths = [4 * (4 - 1) // 2, 3] + >>> list(interleave_evenly(iterables, lengths=lengths)) + [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c'] + + Based on Bresenham's algorithm. + """ + if lengths is None: + try: + lengths = [len(it) for it in iterables] + except TypeError: + raise ValueError( + 'Iterable lengths could not be determined automatically. ' + 'Specify them with the lengths keyword.' + ) + elif len(iterables) != len(lengths): + raise ValueError('Mismatching number of iterables and lengths.') + + dims = len(lengths) + + # sort iterables by length, descending + lengths_permute = sorted( + range(dims), key=lambda i: lengths[i], reverse=True + ) + lengths_desc = [lengths[i] for i in lengths_permute] + iters_desc = [iter(iterables[i]) for i in lengths_permute] + + # the longest iterable is the primary one (Bresenham: the longest + # distance along an axis) + delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:] + iter_primary, iters_secondary = iters_desc[0], iters_desc[1:] + errors = [delta_primary // dims] * len(deltas_secondary) + + to_yield = sum(lengths) + while to_yield: + yield next(iter_primary) + to_yield -= 1 + # update errors for each secondary iterable + errors = [e - delta for e, delta in zip(errors, deltas_secondary)] + + # those iterables for which the error is negative are yielded + # ("diagonal step" in Bresenham) + for i, e_ in enumerate(errors): + if e_ < 0: + yield next(iters_secondary[i]) + to_yield -= 1 + errors[i] += delta_primary + + +def collapse(iterable, base_type=None, levels=None): + """Flatten an iterable with multiple levels of nesting (e.g., a list of + lists of tuples) into non-iterable types. + + >>> iterable = [(1, 2), ([3, 4], [[5], [6]])] + >>> list(collapse(iterable)) + [1, 2, 3, 4, 5, 6] + + Binary and text strings are not considered iterable and + will not be collapsed. + + To avoid collapsing other types, specify *base_type*: + + >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']] + >>> list(collapse(iterable, base_type=tuple)) + ['ab', ('cd', 'ef'), 'gh', 'ij'] + + Specify *levels* to stop flattening after a certain level: + + >>> iterable = [('a', ['b']), ('c', ['d'])] + >>> list(collapse(iterable)) # Fully flattened + ['a', 'b', 'c', 'd'] + >>> list(collapse(iterable, levels=1)) # Only one level flattened + ['a', ['b'], 'c', ['d']] + + """ + stack = deque() + # Add our first node group, treat the iterable as a single node + stack.appendleft((0, repeat(iterable, 1))) + + while stack: + node_group = stack.popleft() + level, nodes = node_group + + # Check if beyond max level + if levels is not None and level > levels: + yield from nodes + continue + + for node in nodes: + # Check if done iterating + if isinstance(node, (str, bytes)) or ( + (base_type is not None) and isinstance(node, base_type) + ): + yield node + # Otherwise try to create child nodes + else: + try: + tree = iter(node) + except TypeError: + yield node + else: + # Save our current location + stack.appendleft(node_group) + # Append the new child node + stack.appendleft((level + 1, tree)) + # Break to process child node + break + + +def side_effect(func, iterable, chunk_size=None, before=None, after=None): + """Invoke *func* on each item in *iterable* (or on each *chunk_size* group + of items) before yielding the item. + + `func` must be a function that takes a single argument. Its return value + will be discarded. + + *before* and *after* are optional functions that take no arguments. They + will be executed before iteration starts and after it ends, respectively. + + `side_effect` can be used for logging, updating progress bars, or anything + that is not functionally "pure." + + Emitting a status message: + + >>> from more_itertools import consume + >>> func = lambda item: print('Received {}'.format(item)) + >>> consume(side_effect(func, range(2))) + Received 0 + Received 1 + + Operating on chunks of items: + + >>> pair_sums = [] + >>> func = lambda chunk: pair_sums.append(sum(chunk)) + >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2)) + [0, 1, 2, 3, 4, 5] + >>> list(pair_sums) + [1, 5, 9] + + Writing to a file-like object: + + >>> from io import StringIO + >>> from more_itertools import consume + >>> f = StringIO() + >>> func = lambda x: print(x, file=f) + >>> before = lambda: print(u'HEADER', file=f) + >>> after = f.close + >>> it = [u'a', u'b', u'c'] + >>> consume(side_effect(func, it, before=before, after=after)) + >>> f.closed + True + + """ + try: + if before is not None: + before() + + if chunk_size is None: + for item in iterable: + func(item) + yield item + else: + for chunk in chunked(iterable, chunk_size): + func(chunk) + yield from chunk + finally: + if after is not None: + after() + + +def sliced(seq, n, strict=False): + """Yield slices of length *n* from the sequence *seq*. + + >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) + [(1, 2, 3), (4, 5, 6)] + + By the default, the last yielded slice will have fewer than *n* elements + if the length of *seq* is not divisible by *n*: + + >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3)) + [(1, 2, 3), (4, 5, 6), (7, 8)] + + If the length of *seq* is not divisible by *n* and *strict* is + ``True``, then ``ValueError`` will be raised before the last + slice is yielded. + + This function will only work for iterables that support slicing. + For non-sliceable iterables, see :func:`chunked`. + + """ + iterator = takewhile(len, (seq[i : i + n] for i in count(0, n))) + if strict: + + def ret(): + for _slice in iterator: + if len(_slice) != n: + raise ValueError("seq is not divisible by n.") + yield _slice + + return iter(ret()) + else: + return iterator + + +def split_at(iterable, pred, maxsplit=-1, keep_separator=False): + """Yield lists of items from *iterable*, where each list is delimited by + an item where callable *pred* returns ``True``. + + >>> list(split_at('abcdcba', lambda x: x == 'b')) + [['a'], ['c', 'd', 'c'], ['a']] + + >>> list(split_at(range(10), lambda n: n % 2 == 1)) + [[0], [2], [4], [6], [8], []] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2)) + [[0], [2], [4, 5, 6, 7, 8, 9]] + + By default, the delimiting items are not included in the output. + To include them, set *keep_separator* to ``True``. + + >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True)) + [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']] + + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + if pred(item): + yield buf + if keep_separator: + yield [item] + if maxsplit == 1: + yield list(it) + return + buf = [] + maxsplit -= 1 + else: + buf.append(item) + yield buf + + +def split_before(iterable, pred, maxsplit=-1): + """Yield lists of items from *iterable*, where each list ends just before + an item for which callable *pred* returns ``True``: + + >>> list(split_before('OneTwo', lambda s: s.isupper())) + [['O', 'n', 'e'], ['T', 'w', 'o']] + + >>> list(split_before(range(10), lambda n: n % 3 == 0)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + if pred(item) and buf: + yield buf + if maxsplit == 1: + yield [item] + list(it) + return + buf = [] + maxsplit -= 1 + buf.append(item) + if buf: + yield buf + + +def split_after(iterable, pred, maxsplit=-1): + """Yield lists of items from *iterable*, where each list ends with an + item where callable *pred* returns ``True``: + + >>> list(split_after('one1two2', lambda s: s.isdigit())) + [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']] + + >>> list(split_after(range(10), lambda n: n % 3 == 0)) + [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2)) + [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]] + + """ + if maxsplit == 0: + yield list(iterable) + return + + buf = [] + it = iter(iterable) + for item in it: + buf.append(item) + if pred(item) and buf: + yield buf + if maxsplit == 1: + buf = list(it) + if buf: + yield buf + return + buf = [] + maxsplit -= 1 + if buf: + yield buf + + +def split_when(iterable, pred, maxsplit=-1): + """Split *iterable* into pieces based on the output of *pred*. + *pred* should be a function that takes successive pairs of items and + returns ``True`` if the iterable should be split in between them. + + For example, to find runs of increasing numbers, split the iterable when + element ``i`` is larger than element ``i + 1``: + + >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y)) + [[1, 2, 3, 3], [2, 5], [2, 4], [2]] + + At most *maxsplit* splits are done. If *maxsplit* is not specified or -1, + then there is no limit on the number of splits: + + >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], + ... lambda x, y: x > y, maxsplit=2)) + [[1, 2, 3, 3], [2, 5], [2, 4, 2]] + + """ + if maxsplit == 0: + yield list(iterable) + return + + it = iter(iterable) + try: + cur_item = next(it) + except StopIteration: + return + + buf = [cur_item] + for next_item in it: + if pred(cur_item, next_item): + yield buf + if maxsplit == 1: + yield [next_item] + list(it) + return + buf = [] + maxsplit -= 1 + + buf.append(next_item) + cur_item = next_item + + yield buf + + +def split_into(iterable, sizes): + """Yield a list of sequential items from *iterable* of length 'n' for each + integer 'n' in *sizes*. + + >>> list(split_into([1,2,3,4,5,6], [1,2,3])) + [[1], [2, 3], [4, 5, 6]] + + If the sum of *sizes* is smaller than the length of *iterable*, then the + remaining items of *iterable* will not be returned. + + >>> list(split_into([1,2,3,4,5,6], [2,3])) + [[1, 2], [3, 4, 5]] + + If the sum of *sizes* is larger than the length of *iterable*, fewer items + will be returned in the iteration that overruns *iterable* and further + lists will be empty: + + >>> list(split_into([1,2,3,4], [1,2,3,4])) + [[1], [2, 3], [4], []] + + When a ``None`` object is encountered in *sizes*, the returned list will + contain items up to the end of *iterable* the same way that itertools.slice + does: + + >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None])) + [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]] + + :func:`split_into` can be useful for grouping a series of items where the + sizes of the groups are not uniform. An example would be where in a row + from a table, multiple columns represent elements of the same feature + (e.g. a point represented by x,y,z) but, the format is not the same for + all columns. + """ + # convert the iterable argument into an iterator so its contents can + # be consumed by islice in case it is a generator + it = iter(iterable) + + for size in sizes: + if size is None: + yield list(it) + return + else: + yield list(islice(it, size)) + + +def padded(iterable, fillvalue=None, n=None, next_multiple=False): + """Yield the elements from *iterable*, followed by *fillvalue*, such that + at least *n* items are emitted. + + >>> list(padded([1, 2, 3], '?', 5)) + [1, 2, 3, '?', '?'] + + If *next_multiple* is ``True``, *fillvalue* will be emitted until the + number of items emitted is a multiple of *n*: + + >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True)) + [1, 2, 3, 4, None, None] + + If *n* is ``None``, *fillvalue* will be emitted indefinitely. + + To create an *iterable* of exactly size *n*, you can truncate with + :func:`islice`. + + >>> list(islice(padded([1, 2, 3], '?'), 5)) + [1, 2, 3, '?', '?'] + >>> list(islice(padded([1, 2, 3, 4, 5, 6, 7, 8], '?'), 5)) + [1, 2, 3, 4, 5] + + """ + iterable = iter(iterable) + iterable_with_repeat = chain(iterable, repeat(fillvalue)) + + if n is None: + return iterable_with_repeat + elif n < 1: + raise ValueError('n must be at least 1') + elif next_multiple: + + def slice_generator(): + for first in iterable: + yield (first,) + yield islice(iterable_with_repeat, n - 1) + + # While elements exist produce slices of size n + return chain.from_iterable(slice_generator()) + else: + # Ensure the first batch is at least size n then iterate + return chain(islice(iterable_with_repeat, n), iterable) + + +def repeat_each(iterable, n=2): + """Repeat each element in *iterable* *n* times. + + >>> list(repeat_each('ABC', 3)) + ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'] + """ + return chain.from_iterable(map(repeat, iterable, repeat(n))) + + +def repeat_last(iterable, default=None): + """After the *iterable* is exhausted, keep yielding its last element. + + >>> list(islice(repeat_last(range(3)), 5)) + [0, 1, 2, 2, 2] + + If the iterable is empty, yield *default* forever:: + + >>> list(islice(repeat_last(range(0), 42), 5)) + [42, 42, 42, 42, 42] + + """ + item = _marker + for item in iterable: + yield item + final = default if item is _marker else item + yield from repeat(final) + + +def distribute(n, iterable): + """Distribute the items from *iterable* among *n* smaller iterables. + + >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) + >>> list(group_1) + [1, 3, 5] + >>> list(group_2) + [2, 4, 6] + + If the length of *iterable* is not evenly divisible by *n*, then the + length of the returned iterables will not be identical: + + >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7]) + >>> [list(c) for c in children] + [[1, 4, 7], [2, 5], [3, 6]] + + If the length of *iterable* is smaller than *n*, then the last returned + iterables will be empty: + + >>> children = distribute(5, [1, 2, 3]) + >>> [list(c) for c in children] + [[1], [2], [3], [], []] + + This function uses :func:`itertools.tee` and may require significant + storage. + + If you need the order items in the smaller iterables to match the + original iterable, see :func:`divide`. + + """ + if n < 1: + raise ValueError('n must be at least 1') + + children = tee(iterable, n) + return [islice(it, index, None, n) for index, it in enumerate(children)] + + +def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None): + """Yield tuples whose elements are offset from *iterable*. + The amount by which the `i`-th item in each tuple is offset is given by + the `i`-th item in *offsets*. + + >>> list(stagger([0, 1, 2, 3])) + [(None, 0, 1), (0, 1, 2), (1, 2, 3)] + >>> list(stagger(range(8), offsets=(0, 2, 4))) + [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] + + By default, the sequence will end when the final element of a tuple is the + last item in the iterable. To continue until the first element of a tuple + is the last item in the iterable, set *longest* to ``True``:: + + >>> list(stagger([0, 1, 2, 3], longest=True)) + [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] + + By default, ``None`` will be used to replace offsets beyond the end of the + sequence. Specify *fillvalue* to use some other value. + + """ + children = tee(iterable, len(offsets)) + + return zip_offset( + *children, offsets=offsets, longest=longest, fillvalue=fillvalue + ) + + +def zip_equal(*iterables): + """``zip`` the input *iterables* together, but raise + ``UnequalIterablesError`` if they aren't all the same length. + + >>> it_1 = range(3) + >>> it_2 = iter('abc') + >>> list(zip_equal(it_1, it_2)) + [(0, 'a'), (1, 'b'), (2, 'c')] + + >>> it_1 = range(3) + >>> it_2 = iter('abcd') + >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + more_itertools.more.UnequalIterablesError: Iterables have different + lengths + + """ + if hexversion >= 0x30A00A6: + warnings.warn( + ( + 'zip_equal will be removed in a future version of ' + 'more-itertools. Use the builtin zip function with ' + 'strict=True instead.' + ), + DeprecationWarning, + ) + + return _zip_equal(*iterables) + + +def zip_offset(*iterables, offsets, longest=False, fillvalue=None): + """``zip`` the input *iterables* together, but offset the `i`-th iterable + by the `i`-th item in *offsets*. + + >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1))) + [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')] + + This can be used as a lightweight alternative to SciPy or pandas to analyze + data sets in which some series have a lead or lag relationship. + + By default, the sequence will end when the shortest iterable is exhausted. + To continue until the longest iterable is exhausted, set *longest* to + ``True``. + + >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True)) + [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')] + + By default, ``None`` will be used to replace offsets beyond the end of the + sequence. Specify *fillvalue* to use some other value. + + """ + if len(iterables) != len(offsets): + raise ValueError("Number of iterables and offsets didn't match") + + staggered = [] + for it, n in zip(iterables, offsets): + if n < 0: + staggered.append(chain(repeat(fillvalue, -n), it)) + elif n > 0: + staggered.append(islice(it, n, None)) + else: + staggered.append(it) + + if longest: + return zip_longest(*staggered, fillvalue=fillvalue) + + return zip(*staggered) + + +def sort_together(iterables, key_list=(0,), key=None, reverse=False): + """Return the input iterables sorted together, with *key_list* as the + priority for sorting. All iterables are trimmed to the length of the + shortest one. + + This can be used like the sorting function in a spreadsheet. If each + iterable represents a column of data, the key list determines which + columns are used for sorting. + + By default, all iterables are sorted using the ``0``-th iterable:: + + >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')] + >>> sort_together(iterables) + [(1, 2, 3, 4), ('d', 'c', 'b', 'a')] + + Set a different key list to sort according to another iterable. + Specifying multiple keys dictates how ties are broken:: + + >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')] + >>> sort_together(iterables, key_list=(1, 2)) + [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')] + + To sort by a function of the elements of the iterable, pass a *key* + function. Its arguments are the elements of the iterables corresponding to + the key list:: + + >>> names = ('a', 'b', 'c') + >>> lengths = (1, 2, 3) + >>> widths = (5, 2, 1) + >>> def area(length, width): + ... return length * width + >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area) + [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)] + + Set *reverse* to ``True`` to sort in descending order. + + >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True) + [(3, 2, 1), ('a', 'b', 'c')] + + """ + if key is None: + # if there is no key function, the key argument to sorted is an + # itemgetter + key_argument = itemgetter(*key_list) + else: + # if there is a key function, call it with the items at the offsets + # specified by the key function as arguments + key_list = list(key_list) + if len(key_list) == 1: + # if key_list contains a single item, pass the item at that offset + # as the only argument to the key function + key_offset = key_list[0] + key_argument = lambda zipped_items: key(zipped_items[key_offset]) + else: + # if key_list contains multiple items, use itemgetter to return a + # tuple of items, which we pass as *args to the key function + get_key_items = itemgetter(*key_list) + key_argument = lambda zipped_items: key( + *get_key_items(zipped_items) + ) + + return list( + zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse)) + ) + + +def unzip(iterable): + """The inverse of :func:`zip`, this function disaggregates the elements + of the zipped *iterable*. + + The ``i``-th iterable contains the ``i``-th element from each element + of the zipped iterable. The first element is used to determine the + length of the remaining elements. + + >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + >>> letters, numbers = unzip(iterable) + >>> list(letters) + ['a', 'b', 'c', 'd'] + >>> list(numbers) + [1, 2, 3, 4] + + This is similar to using ``zip(*iterable)``, but it avoids reading + *iterable* into memory. Note, however, that this function uses + :func:`itertools.tee` and thus may require significant storage. + + """ + head, iterable = spy(iter(iterable)) + if not head: + # empty iterable, e.g. zip([], [], []) + return () + # spy returns a one-length iterable as head + head = head[0] + iterables = tee(iterable, len(head)) + + def itemgetter(i): + def getter(obj): + try: + return obj[i] + except IndexError: + # basically if we have an iterable like + # iter([(1, 2, 3), (4, 5), (6,)]) + # the second unzipped iterable would fail at the third tuple + # since it would try to access tup[1] + # same with the third unzipped iterable and the second tuple + # to support these "improperly zipped" iterables, + # we create a custom itemgetter + # which just stops the unzipped iterables + # at first length mismatch + raise StopIteration + + return getter + + return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables)) + + +def divide(n, iterable): + """Divide the elements from *iterable* into *n* parts, maintaining + order. + + >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) + >>> list(group_1) + [1, 2, 3] + >>> list(group_2) + [4, 5, 6] + + If the length of *iterable* is not evenly divisible by *n*, then the + length of the returned iterables will not be identical: + + >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) + >>> [list(c) for c in children] + [[1, 2, 3], [4, 5], [6, 7]] + + If the length of the iterable is smaller than n, then the last returned + iterables will be empty: + + >>> children = divide(5, [1, 2, 3]) + >>> [list(c) for c in children] + [[1], [2], [3], [], []] + + This function will exhaust the iterable before returning. + If order is not important, see :func:`distribute`, which does not first + pull the iterable into memory. + + """ + if n < 1: + raise ValueError('n must be at least 1') + + try: + iterable[:0] + except TypeError: + seq = tuple(iterable) + else: + seq = iterable + + q, r = divmod(len(seq), n) + + ret = [] + stop = 0 + for i in range(1, n + 1): + start = stop + stop += q + 1 if i <= r else q + ret.append(iter(seq[start:stop])) + + return ret + + +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) + + +def adjacent(predicate, iterable, distance=1): + """Return an iterable over `(bool, item)` tuples where the `item` is + drawn from *iterable* and the `bool` indicates whether + that item satisfies the *predicate* or is adjacent to an item that does. + + For example, to find whether items are adjacent to a ``3``:: + + >>> list(adjacent(lambda x: x == 3, range(6))) + [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)] + + Set *distance* to change what counts as adjacent. For example, to find + whether items are two places away from a ``3``: + + >>> list(adjacent(lambda x: x == 3, range(6), distance=2)) + [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)] + + This is useful for contextualizing the results of a search function. + For example, a code comparison tool might want to identify lines that + have changed, but also surrounding lines to give the viewer of the diff + context. + + The predicate function will only be called once for each item in the + iterable. + + See also :func:`groupby_transform`, which can be used with this function + to group ranges of items with the same `bool` value. + + """ + # Allow distance=0 mainly for testing that it reproduces results with map() + if distance < 0: + raise ValueError('distance must be at least 0') + + i1, i2 = tee(iterable) + padding = [False] * distance + selected = chain(padding, map(predicate, i1), padding) + adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1)) + return zip(adjacent_to_selected, i2) + + +def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None): + """An extension of :func:`itertools.groupby` that can apply transformations + to the grouped data. + + * *keyfunc* is a function computing a key value for each item in *iterable* + * *valuefunc* is a function that transforms the individual items from + *iterable* after grouping + * *reducefunc* is a function that transforms each group of items + + >>> iterable = 'aAAbBBcCC' + >>> keyfunc = lambda k: k.upper() + >>> valuefunc = lambda v: v.lower() + >>> reducefunc = lambda g: ''.join(g) + >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc)) + [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')] + + Each optional argument defaults to an identity function if not specified. + + :func:`groupby_transform` is useful when grouping elements of an iterable + using a separate iterable as the key. To do this, :func:`zip` the iterables + and pass a *keyfunc* that extracts the first element and a *valuefunc* + that extracts the second element:: + + >>> from operator import itemgetter + >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3] + >>> values = 'abcdefghi' + >>> iterable = zip(keys, values) + >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1)) + >>> [(k, ''.join(g)) for k, g in grouper] + [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')] + + Note that the order of items in the iterable is significant. + Only adjacent items are grouped together, so if you don't want any + duplicate groups, you should sort the iterable by the key function. + + """ + ret = groupby(iterable, keyfunc) + if valuefunc: + ret = ((k, map(valuefunc, g)) for k, g in ret) + if reducefunc: + ret = ((k, reducefunc(g)) for k, g in ret) + + return ret + + +class numeric_range(abc.Sequence, abc.Hashable): + """An extension of the built-in ``range()`` function whose arguments can + be any orderable numeric type. + + With only *stop* specified, *start* defaults to ``0`` and *step* + defaults to ``1``. The output items will match the type of *stop*: + + >>> list(numeric_range(3.5)) + [0.0, 1.0, 2.0, 3.0] + + With only *start* and *stop* specified, *step* defaults to ``1``. The + output items will match the type of *start*: + + >>> from decimal import Decimal + >>> start = Decimal('2.1') + >>> stop = Decimal('5.1') + >>> list(numeric_range(start, stop)) + [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')] + + With *start*, *stop*, and *step* specified the output items will match + the type of ``start + step``: + + >>> from fractions import Fraction + >>> start = Fraction(1, 2) # Start at 1/2 + >>> stop = Fraction(5, 2) # End at 5/2 + >>> step = Fraction(1, 2) # Count by 1/2 + >>> list(numeric_range(start, stop, step)) + [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)] + + If *step* is zero, ``ValueError`` is raised. Negative steps are supported: + + >>> list(numeric_range(3, -1, -1.0)) + [3.0, 2.0, 1.0, 0.0] + + Be aware of the limitations of floating point numbers; the representation + of the yielded numbers may be surprising. + + ``datetime.datetime`` objects can be used for *start* and *stop*, if *step* + is a ``datetime.timedelta`` object: + + >>> import datetime + >>> start = datetime.datetime(2019, 1, 1) + >>> stop = datetime.datetime(2019, 1, 3) + >>> step = datetime.timedelta(days=1) + >>> items = iter(numeric_range(start, stop, step)) + >>> next(items) + datetime.datetime(2019, 1, 1, 0, 0) + >>> next(items) + datetime.datetime(2019, 1, 2, 0, 0) + + """ + + _EMPTY_HASH = hash(range(0, 0)) + + def __init__(self, *args): + argc = len(args) + if argc == 1: + (self._stop,) = args + self._start = type(self._stop)(0) + self._step = type(self._stop - self._start)(1) + elif argc == 2: + self._start, self._stop = args + self._step = type(self._stop - self._start)(1) + elif argc == 3: + self._start, self._stop, self._step = args + elif argc == 0: + raise TypeError( + 'numeric_range expected at least ' + '1 argument, got {}'.format(argc) + ) + else: + raise TypeError( + 'numeric_range expected at most ' + '3 arguments, got {}'.format(argc) + ) + + self._zero = type(self._step)(0) + if self._step == self._zero: + raise ValueError('numeric_range() arg 3 must not be zero') + self._growing = self._step > self._zero + + def __bool__(self): + if self._growing: + return self._start < self._stop + else: + return self._start > self._stop + + def __contains__(self, elem): + if self._growing: + if self._start <= elem < self._stop: + return (elem - self._start) % self._step == self._zero + else: + if self._start >= elem > self._stop: + return (self._start - elem) % (-self._step) == self._zero + + return False + + def __eq__(self, other): + if isinstance(other, numeric_range): + empty_self = not bool(self) + empty_other = not bool(other) + if empty_self or empty_other: + return empty_self and empty_other # True if both empty + else: + return ( + self._start == other._start + and self._step == other._step + and self._get_by_index(-1) == other._get_by_index(-1) + ) + else: + return False + + def __getitem__(self, key): + if isinstance(key, int): + return self._get_by_index(key) + elif isinstance(key, slice): + step = self._step if key.step is None else key.step * self._step + + if key.start is None or key.start <= -self._len: + start = self._start + elif key.start >= self._len: + start = self._stop + else: # -self._len < key.start < self._len + start = self._get_by_index(key.start) + + if key.stop is None or key.stop >= self._len: + stop = self._stop + elif key.stop <= -self._len: + stop = self._start + else: # -self._len < key.stop < self._len + stop = self._get_by_index(key.stop) + + return numeric_range(start, stop, step) + else: + raise TypeError( + 'numeric range indices must be ' + 'integers or slices, not {}'.format(type(key).__name__) + ) + + def __hash__(self): + if self: + return hash((self._start, self._get_by_index(-1), self._step)) + else: + return self._EMPTY_HASH + + def __iter__(self): + values = (self._start + (n * self._step) for n in count()) + if self._growing: + return takewhile(partial(gt, self._stop), values) + else: + return takewhile(partial(lt, self._stop), values) + + def __len__(self): + return self._len + + @cached_property + def _len(self): + if self._growing: + start = self._start + stop = self._stop + step = self._step + else: + start = self._stop + stop = self._start + step = -self._step + distance = stop - start + if distance <= self._zero: + return 0 + else: # distance > 0 and step > 0: regular euclidean division + q, r = divmod(distance, step) + return int(q) + int(r != self._zero) + + def __reduce__(self): + return numeric_range, (self._start, self._stop, self._step) + + def __repr__(self): + if self._step == 1: + return "numeric_range({}, {})".format( + repr(self._start), repr(self._stop) + ) + else: + return "numeric_range({}, {}, {})".format( + repr(self._start), repr(self._stop), repr(self._step) + ) + + def __reversed__(self): + return iter( + numeric_range( + self._get_by_index(-1), self._start - self._step, -self._step + ) + ) + + def count(self, value): + return int(value in self) + + def index(self, value): + if self._growing: + if self._start <= value < self._stop: + q, r = divmod(value - self._start, self._step) + if r == self._zero: + return int(q) + else: + if self._start >= value > self._stop: + q, r = divmod(self._start - value, -self._step) + if r == self._zero: + return int(q) + + raise ValueError("{} is not in numeric range".format(value)) + + def _get_by_index(self, i): + if i < 0: + i += self._len + if i < 0 or i >= self._len: + raise IndexError("numeric range object index out of range") + return self._start + i * self._step + + +def count_cycle(iterable, n=None): + """Cycle through the items from *iterable* up to *n* times, yielding + the number of completed cycles along with each item. If *n* is omitted the + process repeats indefinitely. + + >>> list(count_cycle('AB', 3)) + [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] + + """ + iterable = tuple(iterable) + if not iterable: + return iter(()) + counter = count() if n is None else range(n) + return ((i, item) for i in counter for item in iterable) + + +def mark_ends(iterable): + """Yield 3-tuples of the form ``(is_first, is_last, item)``. + + >>> list(mark_ends('ABC')) + [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')] + + Use this when looping over an iterable to take special action on its first + and/or last items: + + >>> iterable = ['Header', 100, 200, 'Footer'] + >>> total = 0 + >>> for is_first, is_last, item in mark_ends(iterable): + ... if is_first: + ... continue # Skip the header + ... if is_last: + ... continue # Skip the footer + ... total += item + >>> print(total) + 300 + """ + it = iter(iterable) + + try: + b = next(it) + except StopIteration: + return + + try: + for i in count(): + a = b + b = next(it) + yield i == 0, False, a + + except StopIteration: + yield i == 0, True, a + + +def locate(iterable, pred=bool, window_size=None): + """Yield the index of each item in *iterable* for which *pred* returns + ``True``. + + *pred* defaults to :func:`bool`, which will select truthy items: + + >>> list(locate([0, 1, 1, 0, 1, 0, 0])) + [1, 2, 4] + + Set *pred* to a custom function to, e.g., find the indexes for a particular + item. + + >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b')) + [1, 3] + + If *window_size* is given, then the *pred* function will be called with + that many items. This enables searching for sub-sequences: + + >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] + >>> pred = lambda *args: args == (1, 2, 3) + >>> list(locate(iterable, pred=pred, window_size=3)) + [1, 5, 9] + + Use with :func:`seekable` to find indexes and then retrieve the associated + items: + + >>> from itertools import count + >>> from more_itertools import seekable + >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count()) + >>> it = seekable(source) + >>> pred = lambda x: x > 100 + >>> indexes = locate(it, pred=pred) + >>> i = next(indexes) + >>> it.seek(i) + >>> next(it) + 106 + + """ + if window_size is None: + return compress(count(), map(pred, iterable)) + + if window_size < 1: + raise ValueError('window size must be at least 1') + + it = windowed(iterable, window_size, fillvalue=_marker) + return compress(count(), starmap(pred, it)) + + +def longest_common_prefix(iterables): + """Yield elements of the longest common prefix amongst given *iterables*. + + >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf'])) + 'ab' + + """ + return (c[0] for c in takewhile(all_equal, zip(*iterables))) + + +def lstrip(iterable, pred): + """Yield the items from *iterable*, but strip any from the beginning + for which *pred* returns ``True``. + + For example, to remove a set of items from the start of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(lstrip(iterable, pred)) + [1, 2, None, 3, False, None] + + This function is analogous to to :func:`str.lstrip`, and is essentially + an wrapper for :func:`itertools.dropwhile`. + + """ + return dropwhile(pred, iterable) + + +def rstrip(iterable, pred): + """Yield the items from *iterable*, but strip any from the end + for which *pred* returns ``True``. + + For example, to remove a set of items from the end of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(rstrip(iterable, pred)) + [None, False, None, 1, 2, None, 3] + + This function is analogous to :func:`str.rstrip`. + + """ + cache = [] + cache_append = cache.append + cache_clear = cache.clear + for x in iterable: + if pred(x): + cache_append(x) + else: + yield from cache + cache_clear() + yield x + + +def strip(iterable, pred): + """Yield the items from *iterable*, but strip any from the + beginning and end for which *pred* returns ``True``. + + For example, to remove a set of items from both ends of an iterable: + + >>> iterable = (None, False, None, 1, 2, None, 3, False, None) + >>> pred = lambda x: x in {None, False, ''} + >>> list(strip(iterable, pred)) + [1, 2, None, 3] + + This function is analogous to :func:`str.strip`. + + """ + return rstrip(lstrip(iterable, pred), pred) + + +class islice_extended: + """An extension of :func:`itertools.islice` that supports negative values + for *stop*, *start*, and *step*. + + >>> iterable = iter('abcdefgh') + >>> list(islice_extended(iterable, -4, -1)) + ['e', 'f', 'g'] + + Slices with negative values require some caching of *iterable*, but this + function takes care to minimize the amount of memory required. + + For example, you can use a negative step with an infinite iterator: + + >>> from itertools import count + >>> list(islice_extended(count(), 110, 99, -2)) + [110, 108, 106, 104, 102, 100] + + You can also use slice notation directly: + + >>> iterable = map(str, count()) + >>> it = islice_extended(iterable)[10:20:2] + >>> list(it) + ['10', '12', '14', '16', '18'] + + """ + + def __init__(self, iterable, *args): + it = iter(iterable) + if args: + self._iterable = _islice_helper(it, slice(*args)) + else: + self._iterable = it + + def __iter__(self): + return self + + def __next__(self): + return next(self._iterable) + + def __getitem__(self, key): + if isinstance(key, slice): + return islice_extended(_islice_helper(self._iterable, key)) + + raise TypeError('islice_extended.__getitem__ argument must be a slice') + + +def _islice_helper(it, s): + start = s.start + stop = s.stop + if s.step == 0: + raise ValueError('step argument must be a non-zero integer or None.') + step = s.step or 1 + + if step > 0: + start = 0 if (start is None) else start + + if start < 0: + # Consume all but the last -start items + cache = deque(enumerate(it, 1), maxlen=-start) + len_iter = cache[-1][0] if cache else 0 + + # Adjust start to be positive + i = max(len_iter + start, 0) + + # Adjust stop to be positive + if stop is None: + j = len_iter + elif stop >= 0: + j = min(stop, len_iter) + else: + j = max(len_iter + stop, 0) + + # Slice the cache + n = j - i + if n <= 0: + return + + for index, item in islice(cache, 0, n, step): + yield item + elif (stop is not None) and (stop < 0): + # Advance to the start position + next(islice(it, start, start), None) + + # When stop is negative, we have to carry -stop items while + # iterating + cache = deque(islice(it, -stop), maxlen=-stop) + + for index, item in enumerate(it): + cached_item = cache.popleft() + if index % step == 0: + yield cached_item + cache.append(item) + else: + # When both start and stop are positive we have the normal case + yield from islice(it, start, stop, step) + else: + start = -1 if (start is None) else start + + if (stop is not None) and (stop < 0): + # Consume all but the last items + n = -stop - 1 + cache = deque(enumerate(it, 1), maxlen=n) + len_iter = cache[-1][0] if cache else 0 + + # If start and stop are both negative they are comparable and + # we can just slice. Otherwise we can adjust start to be negative + # and then slice. + if start < 0: + i, j = start, stop + else: + i, j = min(start - len_iter, -1), None + + for index, item in list(cache)[i:j:step]: + yield item + else: + # Advance to the stop position + if stop is not None: + m = stop + 1 + next(islice(it, m, m), None) + + # stop is positive, so if start is negative they are not comparable + # and we need the rest of the items. + if start < 0: + i = start + n = None + # stop is None and start is positive, so we just need items up to + # the start index. + elif stop is None: + i = None + n = start + 1 + # Both stop and start are positive, so they are comparable. + else: + i = None + n = start - stop + if n <= 0: + return + + cache = list(islice(it, n)) + + yield from cache[i::step] + + +def always_reversible(iterable): + """An extension of :func:`reversed` that supports all iterables, not + just those which implement the ``Reversible`` or ``Sequence`` protocols. + + >>> print(*always_reversible(x for x in range(3))) + 2 1 0 + + If the iterable is already reversible, this function returns the + result of :func:`reversed()`. If the iterable is not reversible, + this function will cache the remaining items in the iterable and + yield them in reverse order, which may require significant storage. + """ + try: + return reversed(iterable) + except TypeError: + return reversed(list(iterable)) + + +def consecutive_groups(iterable, ordering=lambda x: x): + """Yield groups of consecutive items using :func:`itertools.groupby`. + The *ordering* function determines whether two items are adjacent by + returning their position. + + By default, the ordering function is the identity function. This is + suitable for finding runs of numbers: + + >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40] + >>> for group in consecutive_groups(iterable): + ... print(list(group)) + [1] + [10, 11, 12] + [20] + [30, 31, 32, 33] + [40] + + For finding runs of adjacent letters, try using the :meth:`index` method + of a string of letters: + + >>> from string import ascii_lowercase + >>> iterable = 'abcdfgilmnop' + >>> ordering = ascii_lowercase.index + >>> for group in consecutive_groups(iterable, ordering): + ... print(list(group)) + ['a', 'b', 'c', 'd'] + ['f', 'g'] + ['i'] + ['l', 'm', 'n', 'o', 'p'] + + Each group of consecutive items is an iterator that shares it source with + *iterable*. When an an output group is advanced, the previous group is + no longer available unless its elements are copied (e.g., into a ``list``). + + >>> iterable = [1, 2, 11, 12, 21, 22] + >>> saved_groups = [] + >>> for group in consecutive_groups(iterable): + ... saved_groups.append(list(group)) # Copy group elements + >>> saved_groups + [[1, 2], [11, 12], [21, 22]] + + """ + for k, g in groupby( + enumerate(iterable), key=lambda x: x[0] - ordering(x[1]) + ): + yield map(itemgetter(1), g) + + +def difference(iterable, func=sub, *, initial=None): + """This function is the inverse of :func:`itertools.accumulate`. By default + it will compute the first difference of *iterable* using + :func:`operator.sub`: + + >>> from itertools import accumulate + >>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10 + >>> list(difference(iterable)) + [0, 1, 2, 3, 4] + + *func* defaults to :func:`operator.sub`, but other functions can be + specified. They will be applied as follows:: + + A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ... + + For example, to do progressive division: + + >>> iterable = [1, 2, 6, 24, 120] + >>> func = lambda x, y: x // y + >>> list(difference(iterable, func)) + [1, 2, 3, 4, 5] + + If the *initial* keyword is set, the first element will be skipped when + computing successive differences. + + >>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10) + >>> list(difference(it, initial=10)) + [1, 2, 3] + + """ + a, b = tee(iterable) + try: + first = [next(b)] + except StopIteration: + return iter([]) + + if initial is not None: + first = [] + + return chain(first, map(func, b, a)) + + +class SequenceView(Sequence): + """Return a read-only view of the sequence object *target*. + + :class:`SequenceView` objects are analogous to Python's built-in + "dictionary view" types. They provide a dynamic view of a sequence's items, + meaning that when the sequence updates, so does the view. + + >>> seq = ['0', '1', '2'] + >>> view = SequenceView(seq) + >>> view + SequenceView(['0', '1', '2']) + >>> seq.append('3') + >>> view + SequenceView(['0', '1', '2', '3']) + + Sequence views support indexing, slicing, and length queries. They act + like the underlying sequence, except they don't allow assignment: + + >>> view[1] + '1' + >>> view[1:-1] + ['1', '2'] + >>> len(view) + 4 + + Sequence views are useful as an alternative to copying, as they don't + require (much) extra storage. + + """ + + def __init__(self, target): + if not isinstance(target, Sequence): + raise TypeError + self._target = target + + def __getitem__(self, index): + return self._target[index] + + def __len__(self): + return len(self._target) + + def __repr__(self): + return '{}({})'.format(self.__class__.__name__, repr(self._target)) + + +class seekable: + """Wrap an iterator to allow for seeking backward and forward. This + progressively caches the items in the source iterable so they can be + re-visited. + + Call :meth:`seek` with an index to seek to that position in the source + iterable. + + To "reset" an iterator, seek to ``0``: + + >>> from itertools import count + >>> it = seekable((str(n) for n in count())) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> it.seek(0) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> next(it) + '3' + + You can also seek forward: + + >>> it = seekable((str(n) for n in range(20))) + >>> it.seek(10) + >>> next(it) + '10' + >>> it.relative_seek(-2) # Seeking relative to the current position + >>> next(it) + '9' + >>> it.seek(20) # Seeking past the end of the source isn't a problem + >>> list(it) + [] + >>> it.seek(0) # Resetting works even after hitting the end + >>> next(it), next(it), next(it) + ('0', '1', '2') + + Call :meth:`peek` to look ahead one item without advancing the iterator: + + >>> it = seekable('1234') + >>> it.peek() + '1' + >>> list(it) + ['1', '2', '3', '4'] + >>> it.peek(default='empty') + 'empty' + + Before the iterator is at its end, calling :func:`bool` on it will return + ``True``. After it will return ``False``: + + >>> it = seekable('5678') + >>> bool(it) + True + >>> list(it) + ['5', '6', '7', '8'] + >>> bool(it) + False + + You may view the contents of the cache with the :meth:`elements` method. + That returns a :class:`SequenceView`, a view that updates automatically: + + >>> it = seekable((str(n) for n in range(10))) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> elements = it.elements() + >>> elements + SequenceView(['0', '1', '2']) + >>> next(it) + '3' + >>> elements + SequenceView(['0', '1', '2', '3']) + + By default, the cache grows as the source iterable progresses, so beware of + wrapping very large or infinite iterables. Supply *maxlen* to limit the + size of the cache (this of course limits how far back you can seek). + + >>> from itertools import count + >>> it = seekable((str(n) for n in count()), maxlen=2) + >>> next(it), next(it), next(it), next(it) + ('0', '1', '2', '3') + >>> list(it.elements()) + ['2', '3'] + >>> it.seek(0) + >>> next(it), next(it), next(it), next(it) + ('2', '3', '4', '5') + >>> next(it) + '6' + + """ + + def __init__(self, iterable, maxlen=None): + self._source = iter(iterable) + if maxlen is None: + self._cache = [] + else: + self._cache = deque([], maxlen) + self._index = None + + def __iter__(self): + return self + + def __next__(self): + if self._index is not None: + try: + item = self._cache[self._index] + except IndexError: + self._index = None + else: + self._index += 1 + return item + + item = next(self._source) + self._cache.append(item) + return item + + def __bool__(self): + try: + self.peek() + except StopIteration: + return False + return True + + def peek(self, default=_marker): + try: + peeked = next(self) + except StopIteration: + if default is _marker: + raise + return default + if self._index is None: + self._index = len(self._cache) + self._index -= 1 + return peeked + + def elements(self): + return SequenceView(self._cache) + + def seek(self, index): + self._index = index + remainder = index - len(self._cache) + if remainder > 0: + consume(self, remainder) + + def relative_seek(self, count): + index = len(self._cache) + self.seek(max(index + count, 0)) + + +class run_length: + """ + :func:`run_length.encode` compresses an iterable with run-length encoding. + It yields groups of repeated items with the count of how many times they + were repeated: + + >>> uncompressed = 'abbcccdddd' + >>> list(run_length.encode(uncompressed)) + [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + + :func:`run_length.decode` decompresses an iterable that was previously + compressed with run-length encoding. It yields the items of the + decompressed iterable: + + >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + >>> list(run_length.decode(compressed)) + ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd'] + + """ + + @staticmethod + def encode(iterable): + return ((k, ilen(g)) for k, g in groupby(iterable)) + + @staticmethod + def decode(iterable): + return chain.from_iterable(repeat(k, n) for k, n in iterable) + + +def exactly_n(iterable, n, predicate=bool): + """Return ``True`` if exactly ``n`` items in the iterable are ``True`` + according to the *predicate* function. + + >>> exactly_n([True, True, False], 2) + True + >>> exactly_n([True, True, False], 1) + False + >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3) + True + + The iterable will be advanced until ``n + 1`` truthy items are encountered, + so avoid calling it on infinite iterables. + + """ + return len(take(n + 1, filter(predicate, iterable))) == n + + +def circular_shifts(iterable): + """Return a list of circular shifts of *iterable*. + + >>> circular_shifts(range(4)) + [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)] + """ + lst = list(iterable) + return take(len(lst), windowed(cycle(lst), len(lst))) + + +def make_decorator(wrapping_func, result_index=0): + """Return a decorator version of *wrapping_func*, which is a function that + modifies an iterable. *result_index* is the position in that function's + signature where the iterable goes. + + This lets you use itertools on the "production end," i.e. at function + definition. This can augment what the function returns without changing the + function's code. + + For example, to produce a decorator version of :func:`chunked`: + + >>> from more_itertools import chunked + >>> chunker = make_decorator(chunked, result_index=0) + >>> @chunker(3) + ... def iter_range(n): + ... return iter(range(n)) + ... + >>> list(iter_range(9)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + + To only allow truthy items to be returned: + + >>> truth_serum = make_decorator(filter, result_index=1) + >>> @truth_serum(bool) + ... def boolean_test(): + ... return [0, 1, '', ' ', False, True] + ... + >>> list(boolean_test()) + [1, ' ', True] + + The :func:`peekable` and :func:`seekable` wrappers make for practical + decorators: + + >>> from more_itertools import peekable + >>> peekable_function = make_decorator(peekable) + >>> @peekable_function() + ... def str_range(*args): + ... return (str(x) for x in range(*args)) + ... + >>> it = str_range(1, 20, 2) + >>> next(it), next(it), next(it) + ('1', '3', '5') + >>> it.peek() + '7' + >>> next(it) + '7' + + """ + + # See https://sites.google.com/site/bbayles/index/decorator_factory for + # notes on how this works. + def decorator(*wrapping_args, **wrapping_kwargs): + def outer_wrapper(f): + def inner_wrapper(*args, **kwargs): + result = f(*args, **kwargs) + wrapping_args_ = list(wrapping_args) + wrapping_args_.insert(result_index, result) + return wrapping_func(*wrapping_args_, **wrapping_kwargs) + + return inner_wrapper + + return outer_wrapper + + return decorator + + +def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None): + """Return a dictionary that maps the items in *iterable* to categories + defined by *keyfunc*, transforms them with *valuefunc*, and + then summarizes them by category with *reducefunc*. + + *valuefunc* defaults to the identity function if it is unspecified. + If *reducefunc* is unspecified, no summarization takes place: + + >>> keyfunc = lambda x: x.upper() + >>> result = map_reduce('abbccc', keyfunc) + >>> sorted(result.items()) + [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])] + + Specifying *valuefunc* transforms the categorized items: + + >>> keyfunc = lambda x: x.upper() + >>> valuefunc = lambda x: 1 + >>> result = map_reduce('abbccc', keyfunc, valuefunc) + >>> sorted(result.items()) + [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])] + + Specifying *reducefunc* summarizes the categorized items: + + >>> keyfunc = lambda x: x.upper() + >>> valuefunc = lambda x: 1 + >>> reducefunc = sum + >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc) + >>> sorted(result.items()) + [('A', 1), ('B', 2), ('C', 3)] + + You may want to filter the input iterable before applying the map/reduce + procedure: + + >>> all_items = range(30) + >>> items = [x for x in all_items if 10 <= x <= 20] # Filter + >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1 + >>> categories = map_reduce(items, keyfunc=keyfunc) + >>> sorted(categories.items()) + [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])] + >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum) + >>> sorted(summaries.items()) + [(0, 90), (1, 75)] + + Note that all items in the iterable are gathered into a list before the + summarization step, which may require significant storage. + + The returned object is a :obj:`collections.defaultdict` with the + ``default_factory`` set to ``None``, such that it behaves like a normal + dictionary. + + """ + valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc + + ret = defaultdict(list) + for item in iterable: + key = keyfunc(item) + value = valuefunc(item) + ret[key].append(value) + + if reducefunc is not None: + for key, value_list in ret.items(): + ret[key] = reducefunc(value_list) + + ret.default_factory = None + return ret + + +def rlocate(iterable, pred=bool, window_size=None): + """Yield the index of each item in *iterable* for which *pred* returns + ``True``, starting from the right and moving left. + + *pred* defaults to :func:`bool`, which will select truthy items: + + >>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4 + [4, 2, 1] + + Set *pred* to a custom function to, e.g., find the indexes for a particular + item: + + >>> iterable = iter('abcb') + >>> pred = lambda x: x == 'b' + >>> list(rlocate(iterable, pred)) + [3, 1] + + If *window_size* is given, then the *pred* function will be called with + that many items. This enables searching for sub-sequences: + + >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] + >>> pred = lambda *args: args == (1, 2, 3) + >>> list(rlocate(iterable, pred=pred, window_size=3)) + [9, 5, 1] + + Beware, this function won't return anything for infinite iterables. + If *iterable* is reversible, ``rlocate`` will reverse it and search from + the right. Otherwise, it will search from the left and return the results + in reverse order. + + See :func:`locate` to for other example applications. + + """ + if window_size is None: + try: + len_iter = len(iterable) + return (len_iter - i - 1 for i in locate(reversed(iterable), pred)) + except TypeError: + pass + + return reversed(list(locate(iterable, pred, window_size))) + + +def replace(iterable, pred, substitutes, count=None, window_size=1): + """Yield the items from *iterable*, replacing the items for which *pred* + returns ``True`` with the items from the iterable *substitutes*. + + >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1] + >>> pred = lambda x: x == 0 + >>> substitutes = (2, 3) + >>> list(replace(iterable, pred, substitutes)) + [1, 1, 2, 3, 1, 1, 2, 3, 1, 1] + + If *count* is given, the number of replacements will be limited: + + >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0] + >>> pred = lambda x: x == 0 + >>> substitutes = [None] + >>> list(replace(iterable, pred, substitutes, count=2)) + [1, 1, None, 1, 1, None, 1, 1, 0] + + Use *window_size* to control the number of items passed as arguments to + *pred*. This allows for locating and replacing subsequences. + + >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5] + >>> window_size = 3 + >>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred + >>> substitutes = [3, 4] # Splice in these items + >>> list(replace(iterable, pred, substitutes, window_size=window_size)) + [3, 4, 5, 3, 4, 5] + + """ + if window_size < 1: + raise ValueError('window_size must be at least 1') + + # Save the substitutes iterable, since it's used more than once + substitutes = tuple(substitutes) + + # Add padding such that the number of windows matches the length of the + # iterable + it = chain(iterable, [_marker] * (window_size - 1)) + windows = windowed(it, window_size) + + n = 0 + for w in windows: + # If the current window matches our predicate (and we haven't hit + # our maximum number of replacements), splice in the substitutes + # and then consume the following windows that overlap with this one. + # For example, if the iterable is (0, 1, 2, 3, 4...) + # and the window size is 2, we have (0, 1), (1, 2), (2, 3)... + # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2) + if pred(*w): + if (count is None) or (n < count): + n += 1 + yield from substitutes + consume(windows, window_size - 1) + continue + + # If there was no match (or we've reached the replacement limit), + # yield the first item from the window. + if w and (w[0] is not _marker): + yield w[0] + + +def partitions(iterable): + """Yield all possible order-preserving partitions of *iterable*. + + >>> iterable = 'abc' + >>> for part in partitions(iterable): + ... print([''.join(p) for p in part]) + ['abc'] + ['a', 'bc'] + ['ab', 'c'] + ['a', 'b', 'c'] + + This is unrelated to :func:`partition`. + + """ + sequence = list(iterable) + n = len(sequence) + for i in powerset(range(1, n)): + yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))] + + +def set_partitions(iterable, k=None): + """ + Yield the set partitions of *iterable* into *k* parts. Set partitions are + not order-preserving. + + >>> iterable = 'abc' + >>> for part in set_partitions(iterable, 2): + ... print([''.join(p) for p in part]) + ['a', 'bc'] + ['ab', 'c'] + ['b', 'ac'] + + + If *k* is not given, every set partition is generated. + + >>> iterable = 'abc' + >>> for part in set_partitions(iterable): + ... print([''.join(p) for p in part]) + ['abc'] + ['a', 'bc'] + ['ab', 'c'] + ['b', 'ac'] + ['a', 'b', 'c'] + + """ + L = list(iterable) + n = len(L) + if k is not None: + if k < 1: + raise ValueError( + "Can't partition in a negative or zero number of groups" + ) + elif k > n: + return + + def set_partitions_helper(L, k): + n = len(L) + if k == 1: + yield [L] + elif n == k: + yield [[s] for s in L] + else: + e, *M = L + for p in set_partitions_helper(M, k - 1): + yield [[e], *p] + for p in set_partitions_helper(M, k): + for i in range(len(p)): + yield p[:i] + [[e] + p[i]] + p[i + 1 :] + + if k is None: + for k in range(1, n + 1): + yield from set_partitions_helper(L, k) + else: + yield from set_partitions_helper(L, k) + + +class time_limited: + """ + Yield items from *iterable* until *limit_seconds* have passed. + If the time limit expires before all items have been yielded, the + ``timed_out`` parameter will be set to ``True``. + + >>> from time import sleep + >>> def generator(): + ... yield 1 + ... yield 2 + ... sleep(0.2) + ... yield 3 + >>> iterable = time_limited(0.1, generator()) + >>> list(iterable) + [1, 2] + >>> iterable.timed_out + True + + Note that the time is checked before each item is yielded, and iteration + stops if the time elapsed is greater than *limit_seconds*. If your time + limit is 1 second, but it takes 2 seconds to generate the first item from + the iterable, the function will run for 2 seconds and not yield anything. + As a special case, when *limit_seconds* is zero, the iterator never + returns anything. + + """ + + def __init__(self, limit_seconds, iterable): + if limit_seconds < 0: + raise ValueError('limit_seconds must be positive') + self.limit_seconds = limit_seconds + self._iterable = iter(iterable) + self._start_time = monotonic() + self.timed_out = False + + def __iter__(self): + return self + + def __next__(self): + if self.limit_seconds == 0: + self.timed_out = True + raise StopIteration + item = next(self._iterable) + if monotonic() - self._start_time > self.limit_seconds: + self.timed_out = True + raise StopIteration + + return item + + +def only(iterable, default=None, too_long=None): + """If *iterable* has only one item, return it. + If it has zero items, return *default*. + If it has more than one item, raise the exception given by *too_long*, + which is ``ValueError`` by default. + + >>> only([], default='missing') + 'missing' + >>> only([1]) + 1 + >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 1, 2, + and perhaps more.' + >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError + + Note that :func:`only` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check + iterable contents less destructively. + """ + it = iter(iterable) + first_value = next(it, default) + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value + + +def _ichunk(iterable, n): + cache = deque() + chunk = islice(iterable, n) + + def generator(): + while True: + if cache: + yield cache.popleft() + else: + try: + item = next(chunk) + except StopIteration: + return + else: + yield item + + def materialize_next(n=1): + # if n not specified materialize everything + if n is None: + cache.extend(chunk) + return len(cache) + + to_cache = n - len(cache) + + # materialize up to n + if to_cache > 0: + cache.extend(islice(chunk, to_cache)) + + # return number materialized up to n + return min(n, len(cache)) + + return (generator(), materialize_next) + + +def ichunked(iterable, n): + """Break *iterable* into sub-iterables with *n* elements each. + :func:`ichunked` is like :func:`chunked`, but it yields iterables + instead of lists. + + If the sub-iterables are read in order, the elements of *iterable* + won't be stored in memory. + If they are read out of order, :func:`itertools.tee` is used to cache + elements as necessary. + + >>> from itertools import count + >>> all_chunks = ichunked(count(), 4) + >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks) + >>> list(c_2) # c_1's elements have been cached; c_3's haven't been + [4, 5, 6, 7] + >>> list(c_1) + [0, 1, 2, 3] + >>> list(c_3) + [8, 9, 10, 11] + + """ + iterable = iter(iterable) + while True: + # Create new chunk + chunk, materialize_next = _ichunk(iterable, n) + + # Check to see whether we're at the end of the source iterable + if not materialize_next(): + return + + yield chunk + + # Fill previous chunk's cache + materialize_next(None) + + +def iequals(*iterables): + """Return ``True`` if all given *iterables* are equal to each other, + which means that they contain the same elements in the same order. + + The function is useful for comparing iterables of different data types + or iterables that do not support equality checks. + + >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc")) + True + + >>> iequals("abc", "acb") + False + + Not to be confused with :func:`all_equal`, which checks whether all + elements of iterable are equal to each other. + + """ + return all(map(all_equal, zip_longest(*iterables, fillvalue=object()))) + + +def distinct_combinations(iterable, r): + """Yield the distinct combinations of *r* items taken from *iterable*. + + >>> list(distinct_combinations([0, 0, 1], 2)) + [(0, 0), (0, 1)] + + Equivalent to ``set(combinations(iterable))``, except duplicates are not + generated and thrown away. For larger input sequences this is much more + efficient. + + """ + if r < 0: + raise ValueError('r must be non-negative') + elif r == 0: + yield () + return + pool = tuple(iterable) + generators = [unique_everseen(enumerate(pool), key=itemgetter(1))] + current_combo = [None] * r + level = 0 + while generators: + try: + cur_idx, p = next(generators[-1]) + except StopIteration: + generators.pop() + level -= 1 + continue + current_combo[level] = p + if level + 1 == r: + yield tuple(current_combo) + else: + generators.append( + unique_everseen( + enumerate(pool[cur_idx + 1 :], cur_idx + 1), + key=itemgetter(1), + ) + ) + level += 1 + + +def filter_except(validator, iterable, *exceptions): + """Yield the items from *iterable* for which the *validator* function does + not raise one of the specified *exceptions*. + + *validator* is called for each item in *iterable*. + It should be a function that accepts one argument and raises an exception + if that item is not valid. + + >>> iterable = ['1', '2', 'three', '4', None] + >>> list(filter_except(int, iterable, ValueError, TypeError)) + ['1', '2', '4'] + + If an exception other than one given by *exceptions* is raised by + *validator*, it is raised like normal. + """ + for item in iterable: + try: + validator(item) + except exceptions: + pass + else: + yield item + + +def map_except(function, iterable, *exceptions): + """Transform each item from *iterable* with *function* and yield the + result, unless *function* raises one of the specified *exceptions*. + + *function* is called to transform each item in *iterable*. + It should accept one argument. + + >>> iterable = ['1', '2', 'three', '4', None] + >>> list(map_except(int, iterable, ValueError, TypeError)) + [1, 2, 4] + + If an exception other than one given by *exceptions* is raised by + *function*, it is raised like normal. + """ + for item in iterable: + try: + yield function(item) + except exceptions: + pass + + +def map_if(iterable, pred, func, func_else=lambda x: x): + """Evaluate each item from *iterable* using *pred*. If the result is + equivalent to ``True``, transform the item with *func* and yield it. + Otherwise, transform the item with *func_else* and yield it. + + *pred*, *func*, and *func_else* should each be functions that accept + one argument. By default, *func_else* is the identity function. + + >>> from math import sqrt + >>> iterable = list(range(-5, 5)) + >>> iterable + [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] + >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig')) + [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig'] + >>> list(map_if(iterable, lambda x: x >= 0, + ... lambda x: f'{sqrt(x):.2f}', lambda x: None)) + [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00'] + """ + for item in iterable: + yield func(item) if pred(item) else func_else(item) + + +def _sample_unweighted(iterable, k): + # Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li: + # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))". + + # Fill up the reservoir (collection of samples) with the first `k` samples + reservoir = take(k, iterable) + + # Generate random number that's the largest in a sample of k U(0,1) numbers + # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic + W = exp(log(random()) / k) + + # The number of elements to skip before changing the reservoir is a random + # number with a geometric distribution. Sample it using random() and logs. + next_index = k + floor(log(random()) / log(1 - W)) + + for index, element in enumerate(iterable, k): + if index == next_index: + reservoir[randrange(k)] = element + # The new W is the largest in a sample of k U(0, `old_W`) numbers + W *= exp(log(random()) / k) + next_index += floor(log(random()) / log(1 - W)) + 1 + + return reservoir + + +def _sample_weighted(iterable, k, weights): + # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. : + # "Weighted random sampling with a reservoir". + + # Log-transform for numerical stability for weights that are small/large + weight_keys = (log(random()) / weight for weight in weights) + + # Fill up the reservoir (collection of samples) with the first `k` + # weight-keys and elements, then heapify the list. + reservoir = take(k, zip(weight_keys, iterable)) + heapify(reservoir) + + # The number of jumps before changing the reservoir is a random variable + # with an exponential distribution. Sample it using random() and logs. + smallest_weight_key, _ = reservoir[0] + weights_to_skip = log(random()) / smallest_weight_key + + for weight, element in zip(weights, iterable): + if weight >= weights_to_skip: + # The notation here is consistent with the paper, but we store + # the weight-keys in log-space for better numerical stability. + smallest_weight_key, _ = reservoir[0] + t_w = exp(weight * smallest_weight_key) + r_2 = uniform(t_w, 1) # generate U(t_w, 1) + weight_key = log(r_2) / weight + heapreplace(reservoir, (weight_key, element)) + smallest_weight_key, _ = reservoir[0] + weights_to_skip = log(random()) / smallest_weight_key + else: + weights_to_skip -= weight + + # Equivalent to [element for weight_key, element in sorted(reservoir)] + return [heappop(reservoir)[1] for _ in range(k)] + + +def sample(iterable, k, weights=None): + """Return a *k*-length list of elements chosen (without replacement) + from the *iterable*. Like :func:`random.sample`, but works on iterables + of unknown length. + + >>> iterable = range(100) + >>> sample(iterable, 5) # doctest: +SKIP + [81, 60, 96, 16, 4] + + An iterable with *weights* may also be given: + + >>> iterable = range(100) + >>> weights = (i * i + 1 for i in range(100)) + >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP + [79, 67, 74, 66, 78] + + The algorithm can also be used to generate weighted random permutations. + The relative weight of each item determines the probability that it + appears late in the permutation. + + >>> data = "abcdefgh" + >>> weights = range(1, len(data) + 1) + >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP + ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f'] + """ + if k == 0: + return [] + + iterable = iter(iterable) + if weights is None: + return _sample_unweighted(iterable, k) + else: + weights = iter(weights) + return _sample_weighted(iterable, k, weights) + + +def is_sorted(iterable, key=None, reverse=False, strict=False): + """Returns ``True`` if the items of iterable are in sorted order, and + ``False`` otherwise. *key* and *reverse* have the same meaning that they do + in the built-in :func:`sorted` function. + + >>> is_sorted(['1', '2', '3', '4', '5'], key=int) + True + >>> is_sorted([5, 4, 3, 1, 2], reverse=True) + False + + If *strict*, tests for strict sorting, that is, returns ``False`` if equal + elements are found: + + >>> is_sorted([1, 2, 2]) + True + >>> is_sorted([1, 2, 2], strict=True) + False + + The function returns ``False`` after encountering the first out-of-order + item. If there are no out-of-order items, the iterable is exhausted. + """ + + compare = (le if reverse else ge) if strict else (lt if reverse else gt) + it = iterable if key is None else map(key, iterable) + return not any(starmap(compare, pairwise(it))) + + +class AbortThread(BaseException): + pass + + +class callback_iter: + """Convert a function that uses callbacks to an iterator. + + Let *func* be a function that takes a `callback` keyword argument. + For example: + + >>> def func(callback=None): + ... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]: + ... if callback: + ... callback(i, c) + ... return 4 + + + Use ``with callback_iter(func)`` to get an iterator over the parameters + that are delivered to the callback. + + >>> with callback_iter(func) as it: + ... for args, kwargs in it: + ... print(args) + (1, 'a') + (2, 'b') + (3, 'c') + + The function will be called in a background thread. The ``done`` property + indicates whether it has completed execution. + + >>> it.done + True + + If it completes successfully, its return value will be available + in the ``result`` property. + + >>> it.result + 4 + + Notes: + + * If the function uses some keyword argument besides ``callback``, supply + *callback_kwd*. + * If it finished executing, but raised an exception, accessing the + ``result`` property will raise the same exception. + * If it hasn't finished executing, accessing the ``result`` + property from within the ``with`` block will raise ``RuntimeError``. + * If it hasn't finished executing, accessing the ``result`` property from + outside the ``with`` block will raise a + ``more_itertools.AbortThread`` exception. + * Provide *wait_seconds* to adjust how frequently the it is polled for + output. + + """ + + def __init__(self, func, callback_kwd='callback', wait_seconds=0.1): + self._func = func + self._callback_kwd = callback_kwd + self._aborted = False + self._future = None + self._wait_seconds = wait_seconds + # Lazily import concurrent.future + self._executor = __import__( + 'concurrent.futures' + ).futures.ThreadPoolExecutor(max_workers=1) + self._iterator = self._reader() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._aborted = True + self._executor.shutdown() + + def __iter__(self): + return self + + def __next__(self): + return next(self._iterator) + + @property + def done(self): + if self._future is None: + return False + return self._future.done() + + @property + def result(self): + if not self.done: + raise RuntimeError('Function has not yet completed') + + return self._future.result() + + def _reader(self): + q = Queue() + + def callback(*args, **kwargs): + if self._aborted: + raise AbortThread('canceled by user') + + q.put((args, kwargs)) + + self._future = self._executor.submit( + self._func, **{self._callback_kwd: callback} + ) + + while True: + try: + item = q.get(timeout=self._wait_seconds) + except Empty: + pass + else: + q.task_done() + yield item + + if self._future.done(): + break + + remaining = [] + while True: + try: + item = q.get_nowait() + except Empty: + break + else: + q.task_done() + remaining.append(item) + q.join() + yield from remaining + + +def windowed_complete(iterable, n): + """ + Yield ``(beginning, middle, end)`` tuples, where: + + * Each ``middle`` has *n* items from *iterable* + * Each ``beginning`` has the items before the ones in ``middle`` + * Each ``end`` has the items after the ones in ``middle`` + + >>> iterable = range(7) + >>> n = 3 + >>> for beginning, middle, end in windowed_complete(iterable, n): + ... print(beginning, middle, end) + () (0, 1, 2) (3, 4, 5, 6) + (0,) (1, 2, 3) (4, 5, 6) + (0, 1) (2, 3, 4) (5, 6) + (0, 1, 2) (3, 4, 5) (6,) + (0, 1, 2, 3) (4, 5, 6) () + + Note that *n* must be at least 0 and most equal to the length of + *iterable*. + + This function will exhaust the iterable and may require significant + storage. + """ + if n < 0: + raise ValueError('n must be >= 0') + + seq = tuple(iterable) + size = len(seq) + + if n > size: + raise ValueError('n must be <= len(seq)') + + for i in range(size - n + 1): + beginning = seq[:i] + middle = seq[i : i + n] + end = seq[i + n :] + yield beginning, middle, end + + +def all_unique(iterable, key=None): + """ + Returns ``True`` if all the elements of *iterable* are unique (no two + elements are equal). + + >>> all_unique('ABCB') + False + + If a *key* function is specified, it will be used to make comparisons. + + >>> all_unique('ABCb') + True + >>> all_unique('ABCb', str.lower) + False + + The function returns as soon as the first non-unique element is + encountered. Iterables with a mix of hashable and unhashable items can + be used, but the function will be slower for unhashable items. + """ + seenset = set() + seenset_add = seenset.add + seenlist = [] + seenlist_add = seenlist.append + for element in map(key, iterable) if key else iterable: + try: + if element in seenset: + return False + seenset_add(element) + except TypeError: + if element in seenlist: + return False + seenlist_add(element) + return True + + +def nth_product(index, *args): + """Equivalent to ``list(product(*args))[index]``. + + The products of *args* can be ordered lexicographically. + :func:`nth_product` computes the product at sort position *index* without + computing the previous products. + + >>> nth_product(8, range(2), range(2), range(2), range(2)) + (1, 0, 0, 0) + + ``IndexError`` will be raised if the given *index* is invalid. + """ + pools = list(map(tuple, reversed(args))) + ns = list(map(len, pools)) + + c = reduce(mul, ns) + + if index < 0: + index += c + + if not 0 <= index < c: + raise IndexError + + result = [] + for pool, n in zip(pools, ns): + result.append(pool[index % n]) + index //= n + + return tuple(reversed(result)) + + +def nth_permutation(iterable, r, index): + """Equivalent to ``list(permutations(iterable, r))[index]``` + + The subsequences of *iterable* that are of length *r* where order is + important can be ordered lexicographically. :func:`nth_permutation` + computes the subsequence at sort position *index* directly, without + computing the previous subsequences. + + >>> nth_permutation('ghijk', 2, 5) + ('h', 'i') + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = list(iterable) + n = len(pool) + + if r is None or r == n: + r, c = n, factorial(n) + elif not 0 <= r < n: + raise ValueError + else: + c = perm(n, r) + assert c > 0 # factortial(n)>0, and r>> nth_combination_with_replacement(range(5), 3, 5) + (0, 1, 1) + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = tuple(iterable) + n = len(pool) + if (r < 0) or (r > n): + raise ValueError + + c = comb(n + r - 1, r) + + if index < 0: + index += c + + if (index < 0) or (index >= c): + raise IndexError + + result = [] + i = 0 + while r: + r -= 1 + while n >= 0: + num_combs = comb(n + r - 1, r) + if index < num_combs: + break + n -= 1 + i += 1 + index -= num_combs + result.append(pool[i]) + + return tuple(result) + + +def value_chain(*args): + """Yield all arguments passed to the function in the same order in which + they were passed. If an argument itself is iterable then iterate over its + values. + + >>> list(value_chain(1, 2, 3, [4, 5, 6])) + [1, 2, 3, 4, 5, 6] + + Binary and text strings are not considered iterable and are emitted + as-is: + + >>> list(value_chain('12', '34', ['56', '78'])) + ['12', '34', '56', '78'] + + Pre- or postpend a single element to an iterable: + + >>> list(value_chain(1, [2, 3, 4, 5, 6])) + [1, 2, 3, 4, 5, 6] + >>> list(value_chain([1, 2, 3, 4, 5], 6)) + [1, 2, 3, 4, 5, 6] + + Multiple levels of nesting are not flattened. + + """ + for value in args: + if isinstance(value, (str, bytes)): + yield value + continue + try: + yield from value + except TypeError: + yield value + + +def product_index(element, *args): + """Equivalent to ``list(product(*args)).index(element)`` + + The products of *args* can be ordered lexicographically. + :func:`product_index` computes the first index of *element* without + computing the previous products. + + >>> product_index([8, 2], range(10), range(5)) + 42 + + ``ValueError`` will be raised if the given *element* isn't in the product + of *args*. + """ + index = 0 + + for x, pool in zip_longest(element, args, fillvalue=_marker): + if x is _marker or pool is _marker: + raise ValueError('element is not a product of args') + + pool = tuple(pool) + index = index * len(pool) + pool.index(x) + + return index + + +def combination_index(element, iterable): + """Equivalent to ``list(combinations(iterable, r)).index(element)`` + + The subsequences of *iterable* that are of length *r* can be ordered + lexicographically. :func:`combination_index` computes the index of the + first *element*, without computing the previous combinations. + + >>> combination_index('adf', 'abcdefg') + 10 + + ``ValueError`` will be raised if the given *element* isn't one of the + combinations of *iterable*. + """ + element = enumerate(element) + k, y = next(element, (None, None)) + if k is None: + return 0 + + indexes = [] + pool = enumerate(iterable) + for n, x in pool: + if x == y: + indexes.append(n) + tmp, y = next(element, (None, None)) + if tmp is None: + break + else: + k = tmp + else: + raise ValueError('element is not a combination of iterable') + + n, _ = last(pool, default=(n, None)) + + # Python versions below 3.8 don't have math.comb + index = 1 + for i, j in enumerate(reversed(indexes), start=1): + j = n - j + if i <= j: + index += comb(j, i) + + return comb(n + 1, k + 1) - index + + +def combination_with_replacement_index(element, iterable): + """Equivalent to + ``list(combinations_with_replacement(iterable, r)).index(element)`` + + The subsequences with repetition of *iterable* that are of length *r* can + be ordered lexicographically. :func:`combination_with_replacement_index` + computes the index of the first *element*, without computing the previous + combinations with replacement. + + >>> combination_with_replacement_index('adf', 'abcdefg') + 20 + + ``ValueError`` will be raised if the given *element* isn't one of the + combinations with replacement of *iterable*. + """ + element = tuple(element) + l = len(element) + element = enumerate(element) + + k, y = next(element, (None, None)) + if k is None: + return 0 + + indexes = [] + pool = tuple(iterable) + for n, x in enumerate(pool): + while x == y: + indexes.append(n) + tmp, y = next(element, (None, None)) + if tmp is None: + break + else: + k = tmp + if y is None: + break + else: + raise ValueError( + 'element is not a combination with replacement of iterable' + ) + + n = len(pool) + occupations = [0] * n + for p in indexes: + occupations[p] += 1 + + index = 0 + cumulative_sum = 0 + for k in range(1, n): + cumulative_sum += occupations[k - 1] + j = l + n - 1 - k - cumulative_sum + i = n - k + if i <= j: + index += comb(j, i) + + return index + + +def permutation_index(element, iterable): + """Equivalent to ``list(permutations(iterable, r)).index(element)``` + + The subsequences of *iterable* that are of length *r* where order is + important can be ordered lexicographically. :func:`permutation_index` + computes the index of the first *element* directly, without computing + the previous permutations. + + >>> permutation_index([1, 3, 2], range(5)) + 19 + + ``ValueError`` will be raised if the given *element* isn't one of the + permutations of *iterable*. + """ + index = 0 + pool = list(iterable) + for i, x in zip(range(len(pool), -1, -1), element): + r = pool.index(x) + index = index * i + r + del pool[r] + + return index + + +class countable: + """Wrap *iterable* and keep a count of how many items have been consumed. + + The ``items_seen`` attribute starts at ``0`` and increments as the iterable + is consumed: + + >>> iterable = map(str, range(10)) + >>> it = countable(iterable) + >>> it.items_seen + 0 + >>> next(it), next(it) + ('0', '1') + >>> list(it) + ['2', '3', '4', '5', '6', '7', '8', '9'] + >>> it.items_seen + 10 + """ + + def __init__(self, iterable): + self._it = iter(iterable) + self.items_seen = 0 + + def __iter__(self): + return self + + def __next__(self): + item = next(self._it) + self.items_seen += 1 + + return item + + +def chunked_even(iterable, n): + """Break *iterable* into lists of approximately length *n*. + Items are distributed such the lengths of the lists differ by at most + 1 item. + + >>> iterable = [1, 2, 3, 4, 5, 6, 7] + >>> n = 3 + >>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2 + [[1, 2, 3], [4, 5], [6, 7]] + >>> list(chunked(iterable, n)) # List lengths: 3, 3, 1 + [[1, 2, 3], [4, 5, 6], [7]] + + """ + iterable = iter(iterable) + + # Initialize a buffer to process the chunks while keeping + # some back to fill any underfilled chunks + min_buffer = (n - 1) * (n - 2) + buffer = list(islice(iterable, min_buffer)) + + # Append items until we have a completed chunk + for _ in islice(map(buffer.append, iterable), n, None, n): + yield buffer[:n] + del buffer[:n] + + # Check if any chunks need addition processing + if not buffer: + return + length = len(buffer) + + # Chunks are either size `full_size <= n` or `partial_size = full_size - 1` + q, r = divmod(length, n) + num_lists = q + (1 if r > 0 else 0) + q, r = divmod(length, num_lists) + full_size = q + (1 if r > 0 else 0) + partial_size = full_size - 1 + num_full = length - partial_size * num_lists + + # Yield chunks of full size + partial_start_idx = num_full * full_size + if full_size > 0: + for i in range(0, partial_start_idx, full_size): + yield buffer[i : i + full_size] + + # Yield chunks of partial size + if partial_size > 0: + for i in range(partial_start_idx, length, partial_size): + yield buffer[i : i + partial_size] + + +def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False): + """A version of :func:`zip` that "broadcasts" any scalar + (i.e., non-iterable) items into output tuples. + + >>> iterable_1 = [1, 2, 3] + >>> iterable_2 = ['a', 'b', 'c'] + >>> scalar = '_' + >>> list(zip_broadcast(iterable_1, iterable_2, scalar)) + [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')] + + The *scalar_types* keyword argument determines what types are considered + scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to + treat strings and byte strings as iterable: + + >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None)) + [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')] + + If the *strict* keyword argument is ``True``, then + ``UnequalIterablesError`` will be raised if any of the iterables have + different lengths. + """ + + def is_scalar(obj): + if scalar_types and isinstance(obj, scalar_types): + return True + try: + iter(obj) + except TypeError: + return True + else: + return False + + size = len(objects) + if not size: + return + + new_item = [None] * size + iterables, iterable_positions = [], [] + for i, obj in enumerate(objects): + if is_scalar(obj): + new_item[i] = obj + else: + iterables.append(iter(obj)) + iterable_positions.append(i) + + if not iterables: + yield tuple(objects) + return + + zipper = _zip_equal if strict else zip + for item in zipper(*iterables): + for i, new_item[i] in zip(iterable_positions, item): + pass + yield tuple(new_item) + + +def unique_in_window(iterable, n, key=None): + """Yield the items from *iterable* that haven't been seen recently. + *n* is the size of the lookback window. + + >>> iterable = [0, 1, 0, 2, 3, 0] + >>> n = 3 + >>> list(unique_in_window(iterable, n)) + [0, 1, 2, 3, 0] + + The *key* function, if provided, will be used to determine uniqueness: + + >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower())) + ['a', 'b', 'c', 'd', 'a'] + + The items in *iterable* must be hashable. + + """ + if n <= 0: + raise ValueError('n must be greater than 0') + + window = deque(maxlen=n) + counts = defaultdict(int) + use_key = key is not None + + for item in iterable: + if len(window) == n: + to_discard = window[0] + if counts[to_discard] == 1: + del counts[to_discard] + else: + counts[to_discard] -= 1 + + k = key(item) if use_key else item + if k not in counts: + yield item + counts[k] += 1 + window.append(k) + + +def duplicates_everseen(iterable, key=None): + """Yield duplicate elements after their first appearance. + + >>> list(duplicates_everseen('mississippi')) + ['s', 'i', 's', 's', 'i', 'p', 'i'] + >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower)) + ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a'] + + This function is analogous to :func:`unique_everseen` and is subject to + the same performance considerations. + + """ + seen_set = set() + seen_list = [] + use_key = key is not None + + for element in iterable: + k = key(element) if use_key else element + try: + if k not in seen_set: + seen_set.add(k) + else: + yield element + except TypeError: + if k not in seen_list: + seen_list.append(k) + else: + yield element + + +def duplicates_justseen(iterable, key=None): + """Yields serially-duplicate elements after their first appearance. + + >>> list(duplicates_justseen('mississippi')) + ['s', 's', 'p'] + >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower)) + ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a'] + + This function is analogous to :func:`unique_justseen`. + + """ + return flatten(g for _, g in groupby(iterable, key) for _ in g) + + +def classify_unique(iterable, key=None): + """Classify each element in terms of its uniqueness. + + For each element in the input iterable, return a 3-tuple consisting of: + + 1. The element itself + 2. ``False`` if the element is equal to the one preceding it in the input, + ``True`` otherwise (i.e. the equivalent of :func:`unique_justseen`) + 3. ``False`` if this element has been seen anywhere in the input before, + ``True`` otherwise (i.e. the equivalent of :func:`unique_everseen`) + + >>> list(classify_unique('otto')) # doctest: +NORMALIZE_WHITESPACE + [('o', True, True), + ('t', True, True), + ('t', False, False), + ('o', True, False)] + + This function is analogous to :func:`unique_everseen` and is subject to + the same performance considerations. + + """ + seen_set = set() + seen_list = [] + use_key = key is not None + previous = None + + for i, element in enumerate(iterable): + k = key(element) if use_key else element + is_unique_justseen = not i or previous != k + previous = k + is_unique_everseen = False + try: + if k not in seen_set: + seen_set.add(k) + is_unique_everseen = True + except TypeError: + if k not in seen_list: + seen_list.append(k) + is_unique_everseen = True + yield element, is_unique_justseen, is_unique_everseen + + +def minmax(iterable_or_value, *others, key=None, default=_marker): + """Returns both the smallest and largest items in an iterable + or the largest of two or more arguments. + + >>> minmax([3, 1, 5]) + (1, 5) + + >>> minmax(4, 2, 6) + (2, 6) + + If a *key* function is provided, it will be used to transform the input + items for comparison. + + >>> minmax([5, 30], key=str) # '30' sorts before '5' + (30, 5) + + If a *default* value is provided, it will be returned if there are no + input items. + + >>> minmax([], default=(0, 0)) + (0, 0) + + Otherwise ``ValueError`` is raised. + + This function is based on the + `recipe `__ by + Raymond Hettinger and takes care to minimize the number of comparisons + performed. + """ + iterable = (iterable_or_value, *others) if others else iterable_or_value + + it = iter(iterable) + + try: + lo = hi = next(it) + except StopIteration as exc: + if default is _marker: + raise ValueError( + '`minmax()` argument is an empty iterable. ' + 'Provide a `default` value to suppress this error.' + ) from exc + return default + + # Different branches depending on the presence of key. This saves a lot + # of unimportant copies which would slow the "key=None" branch + # significantly down. + if key is None: + for x, y in zip_longest(it, it, fillvalue=lo): + if y < x: + x, y = y, x + if x < lo: + lo = x + if hi < y: + hi = y + + else: + lo_key = hi_key = key(lo) + + for x, y in zip_longest(it, it, fillvalue=lo): + x_key, y_key = key(x), key(y) + + if y_key < x_key: + x, y, x_key, y_key = y, x, y_key, x_key + if x_key < lo_key: + lo, lo_key = x, x_key + if hi_key < y_key: + hi, hi_key = y, y_key + + return lo, hi + + +def constrained_batches( + iterable, max_size, max_count=None, get_len=len, strict=True +): + """Yield batches of items from *iterable* with a combined size limited by + *max_size*. + + >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] + >>> list(constrained_batches(iterable, 10)) + [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')] + + If a *max_count* is supplied, the number of items per batch is also + limited: + + >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1'] + >>> list(constrained_batches(iterable, 10, max_count = 2)) + [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)] + + If a *get_len* function is supplied, use that instead of :func:`len` to + determine item size. + + If *strict* is ``True``, raise ``ValueError`` if any single item is bigger + than *max_size*. Otherwise, allow single items to exceed *max_size*. + """ + if max_size <= 0: + raise ValueError('maximum size must be greater than zero') + + batch = [] + batch_size = 0 + batch_count = 0 + for item in iterable: + item_len = get_len(item) + if strict and item_len > max_size: + raise ValueError('item size exceeds maximum size') + + reached_count = batch_count == max_count + reached_size = item_len + batch_size > max_size + if batch_count and (reached_size or reached_count): + yield tuple(batch) + batch.clear() + batch_size = 0 + batch_count = 0 + + batch.append(item) + batch_size += item_len + batch_count += 1 + + if batch: + yield tuple(batch) + + +def gray_product(*iterables): + """Like :func:`itertools.product`, but return tuples in an order such + that only one element in the generated tuple changes from one iteration + to the next. + + >>> list(gray_product('AB','CD')) + [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')] + + This function consumes all of the input iterables before producing output. + If any of the input iterables have fewer than two items, ``ValueError`` + is raised. + + For information on the algorithm, see + `this section `__ + of Donald Knuth's *The Art of Computer Programming*. + """ + all_iterables = tuple(tuple(x) for x in iterables) + iterable_count = len(all_iterables) + for iterable in all_iterables: + if len(iterable) < 2: + raise ValueError("each iterable must have two or more items") + + # This is based on "Algorithm H" from section 7.2.1.1, page 20. + # a holds the indexes of the source iterables for the n-tuple to be yielded + # f is the array of "focus pointers" + # o is the array of "directions" + a = [0] * iterable_count + f = list(range(iterable_count + 1)) + o = [1] * iterable_count + while True: + yield tuple(all_iterables[i][a[i]] for i in range(iterable_count)) + j = f[0] + f[0] = 0 + if j == iterable_count: + break + a[j] = a[j] + o[j] + if a[j] == 0 or a[j] == len(all_iterables[j]) - 1: + o[j] = -o[j] + f[j] = f[j + 1] + f[j + 1] = j + 1 + + +def partial_product(*iterables): + """Yields tuples containing one item from each iterator, with subsequent + tuples changing a single item at a time by advancing each iterator until it + is exhausted. This sequence guarantees every value in each iterable is + output at least once without generating all possible combinations. + + This may be useful, for example, when testing an expensive function. + + >>> list(partial_product('AB', 'C', 'DEF')) + [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')] + """ + + iterators = list(map(iter, iterables)) + + try: + prod = [next(it) for it in iterators] + except StopIteration: + return + yield tuple(prod) + + for i, it in enumerate(iterators): + for prod[i] in it: + yield tuple(prod) + + +def takewhile_inclusive(predicate, iterable): + """A variant of :func:`takewhile` that yields one additional element. + + >>> list(takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1])) + [1, 4, 6] + + :func:`takewhile` would return ``[1, 4]``. + """ + for x in iterable: + yield x + if not predicate(x): + break + + +def outer_product(func, xs, ys, *args, **kwargs): + """A generalized outer product that applies a binary function to all + pairs of items. Returns a 2D matrix with ``len(xs)`` rows and ``len(ys)`` + columns. + Also accepts ``*args`` and ``**kwargs`` that are passed to ``func``. + + Multiplication table: + + >>> list(outer_product(mul, range(1, 4), range(1, 6))) + [(1, 2, 3, 4, 5), (2, 4, 6, 8, 10), (3, 6, 9, 12, 15)] + + Cross tabulation: + + >>> xs = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'] + >>> ys = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z'] + >>> rows = list(zip(xs, ys)) + >>> count_rows = lambda x, y: rows.count((x, y)) + >>> list(outer_product(count_rows, sorted(set(xs)), sorted(set(ys)))) + [(2, 3, 0), (1, 0, 4)] + + Usage with ``*args`` and ``**kwargs``: + + >>> animals = ['cat', 'wolf', 'mouse'] + >>> list(outer_product(min, animals, animals, key=len)) + [('cat', 'cat', 'cat'), ('cat', 'wolf', 'wolf'), ('cat', 'wolf', 'mouse')] + """ + ys = tuple(ys) + return batched( + starmap(lambda x, y: func(x, y, *args, **kwargs), product(xs, ys)), + n=len(ys), + ) + + +def iter_suppress(iterable, *exceptions): + """Yield each of the items from *iterable*. If the iteration raises one of + the specified *exceptions*, that exception will be suppressed and iteration + will stop. + + >>> from itertools import chain + >>> def breaks_at_five(x): + ... while True: + ... if x >= 5: + ... raise RuntimeError + ... yield x + ... x += 1 + >>> it_1 = iter_suppress(breaks_at_five(1), RuntimeError) + >>> it_2 = iter_suppress(breaks_at_five(2), RuntimeError) + >>> list(chain(it_1, it_2)) + [1, 2, 3, 4, 2, 3, 4] + """ + try: + yield from iterable + except exceptions: + return + + +def filter_map(func, iterable): + """Apply *func* to every element of *iterable*, yielding only those which + are not ``None``. + + >>> elems = ['1', 'a', '2', 'b', '3'] + >>> list(filter_map(lambda s: int(s) if s.isnumeric() else None, elems)) + [1, 2, 3] + """ + for x in iterable: + y = func(x) + if y is not None: + yield y + + +def powerset_of_sets(iterable): + """Yields all possible subsets of the iterable. + + >>> list(powerset_of_sets([1, 2, 3])) # doctest: +SKIP + [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] + >>> list(powerset_of_sets([1, 1, 0])) # doctest: +SKIP + [set(), {1}, {0}, {0, 1}] + + :func:`powerset_of_sets` takes care to minimize the number + of hash operations performed. + """ + sets = tuple(map(set, dict.fromkeys(map(frozenset, zip(iterable))))) + for r in range(len(sets) + 1): + yield from starmap(set().union, combinations(sets, r)) + + +def join_mappings(**field_to_map): + """ + Joins multiple mappings together using their common keys. + + >>> user_scores = {'elliot': 50, 'claris': 60} + >>> user_times = {'elliot': 30, 'claris': 40} + >>> join_mappings(score=user_scores, time=user_times) + {'elliot': {'score': 50, 'time': 30}, 'claris': {'score': 60, 'time': 40}} + """ + ret = defaultdict(dict) + + for field_name, mapping in field_to_map.items(): + for key, value in mapping.items(): + ret[key][field_name] = value + + return dict(ret) + + +def _complex_sumprod(v1, v2): + """High precision sumprod() for complex numbers. + Used by :func:`dft` and :func:`idft`. + """ + + r1 = chain((p.real for p in v1), (-p.imag for p in v1)) + r2 = chain((q.real for q in v2), (q.imag for q in v2)) + i1 = chain((p.real for p in v1), (p.imag for p in v1)) + i2 = chain((q.imag for q in v2), (q.real for q in v2)) + return complex(_fsumprod(r1, r2), _fsumprod(i1, i2)) + + +def dft(xarr): + """Discrete Fourier Tranform. *xarr* is a sequence of complex numbers. + Yields the components of the corresponding transformed output vector. + + >>> import cmath + >>> xarr = [1, 2-1j, -1j, -1+2j] + >>> Xarr = [2, -2-2j, -2j, 4+4j] + >>> all(map(cmath.isclose, dft(xarr), Xarr)) + True + + See :func:`idft` for the inverse Discrete Fourier Transform. + """ + N = len(xarr) + roots_of_unity = [e ** (n / N * tau * -1j) for n in range(N)] + for k in range(N): + coeffs = [roots_of_unity[k * n % N] for n in range(N)] + yield _complex_sumprod(xarr, coeffs) + + +def idft(Xarr): + """Inverse Discrete Fourier Tranform. *Xarr* is a sequence of + complex numbers. Yields the components of the corresponding + inverse-transformed output vector. + + >>> import cmath + >>> xarr = [1, 2-1j, -1j, -1+2j] + >>> Xarr = [2, -2-2j, -2j, 4+4j] + >>> all(map(cmath.isclose, idft(Xarr), xarr)) + True + + See :func:`dft` for the Discrete Fourier Transform. + """ + N = len(Xarr) + roots_of_unity = [e ** (n / N * tau * 1j) for n in range(N)] + for k in range(N): + coeffs = [roots_of_unity[k * n % N] for n in range(N)] + yield _complex_sumprod(Xarr, coeffs) / N + + +def doublestarmap(func, iterable): + """Apply *func* to every item of *iterable* by dictionary unpacking + the item into *func*. + + The difference between :func:`itertools.starmap` and :func:`doublestarmap` + parallels the distinction between ``func(*a)`` and ``func(**a)``. + + >>> iterable = [{'a': 1, 'b': 2}, {'a': 40, 'b': 60}] + >>> list(doublestarmap(lambda a, b: a + b, iterable)) + [3, 100] + + ``TypeError`` will be raised if *func*'s signature doesn't match the + mapping contained in *iterable* or if *iterable* does not contain mappings. + """ + for item in iterable: + yield func(**item) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.pyi b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e94602325935c27066f916356b8b8a3e180e8b6f --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/more.pyi @@ -0,0 +1,709 @@ +"""Stubs for more_itertools.more""" + +from __future__ import annotations + +from types import TracebackType +from typing import ( + Any, + Callable, + Container, + ContextManager, + Generic, + Hashable, + Mapping, + Iterable, + Iterator, + Mapping, + overload, + Reversible, + Sequence, + Sized, + Type, + TypeVar, + type_check_only, +) +from typing_extensions import Protocol + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_U = TypeVar('_U') +_V = TypeVar('_V') +_W = TypeVar('_W') +_T_co = TypeVar('_T_co', covariant=True) +_GenFn = TypeVar('_GenFn', bound=Callable[..., Iterator[Any]]) +_Raisable = BaseException | Type[BaseException] + +@type_check_only +class _SizedIterable(Protocol[_T_co], Sized, Iterable[_T_co]): ... + +@type_check_only +class _SizedReversible(Protocol[_T_co], Sized, Reversible[_T_co]): ... + +@type_check_only +class _SupportsSlicing(Protocol[_T_co]): + def __getitem__(self, __k: slice) -> _T_co: ... + +def chunked( + iterable: Iterable[_T], n: int | None, strict: bool = ... +) -> Iterator[list[_T]]: ... +@overload +def first(iterable: Iterable[_T]) -> _T: ... +@overload +def first(iterable: Iterable[_T], default: _U) -> _T | _U: ... +@overload +def last(iterable: Iterable[_T]) -> _T: ... +@overload +def last(iterable: Iterable[_T], default: _U) -> _T | _U: ... +@overload +def nth_or_last(iterable: Iterable[_T], n: int) -> _T: ... +@overload +def nth_or_last(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... + +class peekable(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> peekable[_T]: ... + def __bool__(self) -> bool: ... + @overload + def peek(self) -> _T: ... + @overload + def peek(self, default: _U) -> _T | _U: ... + def prepend(self, *items: _T) -> None: ... + def __next__(self) -> _T: ... + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, index: slice) -> list[_T]: ... + +def consumer(func: _GenFn) -> _GenFn: ... +def ilen(iterable: Iterable[_T]) -> int: ... +def iterate(func: Callable[[_T], _T], start: _T) -> Iterator[_T]: ... +def with_iter( + context_manager: ContextManager[Iterable[_T]], +) -> Iterator[_T]: ... +def one( + iterable: Iterable[_T], + too_short: _Raisable | None = ..., + too_long: _Raisable | None = ..., +) -> _T: ... +def raise_(exception: _Raisable, *args: Any) -> None: ... +def strictly_n( + iterable: Iterable[_T], + n: int, + too_short: _GenFn | None = ..., + too_long: _GenFn | None = ..., +) -> list[_T]: ... +def distinct_permutations( + iterable: Iterable[_T], r: int | None = ... +) -> Iterator[tuple[_T, ...]]: ... +def intersperse( + e: _U, iterable: Iterable[_T], n: int = ... +) -> Iterator[_T | _U]: ... +def unique_to_each(*iterables: Iterable[_T]) -> list[list[_T]]: ... +@overload +def windowed( + seq: Iterable[_T], n: int, *, step: int = ... +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def windowed( + seq: Iterable[_T], n: int, fillvalue: _U, step: int = ... +) -> Iterator[tuple[_T | _U, ...]]: ... +def substrings(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def substrings_indexes( + seq: Sequence[_T], reverse: bool = ... +) -> Iterator[tuple[Sequence[_T], int, int]]: ... + +class bucket(Generic[_T, _U], Container[_U]): + def __init__( + self, + iterable: Iterable[_T], + key: Callable[[_T], _U], + validator: Callable[[_U], object] | None = ..., + ) -> None: ... + def __contains__(self, value: object) -> bool: ... + def __iter__(self) -> Iterator[_U]: ... + def __getitem__(self, value: object) -> Iterator[_T]: ... + +def spy( + iterable: Iterable[_T], n: int = ... +) -> tuple[list[_T], Iterator[_T]]: ... +def interleave(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def interleave_longest(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def interleave_evenly( + iterables: list[Iterable[_T]], lengths: list[int] | None = ... +) -> Iterator[_T]: ... +def collapse( + iterable: Iterable[Any], + base_type: type | None = ..., + levels: int | None = ..., +) -> Iterator[Any]: ... +@overload +def side_effect( + func: Callable[[_T], object], + iterable: Iterable[_T], + chunk_size: None = ..., + before: Callable[[], object] | None = ..., + after: Callable[[], object] | None = ..., +) -> Iterator[_T]: ... +@overload +def side_effect( + func: Callable[[list[_T]], object], + iterable: Iterable[_T], + chunk_size: int, + before: Callable[[], object] | None = ..., + after: Callable[[], object] | None = ..., +) -> Iterator[_T]: ... +def sliced( + seq: _SupportsSlicing[_T], n: int, strict: bool = ... +) -> Iterator[_T]: ... +def split_at( + iterable: Iterable[_T], + pred: Callable[[_T], object], + maxsplit: int = ..., + keep_separator: bool = ..., +) -> Iterator[list[_T]]: ... +def split_before( + iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... +) -> Iterator[list[_T]]: ... +def split_after( + iterable: Iterable[_T], pred: Callable[[_T], object], maxsplit: int = ... +) -> Iterator[list[_T]]: ... +def split_when( + iterable: Iterable[_T], + pred: Callable[[_T, _T], object], + maxsplit: int = ..., +) -> Iterator[list[_T]]: ... +def split_into( + iterable: Iterable[_T], sizes: Iterable[int | None] +) -> Iterator[list[_T]]: ... +@overload +def padded( + iterable: Iterable[_T], + *, + n: int | None = ..., + next_multiple: bool = ..., +) -> Iterator[_T | None]: ... +@overload +def padded( + iterable: Iterable[_T], + fillvalue: _U, + n: int | None = ..., + next_multiple: bool = ..., +) -> Iterator[_T | _U]: ... +@overload +def repeat_last(iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def repeat_last(iterable: Iterable[_T], default: _U) -> Iterator[_T | _U]: ... +def distribute(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... +@overload +def stagger( + iterable: Iterable[_T], + offsets: _SizedIterable[int] = ..., + longest: bool = ..., +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def stagger( + iterable: Iterable[_T], + offsets: _SizedIterable[int] = ..., + longest: bool = ..., + fillvalue: _U = ..., +) -> Iterator[tuple[_T | _U, ...]]: ... + +class UnequalIterablesError(ValueError): + def __init__(self, details: tuple[int, int, int] | None = ...) -> None: ... + +@overload +def zip_equal(__iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T1], __iter2: Iterable[_T2] +) -> Iterator[tuple[_T1, _T2]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], +) -> Iterator[tuple[_T, ...]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T1 | None]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T1 | None, _T2 | None]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: None = None, +) -> Iterator[tuple[_T | None, ...]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T1 | _U]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + *, + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T1 | _U, _T2 | _U]]: ... +@overload +def zip_offset( + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + *iterables: Iterable[_T], + offsets: _SizedIterable[int], + longest: bool = ..., + fillvalue: _U, +) -> Iterator[tuple[_T | _U, ...]]: ... +def sort_together( + iterables: Iterable[Iterable[_T]], + key_list: Iterable[int] = ..., + key: Callable[..., Any] | None = ..., + reverse: bool = ..., +) -> list[tuple[_T, ...]]: ... +def unzip(iterable: Iterable[Sequence[_T]]) -> tuple[Iterator[_T], ...]: ... +def divide(n: int, iterable: Iterable[_T]) -> list[Iterator[_T]]: ... +def always_iterable( + obj: object, + base_type: type | tuple[type | tuple[Any, ...], ...] | None = ..., +) -> Iterator[Any]: ... +def adjacent( + predicate: Callable[[_T], bool], + iterable: Iterable[_T], + distance: int = ..., +) -> Iterator[tuple[bool, _T]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None = None, + valuefunc: None = None, + reducefunc: None = None, +) -> Iterator[tuple[_T, Iterator[_T]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None, + reducefunc: None, +) -> Iterator[tuple[_U, Iterator[_T]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: Callable[[_T], _V], + reducefunc: None, +) -> Iterable[tuple[_T, Iterable[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: None, +) -> Iterable[tuple[_U, Iterator[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterable[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterable[tuple[_U, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterable[_V]], _W], +) -> Iterable[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterable[_V]], _W], +) -> Iterable[tuple[_U, _W]]: ... + +class numeric_range(Generic[_T, _U], Sequence[_T], Hashable, Reversible[_T]): + @overload + def __init__(self, __stop: _T) -> None: ... + @overload + def __init__(self, __start: _T, __stop: _T) -> None: ... + @overload + def __init__(self, __start: _T, __stop: _T, __step: _U) -> None: ... + def __bool__(self) -> bool: ... + def __contains__(self, elem: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + @overload + def __getitem__(self, key: int) -> _T: ... + @overload + def __getitem__(self, key: slice) -> numeric_range[_T, _U]: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def __reduce__( + self, + ) -> tuple[Type[numeric_range[_T, _U]], tuple[_T, _T, _U]]: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[_T]: ... + def count(self, value: _T) -> int: ... + def index(self, value: _T) -> int: ... # type: ignore + +def count_cycle( + iterable: Iterable[_T], n: int | None = ... +) -> Iterable[tuple[int, _T]]: ... +def mark_ends( + iterable: Iterable[_T], +) -> Iterable[tuple[bool, bool, _T]]: ... +def locate( + iterable: Iterable[_T], + pred: Callable[..., Any] = ..., + window_size: int | None = ..., +) -> Iterator[int]: ... +def lstrip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... +def rstrip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... +def strip( + iterable: Iterable[_T], pred: Callable[[_T], object] +) -> Iterator[_T]: ... + +class islice_extended(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T], *args: int | None) -> None: ... + def __iter__(self) -> islice_extended[_T]: ... + def __next__(self) -> _T: ... + def __getitem__(self, index: slice) -> islice_extended[_T]: ... + +def always_reversible(iterable: Iterable[_T]) -> Iterator[_T]: ... +def consecutive_groups( + iterable: Iterable[_T], ordering: Callable[[_T], int] = ... +) -> Iterator[Iterator[_T]]: ... +@overload +def difference( + iterable: Iterable[_T], + func: Callable[[_T, _T], _U] = ..., + *, + initial: None = ..., +) -> Iterator[_T | _U]: ... +@overload +def difference( + iterable: Iterable[_T], func: Callable[[_T, _T], _U] = ..., *, initial: _U +) -> Iterator[_U]: ... + +class SequenceView(Generic[_T], Sequence[_T]): + def __init__(self, target: Sequence[_T]) -> None: ... + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, index: slice) -> Sequence[_T]: ... + def __len__(self) -> int: ... + +class seekable(Generic[_T], Iterator[_T]): + def __init__( + self, iterable: Iterable[_T], maxlen: int | None = ... + ) -> None: ... + def __iter__(self) -> seekable[_T]: ... + def __next__(self) -> _T: ... + def __bool__(self) -> bool: ... + @overload + def peek(self) -> _T: ... + @overload + def peek(self, default: _U) -> _T | _U: ... + def elements(self) -> SequenceView[_T]: ... + def seek(self, index: int) -> None: ... + def relative_seek(self, count: int) -> None: ... + +class run_length: + @staticmethod + def encode(iterable: Iterable[_T]) -> Iterator[tuple[_T, int]]: ... + @staticmethod + def decode(iterable: Iterable[tuple[_T, int]]) -> Iterator[_T]: ... + +def exactly_n( + iterable: Iterable[_T], n: int, predicate: Callable[[_T], object] = ... +) -> bool: ... +def circular_shifts(iterable: Iterable[_T]) -> list[tuple[_T, ...]]: ... +def make_decorator( + wrapping_func: Callable[..., _U], result_index: int = ... +) -> Callable[..., Callable[[Callable[..., Any]], Callable[..., _U]]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None = ..., + reducefunc: None = ..., +) -> dict[_U, list[_T]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: None = ..., +) -> dict[_U, list[_V]]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None = ..., + reducefunc: Callable[[list[_T]], _W] = ..., +) -> dict[_U, _W]: ... +@overload +def map_reduce( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[list[_V]], _W], +) -> dict[_U, _W]: ... +def rlocate( + iterable: Iterable[_T], + pred: Callable[..., object] = ..., + window_size: int | None = ..., +) -> Iterator[int]: ... +def replace( + iterable: Iterable[_T], + pred: Callable[..., object], + substitutes: Iterable[_U], + count: int | None = ..., + window_size: int = ..., +) -> Iterator[_T | _U]: ... +def partitions(iterable: Iterable[_T]) -> Iterator[list[list[_T]]]: ... +def set_partitions( + iterable: Iterable[_T], k: int | None = ... +) -> Iterator[list[list[_T]]]: ... + +class time_limited(Generic[_T], Iterator[_T]): + def __init__( + self, limit_seconds: float, iterable: Iterable[_T] + ) -> None: ... + def __iter__(self) -> islice_extended[_T]: ... + def __next__(self) -> _T: ... + +@overload +def only( + iterable: Iterable[_T], *, too_long: _Raisable | None = ... +) -> _T | None: ... +@overload +def only( + iterable: Iterable[_T], default: _U, too_long: _Raisable | None = ... +) -> _T | _U: ... +def ichunked(iterable: Iterable[_T], n: int) -> Iterator[Iterator[_T]]: ... +def distinct_combinations( + iterable: Iterable[_T], r: int +) -> Iterator[tuple[_T, ...]]: ... +def filter_except( + validator: Callable[[Any], object], + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_T]: ... +def map_except( + function: Callable[[Any], _U], + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_U]: ... +def map_if( + iterable: Iterable[Any], + pred: Callable[[Any], bool], + func: Callable[[Any], Any], + func_else: Callable[[Any], Any] | None = ..., +) -> Iterator[Any]: ... +def sample( + iterable: Iterable[_T], + k: int, + weights: Iterable[float] | None = ..., +) -> list[_T]: ... +def is_sorted( + iterable: Iterable[_T], + key: Callable[[_T], _U] | None = ..., + reverse: bool = False, + strict: bool = False, +) -> bool: ... + +class AbortThread(BaseException): + pass + +class callback_iter(Generic[_T], Iterator[_T]): + def __init__( + self, + func: Callable[..., Any], + callback_kwd: str = ..., + wait_seconds: float = ..., + ) -> None: ... + def __enter__(self) -> callback_iter[_T]: ... + def __exit__( + self, + exc_type: Type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> bool | None: ... + def __iter__(self) -> callback_iter[_T]: ... + def __next__(self) -> _T: ... + def _reader(self) -> Iterator[_T]: ... + @property + def done(self) -> bool: ... + @property + def result(self) -> Any: ... + +def windowed_complete( + iterable: Iterable[_T], n: int +) -> Iterator[tuple[_T, ...]]: ... +def all_unique( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> bool: ... +def nth_product(index: int, *args: Iterable[_T]) -> tuple[_T, ...]: ... +def nth_combination_with_replacement( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def nth_permutation( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def value_chain(*args: _T | Iterable[_T]) -> Iterable[_T]: ... +def product_index(element: Iterable[_T], *args: Iterable[_T]) -> int: ... +def combination_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def combination_with_replacement_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def permutation_index( + element: Iterable[_T], iterable: Iterable[_T] +) -> int: ... +def repeat_each(iterable: Iterable[_T], n: int = ...) -> Iterator[_T]: ... + +class countable(Generic[_T], Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> countable[_T]: ... + def __next__(self) -> _T: ... + items_seen: int + +def chunked_even(iterable: Iterable[_T], n: int) -> Iterator[list[_T]]: ... +def zip_broadcast( + *objects: _T | Iterable[_T], + scalar_types: type | tuple[type | tuple[Any, ...], ...] | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +def unique_in_window( + iterable: Iterable[_T], n: int, key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def duplicates_everseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def duplicates_justseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def classify_unique( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[tuple[_T, bool, bool]]: ... + +class _SupportsLessThan(Protocol): + def __lt__(self, __other: Any) -> bool: ... + +_SupportsLessThanT = TypeVar("_SupportsLessThanT", bound=_SupportsLessThan) + +@overload +def minmax( + iterable_or_value: Iterable[_SupportsLessThanT], *, key: None = None +) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: Iterable[_T], *, key: Callable[[_T], _SupportsLessThan] +) -> tuple[_T, _T]: ... +@overload +def minmax( + iterable_or_value: Iterable[_SupportsLessThanT], + *, + key: None = None, + default: _U, +) -> _U | tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: Iterable[_T], + *, + key: Callable[[_T], _SupportsLessThan], + default: _U, +) -> _U | tuple[_T, _T]: ... +@overload +def minmax( + iterable_or_value: _SupportsLessThanT, + __other: _SupportsLessThanT, + *others: _SupportsLessThanT, +) -> tuple[_SupportsLessThanT, _SupportsLessThanT]: ... +@overload +def minmax( + iterable_or_value: _T, + __other: _T, + *others: _T, + key: Callable[[_T], _SupportsLessThan], +) -> tuple[_T, _T]: ... +def longest_common_prefix( + iterables: Iterable[Iterable[_T]], +) -> Iterator[_T]: ... +def iequals(*iterables: Iterable[Any]) -> bool: ... +def constrained_batches( + iterable: Iterable[_T], + max_size: int, + max_count: int | None = ..., + get_len: Callable[[_T], object] = ..., + strict: bool = ..., +) -> Iterator[tuple[_T]]: ... +def gray_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def partial_product(*iterables: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def takewhile_inclusive( + predicate: Callable[[_T], bool], iterable: Iterable[_T] +) -> Iterator[_T]: ... +def outer_product( + func: Callable[[_T, _U], _V], + xs: Iterable[_T], + ys: Iterable[_U], + *args: Any, + **kwargs: Any, +) -> Iterator[tuple[_V, ...]]: ... +def iter_suppress( + iterable: Iterable[_T], + *exceptions: Type[BaseException], +) -> Iterator[_T]: ... +def filter_map( + func: Callable[[_T], _V | None], + iterable: Iterable[_T], +) -> Iterator[_V]: ... +def powerset_of_sets(iterable: Iterable[_T]) -> Iterator[set[_T]]: ... +def join_mappings( + **field_to_map: Mapping[_T, _V] +) -> dict[_T, dict[str, _V]]: ... +def doublestarmap( + func: Callable[..., _T], + iterable: Iterable[Mapping[str, Any]], +) -> Iterator[_T]: ... +def dft(xarr: Sequence[complex]) -> Iterator[complex]: ... +def idft(Xarr: Sequence[complex]) -> Iterator[complex]: ... diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.py b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..b32fa955339a07c2a789a15fd2287e70fc94d867 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.py @@ -0,0 +1,1046 @@ +"""Imported from the recipes section of the itertools documentation. + +All functions taken from the recipes section of the itertools library docs +[1]_. +Some backward-compatible usability improvements have been made. + +.. [1] http://docs.python.org/library/itertools.html#recipes + +""" + +import math +import operator + +from collections import deque +from collections.abc import Sized +from functools import partial, reduce +from itertools import ( + chain, + combinations, + compress, + count, + cycle, + groupby, + islice, + product, + repeat, + starmap, + tee, + zip_longest, +) +from random import randrange, sample, choice +from sys import hexversion + +__all__ = [ + 'all_equal', + 'batched', + 'before_and_after', + 'consume', + 'convolve', + 'dotproduct', + 'first_true', + 'factor', + 'flatten', + 'grouper', + 'iter_except', + 'iter_index', + 'matmul', + 'ncycles', + 'nth', + 'nth_combination', + 'padnone', + 'pad_none', + 'pairwise', + 'partition', + 'polynomial_eval', + 'polynomial_from_roots', + 'polynomial_derivative', + 'powerset', + 'prepend', + 'quantify', + 'reshape', + 'random_combination_with_replacement', + 'random_combination', + 'random_permutation', + 'random_product', + 'repeatfunc', + 'roundrobin', + 'sieve', + 'sliding_window', + 'subslices', + 'sum_of_squares', + 'tabulate', + 'tail', + 'take', + 'totient', + 'transpose', + 'triplewise', + 'unique', + 'unique_everseen', + 'unique_justseen', +] + +_marker = object() + + +# zip with strict is available for Python 3.10+ +try: + zip(strict=True) +except TypeError: + _zip_strict = zip +else: + _zip_strict = partial(zip, strict=True) + +# math.sumprod is available for Python 3.12+ +_sumprod = getattr(math, 'sumprod', lambda x, y: dotproduct(x, y)) + + +def take(n, iterable): + """Return first *n* items of the iterable as a list. + + >>> take(3, range(10)) + [0, 1, 2] + + If there are fewer than *n* items in the iterable, all of them are + returned. + + >>> take(10, range(3)) + [0, 1, 2] + + """ + return list(islice(iterable, n)) + + +def tabulate(function, start=0): + """Return an iterator over the results of ``func(start)``, + ``func(start + 1)``, ``func(start + 2)``... + + *func* should be a function that accepts one integer argument. + + If *start* is not specified it defaults to 0. It will be incremented each + time the iterator is advanced. + + >>> square = lambda x: x ** 2 + >>> iterator = tabulate(square, -3) + >>> take(4, iterator) + [9, 4, 1, 0] + + """ + return map(function, count(start)) + + +def tail(n, iterable): + """Return an iterator over the last *n* items of *iterable*. + + >>> t = tail(3, 'ABCDEFG') + >>> list(t) + ['E', 'F', 'G'] + + """ + # If the given iterable has a length, then we can use islice to get its + # final elements. Note that if the iterable is not actually Iterable, + # either islice or deque will throw a TypeError. This is why we don't + # check if it is Iterable. + if isinstance(iterable, Sized): + yield from islice(iterable, max(0, len(iterable) - n), None) + else: + yield from iter(deque(iterable, maxlen=n)) + + +def consume(iterator, n=None): + """Advance *iterable* by *n* steps. If *n* is ``None``, consume it + entirely. + + Efficiently exhausts an iterator without returning values. Defaults to + consuming the whole iterator, but an optional second argument may be + provided to limit consumption. + + >>> i = (x for x in range(10)) + >>> next(i) + 0 + >>> consume(i, 3) + >>> next(i) + 4 + >>> consume(i) + >>> next(i) + Traceback (most recent call last): + File "", line 1, in + StopIteration + + If the iterator has fewer items remaining than the provided limit, the + whole iterator will be consumed. + + >>> i = (x for x in range(3)) + >>> consume(i, 5) + >>> next(i) + Traceback (most recent call last): + File "", line 1, in + StopIteration + + """ + # Use functions that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + deque(iterator, maxlen=0) + else: + # advance to the empty slice starting at position n + next(islice(iterator, n, n), None) + + +def nth(iterable, n, default=None): + """Returns the nth item or a default value. + + >>> l = range(10) + >>> nth(l, 3) + 3 + >>> nth(l, 20, "zebra") + 'zebra' + + """ + return next(islice(iterable, n, None), default) + + +def all_equal(iterable, key=None): + """ + Returns ``True`` if all the elements are equal to each other. + + >>> all_equal('aaaa') + True + >>> all_equal('aaab') + False + + A function that accepts a single argument and returns a transformed version + of each input item can be specified with *key*: + + >>> all_equal('AaaA', key=str.casefold) + True + >>> all_equal([1, 2, 3], key=lambda x: x < 10) + True + + """ + return len(list(islice(groupby(iterable, key), 2))) <= 1 + + +def quantify(iterable, pred=bool): + """Return the how many times the predicate is true. + + >>> quantify([True, False, True]) + 2 + + """ + return sum(map(pred, iterable)) + + +def pad_none(iterable): + """Returns the sequence of elements and then returns ``None`` indefinitely. + + >>> take(5, pad_none(range(3))) + [0, 1, 2, None, None] + + Useful for emulating the behavior of the built-in :func:`map` function. + + See also :func:`padded`. + + """ + return chain(iterable, repeat(None)) + + +padnone = pad_none + + +def ncycles(iterable, n): + """Returns the sequence elements *n* times + + >>> list(ncycles(["a", "b"], 3)) + ['a', 'b', 'a', 'b', 'a', 'b'] + + """ + return chain.from_iterable(repeat(tuple(iterable), n)) + + +def dotproduct(vec1, vec2): + """Returns the dot product of the two iterables. + + >>> dotproduct([10, 10], [20, 20]) + 400 + + """ + return sum(map(operator.mul, vec1, vec2)) + + +def flatten(listOfLists): + """Return an iterator flattening one level of nesting in a list of lists. + + >>> list(flatten([[0, 1], [2, 3]])) + [0, 1, 2, 3] + + See also :func:`collapse`, which can flatten multiple levels of nesting. + + """ + return chain.from_iterable(listOfLists) + + +def repeatfunc(func, times=None, *args): + """Call *func* with *args* repeatedly, returning an iterable over the + results. + + If *times* is specified, the iterable will terminate after that many + repetitions: + + >>> from operator import add + >>> times = 4 + >>> args = 3, 5 + >>> list(repeatfunc(add, times, *args)) + [8, 8, 8, 8] + + If *times* is ``None`` the iterable will not terminate: + + >>> from random import randrange + >>> times = None + >>> args = 1, 11 + >>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP + [2, 4, 8, 1, 8, 4] + + """ + if times is None: + return starmap(func, repeat(args)) + return starmap(func, repeat(args, times)) + + +def _pairwise(iterable): + """Returns an iterator of paired items, overlapping, from the original + + >>> take(4, pairwise(count())) + [(0, 1), (1, 2), (2, 3), (3, 4)] + + On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`. + + """ + a, b = tee(iterable) + next(b, None) + return zip(a, b) + + +try: + from itertools import pairwise as itertools_pairwise +except ImportError: + pairwise = _pairwise +else: + + def pairwise(iterable): + return itertools_pairwise(iterable) + + pairwise.__doc__ = _pairwise.__doc__ + + +class UnequalIterablesError(ValueError): + def __init__(self, details=None): + msg = 'Iterables have different lengths' + if details is not None: + msg += (': index 0 has length {}; index {} has length {}').format( + *details + ) + + super().__init__(msg) + + +def _zip_equal_generator(iterables): + for combo in zip_longest(*iterables, fillvalue=_marker): + for val in combo: + if val is _marker: + raise UnequalIterablesError() + yield combo + + +def _zip_equal(*iterables): + # Check whether the iterables are all the same size. + try: + first_size = len(iterables[0]) + for i, it in enumerate(iterables[1:], 1): + size = len(it) + if size != first_size: + raise UnequalIterablesError(details=(first_size, i, size)) + # All sizes are equal, we can use the built-in zip. + return zip(*iterables) + # If any one of the iterables didn't have a length, start reading + # them until one runs out. + except TypeError: + return _zip_equal_generator(iterables) + + +def grouper(iterable, n, incomplete='fill', fillvalue=None): + """Group elements from *iterable* into fixed-length groups of length *n*. + + >>> list(grouper('ABCDEF', 3)) + [('A', 'B', 'C'), ('D', 'E', 'F')] + + The keyword arguments *incomplete* and *fillvalue* control what happens for + iterables whose length is not a multiple of *n*. + + When *incomplete* is `'fill'`, the last group will contain instances of + *fillvalue*. + + >>> list(grouper('ABCDEFG', 3, incomplete='fill', fillvalue='x')) + [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] + + When *incomplete* is `'ignore'`, the last group will not be emitted. + + >>> list(grouper('ABCDEFG', 3, incomplete='ignore', fillvalue='x')) + [('A', 'B', 'C'), ('D', 'E', 'F')] + + When *incomplete* is `'strict'`, a subclass of `ValueError` will be raised. + + >>> it = grouper('ABCDEFG', 3, incomplete='strict') + >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + UnequalIterablesError + + """ + args = [iter(iterable)] * n + if incomplete == 'fill': + return zip_longest(*args, fillvalue=fillvalue) + if incomplete == 'strict': + return _zip_equal(*args) + if incomplete == 'ignore': + return zip(*args) + else: + raise ValueError('Expected fill, strict, or ignore') + + +def roundrobin(*iterables): + """Yields an item from each iterable, alternating between them. + + >>> list(roundrobin('ABC', 'D', 'EF')) + ['A', 'D', 'E', 'B', 'F', 'C'] + + This function produces the same output as :func:`interleave_longest`, but + may perform better for some inputs (in particular when the number of + iterables is small). + + """ + # Algorithm credited to George Sakkis + iterators = map(iter, iterables) + for num_active in range(len(iterables), 0, -1): + iterators = cycle(islice(iterators, num_active)) + yield from map(next, iterators) + + +def partition(pred, iterable): + """ + Returns a 2-tuple of iterables derived from the input iterable. + The first yields the items that have ``pred(item) == False``. + The second yields the items that have ``pred(item) == True``. + + >>> is_odd = lambda x: x % 2 != 0 + >>> iterable = range(10) + >>> even_items, odd_items = partition(is_odd, iterable) + >>> list(even_items), list(odd_items) + ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9]) + + If *pred* is None, :func:`bool` is used. + + >>> iterable = [0, 1, False, True, '', ' '] + >>> false_items, true_items = partition(None, iterable) + >>> list(false_items), list(true_items) + ([0, False, ''], [1, True, ' ']) + + """ + if pred is None: + pred = bool + + t1, t2, p = tee(iterable, 3) + p1, p2 = tee(map(pred, p)) + return (compress(t1, map(operator.not_, p1)), compress(t2, p2)) + + +def powerset(iterable): + """Yields all possible subsets of the iterable. + + >>> list(powerset([1, 2, 3])) + [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] + + :func:`powerset` will operate on iterables that aren't :class:`set` + instances, so repeated elements in the input will produce repeated elements + in the output. + + >>> seq = [1, 1, 0] + >>> list(powerset(seq)) + [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)] + + For a variant that efficiently yields actual :class:`set` instances, see + :func:`powerset_of_sets`. + """ + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) + + +def unique_everseen(iterable, key=None): + """ + Yield unique elements, preserving order. + + >>> list(unique_everseen('AAAABBBCCDAABBB')) + ['A', 'B', 'C', 'D'] + >>> list(unique_everseen('ABBCcAD', str.lower)) + ['A', 'B', 'C', 'D'] + + Sequences with a mix of hashable and unhashable items can be used. + The function will be slower (i.e., `O(n^2)`) for unhashable items. + + Remember that ``list`` objects are unhashable - you can use the *key* + parameter to transform the list to a tuple (which is hashable) to + avoid a slowdown. + + >>> iterable = ([1, 2], [2, 3], [1, 2]) + >>> list(unique_everseen(iterable)) # Slow + [[1, 2], [2, 3]] + >>> list(unique_everseen(iterable, key=tuple)) # Faster + [[1, 2], [2, 3]] + + Similarly, you may want to convert unhashable ``set`` objects with + ``key=frozenset``. For ``dict`` objects, + ``key=lambda x: frozenset(x.items())`` can be used. + + """ + seenset = set() + seenset_add = seenset.add + seenlist = [] + seenlist_add = seenlist.append + use_key = key is not None + + for element in iterable: + k = key(element) if use_key else element + try: + if k not in seenset: + seenset_add(k) + yield element + except TypeError: + if k not in seenlist: + seenlist_add(k) + yield element + + +def unique_justseen(iterable, key=None): + """Yields elements in order, ignoring serial duplicates + + >>> list(unique_justseen('AAAABBBCCDAABBB')) + ['A', 'B', 'C', 'D', 'A', 'B'] + >>> list(unique_justseen('ABBCcAD', str.lower)) + ['A', 'B', 'C', 'A', 'D'] + + """ + if key is None: + return map(operator.itemgetter(0), groupby(iterable)) + + return map(next, map(operator.itemgetter(1), groupby(iterable, key))) + + +def unique(iterable, key=None, reverse=False): + """Yields unique elements in sorted order. + + >>> list(unique([[1, 2], [3, 4], [1, 2]])) + [[1, 2], [3, 4]] + + *key* and *reverse* are passed to :func:`sorted`. + + >>> list(unique('ABBcCAD', str.casefold)) + ['A', 'B', 'c', 'D'] + >>> list(unique('ABBcCAD', str.casefold, reverse=True)) + ['D', 'c', 'B', 'A'] + + The elements in *iterable* need not be hashable, but they must be + comparable for sorting to work. + """ + return unique_justseen(sorted(iterable, key=key, reverse=reverse), key=key) + + +def iter_except(func, exception, first=None): + """Yields results from a function repeatedly until an exception is raised. + + Converts a call-until-exception interface to an iterator interface. + Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel + to end the loop. + + >>> l = [0, 1, 2] + >>> list(iter_except(l.pop, IndexError)) + [2, 1, 0] + + Multiple exceptions can be specified as a stopping condition: + + >>> l = [1, 2, 3, '...', 4, 5, 6] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [7, 6, 5] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [4, 3, 2] + >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError))) + [] + + """ + try: + if first is not None: + yield first() + while 1: + yield func() + except exception: + pass + + +def first_true(iterable, default=None, pred=None): + """ + Returns the first true value in the iterable. + + If no true value is found, returns *default* + + If *pred* is not None, returns the first item for which + ``pred(item) == True`` . + + >>> first_true(range(10)) + 1 + >>> first_true(range(10), pred=lambda x: x > 5) + 6 + >>> first_true(range(10), default='missing', pred=lambda x: x > 9) + 'missing' + + """ + return next(filter(pred, iterable), default) + + +def random_product(*args, repeat=1): + """Draw an item at random from each of the input iterables. + + >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP + ('c', 3, 'Z') + + If *repeat* is provided as a keyword argument, that many items will be + drawn from each iterable. + + >>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP + ('a', 2, 'd', 3) + + This equivalent to taking a random selection from + ``itertools.product(*args, **kwarg)``. + + """ + pools = [tuple(pool) for pool in args] * repeat + return tuple(choice(pool) for pool in pools) + + +def random_permutation(iterable, r=None): + """Return a random *r* length permutation of the elements in *iterable*. + + If *r* is not specified or is ``None``, then *r* defaults to the length of + *iterable*. + + >>> random_permutation(range(5)) # doctest:+SKIP + (3, 4, 0, 1, 2) + + This equivalent to taking a random selection from + ``itertools.permutations(iterable, r)``. + + """ + pool = tuple(iterable) + r = len(pool) if r is None else r + return tuple(sample(pool, r)) + + +def random_combination(iterable, r): + """Return a random *r* length subsequence of the elements in *iterable*. + + >>> random_combination(range(5), 3) # doctest:+SKIP + (2, 3, 4) + + This equivalent to taking a random selection from + ``itertools.combinations(iterable, r)``. + + """ + pool = tuple(iterable) + n = len(pool) + indices = sorted(sample(range(n), r)) + return tuple(pool[i] for i in indices) + + +def random_combination_with_replacement(iterable, r): + """Return a random *r* length subsequence of elements in *iterable*, + allowing individual elements to be repeated. + + >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP + (0, 0, 1, 2, 2) + + This equivalent to taking a random selection from + ``itertools.combinations_with_replacement(iterable, r)``. + + """ + pool = tuple(iterable) + n = len(pool) + indices = sorted(randrange(n) for i in range(r)) + return tuple(pool[i] for i in indices) + + +def nth_combination(iterable, r, index): + """Equivalent to ``list(combinations(iterable, r))[index]``. + + The subsequences of *iterable* that are of length *r* can be ordered + lexicographically. :func:`nth_combination` computes the subsequence at + sort position *index* directly, without computing the previous + subsequences. + + >>> nth_combination(range(5), 3, 5) + (0, 3, 4) + + ``ValueError`` will be raised If *r* is negative or greater than the length + of *iterable*. + ``IndexError`` will be raised if the given *index* is invalid. + """ + pool = tuple(iterable) + n = len(pool) + if (r < 0) or (r > n): + raise ValueError + + c = 1 + k = min(r, n - r) + for i in range(1, k + 1): + c = c * (n - k + i) // i + + if index < 0: + index += c + + if (index < 0) or (index >= c): + raise IndexError + + result = [] + while r: + c, n, r = c * r // n, n - 1, r - 1 + while index >= c: + index -= c + c, n = c * (n - r) // n, n - 1 + result.append(pool[-1 - n]) + + return tuple(result) + + +def prepend(value, iterator): + """Yield *value*, followed by the elements in *iterator*. + + >>> value = '0' + >>> iterator = ['1', '2', '3'] + >>> list(prepend(value, iterator)) + ['0', '1', '2', '3'] + + To prepend multiple values, see :func:`itertools.chain` + or :func:`value_chain`. + + """ + return chain([value], iterator) + + +def convolve(signal, kernel): + """Convolve the iterable *signal* with the iterable *kernel*. + + >>> signal = (1, 2, 3, 4, 5) + >>> kernel = [3, 2, 1] + >>> list(convolve(signal, kernel)) + [3, 8, 14, 20, 26, 14, 5] + + Note: the input arguments are not interchangeable, as the *kernel* + is immediately consumed and stored. + + """ + # This implementation intentionally doesn't match the one in the itertools + # documentation. + kernel = tuple(kernel)[::-1] + n = len(kernel) + window = deque([0], maxlen=n) * n + for x in chain(signal, repeat(0, n - 1)): + window.append(x) + yield _sumprod(kernel, window) + + +def before_and_after(predicate, it): + """A variant of :func:`takewhile` that allows complete access to the + remainder of the iterator. + + >>> it = iter('ABCdEfGhI') + >>> all_upper, remainder = before_and_after(str.isupper, it) + >>> ''.join(all_upper) + 'ABC' + >>> ''.join(remainder) # takewhile() would lose the 'd' + 'dEfGhI' + + Note that the first iterator must be fully consumed before the second + iterator can generate valid results. + """ + it = iter(it) + transition = [] + + def true_iterator(): + for elem in it: + if predicate(elem): + yield elem + else: + transition.append(elem) + return + + # Note: this is different from itertools recipes to allow nesting + # before_and_after remainders into before_and_after again. See tests + # for an example. + remainder_iterator = chain(transition, it) + + return true_iterator(), remainder_iterator + + +def triplewise(iterable): + """Return overlapping triplets from *iterable*. + + >>> list(triplewise('ABCDE')) + [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')] + + """ + for (a, _), (b, c) in pairwise(pairwise(iterable)): + yield a, b, c + + +def sliding_window(iterable, n): + """Return a sliding window of width *n* over *iterable*. + + >>> list(sliding_window(range(6), 4)) + [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)] + + If *iterable* has fewer than *n* items, then nothing is yielded: + + >>> list(sliding_window(range(3), 4)) + [] + + For a variant with more features, see :func:`windowed`. + """ + it = iter(iterable) + window = deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def subslices(iterable): + """Return all contiguous non-empty subslices of *iterable*. + + >>> list(subslices('ABC')) + [['A'], ['A', 'B'], ['A', 'B', 'C'], ['B'], ['B', 'C'], ['C']] + + This is similar to :func:`substrings`, but emits items in a different + order. + """ + seq = list(iterable) + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + + +def polynomial_from_roots(roots): + """Compute a polynomial's coefficients from its roots. + + >>> roots = [5, -4, 3] # (x - 5) * (x + 4) * (x - 3) + >>> polynomial_from_roots(roots) # x^3 - 4 * x^2 - 17 * x + 60 + [1, -4, -17, 60] + """ + factors = zip(repeat(1), map(operator.neg, roots)) + return list(reduce(convolve, factors, [1])) + + +def iter_index(iterable, value, start=0, stop=None): + """Yield the index of each place in *iterable* that *value* occurs, + beginning with index *start* and ending before index *stop*. + + + >>> list(iter_index('AABCADEAF', 'A')) + [0, 1, 4, 7] + >>> list(iter_index('AABCADEAF', 'A', 1)) # start index is inclusive + [1, 4, 7] + >>> list(iter_index('AABCADEAF', 'A', 1, 7)) # stop index is not inclusive + [1, 4] + + The behavior for non-scalar *values* matches the built-in Python types. + + >>> list(iter_index('ABCDABCD', 'AB')) + [0, 4] + >>> list(iter_index([0, 1, 2, 3, 0, 1, 2, 3], [0, 1])) + [] + >>> list(iter_index([[0, 1], [2, 3], [0, 1], [2, 3]], [0, 1])) + [0, 2] + + See :func:`locate` for a more general means of finding the indexes + associated with particular values. + + """ + seq_index = getattr(iterable, 'index', None) + if seq_index is None: + # Slow path for general iterables + it = islice(iterable, start, stop) + for i, element in enumerate(it, start): + if element is value or element == value: + yield i + else: + # Fast path for sequences + stop = len(iterable) if stop is None else stop + i = start - 1 + try: + while True: + yield (i := seq_index(value, i + 1, stop)) + except ValueError: + pass + + +def sieve(n): + """Yield the primes less than n. + + >>> list(sieve(30)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + """ + if n > 2: + yield 2 + start = 3 + data = bytearray((0, 1)) * (n // 2) + limit = math.isqrt(n) + 1 + for p in iter_index(data, 1, start, limit): + yield from iter_index(data, 1, start, p * p) + data[p * p : n : p + p] = bytes(len(range(p * p, n, p + p))) + start = p * p + yield from iter_index(data, 1, start) + + +def _batched(iterable, n, *, strict=False): + """Batch data into tuples of length *n*. If the number of items in + *iterable* is not divisible by *n*: + * The last batch will be shorter if *strict* is ``False``. + * :exc:`ValueError` will be raised if *strict* is ``True``. + + >>> list(batched('ABCDEFG', 3)) + [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)] + + On Python 3.13 and above, this is an alias for :func:`itertools.batched`. + """ + if n < 1: + raise ValueError('n must be at least one') + it = iter(iterable) + while batch := tuple(islice(it, n)): + if strict and len(batch) != n: + raise ValueError('batched(): incomplete batch') + yield batch + + +if hexversion >= 0x30D00A2: + from itertools import batched as itertools_batched + + def batched(iterable, n, *, strict=False): + return itertools_batched(iterable, n, strict=strict) + +else: + batched = _batched + + batched.__doc__ = _batched.__doc__ + + +def transpose(it): + """Swap the rows and columns of the input matrix. + + >>> list(transpose([(1, 2, 3), (11, 22, 33)])) + [(1, 11), (2, 22), (3, 33)] + + The caller should ensure that the dimensions of the input are compatible. + If the input is empty, no output will be produced. + """ + return _zip_strict(*it) + + +def reshape(matrix, cols): + """Reshape the 2-D input *matrix* to have a column count given by *cols*. + + >>> matrix = [(0, 1), (2, 3), (4, 5)] + >>> cols = 3 + >>> list(reshape(matrix, cols)) + [(0, 1, 2), (3, 4, 5)] + """ + return batched(chain.from_iterable(matrix), cols) + + +def matmul(m1, m2): + """Multiply two matrices. + + >>> list(matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)])) + [(49, 80), (41, 60)] + + The caller should ensure that the dimensions of the input matrices are + compatible with each other. + """ + n = len(m2[0]) + return batched(starmap(_sumprod, product(m1, transpose(m2))), n) + + +def factor(n): + """Yield the prime factors of n. + + >>> list(factor(360)) + [2, 2, 2, 3, 3, 5] + """ + for prime in sieve(math.isqrt(n) + 1): + while not n % prime: + yield prime + n //= prime + if n == 1: + return + if n > 1: + yield n + + +def polynomial_eval(coefficients, x): + """Evaluate a polynomial at a specific value. + + Example: evaluating x^3 - 4 * x^2 - 17 * x + 60 at x = 2.5: + + >>> coefficients = [1, -4, -17, 60] + >>> x = 2.5 + >>> polynomial_eval(coefficients, x) + 8.125 + """ + n = len(coefficients) + if n == 0: + return x * 0 # coerce zero to the type of x + powers = map(pow, repeat(x), reversed(range(n))) + return _sumprod(coefficients, powers) + + +def sum_of_squares(it): + """Return the sum of the squares of the input values. + + >>> sum_of_squares([10, 20, 30]) + 1400 + """ + return _sumprod(*tee(it)) + + +def polynomial_derivative(coefficients): + """Compute the first derivative of a polynomial. + + Example: evaluating the derivative of x^3 - 4 * x^2 - 17 * x + 60 + + >>> coefficients = [1, -4, -17, 60] + >>> derivative_coefficients = polynomial_derivative(coefficients) + >>> derivative_coefficients + [3, -8, -17] + """ + n = len(coefficients) + powers = reversed(range(1, n)) + return list(map(operator.mul, coefficients, powers)) + + +def totient(n): + """Return the count of natural numbers up to *n* that are coprime with *n*. + + >>> totient(9) + 6 + >>> totient(12) + 4 + """ + # The itertools docs use unique_justseen instead of set; see + # https://github.com/more-itertools/more-itertools/issues/823 + for p in set(factor(n)): + n = n // p * (p - 1) + + return n diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.pyi b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..739acec05fb3fdd5778aa27db82face3442c3c3f --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.pyi @@ -0,0 +1,136 @@ +"""Stubs for more_itertools.recipes""" + +from __future__ import annotations + +from typing import ( + Any, + Callable, + Iterable, + Iterator, + overload, + Sequence, + Type, + TypeVar, +) + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_U = TypeVar('_U') + +def take(n: int, iterable: Iterable[_T]) -> list[_T]: ... +def tabulate( + function: Callable[[int], _T], start: int = ... +) -> Iterator[_T]: ... +def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: ... +def consume(iterator: Iterable[_T], n: int | None = ...) -> None: ... +@overload +def nth(iterable: Iterable[_T], n: int) -> _T | None: ... +@overload +def nth(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ... +def all_equal( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> bool: ... +def quantify( + iterable: Iterable[_T], pred: Callable[[_T], bool] = ... +) -> int: ... +def pad_none(iterable: Iterable[_T]) -> Iterator[_T | None]: ... +def padnone(iterable: Iterable[_T]) -> Iterator[_T | None]: ... +def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: ... +def dotproduct(vec1: Iterable[_T1], vec2: Iterable[_T2]) -> Any: ... +def flatten(listOfLists: Iterable[Iterable[_T]]) -> Iterator[_T]: ... +def repeatfunc( + func: Callable[..., _U], times: int | None = ..., *args: Any +) -> Iterator[_U]: ... +def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ... +def grouper( + iterable: Iterable[_T], + n: int, + incomplete: str = ..., + fillvalue: _U = ..., +) -> Iterator[tuple[_T | _U, ...]]: ... +def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: ... +def partition( + pred: Callable[[_T], object] | None, iterable: Iterable[_T] +) -> tuple[Iterator[_T], Iterator[_T]]: ... +def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ... +def unique_everseen( + iterable: Iterable[_T], key: Callable[[_T], _U] | None = ... +) -> Iterator[_T]: ... +def unique_justseen( + iterable: Iterable[_T], key: Callable[[_T], object] | None = ... +) -> Iterator[_T]: ... +def unique( + iterable: Iterable[_T], + key: Callable[[_T], object] | None = ..., + reverse: bool = False, +) -> Iterator[_T]: ... +@overload +def iter_except( + func: Callable[[], _T], + exception: Type[BaseException] | tuple[Type[BaseException], ...], + first: None = ..., +) -> Iterator[_T]: ... +@overload +def iter_except( + func: Callable[[], _T], + exception: Type[BaseException] | tuple[Type[BaseException], ...], + first: Callable[[], _U], +) -> Iterator[_T | _U]: ... +@overload +def first_true( + iterable: Iterable[_T], *, pred: Callable[[_T], object] | None = ... +) -> _T | None: ... +@overload +def first_true( + iterable: Iterable[_T], + default: _U, + pred: Callable[[_T], object] | None = ..., +) -> _T | _U: ... +def random_product( + *args: Iterable[_T], repeat: int = ... +) -> tuple[_T, ...]: ... +def random_permutation( + iterable: Iterable[_T], r: int | None = ... +) -> tuple[_T, ...]: ... +def random_combination(iterable: Iterable[_T], r: int) -> tuple[_T, ...]: ... +def random_combination_with_replacement( + iterable: Iterable[_T], r: int +) -> tuple[_T, ...]: ... +def nth_combination( + iterable: Iterable[_T], r: int, index: int +) -> tuple[_T, ...]: ... +def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[_T | _U]: ... +def convolve(signal: Iterable[_T], kernel: Iterable[_T]) -> Iterator[_T]: ... +def before_and_after( + predicate: Callable[[_T], bool], it: Iterable[_T] +) -> tuple[Iterator[_T], Iterator[_T]]: ... +def triplewise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: ... +def sliding_window( + iterable: Iterable[_T], n: int +) -> Iterator[tuple[_T, ...]]: ... +def subslices(iterable: Iterable[_T]) -> Iterator[list[_T]]: ... +def polynomial_from_roots(roots: Sequence[_T]) -> list[_T]: ... +def iter_index( + iterable: Iterable[_T], + value: Any, + start: int | None = ..., + stop: int | None = ..., +) -> Iterator[int]: ... +def sieve(n: int) -> Iterator[int]: ... +def batched( + iterable: Iterable[_T], n: int, *, strict: bool = False +) -> Iterator[tuple[_T]]: ... +def transpose( + it: Iterable[Iterable[_T]], +) -> Iterator[tuple[_T, ...]]: ... +def reshape( + matrix: Iterable[Iterable[_T]], cols: int +) -> Iterator[tuple[_T, ...]]: ... +def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[tuple[_T]]: ... +def factor(n: int) -> Iterator[int]: ... +def polynomial_eval(coefficients: Sequence[_T], x: _U) -> _U: ... +def sum_of_squares(it: Iterable[_T]) -> _T: ... +def polynomial_derivative(coefficients: Sequence[_T]) -> list[_T]: ... +def totient(n: int) -> int: ... diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made +under the terms of *both* these licenses. diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/LICENSE.BSD @@ -0,0 +1,23 @@ +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. diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1479c8694bfbd583a896dbe9bd33cdb6d7e7371e --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/METADATA @@ -0,0 +1,102 @@ +Metadata-Version: 2.3 +Name: packaging +Version: 24.2 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join ``#pypa`` on Freenode to ask questions or get involved. + + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..678aa5a501dfda29cfdd8a585e038754f008d380 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/RECORD @@ -0,0 +1,25 @@ +packaging-24.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +packaging-24.2.dist-info/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-24.2.dist-info/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-24.2.dist-info/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging-24.2.dist-info/METADATA,sha256=ohH86s6k5mIfQxY2TS0LcSfADeOFa4BiCC-bxZV-pNs,3204 +packaging-24.2.dist-info/RECORD,, +packaging-24.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging-24.2.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +packaging/__init__.py,sha256=dk4Ta_vmdVJxYHDcfyhvQNw8V3PgSBomKNXqg-D2JDY,494 +packaging/_elffile.py,sha256=cflAQAkE25tzhYmq_aCi72QfbT_tn891tPzfpbeHOwE,3306 +packaging/_manylinux.py,sha256=vl5OCoz4kx80H5rwXKeXWjl9WNISGmr4ZgTpTP9lU9c,9612 +packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694 +packaging/_parser.py,sha256=s_TvTvDNK0NrM2QB3VKThdWFM4Nc0P6JnkObkl3MjpM,10236 +packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +packaging/_tokenizer.py,sha256=J6v5H7Jzvb-g81xp_2QACKwO7LxHQA6ikryMU7zXwN8,5273 +packaging/licenses/__init__.py,sha256=1x5M1nEYjcgwEbLt0dXwz2ukjr18DiCzC0sraQqJ-Ww,5715 +packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398 +packaging/markers.py,sha256=c89TNzB7ZdGYhkovm6PYmqGyHxXlYVaLW591PHUNKD8,10561 +packaging/metadata.py,sha256=YJibM7GYe4re8-0a3OlXmGS-XDgTEoO4tlBt2q25Bng,34762 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947 +packaging/specifiers.py,sha256=GG1wPNMcL0fMJO68vF53wKMdwnfehDcaI-r9NpTfilA,40074 +packaging/tags.py,sha256=CFqrJzAzc2XNGexerH__T-Y5Iwq7WbsYXsiLERLWxY0,21014 +packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050 +packaging/version.py,sha256=olfyuk_DPbflNkJ4wBWetXQ17c74x3DB501degUv7DY,16676 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e3c6feefa22927866e3fd5575379ea972b432aaf --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging-24.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.10.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d79f73c574ffc759ef5d2145b1ec742d85c2500b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "24.2" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = f"2014 {__author__}" diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_elffile.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..25f4282cc29cb03d7be881f03dee841d7dbc215a --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_elffile.py @@ -0,0 +1,110 @@ +""" +ELF file parser. + +This provides a class ``ELFFile`` that parses an ELF executable in a similar +interface to ``ZipFile``. Only the read interface is implemented. + +Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca +ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html +""" + +from __future__ import annotations + +import enum +import os +import struct +from typing import IO + + +class ELFInvalid(ValueError): + pass + + +class EIClass(enum.IntEnum): + C32 = 1 + C64 = 2 + + +class EIData(enum.IntEnum): + Lsb = 1 + Msb = 2 + + +class EMachine(enum.IntEnum): + I386 = 3 + S390 = 22 + Arm = 40 + X8664 = 62 + AArc64 = 183 + + +class ELFFile: + """ + Representation of an ELF executable. + """ + + def __init__(self, f: IO[bytes]) -> None: + self._f = f + + try: + ident = self._read("16B") + except struct.error as e: + raise ELFInvalid("unable to parse identification") from e + magic = bytes(ident[:4]) + if magic != b"\x7fELF": + raise ELFInvalid(f"invalid magic: {magic!r}") + + self.capacity = ident[4] # Format for program header (bitness). + self.encoding = ident[5] # Data structure encoding (endianness). + + try: + # e_fmt: Format for program header. + # p_fmt: Format for section header. + # p_idx: Indexes to find p_type, p_offset, and p_filesz. + e_fmt, self._p_fmt, self._p_idx = { + (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. + (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. + }[(self.capacity, self.encoding)] + except KeyError as e: + raise ELFInvalid( + f"unrecognized capacity ({self.capacity}) or " + f"encoding ({self.encoding})" + ) from e + + try: + ( + _, + self.machine, # Architecture type. + _, + _, + self._e_phoff, # Offset of program header. + _, + self.flags, # Processor-specific flags. + _, + self._e_phentsize, # Size of section. + self._e_phnum, # Number of sections. + ) = self._read(e_fmt) + except struct.error as e: + raise ELFInvalid("unable to parse machine and section information") from e + + def _read(self, fmt: str) -> tuple[int, ...]: + return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) + + @property + def interpreter(self) -> str | None: + """ + The path recorded in the ``PT_INTERP`` section header. + """ + for index in range(self._e_phnum): + self._f.seek(self._e_phoff + self._e_phentsize * index) + try: + data = self._read(self._p_fmt) + except struct.error: + continue + if data[self._p_idx[0]] != 3: # Not PT_INTERP. + continue + self._f.seek(data[self._p_idx[1]]) + return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") + return None diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_manylinux.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..61339a6fcc1b82803136f3bf980e0c8f574b2220 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_manylinux.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import collections +import contextlib +import functools +import os +import re +import sys +import warnings +from typing import Generator, Iterator, NamedTuple, Sequence + +from ._elffile import EIClass, EIData, ELFFile, EMachine + +EF_ARM_ABIMASK = 0xFF000000 +EF_ARM_ABI_VER5 = 0x05000000 +EF_ARM_ABI_FLOAT_HARD = 0x00000400 + + +# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` +# as the type for `path` until then. +@contextlib.contextmanager +def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: + try: + with open(path, "rb") as f: + yield ELFFile(f) + except (OSError, TypeError, ValueError): + yield None + + +def _is_linux_armhf(executable: str) -> bool: + # hard-float ABI can be detected from the ELF header of the running + # process + # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.Arm + and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 + and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD + ) + + +def _is_linux_i686(executable: str) -> bool: + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.I386 + ) + + +def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: + if "armv7l" in archs: + return _is_linux_armhf(executable) + if "i686" in archs: + return _is_linux_i686(executable) + allowed_archs = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", + } + return any(arch in allowed_archs for arch in archs) + + +# If glibc ever changes its major version, we need to know what the last +# minor version was, so we can build the complete list of all versions. +# For now, guess what the highest minor version might be, assume it will +# be 50 for testing. Once this actually happens, update the dictionary +# with the actual value. +_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) + + +class _GLibCVersion(NamedTuple): + major: int + minor: int + + +def _glibc_version_string_confstr() -> str | None: + """ + Primary implementation of glibc_version_string using os.confstr. + """ + # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely + # to be broken or missing. This strategy is used in the standard library + # platform module. + # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 + try: + # Should be a string like "glibc 2.17". + version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") + assert version_string is not None + _, version = version_string.rsplit() + except (AssertionError, AttributeError, OSError, ValueError): + # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... + return None + return version + + +def _glibc_version_string_ctypes() -> str | None: + """ + Fallback implementation of glibc_version_string using ctypes. + """ + try: + import ctypes + except ImportError: + return None + + # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen + # manpage says, "If filename is NULL, then the returned handle is for the + # main program". This way we can let the linker do the work to figure out + # which libc our process is actually using. + # + # We must also handle the special case where the executable is not a + # dynamically linked executable. This can occur when using musl libc, + # for example. In this situation, dlopen() will error, leading to an + # OSError. Interestingly, at least in the case of musl, there is no + # errno set on the OSError. The single string argument used to construct + # OSError comes from libc itself and is therefore not portable to + # hard code here. In any case, failure to call dlopen() means we + # can proceed, so we bail on our attempt. + try: + process_namespace = ctypes.CDLL(None) + except OSError: + return None + + try: + gnu_get_libc_version = process_namespace.gnu_get_libc_version + except AttributeError: + # Symbol doesn't exist -> therefore, we are not linked to + # glibc. + return None + + # Call gnu_get_libc_version, which returns a string like "2.5" + gnu_get_libc_version.restype = ctypes.c_char_p + version_str: str = gnu_get_libc_version() + # py2 / py3 compatibility: + if not isinstance(version_str, str): + version_str = version_str.decode("ascii") + + return version_str + + +def _glibc_version_string() -> str | None: + """Returns glibc version string, or None if not using glibc.""" + return _glibc_version_string_confstr() or _glibc_version_string_ctypes() + + +def _parse_glibc_version(version_str: str) -> tuple[int, int]: + """Parse glibc version. + + We use a regexp instead of str.split because we want to discard any + random junk that might come after the minor version -- this might happen + in patched/forked versions of glibc (e.g. Linaro's version of glibc + uses version strings like "2.20-2014.11"). See gh-3588. + """ + m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) + if not m: + warnings.warn( + f"Expected glibc version with 2 components major.minor," + f" got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return -1, -1 + return int(m.group("major")), int(m.group("minor")) + + +@functools.lru_cache +def _get_glibc_version() -> tuple[int, int]: + version_str = _glibc_version_string() + if version_str is None: + return (-1, -1) + return _parse_glibc_version(version_str) + + +# From PEP 513, PEP 600 +def _is_compatible(arch: str, version: _GLibCVersion) -> bool: + sys_glibc = _get_glibc_version() + if sys_glibc < version: + return False + # Check for presence of _manylinux module. + try: + import _manylinux + except ImportError: + return True + if hasattr(_manylinux, "manylinux_compatible"): + result = _manylinux.manylinux_compatible(version[0], version[1], arch) + if result is not None: + return bool(result) + return True + if version == _GLibCVersion(2, 5): + if hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12): + if hasattr(_manylinux, "manylinux2010_compatible"): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17): + if hasattr(_manylinux, "manylinux2014_compatible"): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + (2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + (2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + (2, 5): "manylinux1", +} + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate manylinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be manylinux-compatible. + + :returns: An iterator of compatible manylinux tags. + """ + if not _have_compatible_abi(sys.executable, archs): + return + # Oldest glibc to be supported regardless of architecture is (2, 17). + too_old_glibc2 = _GLibCVersion(2, 16) + if set(archs) & {"x86_64", "i686"}: + # On x86/i686 also oldest glibc to be supported is (2, 5). + too_old_glibc2 = _GLibCVersion(2, 4) + current_glibc = _GLibCVersion(*_get_glibc_version()) + glibc_max_list = [current_glibc] + # We can assume compatibility across glibc major versions. + # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 + # + # Build a list of maximum glibc versions so that we can + # output the canonical list of all glibc from current_glibc + # down to too_old_glibc2, including all intermediary versions. + for glibc_major in range(current_glibc.major - 1, 1, -1): + glibc_minor = _LAST_GLIBC_MINOR[glibc_major] + glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) + for arch in archs: + for glibc_max in glibc_max_list: + if glibc_max.major == too_old_glibc2.major: + min_minor = too_old_glibc2.minor + else: + # For other glibc major versions oldest supported is (x, 0). + min_minor = -1 + for glibc_minor in range(glibc_max.minor, min_minor, -1): + glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) + tag = "manylinux_{}_{}".format(*glibc_version) + if _is_compatible(arch, glibc_version): + yield f"{tag}_{arch}" + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if glibc_version in _LEGACY_MANYLINUX_MAP: + legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] + if _is_compatible(arch, glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_musllinux.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bf30b56319ba862c5c9a1a39a87c6d1cb68718 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_musllinux.py @@ -0,0 +1,85 @@ +"""PEP 656 support. + +This module implements logic to detect if the currently running Python is +linked against musl, and what musl version is used. +""" + +from __future__ import annotations + +import functools +import re +import subprocess +import sys +from typing import Iterator, NamedTuple, Sequence + +from ._elffile import ELFFile + + +class _MuslVersion(NamedTuple): + major: int + minor: int + + +def _parse_musl_version(output: str) -> _MuslVersion | None: + lines = [n for n in (n.strip() for n in output.splitlines()) if n] + if len(lines) < 2 or lines[0][:4] != "musl": + return None + m = re.match(r"Version (\d+)\.(\d+)", lines[1]) + if not m: + return None + return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) + + +@functools.lru_cache +def _get_musl_version(executable: str) -> _MuslVersion | None: + """Detect currently-running musl runtime version. + + This is done by checking the specified executable's dynamic linking + information, and invoking the loader to parse its output for a version + string. If the loader is musl, the output would be something like:: + + musl libc (x86_64) + Version 1.2.2 + Dynamic Program Loader + """ + try: + with open(executable, "rb") as f: + ld = ELFFile(f).interpreter + except (OSError, TypeError, ValueError): + return None + if ld is None or "musl" not in ld: + return None + proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True) + return _parse_musl_version(proc.stderr) + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate musllinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be musllinux-compatible. + + :returns: An iterator of compatible musllinux tags. + """ + sys_musl = _get_musl_version(sys.executable) + if sys_musl is None: # Python not dynamically linked against musl. + return + for arch in archs: + for minor in range(sys_musl.minor, -1, -1): + yield f"musllinux_{sys_musl.major}_{minor}_{arch}" + + +if __name__ == "__main__": # pragma: no cover + import sysconfig + + plat = sysconfig.get_platform() + assert plat.startswith("linux-"), "not linux" + + print("plat:", plat) + print("musl:", _get_musl_version(sys.executable)) + print("tags:", end=" ") + for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): + print(t, end="\n ") diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_parser.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c1238c06eab95f8c90c393383a703aa3b8c366a5 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_parser.py @@ -0,0 +1,354 @@ +"""Handwritten parser of dependency specifiers. + +The docstring for each __parse_* function contains EBNF-inspired grammar representing +the implementation. +""" + +from __future__ import annotations + +import ast +from typing import NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + def __init__(self, value: str) -> None: + self.value = value + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + def serialize(self) -> str: + return str(self) + + +class Value(Node): + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + def serialize(self) -> str: + return str(self) + + +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = Sequence[Union["MarkerList", MarkerAtom, str]] + + +class ParsedRequirement(NamedTuple): + name: str + url: str + extras: list[str] + specifier: str + marker: MarkerList | None + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for dependency specifier +# -------------------------------------------------------------------------------------- +def parse_requirement(source: str) -> ParsedRequirement: + return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: + """ + requirement = WS? IDENTIFIER WS? extras WS? requirement_details + """ + tokenizer.consume("WS") + + name_token = tokenizer.expect( + "IDENTIFIER", expected="package name at the start of dependency specifier" + ) + name = name_token.text + tokenizer.consume("WS") + + extras = _parse_extras(tokenizer) + tokenizer.consume("WS") + + url, specifier, marker = _parse_requirement_details(tokenizer) + tokenizer.expect("END", expected="end of dependency specifier") + + return ParsedRequirement(name, url, extras, specifier, marker) + + +def _parse_requirement_details( + tokenizer: Tokenizer, +) -> tuple[str, str, MarkerList | None]: + """ + requirement_details = AT URL (WS requirement_marker?)? + | specifier WS? (requirement_marker)? + """ + + specifier = "" + url = "" + marker = None + + if tokenizer.check("AT"): + tokenizer.read() + tokenizer.consume("WS") + + url_start = tokenizer.position + url = tokenizer.expect("URL", expected="URL after @").text + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + tokenizer.expect("WS", expected="whitespace after URL") + + # The input might end after whitespace. + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, span_start=url_start, after="URL and whitespace" + ) + else: + specifier_start = tokenizer.position + specifier = _parse_specifier(tokenizer) + tokenizer.consume("WS") + + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=specifier_start, + after=( + "version specifier" + if specifier + else "name and no valid version specifier" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, after: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected end or semicolon (after {after})", + span_start=span_start, + ) + tokenizer.read() + + marker = _parse_marker(tokenizer) + tokenizer.consume("WS") + + return marker + + +def _parse_extras(tokenizer: Tokenizer) -> list[str]: + """ + extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? + """ + if not tokenizer.check("LEFT_BRACKET", peek=True): + return [] + + with tokenizer.enclosing_tokens( + "LEFT_BRACKET", + "RIGHT_BRACKET", + around="extras", + ): + tokenizer.consume("WS") + extras = _parse_extras_list(tokenizer) + tokenizer.consume("WS") + + return extras + + +def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: + """ + extras_list = identifier (wsp* ',' wsp* identifier)* + """ + extras: list[str] = [] + + if not tokenizer.check("IDENTIFIER"): + return extras + + extras.append(tokenizer.read().text) + + while True: + tokenizer.consume("WS") + if tokenizer.check("IDENTIFIER", peek=True): + tokenizer.raise_syntax_error("Expected comma between extra names") + elif not tokenizer.check("COMMA"): + break + + tokenizer.read() + tokenizer.consume("WS") + + extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") + extras.append(extra_token.text) + + return extras + + +def _parse_specifier(tokenizer: Tokenizer) -> str: + """ + specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS + | WS? version_many WS? + """ + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="version specifier", + ): + tokenizer.consume("WS") + parsed_specifiers = _parse_version_many(tokenizer) + tokenizer.consume("WS") + + return parsed_specifiers + + +def _parse_version_many(tokenizer: Tokenizer) -> str: + """ + version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? + """ + parsed_specifiers = "" + while tokenizer.check("SPECIFIER"): + span_start = tokenizer.position + parsed_specifiers += tokenizer.read().text + if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): + tokenizer.raise_syntax_error( + ".* suffix can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position + 1, + ) + if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): + tokenizer.raise_syntax_error( + "Local version label can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position, + ) + tokenizer.consume("WS") + if not tokenizer.check("COMMA"): + break + parsed_specifiers += tokenizer.read().text + tokenizer.consume("WS") + + return parsed_specifiers + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for marker expression +# -------------------------------------------------------------------------------------- +def parse_marker(source: str) -> MarkerList: + return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: + retval = _parse_marker(tokenizer) + tokenizer.expect("END", expected="end of marker expression") + return retval + + +def _parse_marker(tokenizer: Tokenizer) -> MarkerList: + """ + marker = marker_atom (BOOLOP marker_atom)+ + """ + expression = [_parse_marker_atom(tokenizer)] + while tokenizer.check("BOOLOP"): + token = tokenizer.read() + expr_right = _parse_marker_atom(tokenizer) + expression.extend((token.text, expr_right)) + return expression + + +def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: + """ + marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? + | WS? marker_item WS? + """ + + tokenizer.consume("WS") + if tokenizer.check("LEFT_PARENTHESIS", peek=True): + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="marker expression", + ): + tokenizer.consume("WS") + marker: MarkerAtom = _parse_marker(tokenizer) + tokenizer.consume("WS") + else: + marker = _parse_marker_item(tokenizer) + tokenizer.consume("WS") + return marker + + +def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: + """ + marker_item = WS? marker_var WS? marker_op WS? marker_var WS? + """ + tokenizer.consume("WS") + marker_var_left = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + marker_op = _parse_marker_op(tokenizer) + tokenizer.consume("WS") + marker_var_right = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + return (marker_var_left, marker_op, marker_var_right) + + +def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: + """ + marker_var = VARIABLE | QUOTED_STRING + """ + if tokenizer.check("VARIABLE"): + return process_env_var(tokenizer.read().text.replace(".", "_")) + elif tokenizer.check("QUOTED_STRING"): + return process_python_str(tokenizer.read().text) + else: + tokenizer.raise_syntax_error( + message="Expected a marker variable or quoted string" + ) + + +def process_env_var(env_var: str) -> Variable: + if env_var in ("platform_python_implementation", "python_implementation"): + return Variable("platform_python_implementation") + else: + return Variable(env_var) + + +def process_python_str(python_str: str) -> Value: + value = ast.literal_eval(python_str) + return Value(str(value)) + + +def _parse_marker_op(tokenizer: Tokenizer) -> Op: + """ + marker_op = IN | NOT IN | OP + """ + if tokenizer.check("IN"): + tokenizer.read() + return Op("in") + elif tokenizer.check("NOT"): + tokenizer.read() + tokenizer.expect("WS", expected="whitespace after 'not'") + tokenizer.expect("IN", expected="'in' after 'not'") + return Op("not in") + elif tokenizer.check("OP"): + return Op(tokenizer.read().text) + else: + return tokenizer.raise_syntax_error( + "Expected marker operator, one of " + "<=, <, !=, ==, >=, >, ~=, ===, in, not in" + ) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_structures.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_structures.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_tokenizer.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..89d041605c006e326a67f399a58a1fec8eb24acf --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/_tokenizer.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Iterator, NoReturn + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return "\n ".join([self.message, self.source, marker]) + + +DEFAULT_RULES: dict[str, str | re.Pattern[str]] = { + "LEFT_PARENTHESIS": r"\(", + "RIGHT_PARENTHESIS": r"\)", + "LEFT_BRACKET": r"\[", + "RIGHT_BRACKET": r"\]", + "SEMICOLON": r";", + "COMMA": r",", + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": r"(===|==|~=|!=|<=|>=|<|>)", + "BOOLOP": r"\b(or|and)\b", + "IN": r"\bin\b", + "NOT": r"\bnot\b", + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extra + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": r"\@", + "URL": r"[^ \t]+", + "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", + "VERSION_PREFIX_TRAIL": r"\.\*", + "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*", + "WS": r"[ \t]+", + "END": r"$", +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: dict[str, str | re.Pattern[str]], + ) -> None: + self.source = source + self.rules: dict[str, re.Pattern[str]] = { + name: re.compile(pattern) for name, pattern in rules.items() + } + self.next_token: Token | None = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert ( + self.next_token is None + ), f"Cannot check for {name!r}, already have {self.next_token!r}" + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: int | None = None, + span_end: int | None = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens( + self, open_token: str, close_token: str, *, around: str + ) -> Iterator[None]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected matching {close_token} for {open_token}, after {around}", + span_start=open_position, + ) + + self.read() diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..569156d6ca47719f49b753a4781a86a924de173b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/__init__.py @@ -0,0 +1,145 @@ +####################################################################################### +# +# Adapted from: +# https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py +# +# MIT License +# +# Copyright (c) 2017-present Ofek Lev +# +# 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. +# +# +# With additional allowance of arbitrary `LicenseRef-` identifiers, not just +# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`. +# +####################################################################################### +from __future__ import annotations + +import re +from typing import NewType, cast + +from packaging.licenses._spdx import EXCEPTIONS, LICENSES + +__all__ = [ + "NormalizedLicenseExpression", + "InvalidLicenseExpression", + "canonicalize_license_expression", +] + +license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$") + +NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str) + + +class InvalidLicenseExpression(ValueError): + """Raised when a license-expression string is invalid + + >>> canonicalize_license_expression("invalid") + Traceback (most recent call last): + ... + packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' + """ + + +def canonicalize_license_expression( + raw_license_expression: str, +) -> NormalizedLicenseExpression: + if not raw_license_expression: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) + + # Pad any parentheses so tokenization can be achieved by merely splitting on + # whitespace. + license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") + licenseref_prefix = "LicenseRef-" + license_refs = { + ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] + for ref in license_expression.split() + if ref.lower().startswith(licenseref_prefix.lower()) + } + + # Normalize to lower case so we can look up licenses/exceptions + # and so boolean operators are Python-compatible. + license_expression = license_expression.lower() + + tokens = license_expression.split() + + # Rather than implementing boolean logic, we create an expression that Python can + # parse. Everything that is not involved with the grammar itself is treated as + # `False` and the expression should evaluate as such. + python_tokens = [] + for token in tokens: + if token not in {"or", "and", "with", "(", ")"}: + python_tokens.append("False") + elif token == "with": + python_tokens.append("or") + elif token == "(" and python_tokens and python_tokens[-1] not in {"or", "and"}: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) + else: + python_tokens.append(token) + + python_expression = " ".join(python_tokens) + try: + invalid = eval(python_expression, globals(), locals()) + except Exception: + invalid = True + + if invalid is not False: + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) from None + + # Take a final pass to check for unknown licenses/exceptions. + normalized_tokens = [] + for token in tokens: + if token in {"or", "and", "with", "(", ")"}: + normalized_tokens.append(token.upper()) + continue + + if normalized_tokens and normalized_tokens[-1] == "WITH": + if token not in EXCEPTIONS: + message = f"Unknown license exception: {token!r}" + raise InvalidLicenseExpression(message) + + normalized_tokens.append(EXCEPTIONS[token]["id"]) + else: + if token.endswith("+"): + final_token = token[:-1] + suffix = "+" + else: + final_token = token + suffix = "" + + if final_token.startswith("licenseref-"): + if not license_ref_allowed.match(final_token): + message = f"Invalid licenseref: {final_token!r}" + raise InvalidLicenseExpression(message) + normalized_tokens.append(license_refs[final_token] + suffix) + else: + if final_token not in LICENSES: + message = f"Unknown license: {final_token!r}" + raise InvalidLicenseExpression(message) + normalized_tokens.append(LICENSES[final_token]["id"] + suffix) + + normalized_expression = " ".join(normalized_tokens) + + return cast( + NormalizedLicenseExpression, + normalized_expression.replace("( ", "(").replace(" )", ")"), + ) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py new file mode 100644 index 0000000000000000000000000000000000000000..eac22276a34ccd73fc9d70c67ca318a49eb11e77 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py @@ -0,0 +1,759 @@ + +from __future__ import annotations + +from typing import TypedDict + +class SPDXLicense(TypedDict): + id: str + deprecated: bool + +class SPDXException(TypedDict): + id: str + deprecated: bool + + +VERSION = '3.25.0' + +LICENSES: dict[str, SPDXLicense] = { + '0bsd': {'id': '0BSD', 'deprecated': False}, + '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False}, + 'aal': {'id': 'AAL', 'deprecated': False}, + 'abstyles': {'id': 'Abstyles', 'deprecated': False}, + 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False}, + 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False}, + 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False}, + 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False}, + 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False}, + 'adsl': {'id': 'ADSL', 'deprecated': False}, + 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False}, + 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False}, + 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False}, + 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False}, + 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False}, + 'afmparse': {'id': 'Afmparse', 'deprecated': False}, + 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True}, + 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False}, + 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False}, + 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True}, + 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False}, + 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False}, + 'aladdin': {'id': 'Aladdin', 'deprecated': False}, + 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False}, + 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False}, + 'aml': {'id': 'AML', 'deprecated': False}, + 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False}, + 'ampas': {'id': 'AMPAS', 'deprecated': False}, + 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False}, + 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False}, + 'any-osi': {'id': 'any-OSI', 'deprecated': False}, + 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False}, + 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False}, + 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False}, + 'apafml': {'id': 'APAFML', 'deprecated': False}, + 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False}, + 'app-s2p': {'id': 'App-s2p', 'deprecated': False}, + 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False}, + 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False}, + 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False}, + 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False}, + 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False}, + 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False}, + 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False}, + 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False}, + 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False}, + 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False}, + 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False}, + 'baekmuk': {'id': 'Baekmuk', 'deprecated': False}, + 'bahyph': {'id': 'Bahyph', 'deprecated': False}, + 'barr': {'id': 'Barr', 'deprecated': False}, + 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False}, + 'beerware': {'id': 'Beerware', 'deprecated': False}, + 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False}, + 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False}, + 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False}, + 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False}, + 'blessing': {'id': 'blessing', 'deprecated': False}, + 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False}, + 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False}, + 'borceux': {'id': 'Borceux', 'deprecated': False}, + 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False}, + 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False}, + 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False}, + 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False}, + 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False}, + 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False}, + 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True}, + 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True}, + 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False}, + 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False}, + 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False}, + 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False}, + 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False}, + 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False}, + 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False}, + 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False}, + 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False}, + 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False}, + 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False}, + 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False}, + 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False}, + 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False}, + 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False}, + 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False}, + 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False}, + 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False}, + 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False}, + 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False}, + 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False}, + 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False}, + 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False}, + 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False}, + 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False}, + 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False}, + 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False}, + 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False}, + 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False}, + 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True}, + 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False}, + 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False}, + 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False}, + 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False}, + 'caldera': {'id': 'Caldera', 'deprecated': False}, + 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False}, + 'catharon': {'id': 'Catharon', 'deprecated': False}, + 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False}, + 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False}, + 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False}, + 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False}, + 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False}, + 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False}, + 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False}, + 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False}, + 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False}, + 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False}, + 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False}, + 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False}, + 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False}, + 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False}, + 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False}, + 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False}, + 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False}, + 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False}, + 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False}, + 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False}, + 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False}, + 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False}, + 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False}, + 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False}, + 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False}, + 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False}, + 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False}, + 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False}, + 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False}, + 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False}, + 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False}, + 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False}, + 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False}, + 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False}, + 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False}, + 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False}, + 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False}, + 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False}, + 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False}, + 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False}, + 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False}, + 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False}, + 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False}, + 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False}, + 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False}, + 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False}, + 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False}, + 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False}, + 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False}, + 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False}, + 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False}, + 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False}, + 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False}, + 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False}, + 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False}, + 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False}, + 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False}, + 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False}, + 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False}, + 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False}, + 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False}, + 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False}, + 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False}, + 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False}, + 'cecill-b': {'id': 'CECILL-B', 'deprecated': False}, + 'cecill-c': {'id': 'CECILL-C', 'deprecated': False}, + 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False}, + 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False}, + 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False}, + 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False}, + 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False}, + 'cfitsio': {'id': 'CFITSIO', 'deprecated': False}, + 'check-cvs': {'id': 'check-cvs', 'deprecated': False}, + 'checkmk': {'id': 'checkmk', 'deprecated': False}, + 'clartistic': {'id': 'ClArtistic', 'deprecated': False}, + 'clips': {'id': 'Clips', 'deprecated': False}, + 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False}, + 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False}, + 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False}, + 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False}, + 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False}, + 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False}, + 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False}, + 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False}, + 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False}, + 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False}, + 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False}, + 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False}, + 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False}, + 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False}, + 'cronyx': {'id': 'Cronyx', 'deprecated': False}, + 'crossword': {'id': 'Crossword', 'deprecated': False}, + 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False}, + 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False}, + 'cube': {'id': 'Cube', 'deprecated': False}, + 'curl': {'id': 'curl', 'deprecated': False}, + 'cve-tou': {'id': 'cve-tou', 'deprecated': False}, + 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False}, + 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False}, + 'diffmark': {'id': 'diffmark', 'deprecated': False}, + 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False}, + 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False}, + 'doc': {'id': 'DOC', 'deprecated': False}, + 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, + 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False}, + 'dotseqn': {'id': 'Dotseqn', 'deprecated': False}, + 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False}, + 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False}, + 'dsdp': {'id': 'DSDP', 'deprecated': False}, + 'dtoa': {'id': 'dtoa', 'deprecated': False}, + 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False}, + 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False}, + 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False}, + 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True}, + 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False}, + 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False}, + 'egenix': {'id': 'eGenix', 'deprecated': False}, + 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False}, + 'entessa': {'id': 'Entessa', 'deprecated': False}, + 'epics': {'id': 'EPICS', 'deprecated': False}, + 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False}, + 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False}, + 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False}, + 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False}, + 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False}, + 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False}, + 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False}, + 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False}, + 'eurosym': {'id': 'Eurosym', 'deprecated': False}, + 'fair': {'id': 'Fair', 'deprecated': False}, + 'fbm': {'id': 'FBM', 'deprecated': False}, + 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False}, + 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False}, + 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False}, + 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False}, + 'freeimage': {'id': 'FreeImage', 'deprecated': False}, + 'fsfap': {'id': 'FSFAP', 'deprecated': False}, + 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False}, + 'fsful': {'id': 'FSFUL', 'deprecated': False}, + 'fsfullr': {'id': 'FSFULLR', 'deprecated': False}, + 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, + 'ftl': {'id': 'FTL', 'deprecated': False}, + 'furuseth': {'id': 'Furuseth', 'deprecated': False}, + 'fwlw': {'id': 'fwlw', 'deprecated': False}, + 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, + 'gd': {'id': 'GD', 'deprecated': False}, + 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True}, + 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False}, + 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False}, + 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False}, + 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False}, + 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False}, + 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True}, + 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False}, + 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False}, + 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False}, + 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False}, + 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False}, + 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True}, + 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False}, + 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False}, + 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False}, + 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False}, + 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False}, + 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False}, + 'giftware': {'id': 'Giftware', 'deprecated': False}, + 'gl2ps': {'id': 'GL2PS', 'deprecated': False}, + 'glide': {'id': 'Glide', 'deprecated': False}, + 'glulxe': {'id': 'Glulxe', 'deprecated': False}, + 'glwtpl': {'id': 'GLWTPL', 'deprecated': False}, + 'gnuplot': {'id': 'gnuplot', 'deprecated': False}, + 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True}, + 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True}, + 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False}, + 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False}, + 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True}, + 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True}, + 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False}, + 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False}, + 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True}, + 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True}, + 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True}, + 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True}, + 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True}, + 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True}, + 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True}, + 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False}, + 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False}, + 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True}, + 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True}, + 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False}, + 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False}, + 'gtkbook': {'id': 'gtkbook', 'deprecated': False}, + 'gutmann': {'id': 'Gutmann', 'deprecated': False}, + 'haskellreport': {'id': 'HaskellReport', 'deprecated': False}, + 'hdparm': {'id': 'hdparm', 'deprecated': False}, + 'hidapi': {'id': 'HIDAPI', 'deprecated': False}, + 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False}, + 'hp-1986': {'id': 'HP-1986', 'deprecated': False}, + 'hp-1989': {'id': 'HP-1989', 'deprecated': False}, + 'hpnd': {'id': 'HPND', 'deprecated': False}, + 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False}, + 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False}, + 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False}, + 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False}, + 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False}, + 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False}, + 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False}, + 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False}, + 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False}, + 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False}, + 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False}, + 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False}, + 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False}, + 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False}, + 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False}, + 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False}, + 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False}, + 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False}, + 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False}, + 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False}, + 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False}, + 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False}, + 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False}, + 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False}, + 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False}, + 'icu': {'id': 'ICU', 'deprecated': False}, + 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False}, + 'ijg': {'id': 'IJG', 'deprecated': False}, + 'ijg-short': {'id': 'IJG-short', 'deprecated': False}, + 'imagemagick': {'id': 'ImageMagick', 'deprecated': False}, + 'imatix': {'id': 'iMatix', 'deprecated': False}, + 'imlib2': {'id': 'Imlib2', 'deprecated': False}, + 'info-zip': {'id': 'Info-ZIP', 'deprecated': False}, + 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False}, + 'intel': {'id': 'Intel', 'deprecated': False}, + 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False}, + 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False}, + 'ipa': {'id': 'IPA', 'deprecated': False}, + 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False}, + 'isc': {'id': 'ISC', 'deprecated': False}, + 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False}, + 'jam': {'id': 'Jam', 'deprecated': False}, + 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False}, + 'jpl-image': {'id': 'JPL-image', 'deprecated': False}, + 'jpnic': {'id': 'JPNIC', 'deprecated': False}, + 'json': {'id': 'JSON', 'deprecated': False}, + 'kastrup': {'id': 'Kastrup', 'deprecated': False}, + 'kazlib': {'id': 'Kazlib', 'deprecated': False}, + 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False}, + 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False}, + 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False}, + 'latex2e': {'id': 'Latex2e', 'deprecated': False}, + 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False}, + 'leptonica': {'id': 'Leptonica', 'deprecated': False}, + 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True}, + 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True}, + 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False}, + 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False}, + 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True}, + 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True}, + 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False}, + 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False}, + 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True}, + 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True}, + 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False}, + 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False}, + 'lgpllr': {'id': 'LGPLLR', 'deprecated': False}, + 'libpng': {'id': 'Libpng', 'deprecated': False}, + 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False}, + 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False}, + 'libtiff': {'id': 'libtiff', 'deprecated': False}, + 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False}, + 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False}, + 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False}, + 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False}, + 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False}, + 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False}, + 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False}, + 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False}, + 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False}, + 'loop': {'id': 'LOOP', 'deprecated': False}, + 'lpd-document': {'id': 'LPD-document', 'deprecated': False}, + 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False}, + 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False}, + 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False}, + 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False}, + 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False}, + 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False}, + 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False}, + 'lsof': {'id': 'lsof', 'deprecated': False}, + 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False}, + 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False}, + 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False}, + 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False}, + 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False}, + 'magaz': {'id': 'magaz', 'deprecated': False}, + 'mailprio': {'id': 'mailprio', 'deprecated': False}, + 'makeindex': {'id': 'MakeIndex', 'deprecated': False}, + 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False}, + 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False}, + 'metamail': {'id': 'metamail', 'deprecated': False}, + 'minpack': {'id': 'Minpack', 'deprecated': False}, + 'miros': {'id': 'MirOS', 'deprecated': False}, + 'mit': {'id': 'MIT', 'deprecated': False}, + 'mit-0': {'id': 'MIT-0', 'deprecated': False}, + 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False}, + 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False}, + 'mit-enna': {'id': 'MIT-enna', 'deprecated': False}, + 'mit-feh': {'id': 'MIT-feh', 'deprecated': False}, + 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False}, + 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False}, + 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False}, + 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False}, + 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False}, + 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False}, + 'mitnfa': {'id': 'MITNFA', 'deprecated': False}, + 'mmixware': {'id': 'MMIXware', 'deprecated': False}, + 'motosoto': {'id': 'Motosoto', 'deprecated': False}, + 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False}, + 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False}, + 'mpich2': {'id': 'mpich2', 'deprecated': False}, + 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False}, + 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False}, + 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False}, + 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False}, + 'mplus': {'id': 'mplus', 'deprecated': False}, + 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False}, + 'ms-pl': {'id': 'MS-PL', 'deprecated': False}, + 'ms-rl': {'id': 'MS-RL', 'deprecated': False}, + 'mtll': {'id': 'MTLL', 'deprecated': False}, + 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False}, + 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False}, + 'multics': {'id': 'Multics', 'deprecated': False}, + 'mup': {'id': 'Mup', 'deprecated': False}, + 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False}, + 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False}, + 'naumen': {'id': 'Naumen', 'deprecated': False}, + 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False}, + 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False}, + 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False}, + 'ncl': {'id': 'NCL', 'deprecated': False}, + 'ncsa': {'id': 'NCSA', 'deprecated': False}, + 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True}, + 'netcdf': {'id': 'NetCDF', 'deprecated': False}, + 'newsletr': {'id': 'Newsletr', 'deprecated': False}, + 'ngpl': {'id': 'NGPL', 'deprecated': False}, + 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False}, + 'nist-pd': {'id': 'NIST-PD', 'deprecated': False}, + 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False}, + 'nist-software': {'id': 'NIST-Software', 'deprecated': False}, + 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False}, + 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False}, + 'nlpl': {'id': 'NLPL', 'deprecated': False}, + 'nokia': {'id': 'Nokia', 'deprecated': False}, + 'nosl': {'id': 'NOSL', 'deprecated': False}, + 'noweb': {'id': 'Noweb', 'deprecated': False}, + 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False}, + 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False}, + 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False}, + 'nrl': {'id': 'NRL', 'deprecated': False}, + 'ntp': {'id': 'NTP', 'deprecated': False}, + 'ntp-0': {'id': 'NTP-0', 'deprecated': False}, + 'nunit': {'id': 'Nunit', 'deprecated': True}, + 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False}, + 'oar': {'id': 'OAR', 'deprecated': False}, + 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False}, + 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False}, + 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False}, + 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False}, + 'offis': {'id': 'OFFIS', 'deprecated': False}, + 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False}, + 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False}, + 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False}, + 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False}, + 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False}, + 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False}, + 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False}, + 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False}, + 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False}, + 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False}, + 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False}, + 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False}, + 'ogtsl': {'id': 'OGTSL', 'deprecated': False}, + 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False}, + 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False}, + 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False}, + 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False}, + 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False}, + 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False}, + 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False}, + 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False}, + 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False}, + 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False}, + 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False}, + 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False}, + 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False}, + 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False}, + 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False}, + 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False}, + 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False}, + 'oml': {'id': 'OML', 'deprecated': False}, + 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False}, + 'openssl': {'id': 'OpenSSL', 'deprecated': False}, + 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False}, + 'openvision': {'id': 'OpenVision', 'deprecated': False}, + 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False}, + 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False}, + 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False}, + 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False}, + 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False}, + 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False}, + 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False}, + 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False}, + 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False}, + 'padl': {'id': 'PADL', 'deprecated': False}, + 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False}, + 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False}, + 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False}, + 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False}, + 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False}, + 'pixar': {'id': 'Pixar', 'deprecated': False}, + 'pkgconf': {'id': 'pkgconf', 'deprecated': False}, + 'plexus': {'id': 'Plexus', 'deprecated': False}, + 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False}, + 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False}, + 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False}, + 'postgresql': {'id': 'PostgreSQL', 'deprecated': False}, + 'ppl': {'id': 'PPL', 'deprecated': False}, + 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False}, + 'psfrag': {'id': 'psfrag', 'deprecated': False}, + 'psutils': {'id': 'psutils', 'deprecated': False}, + 'python-2.0': {'id': 'Python-2.0', 'deprecated': False}, + 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False}, + 'python-ldap': {'id': 'python-ldap', 'deprecated': False}, + 'qhull': {'id': 'Qhull', 'deprecated': False}, + 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False}, + 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False}, + 'radvd': {'id': 'radvd', 'deprecated': False}, + 'rdisc': {'id': 'Rdisc', 'deprecated': False}, + 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False}, + 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False}, + 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False}, + 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False}, + 'rsa-md': {'id': 'RSA-MD', 'deprecated': False}, + 'rscpl': {'id': 'RSCPL', 'deprecated': False}, + 'ruby': {'id': 'Ruby', 'deprecated': False}, + 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False}, + 'sax-pd': {'id': 'SAX-PD', 'deprecated': False}, + 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False}, + 'saxpath': {'id': 'Saxpath', 'deprecated': False}, + 'scea': {'id': 'SCEA', 'deprecated': False}, + 'schemereport': {'id': 'SchemeReport', 'deprecated': False}, + 'sendmail': {'id': 'Sendmail', 'deprecated': False}, + 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False}, + 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False}, + 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False}, + 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False}, + 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False}, + 'sgp4': {'id': 'SGP4', 'deprecated': False}, + 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False}, + 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False}, + 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False}, + 'sissl': {'id': 'SISSL', 'deprecated': False}, + 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False}, + 'sl': {'id': 'SL', 'deprecated': False}, + 'sleepycat': {'id': 'Sleepycat', 'deprecated': False}, + 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, + 'smppl': {'id': 'SMPPL', 'deprecated': False}, + 'snia': {'id': 'SNIA', 'deprecated': False}, + 'snprintf': {'id': 'snprintf', 'deprecated': False}, + 'softsurfer': {'id': 'softSurfer', 'deprecated': False}, + 'soundex': {'id': 'Soundex', 'deprecated': False}, + 'spencer-86': {'id': 'Spencer-86', 'deprecated': False}, + 'spencer-94': {'id': 'Spencer-94', 'deprecated': False}, + 'spencer-99': {'id': 'Spencer-99', 'deprecated': False}, + 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False}, + 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False}, + 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False}, + 'ssh-short': {'id': 'SSH-short', 'deprecated': False}, + 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False}, + 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False}, + 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True}, + 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False}, + 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False}, + 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False}, + 'sunpro': {'id': 'SunPro', 'deprecated': False}, + 'swl': {'id': 'SWL', 'deprecated': False}, + 'swrule': {'id': 'swrule', 'deprecated': False}, + 'symlinks': {'id': 'Symlinks', 'deprecated': False}, + 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False}, + 'tcl': {'id': 'TCL', 'deprecated': False}, + 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False}, + 'termreadkey': {'id': 'TermReadKey', 'deprecated': False}, + 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False}, + 'threeparttable': {'id': 'threeparttable', 'deprecated': False}, + 'tmate': {'id': 'TMate', 'deprecated': False}, + 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False}, + 'tosl': {'id': 'TOSL', 'deprecated': False}, + 'tpdl': {'id': 'TPDL', 'deprecated': False}, + 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False}, + 'ttwl': {'id': 'TTWL', 'deprecated': False}, + 'ttyp0': {'id': 'TTYP0', 'deprecated': False}, + 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False}, + 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False}, + 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False}, + 'ucar': {'id': 'UCAR', 'deprecated': False}, + 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False}, + 'ulem': {'id': 'ulem', 'deprecated': False}, + 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False}, + 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False}, + 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False}, + 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False}, + 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False}, + 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False}, + 'unlicense': {'id': 'Unlicense', 'deprecated': False}, + 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False}, + 'urt-rle': {'id': 'URT-RLE', 'deprecated': False}, + 'vim': {'id': 'Vim', 'deprecated': False}, + 'vostrom': {'id': 'VOSTROM', 'deprecated': False}, + 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False}, + 'w3c': {'id': 'W3C', 'deprecated': False}, + 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False}, + 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False}, + 'w3m': {'id': 'w3m', 'deprecated': False}, + 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False}, + 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False}, + 'wsuipa': {'id': 'Wsuipa', 'deprecated': False}, + 'wtfpl': {'id': 'WTFPL', 'deprecated': False}, + 'wxwindows': {'id': 'wxWindows', 'deprecated': True}, + 'x11': {'id': 'X11', 'deprecated': False}, + 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False}, + 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False}, + 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False}, + 'xerox': {'id': 'Xerox', 'deprecated': False}, + 'xfig': {'id': 'Xfig', 'deprecated': False}, + 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False}, + 'xinetd': {'id': 'xinetd', 'deprecated': False}, + 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False}, + 'xlock': {'id': 'xlock', 'deprecated': False}, + 'xnet': {'id': 'Xnet', 'deprecated': False}, + 'xpp': {'id': 'xpp', 'deprecated': False}, + 'xskat': {'id': 'XSkat', 'deprecated': False}, + 'xzoom': {'id': 'xzoom', 'deprecated': False}, + 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False}, + 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False}, + 'zed': {'id': 'Zed', 'deprecated': False}, + 'zeeff': {'id': 'Zeeff', 'deprecated': False}, + 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False}, + 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False}, + 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False}, + 'zlib': {'id': 'Zlib', 'deprecated': False}, + 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False}, + 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False}, + 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False}, + 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False}, +} + +EXCEPTIONS: dict[str, SPDXException] = { + '389-exception': {'id': '389-exception', 'deprecated': False}, + 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False}, + 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False}, + 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False}, + 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False}, + 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False}, + 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False}, + 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False}, + 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False}, + 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False}, + 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False}, + 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False}, + 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False}, + 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False}, + 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False}, + 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False}, + 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False}, + 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False}, + 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False}, + 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False}, + 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False}, + 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False}, + 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False}, + 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False}, + 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False}, + 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False}, + 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False}, + 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False}, + 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False}, + 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False}, + 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False}, + 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False}, + 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False}, + 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False}, + 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False}, + 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False}, + 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, + 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False}, + 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False}, + 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False}, + 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False}, + 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False}, + 'llgpl': {'id': 'LLGPL', 'deprecated': False}, + 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False}, + 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False}, + 'mif-exception': {'id': 'mif-exception', 'deprecated': False}, + 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True}, + 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False}, + 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False}, + 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False}, + 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False}, + 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False}, + 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False}, + 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False}, + 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False}, + 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False}, + 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False}, + 'romic-exception': {'id': 'romic-exception', 'deprecated': False}, + 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False}, + 'sane-exception': {'id': 'SANE-exception', 'deprecated': False}, + 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False}, + 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False}, + 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False}, + 'swi-exception': {'id': 'SWI-exception', 'deprecated': False}, + 'swift-exception': {'id': 'Swift-exception', 'deprecated': False}, + 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False}, + 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False}, + 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False}, + 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False}, + 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False}, + 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False}, + 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False}, +} diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/markers.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..fb7f49cf8cd43ffae71e3e8d15174d7536f9da02 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/markers.py @@ -0,0 +1,331 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import operator +import os +import platform +import sys +from typing import Any, Callable, TypedDict, cast + +from ._parser import MarkerAtom, MarkerList, Op, Value, Variable +from ._parser import parse_marker as _parse_marker +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + +Operator = Callable[[str, str], bool] + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Environment(TypedDict): + implementation_name: str + """The implementation's identifier, e.g. ``'cpython'``.""" + + implementation_version: str + """ + The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or + ``'7.3.13'`` for PyPy3.10 v7.3.13. + """ + + os_name: str + """ + The value of :py:data:`os.name`. The name of the operating system dependent module + imported, e.g. ``'posix'``. + """ + + platform_machine: str + """ + Returns the machine type, e.g. ``'i386'``. + + An empty string if the value cannot be determined. + """ + + platform_release: str + """ + The system's release, e.g. ``'2.2.0'`` or ``'NT'``. + + An empty string if the value cannot be determined. + """ + + platform_system: str + """ + The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. + + An empty string if the value cannot be determined. + """ + + platform_version: str + """ + The system's release version, e.g. ``'#3 on degas'``. + + An empty string if the value cannot be determined. + """ + + python_full_version: str + """ + The Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python :py:data:`sys.version`, this value will always include + the patchlevel (it defaults to 0). + """ + + platform_python_implementation: str + """ + A string identifying the Python implementation, e.g. ``'CPython'``. + """ + + python_version: str + """The Python version as string ``'major.minor'``.""" + + sys_platform: str + """ + This string contains a platform identifier that can be used to append + platform-specific components to :py:data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python + was built. + """ + + +def _normalize_extra_values(results: Any) -> Any: + """ + Normalize extra values. + """ + if isinstance(results[0], tuple): + lhs, op, rhs = results[0] + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + results[0] = lhs, op, rhs + return results + + +def _format_marker( + marker: list[str] | MarkerAtom | str, first: bool | None = True +) -> str: + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs: str, op: Op, rhs: str) -> bool: + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize(*values: str, key: str) -> tuple[str, ...]: + # PEP 685 – Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + return tuple(canonicalize_name(v) for v in values) + + # other environment markers don't have such standards + return values + + +def _evaluate_markers(markers: MarkerList, environment: dict[str, str]) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, str)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info: sys._version_info) -> str: + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Environment: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash((self.__class__.__name__, str(self))) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate(self, environment: dict[str, str] | None = None) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. + + The environment is determined from the current Python process. + """ + current_environment = cast("dict[str, str]", default_environment()) + current_environment["extra"] = "" + if environment is not None: + current_environment.update(environment) + # The API used to allow setting extra to None. We need to handle this + # case for backwards compatibility. + if current_environment["extra"] is None: + current_environment["extra"] = "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version(env: dict[str, str]) -> dict[str, str]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + if env["python_full_version"].endswith("+"): + env["python_full_version"] += "local" + return env diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/metadata.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..721f411cfc44f6d24c13112e4246b5ad776a5e0b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/metadata.py @@ -0,0 +1,863 @@ +from __future__ import annotations + +import email.feedparser +import email.header +import email.message +import email.parser +import email.policy +import pathlib +import sys +import typing +from typing import ( + Any, + Callable, + Generic, + Literal, + TypedDict, + cast, +) + +from . import licenses, requirements, specifiers, utils +from . import version as version_module +from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +if sys.version_info >= (3, 11): # pragma: no cover + ExceptionGroup = ExceptionGroup +else: # pragma: no cover + + class ExceptionGroup(Exception): + """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. + + If :external:exc:`ExceptionGroup` is already defined by Python itself, + that version is used instead. + """ + + message: str + exceptions: list[Exception] + + def __init__(self, message: str, exceptions: list[Exception]) -> None: + self.message = message + self.exceptions = exceptions + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" + + +class InvalidMetadata(ValueError): + """A metadata field contains invalid data.""" + + field: str + """The name of the field that contains invalid data.""" + + def __init__(self, field: str, message: str) -> None: + self.field = field + super().__init__(message) + + +# The RawMetadata class attempts to make as few assumptions about the underlying +# serialization formats as possible. The idea is that as long as a serialization +# formats offer some very basic primitives in *some* way then we can support +# serializing to and from that format. +class RawMetadata(TypedDict, total=False): + """A dictionary of raw core metadata. + + Each field in core metadata maps to a key of this dictionary (when data is + provided). The key is lower-case and underscores are used instead of dashes + compared to the equivalent core metadata field. Any core metadata field that + can be specified multiple times or can hold multiple values in a single + field have a key with a plural name. See :class:`Metadata` whose attributes + match the keys of this dictionary. + + Core metadata fields that can be specified multiple times are stored as a + list or dict depending on which is appropriate for the field. Any fields + which hold multiple values in a single field are stored as a list. + + """ + + # Metadata 1.0 - PEP 241 + metadata_version: str + name: str + version: str + platforms: list[str] + summary: str + description: str + keywords: list[str] + home_page: str + author: str + author_email: str + license: str + + # Metadata 1.1 - PEP 314 + supported_platforms: list[str] + download_url: str + classifiers: list[str] + requires: list[str] + provides: list[str] + obsoletes: list[str] + + # Metadata 1.2 - PEP 345 + maintainer: str + maintainer_email: str + requires_dist: list[str] + provides_dist: list[str] + obsoletes_dist: list[str] + requires_python: str + requires_external: list[str] + project_urls: dict[str, str] + + # Metadata 2.0 + # PEP 426 attempted to completely revamp the metadata format + # but got stuck without ever being able to build consensus on + # it and ultimately ended up withdrawn. + # + # However, a number of tools had started emitting METADATA with + # `2.0` Metadata-Version, so for historical reasons, this version + # was skipped. + + # Metadata 2.1 - PEP 566 + description_content_type: str + provides_extra: list[str] + + # Metadata 2.2 - PEP 643 + dynamic: list[str] + + # Metadata 2.3 - PEP 685 + # No new fields were added in PEP 685, just some edge case were + # tightened up to provide better interoptability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + +_STRING_FIELDS = { + "author", + "author_email", + "description", + "description_content_type", + "download_url", + "home_page", + "license", + "license_expression", + "maintainer", + "maintainer_email", + "metadata_version", + "name", + "requires_python", + "summary", + "version", +} + +_LIST_FIELDS = { + "classifiers", + "dynamic", + "license_files", + "obsoletes", + "obsoletes_dist", + "platforms", + "provides", + "provides_dist", + "provides_extra", + "requires", + "requires_dist", + "requires_external", + "supported_platforms", +} + +_DICT_FIELDS = { + "project_urls", +} + + +def _parse_keywords(data: str) -> list[str]: + """Split a string of comma-separated keywords into a list of keywords.""" + return [k.strip() for k in data.split(",")] + + +def _parse_project_urls(data: list[str]) -> dict[str, str]: + """Parse a list of label/URL string pairings separated by a comma.""" + urls = {} + for pair in data: + # Our logic is slightly tricky here as we want to try and do + # *something* reasonable with malformed data. + # + # The main thing that we have to worry about, is data that does + # not have a ',' at all to split the label from the Value. There + # isn't a singular right answer here, and we will fail validation + # later on (if the caller is validating) so it doesn't *really* + # matter, but since the missing value has to be an empty str + # and our return value is dict[str, str], if we let the key + # be the missing value, then they'd have multiple '' values that + # overwrite each other in a accumulating dict. + # + # The other potentional issue is that it's possible to have the + # same label multiple times in the metadata, with no solid "right" + # answer with what to do in that case. As such, we'll do the only + # thing we can, which is treat the field as unparseable and add it + # to our list of unparsed fields. + parts = [p.strip() for p in pair.split(",", 1)] + parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items + + # TODO: The spec doesn't say anything about if the keys should be + # considered case sensitive or not... logically they should + # be case-preserving and case-insensitive, but doing that + # would open up more cases where we might have duplicate + # entries. + label, url = parts + if label in urls: + # The label already exists in our set of urls, so this field + # is unparseable, and we can just add the whole thing to our + # unparseable data and stop processing it. + raise KeyError("duplicate labels in project urls") + urls[label] = url + + return urls + + +def _get_payload(msg: email.message.Message, source: bytes | str) -> str: + """Get the body of the message.""" + # If our source is a str, then our caller has managed encodings for us, + # and we don't need to deal with it. + if isinstance(source, str): + payload = msg.get_payload() + assert isinstance(payload, str) + return payload + # If our source is a bytes, then we're managing the encoding and we need + # to deal with it. + else: + bpayload = msg.get_payload(decode=True) + assert isinstance(bpayload, bytes) + try: + return bpayload.decode("utf8", "strict") + except UnicodeDecodeError as exc: + raise ValueError("payload in an invalid encoding") from exc + + +# The various parse_FORMAT functions here are intended to be as lenient as +# possible in their parsing, while still returning a correctly typed +# RawMetadata. +# +# To aid in this, we also generally want to do as little touching of the +# data as possible, except where there are possibly some historic holdovers +# that make valid data awkward to work with. +# +# While this is a lower level, intermediate format than our ``Metadata`` +# class, some light touch ups can make a massive difference in usability. + +# Map METADATA fields to RawMetadata. +_EMAIL_TO_RAW_MAPPING = { + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "description", + "description-content-type": "description_content_type", + "download-url": "download_url", + "dynamic": "dynamic", + "home-page": "home_page", + "keywords": "keywords", + "license": "license", + "license-expression": "license_expression", + "license-file": "license_files", + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "metadata-version": "metadata_version", + "name": "name", + "obsoletes": "obsoletes", + "obsoletes-dist": "obsoletes_dist", + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + "provides-dist": "provides_dist", + "provides-extra": "provides_extra", + "requires": "requires", + "requires-dist": "requires_dist", + "requires-external": "requires_external", + "requires-python": "requires_python", + "summary": "summary", + "supported-platform": "supported_platforms", + "version": "version", +} +_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} + + +def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: + """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). + + This function returns a two-item tuple of dicts. The first dict is of + recognized fields from the core metadata specification. Fields that can be + parsed and translated into Python's built-in types are converted + appropriately. All other fields are left as-is. Fields that are allowed to + appear multiple times are stored as lists. + + The second dict contains all other fields from the metadata. This includes + any unrecognized fields. It also includes any fields which are expected to + be parsed into a built-in type but were not formatted appropriately. Finally, + any fields that are expected to appear only once but are repeated are + included in this dict. + + """ + raw: dict[str, str | list[str] | dict[str, str]] = {} + unparsed: dict[str, list[str]] = {} + + if isinstance(data, str): + parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) + else: + parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) + + # We have to wrap parsed.keys() in a set, because in the case of multiple + # values for a key (a list), the key will appear multiple times in the + # list of keys, but we're avoiding that by using get_all(). + for name in frozenset(parsed.keys()): + # Header names in RFC are case insensitive, so we'll normalize to all + # lower case to make comparisons easier. + name = name.lower() + + # We use get_all() here, even for fields that aren't multiple use, + # because otherwise someone could have e.g. two Name fields, and we + # would just silently ignore it rather than doing something about it. + headers = parsed.get_all(name) or [] + + # The way the email module works when parsing bytes is that it + # unconditionally decodes the bytes as ascii using the surrogateescape + # handler. When you pull that data back out (such as with get_all() ), + # it looks to see if the str has any surrogate escapes, and if it does + # it wraps it in a Header object instead of returning the string. + # + # As such, we'll look for those Header objects, and fix up the encoding. + value = [] + # Flag if we have run into any issues processing the headers, thus + # signalling that the data belongs in 'unparsed'. + valid_encoding = True + for h in headers: + # It's unclear if this can return more types than just a Header or + # a str, so we'll just assert here to make sure. + assert isinstance(h, (email.header.Header, str)) + + # If it's a header object, we need to do our little dance to get + # the real data out of it. In cases where there is invalid data + # we're going to end up with mojibake, but there's no obvious, good + # way around that without reimplementing parts of the Header object + # ourselves. + # + # That should be fine since, if mojibacked happens, this key is + # going into the unparsed dict anyways. + if isinstance(h, email.header.Header): + # The Header object stores it's data as chunks, and each chunk + # can be independently encoded, so we'll need to check each + # of them. + chunks: list[tuple[bytes, str | None]] = [] + for bin, encoding in email.header.decode_header(h): + try: + bin.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((bin, encoding)) + + # Turn our chunks back into a Header object, then let that + # Header object do the right thing to turn them into a + # string for us. + value.append(str(email.header.make_header(chunks))) + # This is already a string, so just add it. + else: + value.append(h) + + # We've processed all of our values to get them into a list of str, + # but we may have mojibake data, in which case this is an unparsed + # field. + if not valid_encoding: + unparsed[name] = value + continue + + raw_name = _EMAIL_TO_RAW_MAPPING.get(name) + if raw_name is None: + # This is a bit of a weird situation, we've encountered a key that + # we don't know what it means, so we don't know whether it's meant + # to be a list or not. + # + # Since we can't really tell one way or another, we'll just leave it + # as a list, even though it may be a single item list, because that's + # what makes the most sense for email headers. + unparsed[name] = value + continue + + # If this is one of our string fields, then we'll check to see if our + # value is a list of a single item. If it is then we'll assume that + # it was emitted as a single string, and unwrap the str from inside + # the list. + # + # If it's any other kind of data, then we haven't the faintest clue + # what we should parse it as, and we have to just add it to our list + # of unparsed stuff. + if raw_name in _STRING_FIELDS and len(value) == 1: + raw[raw_name] = value[0] + # If this is one of our list of string fields, then we can just assign + # the value, since email *only* has strings, and our get_all() call + # above ensures that this is a list. + elif raw_name in _LIST_FIELDS: + raw[raw_name] = value + # Special Case: Keywords + # The keywords field is implemented in the metadata spec as a str, + # but it conceptually is a list of strings, and is serialized using + # ", ".join(keywords), so we'll do some light data massaging to turn + # this into what it logically is. + elif raw_name == "keywords" and len(value) == 1: + raw[raw_name] = _parse_keywords(value[0]) + # Special Case: Project-URL + # The project urls is implemented in the metadata spec as a list of + # specially-formatted strings that represent a key and a value, which + # is fundamentally a mapping, however the email format doesn't support + # mappings in a sane way, so it was crammed into a list of strings + # instead. + # + # We will do a little light data massaging to turn this into a map as + # it logically should be. + elif raw_name == "project_urls": + try: + raw[raw_name] = _parse_project_urls(value) + except KeyError: + unparsed[name] = value + # Nothing that we've done has managed to parse this, so it'll just + # throw it in our unparseable data and move on. + else: + unparsed[name] = value + + # We need to support getting the Description from the message payload in + # addition to getting it from the the headers. This does mean, though, there + # is the possibility of it being set both ways, in which case we put both + # in 'unparsed' since we don't know which is right. + try: + payload = _get_payload(parsed, data) + except ValueError: + unparsed.setdefault("description", []).append( + parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] + ) + else: + if payload: + # Check to see if we've already got a description, if so then both + # it, and this body move to unparseable. + if "description" in raw: + description_header = cast(str, raw.pop("description")) + unparsed.setdefault("description", []).extend( + [description_header, payload] + ) + elif "description" in unparsed: + unparsed["description"].append(payload) + else: + raw["description"] = payload + + # We need to cast our `raw` to a metadata, because a TypedDict only support + # literal key names, but we're computing our key names on purpose, but the + # way this function is implemented, our `TypedDict` can only have valid key + # names. + return cast(RawMetadata, raw), unparsed + + +_NOT_FOUND = object() + + +# Keep the two values in sync. +_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] + +_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) + + +class _Validator(Generic[T]): + """Validate a metadata field. + + All _process_*() methods correspond to a core metadata field. The method is + called with the field's raw value. If the raw value is valid it is returned + in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). + If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause + as appropriate). + """ + + name: str + raw_name: str + added: _MetadataVersion + + def __init__( + self, + *, + added: _MetadataVersion = "1.0", + ) -> None: + self.added = added + + def __set_name__(self, _owner: Metadata, name: str) -> None: + self.name = name + self.raw_name = _RAW_TO_EMAIL_MAPPING[name] + + def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: + # With Python 3.8, the caching can be replaced with functools.cached_property(). + # No need to check the cache as attribute lookup will resolve into the + # instance's __dict__ before __get__ is called. + cache = instance.__dict__ + value = instance._raw.get(self.name) + + # To make the _process_* methods easier, we'll check if the value is None + # and if this field is NOT a required attribute, and if both of those + # things are true, we'll skip the the converter. This will mean that the + # converters never have to deal with the None union. + if self.name in _REQUIRED_ATTRS or value is not None: + try: + converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") + except AttributeError: + pass + else: + value = converter(value) + + cache[self.name] = value + try: + del instance._raw[self.name] # type: ignore[misc] + except KeyError: + pass + + return cast(T, value) + + def _invalid_metadata( + self, msg: str, cause: Exception | None = None + ) -> InvalidMetadata: + exc = InvalidMetadata( + self.raw_name, msg.format_map({"field": repr(self.raw_name)}) + ) + exc.__cause__ = cause + return exc + + def _process_metadata_version(self, value: str) -> _MetadataVersion: + # Implicitly makes Metadata-Version required. + if value not in _VALID_METADATA_VERSIONS: + raise self._invalid_metadata(f"{value!r} is not a valid metadata version") + return cast(_MetadataVersion, value) + + def _process_name(self, value: str) -> str: + if not value: + raise self._invalid_metadata("{field} is a required field") + # Validate the name as a side-effect. + try: + utils.canonicalize_name(value, validate=True) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return value + + def _process_version(self, value: str) -> version_module.Version: + if not value: + raise self._invalid_metadata("{field} is a required field") + try: + return version_module.parse(value) + except version_module.InvalidVersion as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_summary(self, value: str) -> str: + """Check the field contains no newlines.""" + if "\n" in value: + raise self._invalid_metadata("{field} must be a single line") + return value + + def _process_description_content_type(self, value: str) -> str: + content_types = {"text/plain", "text/x-rst", "text/markdown"} + message = email.message.EmailMessage() + message["content-type"] = value + + content_type, parameters = ( + # Defaults to `text/plain` if parsing failed. + message.get_content_type().lower(), + message["content-type"].params, + ) + # Check if content-type is valid or defaulted to `text/plain` and thus was + # not parseable. + if content_type not in content_types or content_type not in value.lower(): + raise self._invalid_metadata( + f"{{field}} must be one of {list(content_types)}, not {value!r}" + ) + + charset = parameters.get("charset", "UTF-8") + if charset != "UTF-8": + raise self._invalid_metadata( + f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" + ) + + markdown_variants = {"GFM", "CommonMark"} + variant = parameters.get("variant", "GFM") # Use an acceptable default. + if content_type == "text/markdown" and variant not in markdown_variants: + raise self._invalid_metadata( + f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " + f"not {variant!r}", + ) + return value + + def _process_dynamic(self, value: list[str]) -> list[str]: + for dynamic_field in map(str.lower, value): + if dynamic_field in {"name", "version", "metadata-version"}: + raise self._invalid_metadata( + f"{dynamic_field!r} is not allowed as a dynamic field" + ) + elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: + raise self._invalid_metadata( + f"{dynamic_field!r} is not a valid dynamic field" + ) + return list(map(str.lower, value)) + + def _process_provides_extra( + self, + value: list[str], + ) -> list[utils.NormalizedName]: + normalized_names = [] + try: + for name in value: + normalized_names.append(utils.canonicalize_name(name, validate=True)) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return normalized_names + + def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: + try: + return specifiers.SpecifierSet(value) + except specifiers.InvalidSpecifier as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_requires_dist( + self, + value: list[str], + ) -> list[requirements.Requirement]: + reqs = [] + try: + for req in value: + reqs.append(requirements.Requirement(req)) + except requirements.InvalidRequirement as exc: + raise self._invalid_metadata( + f"{req!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return reqs + + def _process_license_expression( + self, value: str + ) -> NormalizedLicenseExpression | None: + try: + return licenses.canonicalize_license_expression(value) + except ValueError as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_license_files(self, value: list[str]) -> list[str]: + paths = [] + for path in value: + if ".." in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "parent directory indicators are not allowed" + ) + if "*" in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be resolved" + ) + if ( + pathlib.PurePosixPath(path).is_absolute() + or pathlib.PureWindowsPath(path).is_absolute() + ): + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be relative" + ) + if pathlib.PureWindowsPath(path).as_posix() != path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "paths must use '/' delimiter" + ) + paths.append(path) + return paths + + +class Metadata: + """Representation of distribution metadata. + + Compared to :class:`RawMetadata`, this class provides objects representing + metadata fields instead of only using built-in types. Any invalid metadata + will cause :exc:`InvalidMetadata` to be raised (with a + :py:attr:`~BaseException.__cause__` attribute as appropriate). + """ + + _raw: RawMetadata + + @classmethod + def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: + """Create an instance from :class:`RawMetadata`. + + If *validate* is true, all metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + ins = cls() + ins._raw = data.copy() # Mutations occur due to caching enriched values. + + if validate: + exceptions: list[Exception] = [] + try: + metadata_version = ins.metadata_version + metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) + except InvalidMetadata as metadata_version_exc: + exceptions.append(metadata_version_exc) + metadata_version = None + + # Make sure to check for the fields that are present, the required + # fields (so their absence can be reported). + fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS + # Remove fields that have already been checked. + fields_to_check -= {"metadata_version"} + + for key in fields_to_check: + try: + if metadata_version: + # Can't use getattr() as that triggers descriptor protocol which + # will fail due to no value for the instance argument. + try: + field_metadata_version = cls.__dict__[key].added + except KeyError: + exc = InvalidMetadata(key, f"unrecognized field: {key!r}") + exceptions.append(exc) + continue + field_age = _VALID_METADATA_VERSIONS.index( + field_metadata_version + ) + if field_age > metadata_age: + field = _RAW_TO_EMAIL_MAPPING[key] + exc = InvalidMetadata( + field, + f"{field} introduced in metadata version " + f"{field_metadata_version}, not {metadata_version}", + ) + exceptions.append(exc) + continue + getattr(ins, key) + except InvalidMetadata as exc: + exceptions.append(exc) + + if exceptions: + raise ExceptionGroup("invalid metadata", exceptions) + + return ins + + @classmethod + def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: + """Parse metadata from email headers. + + If *validate* is true, the metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + raw, unparsed = parse_email(data) + + if validate: + exceptions: list[Exception] = [] + for unparsed_key in unparsed: + if unparsed_key in _EMAIL_TO_RAW_MAPPING: + message = f"{unparsed_key!r} has invalid data" + else: + message = f"unrecognized field: {unparsed_key!r}" + exceptions.append(InvalidMetadata(unparsed_key, message)) + + if exceptions: + raise ExceptionGroup("unparsed", exceptions) + + try: + return cls.from_raw(raw, validate=validate) + except ExceptionGroup as exc_group: + raise ExceptionGroup( + "invalid or unparsed metadata", exc_group.exceptions + ) from None + + metadata_version: _Validator[_MetadataVersion] = _Validator() + """:external:ref:`core-metadata-metadata-version` + (required; validated to be a valid metadata version)""" + # `name` is not normalized/typed to NormalizedName so as to provide access to + # the original/raw name. + name: _Validator[str] = _Validator() + """:external:ref:`core-metadata-name` + (required; validated using :func:`~packaging.utils.canonicalize_name` and its + *validate* parameter)""" + version: _Validator[version_module.Version] = _Validator() + """:external:ref:`core-metadata-version` (required)""" + dynamic: _Validator[list[str] | None] = _Validator( + added="2.2", + ) + """:external:ref:`core-metadata-dynamic` + (validated against core metadata field names and lowercased)""" + platforms: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-platform`""" + supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-supported-platform`""" + summary: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" + description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body + """:external:ref:`core-metadata-description`""" + description_content_type: _Validator[str | None] = _Validator(added="2.1") + """:external:ref:`core-metadata-description-content-type` (validated)""" + keywords: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-keywords`""" + home_page: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-home-page`""" + download_url: _Validator[str | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-download-url`""" + author: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author`""" + author_email: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author-email`""" + maintainer: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer`""" + maintainer_email: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer-email`""" + license: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-license`""" + license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( + added="2.4" + ) + """:external:ref:`core-metadata-license-expression`""" + license_files: _Validator[list[str] | None] = _Validator(added="2.4") + """:external:ref:`core-metadata-license-file`""" + classifiers: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-classifier`""" + requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-dist`""" + requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-python`""" + # Because `Requires-External` allows for non-PEP 440 version specifiers, we + # don't do any processing on the values. + requires_external: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-requires-external`""" + project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-project-url`""" + # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation + # regardless of metadata version. + provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( + added="2.1", + ) + """:external:ref:`core-metadata-provides-extra`""" + provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-provides-dist`""" + obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-obsoletes-dist`""" + requires: _Validator[list[str] | None] = _Validator(added="1.1") + """``Requires`` (deprecated)""" + provides: _Validator[list[str] | None] = _Validator(added="1.1") + """``Provides`` (deprecated)""" + obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") + """``Obsoletes`` (deprecated)""" diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/requirements.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..4e068c9567def3564f238a76fe7ab46b569f33e5 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/requirements.py @@ -0,0 +1,91 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import annotations + +from typing import Any, Iterator + +from ._parser import parse_requirement as _parse_requirement +from ._tokenizer import ParserSyntaxError +from .markers import Marker, _normalize_extra_values +from .specifiers import SpecifierSet +from .utils import canonicalize_name + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +class Requirement: + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string: str) -> None: + try: + parsed = _parse_requirement(requirement_string) + except ParserSyntaxError as e: + raise InvalidRequirement(str(e)) from e + + self.name: str = parsed.name + self.url: str | None = parsed.url or None + self.extras: set[str] = set(parsed.extras or []) + self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) + self.marker: Marker | None = None + if parsed.marker is not None: + self.marker = Marker.__new__(Marker) + self.marker._markers = _normalize_extra_values(parsed.marker) + + def _iter_parts(self, name: str) -> Iterator[str]: + yield name + + if self.extras: + formatted_extras = ",".join(sorted(self.extras)) + yield f"[{formatted_extras}]" + + if self.specifier: + yield str(self.specifier) + + if self.url: + yield f"@ {self.url}" + if self.marker: + yield " " + + if self.marker: + yield f"; {self.marker}" + + def __str__(self) -> str: + return "".join(self._iter_parts(self.name)) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash( + ( + self.__class__.__name__, + *self._iter_parts(canonicalize_name(self.name)), + ) + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Requirement): + return NotImplemented + + return ( + canonicalize_name(self.name) == canonicalize_name(other.name) + and self.extras == other.extras + and self.specifier == other.specifier + and self.url == other.url + and self.marker == other.marker + ) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..b30926af8bf4f47efe98eea44d5ded4cb6f7e07d --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py @@ -0,0 +1,1020 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import itertools +import re +from typing import Callable, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version: + if not isinstance(version, Version): + version = Version(version) + return version + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + self._spec: tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 + @property # type: ignore[override] + def prereleases(self) -> bool: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "===", ">", "<"]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if Version(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + canonical_version = canonicalize_version( + self._spec[1], + strip_trailing_zero=(self._spec[0] != "~="), + ) + return self._spec[0], canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + prospective.public, strip_trailing_zero=False + ) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by bangs and dots, and pretend that there is + # an implicit dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = Version(prospective.public) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) <= Version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) >= Version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + False + >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") + True + >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) + True + """ + + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version, this allows us to have a shortcut for + # "2.0" in Specifier(">=2") + normalized_item = _coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if normalized_item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + operator_callable: CallableOperator = self._get_operator(self.operator) + return operator_callable(normalized_item, self.version) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(Specifier().contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = _coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later in case nothing + # else matches this specifier. + if parsed_version.is_prerelease and not ( + prereleases or self.prereleases + ): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the beginning. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return ( + list(itertools.chain.from_iterable(left_split)), + list(itertools.chain.from_iterable(right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Make each individual specifier a Specifier and save in a frozen set + # for later. + self._specs = frozenset(map(Specifier, split_specifiers)) + else: + # Save the supplied specifiers in a frozen set. + self._specs = frozenset(specifiers) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease " + "overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + # Ensure that our item is a Version instance. + if not isinstance(item, Version): + item = Version(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + if installed and item.is_prerelease: + item = Version(item.base_version) + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all(s.contains(item, prereleases=prereleases) for s in self._specs) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + [] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iter(iterable) + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases. + else: + filtered: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + + for item in iterable: + parsed_version = _coerce_version(item) + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return iter(found_prereleases) + + return iter(filtered) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/tags.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..f5903402abb5a0aed37bb23914f678ef7e34a554 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/tags.py @@ -0,0 +1,617 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import logging +import platform +import re +import struct +import subprocess +import sys +import sysconfig +from importlib.machinery import EXTENSION_SUFFIXES +from typing import ( + Iterable, + Iterator, + Sequence, + Tuple, + cast, +) + +from . import _manylinux, _musllinux + +logger = logging.getLogger(__name__) + +PythonVersion = Sequence[int] +AppleVersion = Tuple[int, int] + +INTERPRETER_SHORT_NAMES: dict[str, str] = { + "python": "py", # Generic. + "cpython": "cp", + "pypy": "pp", + "ironpython": "ip", + "jython": "jy", +} + + +_32_BIT_INTERPRETER = struct.calcsize("P") == 4 + + +class Tag: + """ + A representation of the tag triple for a wheel. + + Instances are considered immutable and thus are hashable. Equality checking + is also supported. + """ + + __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] + + def __init__(self, interpreter: str, abi: str, platform: str) -> None: + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + # The __hash__ of every single element in a Set[Tag] will be evaluated each time + # that a set calls its `.disjoint()` method, which may be called hundreds of + # times when scanning a page of links for packages with tags matching that + # Set[Tag]. Pre-computing the value here produces significant speedups for + # downstream consumers. + self._hash = hash((self._interpreter, self._abi, self._platform)) + + @property + def interpreter(self) -> str: + return self._interpreter + + @property + def abi(self) -> str: + return self._abi + + @property + def platform(self) -> str: + return self._platform + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Tag): + return NotImplemented + + return ( + (self._hash == other._hash) # Short-circuit ASAP for perf reasons. + and (self._platform == other._platform) + and (self._abi == other._abi) + and (self._interpreter == other._interpreter) + ) + + def __hash__(self) -> int: + return self._hash + + def __str__(self) -> str: + return f"{self._interpreter}-{self._abi}-{self._platform}" + + def __repr__(self) -> str: + return f"<{self} @ {id(self)}>" + + +def parse_tag(tag: str) -> frozenset[Tag]: + """ + Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. + + Returning a set is required due to the possibility that the tag is a + compressed tag set. + """ + tags = set() + interpreters, abis, platforms = tag.split("-") + for interpreter in interpreters.split("."): + for abi in abis.split("."): + for platform_ in platforms.split("."): + tags.add(Tag(interpreter, abi, platform_)) + return frozenset(tags) + + +def _get_config_var(name: str, warn: bool = False) -> int | str | None: + value: int | str | None = sysconfig.get_config_var(name) + if value is None and warn: + logger.debug( + "Config variable '%s' is unset, Python ABI tag may be incorrect", name + ) + return value + + +def _normalize_string(string: str) -> str: + return string.replace(".", "_").replace("-", "_").replace(" ", "_") + + +def _is_threaded_cpython(abis: list[str]) -> bool: + """ + Determine if the ABI corresponds to a threaded (`--disable-gil`) build. + + The threaded builds are indicated by a "t" in the abiflags. + """ + if len(abis) == 0: + return False + # expect e.g., cp313 + m = re.match(r"cp\d+(.*)", abis[0]) + if not m: + return False + abiflags = m.group(1) + return "t" in abiflags + + +def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3. + + PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) + builds do not support abi3. + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading + + +def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: + py_version = tuple(py_version) # To allow for version comparison. + abis = [] + version = _version_nodot(py_version[:2]) + threading = debug = pymalloc = ucs4 = "" + with_debug = _get_config_var("Py_DEBUG", warn) + has_refcount = hasattr(sys, "gettotalrefcount") + # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled + # extension modules is the best option. + # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 + has_ext = "_d.pyd" in EXTENSION_SUFFIXES + if with_debug or (with_debug is None and (has_refcount or has_ext)): + debug = "d" + if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): + threading = "t" + if py_version < (3, 8): + with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) + if with_pymalloc or with_pymalloc is None: + pymalloc = "m" + if py_version < (3, 3): + unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) + if unicode_size == 4 or ( + unicode_size is None and sys.maxunicode == 0x10FFFF + ): + ucs4 = "u" + elif debug: + # Debug builds can also load "normal" extension modules. + # We can also assume no UCS-4 or pymalloc requirement. + abis.append(f"cp{version}{threading}") + abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") + return abis + + +def cpython_tags( + python_version: PythonVersion | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a CPython interpreter. + + The tags consist of: + - cp-- + - cp-abi3- + - cp-none- + - cp-abi3- # Older Python versions down to 3.2. + + If python_version only specifies a major version then user-provided ABIs and + the 'none' ABItag will be used. + + If 'abi3' or 'none' are specified in 'abis' then they will be yielded at + their normal position and not at the beginning. + """ + if not python_version: + python_version = sys.version_info[:2] + + interpreter = f"cp{_version_nodot(python_version[:2])}" + + if abis is None: + if len(python_version) > 1: + abis = _cpython_abis(python_version, warn) + else: + abis = [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: + pass + + platforms = list(platforms or platform_tags()) + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + threading = _is_threaded_cpython(abis) + use_abi3 = _abi3_applies(python_version, threading) + if use_abi3: + yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) + yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) + + if use_abi3: + for minor_version in range(python_version[1] - 1, 1, -1): + for platform_ in platforms: + version = _version_nodot((python_version[0], minor_version)) + interpreter = f"cp{version}" + yield Tag(interpreter, "abi3", platform_) + + +def _generic_abi() -> list[str]: + """ + Return the ABI tag based on EXT_SUFFIX. + """ + # The following are examples of `EXT_SUFFIX`. + # We want to keep the parts which are related to the ABI and remove the + # parts which are related to the platform: + # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 + # - mac: '.cpython-310-darwin.so' => cp310 + # - win: '.cp310-win_amd64.pyd' => cp310 + # - win: '.pyd' => cp37 (uses _cpython_abis()) + # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 + # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' + # => graalpy_38_native + + ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) + if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": + raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") + parts = ext_suffix.split(".") + if len(parts) < 3: + # CPython3.7 and earlier uses ".pyd" on Windows. + return _cpython_abis(sys.version_info[:2]) + soabi = parts[1] + if soabi.startswith("cpython"): + # non-windows + abi = "cp" + soabi.split("-")[1] + elif soabi.startswith("cp"): + # windows + abi = soabi.split("-")[0] + elif soabi.startswith("pypy"): + abi = "-".join(soabi.split("-")[:2]) + elif soabi.startswith("graalpy"): + abi = "-".join(soabi.split("-")[:3]) + elif soabi: + # pyston, ironpython, others? + abi = soabi + else: + return [] + return [_normalize_string(abi)] + + +def generic_tags( + interpreter: str | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a generic interpreter. + + The tags consist of: + - -- + + The "none" ABI will be added if it was not explicitly provided. + """ + if not interpreter: + interp_name = interpreter_name() + interp_version = interpreter_version(warn=warn) + interpreter = "".join([interp_name, interp_version]) + if abis is None: + abis = _generic_abi() + else: + abis = list(abis) + platforms = list(platforms or platform_tags()) + if "none" not in abis: + abis.append("none") + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + +def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: + """ + Yields Python versions in descending order. + + After the latest version, the major-only version will be yielded, and then + all previous versions of that major version. + """ + if len(py_version) > 1: + yield f"py{_version_nodot(py_version[:2])}" + yield f"py{py_version[0]}" + if len(py_version) > 1: + for minor in range(py_version[1] - 1, -1, -1): + yield f"py{_version_nodot((py_version[0], minor))}" + + +def compatible_tags( + python_version: PythonVersion | None = None, + interpreter: str | None = None, + platforms: Iterable[str] | None = None, +) -> Iterator[Tag]: + """ + Yields the sequence of tags that are compatible with a specific version of Python. + + The tags consist of: + - py*-none- + - -none-any # ... if `interpreter` is provided. + - py*-none-any + """ + if not python_version: + python_version = sys.version_info[:2] + platforms = list(platforms or platform_tags()) + for version in _py_interpreter_range(python_version): + for platform_ in platforms: + yield Tag(version, "none", platform_) + if interpreter: + yield Tag(interpreter, "none", "any") + for version in _py_interpreter_range(python_version): + yield Tag(version, "none", "any") + + +def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: + if not is_32bit: + return arch + + if arch.startswith("ppc"): + return "ppc" + + return "i386" + + +def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: + formats = [cpu_arch] + if cpu_arch == "x86_64": + if version < (10, 4): + return [] + formats.extend(["intel", "fat64", "fat32"]) + + elif cpu_arch == "i386": + if version < (10, 4): + return [] + formats.extend(["intel", "fat32", "fat"]) + + elif cpu_arch == "ppc64": + # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? + if version > (10, 5) or version < (10, 4): + return [] + formats.append("fat64") + + elif cpu_arch == "ppc": + if version > (10, 6): + return [] + formats.extend(["fat32", "fat"]) + + if cpu_arch in {"arm64", "x86_64"}: + formats.append("universal2") + + if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: + formats.append("universal") + + return formats + + +def mac_platforms( + version: AppleVersion | None = None, arch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for a macOS system. + + The `version` parameter is a two-item tuple specifying the macOS version to + generate platform tags for. The `arch` parameter is the CPU architecture to + generate platform tags for. Both parameters default to the appropriate value + for the current system. + """ + version_str, _, cpu_arch = platform.mac_ver() + if version is None: + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + if version == (10, 16): + # When built against an older macOS SDK, Python will report macOS 10.16 + # instead of the real version. + version_str = subprocess.run( + [ + sys.executable, + "-sS", + "-c", + "import platform; print(platform.mac_ver()[0])", + ], + check=True, + env={"SYSTEM_VERSION_COMPAT": "0"}, + stdout=subprocess.PIPE, + text=True, + ).stdout + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + else: + version = version + if arch is None: + arch = _mac_arch(cpu_arch) + else: + arch = arch + + if (10, 0) <= version and version < (11, 0): + # Prior to Mac OS 11, each yearly release of Mac OS bumped the + # "minor" version number. The major version was always 10. + major_version = 10 + for minor_version in range(version[1], -1, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Starting with Mac OS 11, each yearly release bumps the major version + # number. The minor versions are now the midyear updates. + minor_version = 0 + for major_version in range(version[0], 10, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Mac OS 11 on x86_64 is compatible with binaries from previous releases. + # Arm64 support was introduced in 11.0, so no Arm binaries from previous + # releases exist. + # + # However, the "universal2" binary format can have a + # macOS version earlier than 11.0 when the x86_64 part of the binary supports + # that version of macOS. + major_version = 10 + if arch == "x86_64": + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + else: + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_format = "universal2" + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + +def ios_platforms( + version: AppleVersion | None = None, multiarch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for an iOS system. + + :param version: A two-item tuple specifying the iOS version to generate + platform tags for. Defaults to the current iOS version. + :param multiarch: The CPU architecture+ABI to generate platform tags for - + (the value used by `sys.implementation._multiarch` e.g., + `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current + multiarch value. + """ + if version is None: + # if iOS is the current platform, ios_ver *must* be defined. However, + # it won't exist for CPython versions before 3.13, which causes a mypy + # error. + _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] + version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) + + if multiarch is None: + multiarch = sys.implementation._multiarch + multiarch = multiarch.replace("-", "_") + + ios_platform_template = "ios_{major}_{minor}_{multiarch}" + + # Consider any iOS major.minor version from the version requested, down to + # 12.0. 12.0 is the first iOS version that is known to have enough features + # to support CPython. Consider every possible minor release up to X.9. There + # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra + # candidates that won't ever match doesn't really hurt, and it saves us from + # having to keep an explicit list of known iOS versions in the code. Return + # the results descending order of version number. + + # If the requested major version is less than 12, there won't be any matches. + if version[0] < 12: + return + + # Consider the actual X.Y version that was requested. + yield ios_platform_template.format( + major=version[0], minor=version[1], multiarch=multiarch + ) + + # Consider every minor version from X.0 to the minor version prior to the + # version requested by the platform. + for minor in range(version[1] - 1, -1, -1): + yield ios_platform_template.format( + major=version[0], minor=minor, multiarch=multiarch + ) + + for major in range(version[0] - 1, 11, -1): + for minor in range(9, -1, -1): + yield ios_platform_template.format( + major=major, minor=minor, multiarch=multiarch + ) + + +def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: + linux = _normalize_string(sysconfig.get_platform()) + if not linux.startswith("linux_"): + # we should never be here, just yield the sysconfig one and return + yield linux + return + if is_32bit: + if linux == "linux_x86_64": + linux = "linux_i686" + elif linux == "linux_aarch64": + linux = "linux_armv8l" + _, arch = linux.split("_", 1) + archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) + yield from _manylinux.platform_tags(archs) + yield from _musllinux.platform_tags(archs) + for arch in archs: + yield f"linux_{arch}" + + +def _generic_platforms() -> Iterator[str]: + yield _normalize_string(sysconfig.get_platform()) + + +def platform_tags() -> Iterator[str]: + """ + Provides the platform tags for this installation. + """ + if platform.system() == "Darwin": + return mac_platforms() + elif platform.system() == "iOS": + return ios_platforms() + elif platform.system() == "Linux": + return _linux_platforms() + else: + return _generic_platforms() + + +def interpreter_name() -> str: + """ + Returns the name of the running interpreter. + + Some implementations have a reserved, two-letter abbreviation which will + be returned when appropriate. + """ + name = sys.implementation.name + return INTERPRETER_SHORT_NAMES.get(name) or name + + +def interpreter_version(*, warn: bool = False) -> str: + """ + Returns the version of the running interpreter. + """ + version = _get_config_var("py_version_nodot", warn=warn) + if version: + version = str(version) + else: + version = _version_nodot(sys.version_info[:2]) + return version + + +def _version_nodot(version: PythonVersion) -> str: + return "".join(map(str, version)) + + +def sys_tags(*, warn: bool = False) -> Iterator[Tag]: + """ + Returns the sequence of tag triples for the running interpreter. + + The order of the sequence corresponds to priority order for the + interpreter, from most to least important. + """ + + interp_name = interpreter_name() + if interp_name == "cp": + yield from cpython_tags(warn=warn) + else: + yield from generic_tags() + + if interp_name == "pp": + interp = "pp3" + elif interp_name == "cp": + interp = "cp" + interpreter_version(warn=warn) + else: + interp = None + yield from compatible_tags(interpreter=interp) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/utils.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23450953df74eccd9c13cd2a955ce09d1f968565 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/utils.py @@ -0,0 +1,163 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import functools +import re +from typing import NewType, Tuple, Union, cast + +from .tags import Tag, parse_tag +from .version import InvalidVersion, Version, _TrimmedRelease + +BuildTag = Union[Tuple[()], Tuple[int, str]] +NormalizedName = NewType("NormalizedName", str) + + +class InvalidName(ValueError): + """ + An invalid distribution name; users should refer to the packaging user guide. + """ + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +# Core metadata spec for `Name` +_validate_regex = re.compile( + r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE +) +_canonicalize_regex = re.compile(r"[-_.]+") +_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$") +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)") + + +def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: + if validate and not _validate_regex.match(name): + raise InvalidName(f"name is invalid: {name!r}") + # This is taken from PEP 503. + value = _canonicalize_regex.sub("-", name).lower() + return cast(NormalizedName, value) + + +def is_normalized_name(name: str) -> bool: + return _normalized_regex.match(name) is not None + + +@functools.singledispatch +def canonicalize_version( + version: Version | str, *, strip_trailing_zero: bool = True +) -> str: + """ + Return a canonical form of a version as a string. + + >>> canonicalize_version('1.0.1') + '1.0.1' + + Per PEP 625, versions may have multiple canonical forms, differing + only by trailing zeros. + + >>> canonicalize_version('1.0.0') + '1' + >>> canonicalize_version('1.0.0', strip_trailing_zero=False) + '1.0.0' + + Invalid versions are returned unaltered. + + >>> canonicalize_version('foo bar baz') + 'foo bar baz' + """ + return str(_TrimmedRelease(str(version)) if strip_trailing_zero else version) + + +@canonicalize_version.register +def _(version: str, *, strip_trailing_zero: bool = True) -> str: + try: + parsed = Version(version) + except InvalidVersion: + # Legacy versions cannot be normalized + return version + return canonicalize_version(parsed, strip_trailing_zero=strip_trailing_zero) + + +def parse_wheel_filename( + filename: str, +) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename!r}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename!r}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name. + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename!r}") + name = canonicalize_name(name_part) + + try: + version = Version(parts[1]) + except InvalidVersion as e: + raise InvalidWheelFilename( + f"Invalid wheel filename (invalid version): {filename!r}" + ) from e + + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in {filename!r}" + ) + build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tags = parse_tag(parts[-1]) + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename!r}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") + + name = canonicalize_name(name_part) + + try: + version = Version(version_part) + except InvalidVersion as e: + raise InvalidSdistFilename( + f"Invalid sdist filename (invalid version): {filename!r}" + ) from e + + return (name, version) diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/version.py b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbda20e463b8d9389ecd65f74af33810a02bdd --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/_vendor/packaging/version.py @@ -0,0 +1,582 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +from __future__ import annotations + +import itertools +import re +from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: tuple[int, ...] + dev: tuple[str, int] | None + pre: tuple[str, int] | None + post: tuple[str, int] | None + local: LocalType | None + + +def parse(version: str) -> Version: + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# 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
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?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
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+
+        # 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) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> tuple[str, int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        rel = super().release
+        nonzeros = (index for index, val in enumerate(rel) if val)
+        last_nonzero = max(nonzeros, default=0)
+        return rel[: last_nonzero + 1]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a 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)
+
+    assert not letter
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    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_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    # 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 not a 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: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric 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 (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ab51ef36add104ccb48652a207a3667ba9b582c7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/METADATA
@@ -0,0 +1,319 @@
+Metadata-Version: 2.3
+Name: platformdirs
+Version: 4.2.2
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Documentation, https://platformdirs.readthedocs.io
+Project-URL: Homepage, https://github.com/platformdirs/platformdirs
+Project-URL: Source, https://github.com/platformdirs/platformdirs
+Project-URL: Tracker, https://github.com/platformdirs/platformdirs/issues
+Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt 
+License-Expression: MIT
+License-File: LICENSE
+Keywords: appdirs,application,cache,directory,log,user
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.8
+Provides-Extra: docs
+Requires-Dist: furo>=2023.9.10; extra == 'docs'
+Requires-Dist: proselint>=0.13; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints>=1.25.2; extra == 'docs'
+Requires-Dist: sphinx>=7.2.6; extra == 'docs'
+Provides-Extra: test
+Requires-Dist: appdirs==1.4.4; extra == 'test'
+Requires-Dist: covdefaults>=2.3; extra == 'test'
+Requires-Dist: pytest-cov>=4.1; extra == 'test'
+Requires-Dist: pytest-mock>=3.12; extra == 'test'
+Requires-Dist: pytest>=7.4.3; extra == 'test'
+Provides-Extra: type
+Requires-Dist: mypy>=1.8; extra == 'type'
+Description-Content-Type: text/x-rst
+
+The problem
+===========
+
+.. image:: https://github.com/platformdirs/platformdirs/actions/workflows/check.yml/badge.svg
+   :target: https://github.com/platformdirs/platformdirs/actions
+
+When writing desktop application, finding the right location to store user data
+and configuration varies per platform. Even for single-platform apps, there
+may by plenty of nuances in figuring out the right location.
+
+For example, if running on macOS, you should use::
+
+    ~/Library/Application Support/
+
+If on Windows (at least English Win) that should be::
+
+    C:\Documents and Settings\\Application Data\Local Settings\\
+
+or possibly::
+
+    C:\Documents and Settings\\Application Data\\
+
+for `roaming profiles `_ but that is another story.
+
+On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be::
+
+    ~/.local/share/
+
+.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+
+``platformdirs`` to the rescue
+==============================
+
+This kind of thing is what the ``platformdirs`` package is for.
+``platformdirs`` will help you choose an appropriate:
+
+- user data dir (``user_data_dir``)
+- user config dir (``user_config_dir``)
+- user cache dir (``user_cache_dir``)
+- site data dir (``site_data_dir``)
+- site config dir (``site_config_dir``)
+- user log dir (``user_log_dir``)
+- user documents dir (``user_documents_dir``)
+- user downloads dir (``user_downloads_dir``)
+- user pictures dir (``user_pictures_dir``)
+- user videos dir (``user_videos_dir``)
+- user music dir (``user_music_dir``)
+- user desktop dir (``user_desktop_dir``)
+- user runtime dir (``user_runtime_dir``)
+
+And also:
+
+- Is slightly opinionated on the directory names used. Look for "OPINION" in
+  documentation and code for when an opinion is being applied.
+
+Example output
+==============
+
+On macOS:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> user_documents_dir()
+    '/Users/trentm/Documents'
+    >>> user_downloads_dir()
+    '/Users/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/Users/trentm/Pictures'
+    >>> user_videos_dir()
+    '/Users/trentm/Movies'
+    >>> user_music_dir()
+    '/Users/trentm/Music'
+    >>> user_desktop_dir()
+    '/Users/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+On Windows:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
+    >>> user_data_dir(appname, appauthor, roaming=True)
+    'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
+    >>> user_log_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
+    >>> user_documents_dir()
+    'C:\\Users\\trentm\\Documents'
+    >>> user_downloads_dir()
+    'C:\\Users\\trentm\\Downloads'
+    >>> user_pictures_dir()
+    'C:\\Users\\trentm\\Pictures'
+    >>> user_videos_dir()
+    'C:\\Users\\trentm\\Videos'
+    >>> user_music_dir()
+    'C:\\Users\\trentm\\Music'
+    >>> user_desktop_dir()
+    'C:\\Users\\trentm\\Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'
+
+On Linux:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/home/trentm/.local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/usr/local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor, multipath=True)
+    '/usr/local/share/SuperApp:/usr/share/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/home/trentm/.cache/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/home/trentm/.local/state/SuperApp/log'
+    >>> user_config_dir(appname)
+    '/home/trentm/.config/SuperApp'
+    >>> user_documents_dir()
+    '/home/trentm/Documents'
+    >>> user_downloads_dir()
+    '/home/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/home/trentm/Pictures'
+    >>> user_videos_dir()
+    '/home/trentm/Videos'
+    >>> user_music_dir()
+    '/home/trentm/Music'
+    >>> user_desktop_dir()
+    '/home/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/run/user/{os.getuid()}/SuperApp'
+    >>> site_config_dir(appname)
+    '/etc/xdg/SuperApp'
+    >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
+    >>> site_config_dir(appname, multipath=True)
+    '/etc/SuperApp:/usr/local/etc/SuperApp'
+
+On Android::
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/log'
+    >>> user_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_documents_dir()
+    '/storage/emulated/0/Documents'
+    >>> user_downloads_dir()
+    '/storage/emulated/0/Downloads'
+    >>> user_pictures_dir()
+    '/storage/emulated/0/Pictures'
+    >>> user_videos_dir()
+    '/storage/emulated/0/DCIM/Camera'
+    >>> user_music_dir()
+    '/storage/emulated/0/Music'
+    >>> user_desktop_dir()
+    '/storage/emulated/0/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/tmp'
+
+Note: Some android apps like Termux and Pydroid are used as shells. These
+apps are used by the end user to emulate Linux environment. Presence of
+``SHELL`` environment variable is used by Platformdirs to differentiate
+between general android apps and android apps used as shells. Shell android
+apps also support ``XDG_*`` environment variables.
+
+
+``PlatformDirs`` for convenience
+================================
+
+.. code-block:: pycon
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+Per-version isolation
+=====================
+
+If you have multiple versions of your app in use that you want to be
+able to run side-by-side, then you may want version-isolation for these
+dirs::
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp/1.0'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp/1.0'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'
+
+Be wary of using this for configuration files though; you'll need to handle
+migrating configuration files manually.
+
+Why this Fork?
+==============
+
+This repository is a friendly fork of the wonderful work started by
+`ActiveState `_ who created
+``appdirs``, this package's ancestor.
+
+Maintaining an open source project is no easy task, particularly
+from within an organization, and the Python community is indebted
+to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for
+creating an incredibly useful simple module, as evidenced by the wide
+number of users it has attracted over the years.
+
+Nonetheless, given the number of long-standing open issues
+and pull requests, and no clear path towards `ensuring
+that maintenance of the package would continue or grow
+`_, this fork was
+created.
+
+Contributions are most welcome.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..64c0c8ea2eeca2768ee87d653fa3539517b0d6bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/RECORD
@@ -0,0 +1,23 @@
+platformdirs-4.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+platformdirs-4.2.2.dist-info/METADATA,sha256=zmsie01G1MtXR0wgIv5XpVeTO7idr0WWvfmxKsKWuGk,11429
+platformdirs-4.2.2.dist-info/RECORD,,
+platformdirs-4.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.2.2.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
+platformdirs-4.2.2.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=EMGE8qeHRR9CzDFr8kL3tA8hdZZniYjXBVZd0UGTWK0,22225
+platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
+platformdirs/__pycache__/__init__.cpython-312.pyc,,
+platformdirs/__pycache__/__main__.cpython-312.pyc,,
+platformdirs/__pycache__/android.cpython-312.pyc,,
+platformdirs/__pycache__/api.cpython-312.pyc,,
+platformdirs/__pycache__/macos.cpython-312.pyc,,
+platformdirs/__pycache__/unix.cpython-312.pyc,,
+platformdirs/__pycache__/version.cpython-312.pyc,,
+platformdirs/__pycache__/windows.cpython-312.pyc,,
+platformdirs/android.py,sha256=xZXY9Jd46WOsxT2U6-5HsNtDZ-IQqxcEUrBLl3hYk4o,9016
+platformdirs/api.py,sha256=QBYdUac2eC521ek_y53uD1Dcq-lJX8IgSRVd4InC6uc,8996
+platformdirs/macos.py,sha256=wftsbsvq6nZ0WORXSiCrZNkRHz_WKuktl0a6mC7MFkI,5580
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=Cci9Wqt35dAMsg6HT9nRGHSBW5obb0pR3AE1JJnsCXg,10643
+platformdirs/version.py,sha256=r7F76tZRjgQKzrpx_I0_ZMQOMU-PS7eGnHD7zEK3KB0,411
+platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..516596c76787b10928cbab24f22c0ea00433b15d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.24.2
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f35fed9191b1142ddaada8a96de4a9461c5d796c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs-4.2.2.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2010-202x The platformdirs developers
+
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f7d9490d12b7224fc5d5348823619f262a0aae5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__init__.py
@@ -0,0 +1,627 @@
+"""
+Utilities for determining application-specific dirs.
+
+See  for details and usage.
+
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+from .version import __version__
+from .version import __version_tuple__ as __version_info__
+
+if TYPE_CHECKING:
+    from pathlib import Path
+    from typing import Literal
+
+
+def _set_platform_dir_class() -> type[PlatformDirsABC]:
+    if sys.platform == "win32":
+        from platformdirs.windows import Windows as Result  # noqa: PLC0415
+    elif sys.platform == "darwin":
+        from platformdirs.macos import MacOS as Result  # noqa: PLC0415
+    else:
+        from platformdirs.unix import Unix as Result  # noqa: PLC0415
+
+    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
+        if os.getenv("SHELL") or os.getenv("PREFIX"):
+            return Result
+
+        from platformdirs.android import _android_folder  # noqa: PLC0415
+
+        if _android_folder() is not None:
+            from platformdirs.android import Android  # noqa: PLC0415
+
+            return Android  # return to avoid redefinition of a result
+
+    return Result
+
+
+PlatformDirs = _set_platform_dir_class()  #: Currently active platform
+AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
+
+
+def user_data_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_dir
+
+
+def site_data_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_dir
+
+
+def user_config_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_dir
+
+
+def site_config_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config directory shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_dir
+
+
+def user_cache_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_dir
+
+
+def site_cache_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_dir
+
+
+def user_state_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_dir
+
+
+def user_log_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_dir
+
+
+def user_documents_dir() -> str:
+    """:returns: documents directory tied to the user"""
+    return PlatformDirs().user_documents_dir
+
+
+def user_downloads_dir() -> str:
+    """:returns: downloads directory tied to the user"""
+    return PlatformDirs().user_downloads_dir
+
+
+def user_pictures_dir() -> str:
+    """:returns: pictures directory tied to the user"""
+    return PlatformDirs().user_pictures_dir
+
+
+def user_videos_dir() -> str:
+    """:returns: videos directory tied to the user"""
+    return PlatformDirs().user_videos_dir
+
+
+def user_music_dir() -> str:
+    """:returns: music directory tied to the user"""
+    return PlatformDirs().user_music_dir
+
+
+def user_desktop_dir() -> str:
+    """:returns: desktop directory tied to the user"""
+    return PlatformDirs().user_desktop_dir
+
+
+def user_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_dir
+
+
+def site_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime directory shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_dir
+
+
+def user_data_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_data_path
+
+
+def site_data_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: data path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_path
+
+
+def user_config_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_config_path
+
+
+def site_config_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: config path shared by the users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_path
+
+
+def site_cache_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache directory tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_path
+
+
+def user_cache_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: cache path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_cache_path
+
+
+def user_state_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: state path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+    ).user_state_path
+
+
+def user_log_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: log path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_log_path
+
+
+def user_documents_path() -> Path:
+    """:returns: documents a path tied to the user"""
+    return PlatformDirs().user_documents_path
+
+
+def user_downloads_path() -> Path:
+    """:returns: downloads path tied to the user"""
+    return PlatformDirs().user_downloads_path
+
+
+def user_pictures_path() -> Path:
+    """:returns: pictures path tied to the user"""
+    return PlatformDirs().user_pictures_path
+
+
+def user_videos_path() -> Path:
+    """:returns: videos path tied to the user"""
+    return PlatformDirs().user_videos_path
+
+
+def user_music_path() -> Path:
+    """:returns: music path tied to the user"""
+    return PlatformDirs().user_music_path
+
+
+def user_desktop_path() -> Path:
+    """:returns: desktop path tied to the user"""
+    return PlatformDirs().user_desktop_path
+
+
+def user_runtime_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path tied to the user
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).user_runtime_path
+
+
+def site_runtime_path(
+    appname: str | None = None,
+    appauthor: str | None | Literal[False] = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """
+    :param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :returns: runtime path shared by users
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_path
+
+
+__all__ = [
+    "AppDirs",
+    "PlatformDirs",
+    "PlatformDirsABC",
+    "__version__",
+    "__version_info__",
+    "site_cache_dir",
+    "site_cache_path",
+    "site_config_dir",
+    "site_config_path",
+    "site_data_dir",
+    "site_data_path",
+    "site_runtime_dir",
+    "site_runtime_path",
+    "user_cache_dir",
+    "user_cache_path",
+    "user_config_dir",
+    "user_config_path",
+    "user_data_dir",
+    "user_data_path",
+    "user_desktop_dir",
+    "user_desktop_path",
+    "user_documents_dir",
+    "user_documents_path",
+    "user_downloads_dir",
+    "user_downloads_path",
+    "user_log_dir",
+    "user_log_path",
+    "user_music_dir",
+    "user_music_path",
+    "user_pictures_dir",
+    "user_pictures_path",
+    "user_runtime_dir",
+    "user_runtime_path",
+    "user_state_dir",
+    "user_state_path",
+    "user_videos_dir",
+    "user_videos_path",
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__main__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..922c521358e349470ec48d6372b8f8ee8641128a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/__main__.py
@@ -0,0 +1,55 @@
+"""Main entry point."""
+
+from __future__ import annotations
+
+from platformdirs import PlatformDirs, __version__
+
+PROPS = (
+    "user_data_dir",
+    "user_config_dir",
+    "user_cache_dir",
+    "user_state_dir",
+    "user_log_dir",
+    "user_documents_dir",
+    "user_downloads_dir",
+    "user_pictures_dir",
+    "user_videos_dir",
+    "user_music_dir",
+    "user_runtime_dir",
+    "site_data_dir",
+    "site_config_dir",
+    "site_cache_dir",
+    "site_runtime_dir",
+)
+
+
+def main() -> None:
+    """Run the main entry point."""
+    app_name = "MyApp"
+    app_author = "MyCompany"
+
+    print(f"-- platformdirs {__version__} --")  # noqa: T201
+
+    print("-- app dirs (with optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author, version="1.0")
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (with disabled 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name, appauthor=False)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+
+if __name__ == "__main__":
+    main()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/android.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/android.py
new file mode 100644
index 0000000000000000000000000000000000000000..afd3141c725873847bdecf88222c73ff7d5afc39
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/android.py
@@ -0,0 +1,249 @@
+"""Android."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING, cast
+
+from .api import PlatformDirsABC
+
+
+class Android(PlatformDirsABC):
+    """
+    Follows the guidance `from here `_.
+
+    Makes use of the `appname `, `version
+    `, `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``/data/user///files/``"""
+        return self._append_app_name_and_version(cast(str, _android_folder()), "files")
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. \
+        ``/data/user///shared_prefs/``
+        """
+        return self._append_app_name_and_version(cast(str, _android_folder()), "shared_prefs")
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `user_config_dir`"""
+        return self.user_config_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g.,``/data/user///cache/``"""
+        return self._append_app_name_and_version(cast(str, _android_folder()), "cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, same as `user_cache_dir`"""
+        return self.user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """
+        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,
+          e.g. ``/data/user///cache//log``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``"""
+        return _android_documents_folder()
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``"""
+        return _android_downloads_folder()
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``"""
+        return _android_pictures_folder()
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``"""
+        return _android_videos_folder()
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``/storage/emulated/0/Music``"""
+        return _android_music_folder()
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``"""
+        return "/storage/emulated/0/Desktop"
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,
+          e.g. ``/data/user///cache//tmp``
+        """
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "tmp")  # noqa: PTH118
+        return path
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+@lru_cache(maxsize=1)
+def _android_folder() -> str | None:  # noqa: C901, PLR0912
+    """:return: base folder for the Android OS or None if it cannot be found"""
+    result: str | None = None
+    # type checker isn't happy with our "import android", just don't do this when type checking see
+    # https://stackoverflow.com/a/61394121
+    if not TYPE_CHECKING:
+        try:
+            # First try to get a path to android app using python4android (if available)...
+            from android import mActivity  # noqa: PLC0415
+
+            context = cast("android.content.Context", mActivity.getApplicationContext())  # noqa: F821
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        try:
+            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful
+            # result...
+            from jnius import autoclass  # noqa: PLC0415
+
+            context = autoclass("android.content.Context")
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        # and if that fails, too, find an android folder looking at path on the sys.path
+        # warning: only works for apps installed under /data, not adopted storage etc.
+        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    if result is None:
+        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into
+        # account
+        pattern = re.compile(r"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    return result
+
+
+@lru_cache(maxsize=1)
+def _android_documents_folder() -> str:
+    """:return: documents folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        documents_dir = "/storage/emulated/0/Documents"
+
+    return documents_dir
+
+
+@lru_cache(maxsize=1)
+def _android_downloads_folder() -> str:
+    """:return: downloads folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        downloads_dir = "/storage/emulated/0/Downloads"
+
+    return downloads_dir
+
+
+@lru_cache(maxsize=1)
+def _android_pictures_folder() -> str:
+    """:return: pictures folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        pictures_dir = "/storage/emulated/0/Pictures"
+
+    return pictures_dir
+
+
+@lru_cache(maxsize=1)
+def _android_videos_folder() -> str:
+    """:return: videos folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        videos_dir = "/storage/emulated/0/DCIM/Camera"
+
+    return videos_dir
+
+
+@lru_cache(maxsize=1)
+def _android_music_folder() -> str:
+    """:return: music folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        music_dir = "/storage/emulated/0/Music"
+
+    return music_dir
+
+
+__all__ = [
+    "Android",
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/api.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..c50caa648a6d18f5b515404ac5a4d0e41a072739
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/api.py
@@ -0,0 +1,292 @@
+"""Base API."""
+
+from __future__ import annotations
+
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Iterator, Literal
+
+
+class PlatformDirsABC(ABC):  # noqa: PLR0904
+    """Abstract base class for platform directories."""
+
+    def __init__(  # noqa: PLR0913, PLR0917
+        self,
+        appname: str | None = None,
+        appauthor: str | None | Literal[False] = None,
+        version: str | None = None,
+        roaming: bool = False,  # noqa: FBT001, FBT002
+        multipath: bool = False,  # noqa: FBT001, FBT002
+        opinion: bool = True,  # noqa: FBT001, FBT002
+        ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    ) -> None:
+        """
+        Create a new platform directory.
+
+        :param appname: See `appname`.
+        :param appauthor: See `appauthor`.
+        :param version: See `version`.
+        :param roaming: See `roaming`.
+        :param multipath: See `multipath`.
+        :param opinion: See `opinion`.
+        :param ensure_exists: See `ensure_exists`.
+
+        """
+        self.appname = appname  #: The name of application.
+        self.appauthor = appauthor
+        """
+        The name of the app author or distributing body for this application.
+
+        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.
+
+        """
+        self.version = version
+        """
+        An optional version path element to append to the path.
+
+        You might want to use this if you want multiple versions of your app to be able to run independently. If used,
+        this would typically be ``.``.
+
+        """
+        self.roaming = roaming
+        """
+        Whether to use the roaming appdata directory on Windows.
+
+        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on
+        login (see
+        `here `_).
+
+        """
+        self.multipath = multipath
+        """
+        An optional parameter which indicates that the entire list of data dirs should be returned.
+
+        By default, the first item would only be returned.
+
+        """
+        self.opinion = opinion  #: A flag to indicating to use opinionated values.
+        self.ensure_exists = ensure_exists
+        """
+        Optionally create the directory (and any missing parents) upon access if it does not exist.
+
+        By default, no directories are created.
+
+        """
+
+    def _append_app_name_and_version(self, *base: str) -> str:
+        params = list(base[1:])
+        if self.appname:
+            params.append(self.appname)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(base[0], *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    def _optionally_create_directory(self, path: str) -> None:
+        if self.ensure_exists:
+            Path(path).mkdir(parents=True, exist_ok=True)
+
+    @property
+    @abstractmethod
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users"""
+
+    @property
+    @abstractmethod
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users"""
+
+    @property
+    def user_data_path(self) -> Path:
+        """:return: data path tied to the user"""
+        return Path(self.user_data_dir)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users"""
+        return Path(self.site_data_dir)
+
+    @property
+    def user_config_path(self) -> Path:
+        """:return: config path tied to the user"""
+        return Path(self.user_config_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users"""
+        return Path(self.site_config_dir)
+
+    @property
+    def user_cache_path(self) -> Path:
+        """:return: cache path tied to the user"""
+        return Path(self.user_cache_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users"""
+        return Path(self.site_cache_dir)
+
+    @property
+    def user_state_path(self) -> Path:
+        """:return: state path tied to the user"""
+        return Path(self.user_state_dir)
+
+    @property
+    def user_log_path(self) -> Path:
+        """:return: log path tied to the user"""
+        return Path(self.user_log_dir)
+
+    @property
+    def user_documents_path(self) -> Path:
+        """:return: documents a path tied to the user"""
+        return Path(self.user_documents_dir)
+
+    @property
+    def user_downloads_path(self) -> Path:
+        """:return: downloads path tied to the user"""
+        return Path(self.user_downloads_dir)
+
+    @property
+    def user_pictures_path(self) -> Path:
+        """:return: pictures path tied to the user"""
+        return Path(self.user_pictures_dir)
+
+    @property
+    def user_videos_path(self) -> Path:
+        """:return: videos path tied to the user"""
+        return Path(self.user_videos_dir)
+
+    @property
+    def user_music_path(self) -> Path:
+        """:return: music path tied to the user"""
+        return Path(self.user_music_dir)
+
+    @property
+    def user_desktop_path(self) -> Path:
+        """:return: desktop path tied to the user"""
+        return Path(self.user_desktop_dir)
+
+    @property
+    def user_runtime_path(self) -> Path:
+        """:return: runtime path tied to the user"""
+        return Path(self.user_runtime_dir)
+
+    @property
+    def site_runtime_path(self) -> Path:
+        """:return: runtime path shared by users"""
+        return Path(self.site_runtime_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield self.site_config_dir
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield self.site_data_dir
+
+    def iter_cache_dirs(self) -> Iterator[str]:
+        """:yield: all user and site cache directories."""
+        yield self.user_cache_dir
+        yield self.site_cache_dir
+
+    def iter_runtime_dirs(self) -> Iterator[str]:
+        """:yield: all user and site runtime directories."""
+        yield self.user_runtime_dir
+        yield self.site_runtime_dir
+
+    def iter_config_paths(self) -> Iterator[Path]:
+        """:yield: all user and site configuration paths."""
+        for path in self.iter_config_dirs():
+            yield Path(path)
+
+    def iter_data_paths(self) -> Iterator[Path]:
+        """:yield: all user and site data paths."""
+        for path in self.iter_data_dirs():
+            yield Path(path)
+
+    def iter_cache_paths(self) -> Iterator[Path]:
+        """:yield: all user and site cache paths."""
+        for path in self.iter_cache_dirs():
+            yield Path(path)
+
+    def iter_runtime_paths(self) -> Iterator[Path]:
+        """:yield: all user and site runtime paths."""
+        for path in self.iter_runtime_dirs():
+            yield Path(path)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/macos.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/macos.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb1ba5df1dacfb4cbedc66e0ddd81a4057d4ebbe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/macos.py
@@ -0,0 +1,130 @@
+"""macOS."""
+
+from __future__ import annotations
+
+import os.path
+import sys
+
+from .api import PlatformDirsABC
+
+
+class MacOS(PlatformDirsABC):
+    """
+    Platform directories for the macOS operating system.
+
+    Follows the guidance from
+    `Apple documentation `_.
+    Makes use of the `appname `,
+    `version `,
+    `ensure_exists `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support"))  # noqa: PTH111
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``/opt/homebrew/share/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``/opt/homebrew/share/$appname/$version:/Library/Application Support/$appname/$version``
+        """
+        is_homebrew = sys.prefix.startswith("/opt/homebrew")
+        path_list = [self._append_app_name_and_version("/opt/homebrew/share")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Application Support"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))  # noqa: PTH111
+
+    @property
+    def site_cache_dir(self) -> str:
+        """
+        :return: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``.
+          If we're using a Python binary managed by `Homebrew `_, the directory
+          will be under the Homebrew prefix, e.g. ``/opt/homebrew/var/cache/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``/opt/homebrew/var/cache/$appname/$version:/Library/Caches/$appname/$version``
+        """
+        is_homebrew = sys.prefix.startswith("/opt/homebrew")
+        path_list = [self._append_app_name_and_version("/opt/homebrew/var/cache")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Caches"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))  # noqa: PTH111
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return os.path.expanduser("~/Documents")  # noqa: PTH111
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return os.path.expanduser("~/Downloads")  # noqa: PTH111
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return os.path.expanduser("~/Pictures")  # noqa: PTH111
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Movies``"""
+        return os.path.expanduser("~/Movies")  # noqa: PTH111
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return os.path.expanduser("~/Music")  # noqa: PTH111
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return os.path.expanduser("~/Desktop")  # noqa: PTH111
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))  # noqa: PTH111
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+__all__ = [
+    "MacOS",
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/unix.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..9500ade614ce4e698ce02e23c8d7b52988a2b1a8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/unix.py
@@ -0,0 +1,275 @@
+"""Unix."""
+
+from __future__ import annotations
+
+import os
+import sys
+from configparser import ConfigParser
+from pathlib import Path
+from typing import Iterator, NoReturn
+
+from .api import PlatformDirsABC
+
+if sys.platform == "win32":
+
+    def getuid() -> NoReturn:
+        msg = "should only be used on Unix"
+        raise RuntimeError(msg)
+
+else:
+    from os import getuid
+
+
+class Unix(PlatformDirsABC):  # noqa: PLR0904
+    """
+    On Unix/Linux, we follow the `XDG Basedir Spec `_.
+
+    The spec allows overriding directories with environment variables. The examples shown are the default values,
+    alongside the name of the environment variable that overrides them. Makes use of the `appname
+    `, `version `, `multipath
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or
+         ``$XDG_DATA_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_DATA_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/share")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_DATA_DIRS", "")
+        if not path.strip():
+            path = f"/usr/local/share{os.pathsep}/usr/share"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_data_dir(self) -> str:
+        """
+        :return: data directories shared by users (if `multipath ` is
+         enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the
+         OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``
+        """
+        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False
+        dirs = self._site_data_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_config_dir(self) -> str:
+        """
+        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or
+         ``$XDG_CONFIG_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CONFIG_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.config")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        path = os.environ.get("XDG_CONFIG_DIRS", "")
+        if not path.strip():
+            path = "/etc/xdg"
+        return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)]
+
+    @property
+    def site_config_dir(self) -> str:
+        """
+        :return: config directories shared by users (if `multipath `
+         is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by
+         the OS path separator), e.g. ``/etc/xdg/$appname/$version``
+        """
+        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False
+        dirs = self._site_config_dirs
+        if not self.multipath:
+            return dirs[0]
+        return os.pathsep.join(dirs)
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or
+         ``~/$XDG_CACHE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_CACHE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.cache")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
+        return self._append_app_name_and_version("/var/cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """
+        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or
+         ``$XDG_STATE_HOME/$appname/$version``
+        """
+        path = os.environ.get("XDG_STATE_HOME", "")
+        if not path.strip():
+            path = os.path.expanduser("~/.local/state")  # noqa: PTH111
+        return self._append_app_name_and_version(path)
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
+        path = self.user_state_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user, e.g. ``~/Documents``"""
+        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user, e.g. ``~/Videos``"""
+        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user, e.g. ``~/Music``"""
+        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or
+         ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+         For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if
+         exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR``
+         is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = f"/var/run/user/{getuid()}"
+                if not Path(path).exists():
+                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108
+            else:
+                path = f"/run/user/{getuid()}"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """
+        :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \
+        ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will
+        fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
+
+        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir`
+        instead.
+
+        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
+        """
+        path = os.environ.get("XDG_RUNTIME_DIR", "")
+        if not path.strip():
+            if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+                path = "/var/run"
+            else:
+                path = "/run"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_config_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
+        if self.multipath:
+            # If multipath is True, the first path is returned.
+            directory = directory.split(os.pathsep)[0]
+        return Path(directory)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield from self._site_config_dirs
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield from self._site_data_dirs
+
+
+def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
+    media_dir = _get_user_dirs_folder(env_var)
+    if media_dir is None:
+        media_dir = os.environ.get(env_var, "").strip()
+        if not media_dir:
+            media_dir = os.path.expanduser(fallback_tilde_path)  # noqa: PTH111
+
+    return media_dir
+
+
+def _get_user_dirs_folder(key: str) -> str | None:
+    """
+    Return directory from user-dirs.dirs config file.
+
+    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
+
+    """
+    user_dirs_config_path = Path(Unix().user_config_dir) / "user-dirs.dirs"
+    if user_dirs_config_path.exists():
+        parser = ConfigParser()
+
+        with user_dirs_config_path.open() as stream:
+            # Add fake section header, so ConfigParser doesn't complain
+            parser.read_string(f"[top]\n{stream.read()}")
+
+        if key not in parser["top"]:
+            return None
+
+        path = parser["top"][key].strip('"')
+        # Handle relative home paths
+        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111
+
+    return None
+
+
+__all__ = [
+    "Unix",
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/version.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..6483ddce0bcfbaa01a5b3dc3f8b864de20ef0683
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/version.py
@@ -0,0 +1,16 @@
+# file generated by setuptools_scm
+# don't change, don't track in version control
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple, Union
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+else:
+    VERSION_TUPLE = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+
+__version__ = version = '4.2.2'
+__version_tuple__ = version_tuple = (4, 2, 2)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/windows.py b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7bc96091a2b1cd078a0847519cb5dd50a5d8898
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/platformdirs/windows.py
@@ -0,0 +1,272 @@
+"""Windows."""
+
+from __future__ import annotations
+
+import os
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+
+class Windows(PlatformDirsABC):
+    """
+    `MSDN on where to store app data files `_.
+
+    Makes use of the `appname `, `appauthor
+    `, `version `, `roaming
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """
+        :return: data directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
+         ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
+        """
+        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
+        path = os.path.normpath(get_win_folder(const))
+        return self._append_parts(path)
+
+    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
+        params = []
+        if self.appname:
+            if self.appauthor is not False:
+                author = self.appauthor or self.appname
+                params.append(author)
+            params.append(self.appname)
+            if opinion_value is not None and self.opinion:
+                params.append(opinion_value)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(path, *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_data_dir(self) -> str:
+        """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:return: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:return: config directory shared by the users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """
+        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
+         ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
+        """
+        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """:return: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
+        path = self.user_data_dir
+        if self.opinion:
+            path = os.path.join(path, "Logs")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""
+        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""
+        return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
+
+    @property
+    def user_music_dir(self) -> str:
+        """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""
+        return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """
+        :return: runtime directory tied to the user, e.g.
+         ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
+        """
+        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))  # noqa: PTH118
+        return self._append_parts(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:return: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+def get_win_folder_from_env_vars(csidl_name: str) -> str:
+    """Get folder from environment variables."""
+    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
+    if result is not None:
+        return result
+
+    env_var_name = {
+        "CSIDL_APPDATA": "APPDATA",
+        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
+        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
+    }.get(csidl_name)
+    if env_var_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    result = os.environ.get(env_var_name)
+    if result is None:
+        msg = f"Unset environment variable: {env_var_name}"
+        raise ValueError(msg)
+    return result
+
+
+def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:
+    """Get a folder for a CSIDL name that does not exist as an environment variable."""
+    if csidl_name == "CSIDL_PERSONAL":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYPICTURES":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYVIDEO":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYMUSIC":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music")  # noqa: PTH118
+    return None
+
+
+def get_win_folder_from_registry(csidl_name: str) -> str:
+    """
+    Get folder from the registry.
+
+    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
+    for all CSIDL_* names.
+
+    """
+    shell_folder_name = {
+        "CSIDL_APPDATA": "AppData",
+        "CSIDL_COMMON_APPDATA": "Common AppData",
+        "CSIDL_LOCAL_APPDATA": "Local AppData",
+        "CSIDL_PERSONAL": "Personal",
+        "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
+        "CSIDL_MYPICTURES": "My Pictures",
+        "CSIDL_MYVIDEO": "My Video",
+        "CSIDL_MYMUSIC": "My Music",
+    }.get(csidl_name)
+    if shell_folder_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
+        raise NotImplementedError
+    import winreg  # noqa: PLC0415
+
+    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
+    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
+    return str(directory)
+
+
+def get_win_folder_via_ctypes(csidl_name: str) -> str:
+    """Get folder with ctypes."""
+    # There is no 'CSIDL_DOWNLOADS'.
+    # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
+    # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
+
+    import ctypes  # noqa: PLC0415
+
+    csidl_const = {
+        "CSIDL_APPDATA": 26,
+        "CSIDL_COMMON_APPDATA": 35,
+        "CSIDL_LOCAL_APPDATA": 28,
+        "CSIDL_PERSONAL": 5,
+        "CSIDL_MYPICTURES": 39,
+        "CSIDL_MYVIDEO": 14,
+        "CSIDL_MYMUSIC": 13,
+        "CSIDL_DOWNLOADS": 40,
+        "CSIDL_DESKTOPDIRECTORY": 16,
+    }.get(csidl_name)
+    if csidl_const is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+
+    buf = ctypes.create_unicode_buffer(1024)
+    windll = getattr(ctypes, "windll")  # noqa: B009 # using getattr to avoid false positive with mypy type checker
+    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
+
+    # Downgrade to short path name if it has high-bit chars.
+    if any(ord(c) > 255 for c in buf):  # noqa: PLR2004
+        buf2 = ctypes.create_unicode_buffer(1024)
+        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
+            buf = buf2
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(buf.value, "Downloads")  # noqa: PTH118
+
+    return buf.value
+
+
+def _pick_get_win_folder() -> Callable[[str], str]:
+    try:
+        import ctypes  # noqa: PLC0415
+    except ImportError:
+        pass
+    else:
+        if hasattr(ctypes, "windll"):
+            return get_win_folder_via_ctypes
+    try:
+        import winreg  # noqa: PLC0415, F401
+    except ImportError:
+        return get_win_folder_from_env_vars
+    else:
+        return get_win_folder_from_registry
+
+
+get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
+
+__all__ = [
+    "Windows",
+]
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..e859590f886cd78344206af1a8ccb3080d4385e0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Taneli Hukkinen
+
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..efd87ecc1659a43c0a6e37bdc77954f352172acc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/METADATA
@@ -0,0 +1,206 @@
+Metadata-Version: 2.1
+Name: tomli
+Version: 2.0.1
+Summary: A lil' TOML parser
+Keywords: toml
+Author-email: Taneli Hukkinen 
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: MacOS
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Typing :: Typed
+Project-URL: Changelog, https://github.com/hukkin/tomli/blob/master/CHANGELOG.md
+Project-URL: Homepage, https://github.com/hukkin/tomli
+
+[![Build Status](https://github.com/hukkin/tomli/workflows/Tests/badge.svg?branch=master)](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
+[![codecov.io](https://codecov.io/gh/hukkin/tomli/branch/master/graph/badge.svg)](https://codecov.io/gh/hukkin/tomli)
+[![PyPI version](https://img.shields.io/pypi/v/tomli)](https://pypi.org/project/tomli)
+
+# Tomli
+
+> A lil' TOML parser
+
+**Table of Contents**  *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
+
+
+
+- [Intro](#intro)
+- [Installation](#installation)
+- [Usage](#usage)
+  - [Parse a TOML string](#parse-a-toml-string)
+  - [Parse a TOML file](#parse-a-toml-file)
+  - [Handle invalid TOML](#handle-invalid-toml)
+  - [Construct `decimal.Decimal`s from TOML floats](#construct-decimaldecimals-from-toml-floats)
+- [FAQ](#faq)
+  - [Why this parser?](#why-this-parser)
+  - [Is comment preserving round-trip parsing supported?](#is-comment-preserving-round-trip-parsing-supported)
+  - [Is there a `dumps`, `write` or `encode` function?](#is-there-a-dumps-write-or-encode-function)
+  - [How do TOML types map into Python types?](#how-do-toml-types-map-into-python-types)
+- [Performance](#performance)
+
+
+
+## Intro
+
+Tomli is a Python library for parsing [TOML](https://toml.io).
+Tomli is fully compatible with [TOML v1.0.0](https://toml.io/en/v1.0.0).
+
+## Installation
+
+```bash
+pip install tomli
+```
+
+## Usage
+
+### Parse a TOML string
+
+```python
+import tomli
+
+toml_str = """
+           gretzky = 99
+
+           [kurri]
+           jari = 17
+           """
+
+toml_dict = tomli.loads(toml_str)
+assert toml_dict == {"gretzky": 99, "kurri": {"jari": 17}}
+```
+
+### Parse a TOML file
+
+```python
+import tomli
+
+with open("path_to_file/conf.toml", "rb") as f:
+    toml_dict = tomli.load(f)
+```
+
+The file must be opened in binary mode (with the `"rb"` flag).
+Binary mode will enforce decoding the file as UTF-8 with universal newlines disabled,
+both of which are required to correctly parse TOML.
+
+### Handle invalid TOML
+
+```python
+import tomli
+
+try:
+    toml_dict = tomli.loads("]] this is invalid TOML [[")
+except tomli.TOMLDecodeError:
+    print("Yep, definitely not valid.")
+```
+
+Note that error messages are considered informational only.
+They should not be assumed to stay constant across Tomli versions.
+
+### Construct `decimal.Decimal`s from TOML floats
+
+```python
+from decimal import Decimal
+import tomli
+
+toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal)
+assert toml_dict["precision-matters"] == Decimal("0.982492")
+```
+
+Note that `decimal.Decimal` can be replaced with another callable that converts a TOML float from string to a Python type.
+The `decimal.Decimal` is, however, a practical choice for use cases where float inaccuracies can not be tolerated.
+
+Illegal types are `dict` and `list`, and their subtypes.
+A `ValueError` will be raised if `parse_float` produces illegal types.
+
+## FAQ
+
+### Why this parser?
+
+- it's lil'
+- pure Python with zero dependencies
+- the fastest pure Python parser [\*](#performance):
+  15x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
+  2.4x as fast as [toml](https://pypi.org/project/toml/)
+- outputs [basic data types](#how-do-toml-types-map-into-python-types) only
+- 100% spec compliant: passes all tests in
+  [a test set](https://github.com/toml-lang/compliance/pull/8)
+  soon to be merged to the official
+  [compliance tests for TOML](https://github.com/toml-lang/compliance)
+  repository
+- thoroughly tested: 100% branch coverage
+
+### Is comment preserving round-trip parsing supported?
+
+No.
+
+The `tomli.loads` function returns a plain `dict` that is populated with builtin types and types from the standard library only.
+Preserving comments requires a custom type to be returned so will not be supported,
+at least not by the `tomli.loads` and `tomli.load` functions.
+
+Look into [TOML Kit](https://github.com/sdispater/tomlkit) if preservation of style is what you need.
+
+### Is there a `dumps`, `write` or `encode` function?
+
+[Tomli-W](https://github.com/hukkin/tomli-w) is the write-only counterpart of Tomli, providing `dump` and `dumps` functions.
+
+The core library does not include write capability, as most TOML use cases are read-only, and Tomli intends to be minimal.
+
+### How do TOML types map into Python types?
+
+| TOML type        | Python type         | Details                                                      |
+| ---------------- | ------------------- | ------------------------------------------------------------ |
+| Document Root    | `dict`              |                                                              |
+| Key              | `str`               |                                                              |
+| String           | `str`               |                                                              |
+| Integer          | `int`               |                                                              |
+| Float            | `float`             |                                                              |
+| Boolean          | `bool`              |                                                              |
+| Offset Date-Time | `datetime.datetime` | `tzinfo` attribute set to an instance of `datetime.timezone` |
+| Local Date-Time  | `datetime.datetime` | `tzinfo` attribute set to `None`                             |
+| Local Date       | `datetime.date`     |                                                              |
+| Local Time       | `datetime.time`     |                                                              |
+| Array            | `list`              |                                                              |
+| Table            | `dict`              |                                                              |
+| Inline Table     | `dict`              |                                                              |
+
+## Performance
+
+The `benchmark/` folder in this repository contains a performance benchmark for comparing the various Python TOML parsers.
+The benchmark can be run with `tox -e benchmark-pypi`.
+Running the benchmark on my personal computer output the following:
+
+```console
+foo@bar:~/dev/tomli$ tox -e benchmark-pypi
+benchmark-pypi installed: attrs==19.3.0,click==7.1.2,pytomlpp==1.0.2,qtoml==0.3.0,rtoml==0.7.0,toml==0.10.2,tomli==1.1.0,tomlkit==0.7.2
+benchmark-pypi run-test-pre: PYTHONHASHSEED='2658546909'
+benchmark-pypi run-test: commands[0] | python -c 'import datetime; print(datetime.date.today())'
+2021-07-23
+benchmark-pypi run-test: commands[1] | python --version
+Python 3.8.10
+benchmark-pypi run-test: commands[2] | python benchmark/run.py
+Parsing data.toml 5000 times:
+------------------------------------------------------
+    parser |  exec time | performance (more is better)
+-----------+------------+-----------------------------
+     rtoml |    0.901 s | baseline (100%)
+  pytomlpp |     1.08 s | 83.15%
+     tomli |     3.89 s | 23.15%
+      toml |     9.36 s | 9.63%
+     qtoml |     11.5 s | 7.82%
+   tomlkit |     56.8 s | 1.59%
+```
+
+The parsers are ordered from fastest to slowest, using the fastest parser as baseline.
+Tomli performed the best out of all pure Python TOML parsers,
+losing only to pytomlpp (wraps C++) and rtoml (wraps Rust).
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..1db8063ec5c3ba925e681030347e8d396eb934be
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/RECORD
@@ -0,0 +1,15 @@
+tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875
+tomli-2.0.1.dist-info/RECORD,,
+tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tomli-2.0.1.dist-info/WHEEL,sha256=jPMR_Dzkc4X4icQtmz81lnNY_kAsfog7ry7qoRvYLXw,81
+tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396
+tomli/__pycache__/__init__.cpython-312.pyc,,
+tomli/__pycache__/_parser.cpython-312.pyc,,
+tomli/__pycache__/_re.cpython-312.pyc,,
+tomli/__pycache__/_types.cpython-312.pyc,,
+tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633
+tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943
+tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..c727d148239a36b0e8de2b97fdb23fb96da78869
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli-2.0.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.6.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c6ec97ec6961bcf184b6e0b2437b9924db0b9de
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/__init__.py
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+__all__ = ("loads", "load", "TOMLDecodeError")
+__version__ = "2.0.1"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
+
+from ._parser import TOMLDecodeError, load, loads
+
+# Pretend this exception was created here.
+TOMLDecodeError.__module__ = __name__
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_parser.py b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1bb0aa19a556725aa2ae2b8cea95489c99a9078
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_parser.py
@@ -0,0 +1,691 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+import string
+from types import MappingProxyType
+from typing import Any, BinaryIO, NamedTuple
+
+from ._re import (
+    RE_DATETIME,
+    RE_LOCALTIME,
+    RE_NUMBER,
+    match_to_datetime,
+    match_to_localtime,
+    match_to_number,
+)
+from ._types import Key, ParseFloat, Pos
+
+ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
+
+# Neither of these sets include quotation mark or backslash. They are
+# currently handled as separate cases in the parser functions.
+ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t")
+ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n")
+
+ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS
+ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+
+ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS
+
+TOML_WS = frozenset(" \t")
+TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n")
+BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_")
+KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'")
+HEXDIGIT_CHARS = frozenset(string.hexdigits)
+
+BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(
+    {
+        "\\b": "\u0008",  # backspace
+        "\\t": "\u0009",  # tab
+        "\\n": "\u000A",  # linefeed
+        "\\f": "\u000C",  # form feed
+        "\\r": "\u000D",  # carriage return
+        '\\"': "\u0022",  # quote
+        "\\\\": "\u005C",  # backslash
+    }
+)
+
+
+class TOMLDecodeError(ValueError):
+    """An error raised if a document is not valid TOML."""
+
+
+def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:
+    """Parse TOML from a binary file object."""
+    b = __fp.read()
+    try:
+        s = b.decode()
+    except AttributeError:
+        raise TypeError(
+            "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
+        ) from None
+    return loads(s, parse_float=parse_float)
+
+
+def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901
+    """Parse TOML from a string."""
+
+    # The spec allows converting "\r\n" to "\n", even in string
+    # literals. Let's do so to simplify parsing.
+    src = __s.replace("\r\n", "\n")
+    pos = 0
+    out = Output(NestedDict(), Flags())
+    header: Key = ()
+    parse_float = make_safe_parse_float(parse_float)
+
+    # Parse one statement at a time
+    # (typically means one line in TOML source)
+    while True:
+        # 1. Skip line leading whitespace
+        pos = skip_chars(src, pos, TOML_WS)
+
+        # 2. Parse rules. Expect one of the following:
+        #    - end of file
+        #    - end of line
+        #    - comment
+        #    - key/value pair
+        #    - append dict to list (and move to its namespace)
+        #    - create dict (and move to its namespace)
+        # Skip trailing whitespace when applicable.
+        try:
+            char = src[pos]
+        except IndexError:
+            break
+        if char == "\n":
+            pos += 1
+            continue
+        if char in KEY_INITIAL_CHARS:
+            pos = key_value_rule(src, pos, out, header, parse_float)
+            pos = skip_chars(src, pos, TOML_WS)
+        elif char == "[":
+            try:
+                second_char: str | None = src[pos + 1]
+            except IndexError:
+                second_char = None
+            out.flags.finalize_pending()
+            if second_char == "[":
+                pos, header = create_list_rule(src, pos, out)
+            else:
+                pos, header = create_dict_rule(src, pos, out)
+            pos = skip_chars(src, pos, TOML_WS)
+        elif char != "#":
+            raise suffixed_err(src, pos, "Invalid statement")
+
+        # 3. Skip comment
+        pos = skip_comment(src, pos)
+
+        # 4. Expect end of line or end of file
+        try:
+            char = src[pos]
+        except IndexError:
+            break
+        if char != "\n":
+            raise suffixed_err(
+                src, pos, "Expected newline or end of document after a statement"
+            )
+        pos += 1
+
+    return out.data.dict
+
+
+class Flags:
+    """Flags that map to parsed keys/namespaces."""
+
+    # Marks an immutable namespace (inline array or inline table).
+    FROZEN = 0
+    # Marks a nest that has been explicitly created and can no longer
+    # be opened using the "[table]" syntax.
+    EXPLICIT_NEST = 1
+
+    def __init__(self) -> None:
+        self._flags: dict[str, dict] = {}
+        self._pending_flags: set[tuple[Key, int]] = set()
+
+    def add_pending(self, key: Key, flag: int) -> None:
+        self._pending_flags.add((key, flag))
+
+    def finalize_pending(self) -> None:
+        for key, flag in self._pending_flags:
+            self.set(key, flag, recursive=False)
+        self._pending_flags.clear()
+
+    def unset_all(self, key: Key) -> None:
+        cont = self._flags
+        for k in key[:-1]:
+            if k not in cont:
+                return
+            cont = cont[k]["nested"]
+        cont.pop(key[-1], None)
+
+    def set(self, key: Key, flag: int, *, recursive: bool) -> None:  # noqa: A003
+        cont = self._flags
+        key_parent, key_stem = key[:-1], key[-1]
+        for k in key_parent:
+            if k not in cont:
+                cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}
+            cont = cont[k]["nested"]
+        if key_stem not in cont:
+            cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}}
+        cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)
+
+    def is_(self, key: Key, flag: int) -> bool:
+        if not key:
+            return False  # document root has no flags
+        cont = self._flags
+        for k in key[:-1]:
+            if k not in cont:
+                return False
+            inner_cont = cont[k]
+            if flag in inner_cont["recursive_flags"]:
+                return True
+            cont = inner_cont["nested"]
+        key_stem = key[-1]
+        if key_stem in cont:
+            cont = cont[key_stem]
+            return flag in cont["flags"] or flag in cont["recursive_flags"]
+        return False
+
+
+class NestedDict:
+    def __init__(self) -> None:
+        # The parsed content of the TOML document
+        self.dict: dict[str, Any] = {}
+
+    def get_or_create_nest(
+        self,
+        key: Key,
+        *,
+        access_lists: bool = True,
+    ) -> dict:
+        cont: Any = self.dict
+        for k in key:
+            if k not in cont:
+                cont[k] = {}
+            cont = cont[k]
+            if access_lists and isinstance(cont, list):
+                cont = cont[-1]
+            if not isinstance(cont, dict):
+                raise KeyError("There is no nest behind this key")
+        return cont
+
+    def append_nest_to_list(self, key: Key) -> None:
+        cont = self.get_or_create_nest(key[:-1])
+        last_key = key[-1]
+        if last_key in cont:
+            list_ = cont[last_key]
+            if not isinstance(list_, list):
+                raise KeyError("An object other than list found behind this key")
+            list_.append({})
+        else:
+            cont[last_key] = [{}]
+
+
+class Output(NamedTuple):
+    data: NestedDict
+    flags: Flags
+
+
+def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:
+    try:
+        while src[pos] in chars:
+            pos += 1
+    except IndexError:
+        pass
+    return pos
+
+
+def skip_until(
+    src: str,
+    pos: Pos,
+    expect: str,
+    *,
+    error_on: frozenset[str],
+    error_on_eof: bool,
+) -> Pos:
+    try:
+        new_pos = src.index(expect, pos)
+    except ValueError:
+        new_pos = len(src)
+        if error_on_eof:
+            raise suffixed_err(src, new_pos, f"Expected {expect!r}") from None
+
+    if not error_on.isdisjoint(src[pos:new_pos]):
+        while src[pos] not in error_on:
+            pos += 1
+        raise suffixed_err(src, pos, f"Found invalid character {src[pos]!r}")
+    return new_pos
+
+
+def skip_comment(src: str, pos: Pos) -> Pos:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char == "#":
+        return skip_until(
+            src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False
+        )
+    return pos
+
+
+def skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:
+    while True:
+        pos_before_skip = pos
+        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
+        pos = skip_comment(src, pos)
+        if pos == pos_before_skip:
+            return pos
+
+
+def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
+    pos += 1  # Skip "["
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, key = parse_key(src, pos)
+
+    if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):
+        raise suffixed_err(src, pos, f"Cannot declare {key} twice")
+    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
+    try:
+        out.data.get_or_create_nest(key)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+
+    if not src.startswith("]", pos):
+        raise suffixed_err(src, pos, "Expected ']' at the end of a table declaration")
+    return pos + 1, key
+
+
+def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
+    pos += 2  # Skip "[["
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, key = parse_key(src, pos)
+
+    if out.flags.is_(key, Flags.FROZEN):
+        raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+    # Free the namespace now that it points to another empty list item...
+    out.flags.unset_all(key)
+    # ...but this key precisely is still prohibited from table declaration
+    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
+    try:
+        out.data.append_nest_to_list(key)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+
+    if not src.startswith("]]", pos):
+        raise suffixed_err(src, pos, "Expected ']]' at the end of an array declaration")
+    return pos + 2, key
+
+
+def key_value_rule(
+    src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat
+) -> Pos:
+    pos, key, value = parse_key_value_pair(src, pos, parse_float)
+    key_parent, key_stem = key[:-1], key[-1]
+    abs_key_parent = header + key_parent
+
+    relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))
+    for cont_key in relative_path_cont_keys:
+        # Check that dotted key syntax does not redefine an existing table
+        if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):
+            raise suffixed_err(src, pos, f"Cannot redefine namespace {cont_key}")
+        # Containers in the relative path can't be opened with the table syntax or
+        # dotted key/value syntax in following table sections.
+        out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)
+
+    if out.flags.is_(abs_key_parent, Flags.FROZEN):
+        raise suffixed_err(
+            src, pos, f"Cannot mutate immutable namespace {abs_key_parent}"
+        )
+
+    try:
+        nest = out.data.get_or_create_nest(abs_key_parent)
+    except KeyError:
+        raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+    if key_stem in nest:
+        raise suffixed_err(src, pos, "Cannot overwrite a value")
+    # Mark inline table and array namespaces recursively immutable
+    if isinstance(value, (dict, list)):
+        out.flags.set(header + key, Flags.FROZEN, recursive=True)
+    nest[key_stem] = value
+    return pos
+
+
+def parse_key_value_pair(
+    src: str, pos: Pos, parse_float: ParseFloat
+) -> tuple[Pos, Key, Any]:
+    pos, key = parse_key(src, pos)
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char != "=":
+        raise suffixed_err(src, pos, "Expected '=' after a key in a key/value pair")
+    pos += 1
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, value = parse_value(src, pos, parse_float)
+    return pos, key, value
+
+
+def parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:
+    pos, key_part = parse_key_part(src, pos)
+    key: Key = (key_part,)
+    pos = skip_chars(src, pos, TOML_WS)
+    while True:
+        try:
+            char: str | None = src[pos]
+        except IndexError:
+            char = None
+        if char != ".":
+            return pos, key
+        pos += 1
+        pos = skip_chars(src, pos, TOML_WS)
+        pos, key_part = parse_key_part(src, pos)
+        key += (key_part,)
+        pos = skip_chars(src, pos, TOML_WS)
+
+
+def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char in BARE_KEY_CHARS:
+        start_pos = pos
+        pos = skip_chars(src, pos, BARE_KEY_CHARS)
+        return pos, src[start_pos:pos]
+    if char == "'":
+        return parse_literal_str(src, pos)
+    if char == '"':
+        return parse_one_line_basic_str(src, pos)
+    raise suffixed_err(src, pos, "Invalid initial character for a key part")
+
+
+def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
+    pos += 1
+    return parse_basic_str(src, pos, multiline=False)
+
+
+def parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]:
+    pos += 1
+    array: list = []
+
+    pos = skip_comments_and_array_ws(src, pos)
+    if src.startswith("]", pos):
+        return pos + 1, array
+    while True:
+        pos, val = parse_value(src, pos, parse_float)
+        array.append(val)
+        pos = skip_comments_and_array_ws(src, pos)
+
+        c = src[pos : pos + 1]
+        if c == "]":
+            return pos + 1, array
+        if c != ",":
+            raise suffixed_err(src, pos, "Unclosed array")
+        pos += 1
+
+        pos = skip_comments_and_array_ws(src, pos)
+        if src.startswith("]", pos):
+            return pos + 1, array
+
+
+def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]:
+    pos += 1
+    nested_dict = NestedDict()
+    flags = Flags()
+
+    pos = skip_chars(src, pos, TOML_WS)
+    if src.startswith("}", pos):
+        return pos + 1, nested_dict.dict
+    while True:
+        pos, key, value = parse_key_value_pair(src, pos, parse_float)
+        key_parent, key_stem = key[:-1], key[-1]
+        if flags.is_(key, Flags.FROZEN):
+            raise suffixed_err(src, pos, f"Cannot mutate immutable namespace {key}")
+        try:
+            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
+        except KeyError:
+            raise suffixed_err(src, pos, "Cannot overwrite a value") from None
+        if key_stem in nest:
+            raise suffixed_err(src, pos, f"Duplicate inline table key {key_stem!r}")
+        nest[key_stem] = value
+        pos = skip_chars(src, pos, TOML_WS)
+        c = src[pos : pos + 1]
+        if c == "}":
+            return pos + 1, nested_dict.dict
+        if c != ",":
+            raise suffixed_err(src, pos, "Unclosed inline table")
+        if isinstance(value, (dict, list)):
+            flags.set(key, Flags.FROZEN, recursive=True)
+        pos += 1
+        pos = skip_chars(src, pos, TOML_WS)
+
+
+def parse_basic_str_escape(
+    src: str, pos: Pos, *, multiline: bool = False
+) -> tuple[Pos, str]:
+    escape_id = src[pos : pos + 2]
+    pos += 2
+    if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:
+        # Skip whitespace until next non-whitespace character or end of
+        # the doc. Error if non-whitespace is found before newline.
+        if escape_id != "\\\n":
+            pos = skip_chars(src, pos, TOML_WS)
+            try:
+                char = src[pos]
+            except IndexError:
+                return pos, ""
+            if char != "\n":
+                raise suffixed_err(src, pos, "Unescaped '\\' in a string")
+            pos += 1
+        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
+        return pos, ""
+    if escape_id == "\\u":
+        return parse_hex_char(src, pos, 4)
+    if escape_id == "\\U":
+        return parse_hex_char(src, pos, 8)
+    try:
+        return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
+    except KeyError:
+        raise suffixed_err(src, pos, "Unescaped '\\' in a string") from None
+
+
+def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
+    return parse_basic_str_escape(src, pos, multiline=True)
+
+
+def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:
+    hex_str = src[pos : pos + hex_len]
+    if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):
+        raise suffixed_err(src, pos, "Invalid hex value")
+    pos += hex_len
+    hex_int = int(hex_str, 16)
+    if not is_unicode_scalar_value(hex_int):
+        raise suffixed_err(src, pos, "Escaped character is not a Unicode scalar value")
+    return pos, chr(hex_int)
+
+
+def parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:
+    pos += 1  # Skip starting apostrophe
+    start_pos = pos
+    pos = skip_until(
+        src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True
+    )
+    return pos + 1, src[start_pos:pos]  # Skip ending apostrophe
+
+
+def parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:
+    pos += 3
+    if src.startswith("\n", pos):
+        pos += 1
+
+    if literal:
+        delim = "'"
+        end_pos = skip_until(
+            src,
+            pos,
+            "'''",
+            error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,
+            error_on_eof=True,
+        )
+        result = src[pos:end_pos]
+        pos = end_pos + 3
+    else:
+        delim = '"'
+        pos, result = parse_basic_str(src, pos, multiline=True)
+
+    # Add at maximum two extra apostrophes/quotes if the end sequence
+    # is 4 or 5 chars long instead of just 3.
+    if not src.startswith(delim, pos):
+        return pos, result
+    pos += 1
+    if not src.startswith(delim, pos):
+        return pos, result + delim
+    pos += 1
+    return pos, result + (delim * 2)
+
+
+def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
+    if multiline:
+        error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+        parse_escapes = parse_basic_str_escape_multiline
+    else:
+        error_on = ILLEGAL_BASIC_STR_CHARS
+        parse_escapes = parse_basic_str_escape
+    result = ""
+    start_pos = pos
+    while True:
+        try:
+            char = src[pos]
+        except IndexError:
+            raise suffixed_err(src, pos, "Unterminated string") from None
+        if char == '"':
+            if not multiline:
+                return pos + 1, result + src[start_pos:pos]
+            if src.startswith('"""', pos):
+                return pos + 3, result + src[start_pos:pos]
+            pos += 1
+            continue
+        if char == "\\":
+            result += src[start_pos:pos]
+            pos, parsed_escape = parse_escapes(src, pos)
+            result += parsed_escape
+            start_pos = pos
+            continue
+        if char in error_on:
+            raise suffixed_err(src, pos, f"Illegal character {char!r}")
+        pos += 1
+
+
+def parse_value(  # noqa: C901
+    src: str, pos: Pos, parse_float: ParseFloat
+) -> tuple[Pos, Any]:
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+
+    # IMPORTANT: order conditions based on speed of checking and likelihood
+
+    # Basic strings
+    if char == '"':
+        if src.startswith('"""', pos):
+            return parse_multiline_str(src, pos, literal=False)
+        return parse_one_line_basic_str(src, pos)
+
+    # Literal strings
+    if char == "'":
+        if src.startswith("'''", pos):
+            return parse_multiline_str(src, pos, literal=True)
+        return parse_literal_str(src, pos)
+
+    # Booleans
+    if char == "t":
+        if src.startswith("true", pos):
+            return pos + 4, True
+    if char == "f":
+        if src.startswith("false", pos):
+            return pos + 5, False
+
+    # Arrays
+    if char == "[":
+        return parse_array(src, pos, parse_float)
+
+    # Inline tables
+    if char == "{":
+        return parse_inline_table(src, pos, parse_float)
+
+    # Dates and times
+    datetime_match = RE_DATETIME.match(src, pos)
+    if datetime_match:
+        try:
+            datetime_obj = match_to_datetime(datetime_match)
+        except ValueError as e:
+            raise suffixed_err(src, pos, "Invalid date or datetime") from e
+        return datetime_match.end(), datetime_obj
+    localtime_match = RE_LOCALTIME.match(src, pos)
+    if localtime_match:
+        return localtime_match.end(), match_to_localtime(localtime_match)
+
+    # Integers and "normal" floats.
+    # The regex will greedily match any type starting with a decimal
+    # char, so needs to be located after handling of dates and times.
+    number_match = RE_NUMBER.match(src, pos)
+    if number_match:
+        return number_match.end(), match_to_number(number_match, parse_float)
+
+    # Special floats
+    first_three = src[pos : pos + 3]
+    if first_three in {"inf", "nan"}:
+        return pos + 3, parse_float(first_three)
+    first_four = src[pos : pos + 4]
+    if first_four in {"-inf", "+inf", "-nan", "+nan"}:
+        return pos + 4, parse_float(first_four)
+
+    raise suffixed_err(src, pos, "Invalid value")
+
+
+def suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError:
+    """Return a `TOMLDecodeError` where error message is suffixed with
+    coordinates in source."""
+
+    def coord_repr(src: str, pos: Pos) -> str:
+        if pos >= len(src):
+            return "end of document"
+        line = src.count("\n", 0, pos) + 1
+        if line == 1:
+            column = pos + 1
+        else:
+            column = pos - src.rindex("\n", 0, pos)
+        return f"line {line}, column {column}"
+
+    return TOMLDecodeError(f"{msg} (at {coord_repr(src, pos)})")
+
+
+def is_unicode_scalar_value(codepoint: int) -> bool:
+    return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)
+
+
+def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
+    """A decorator to make `parse_float` safe.
+
+    `parse_float` must not return dicts or lists, because these types
+    would be mixed with parsed TOML tables and arrays, thus confusing
+    the parser. The returned decorated callable raises `ValueError`
+    instead of returning illegal types.
+    """
+    # The default `float` callable never returns illegal types. Optimize it.
+    if parse_float is float:  # type: ignore[comparison-overlap]
+        return float
+
+    def safe_parse_float(float_str: str) -> Any:
+        float_value = parse_float(float_str)
+        if isinstance(float_value, (dict, list)):
+            raise ValueError("parse_float must not return dicts or lists")
+        return float_value
+
+    return safe_parse_float
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_re.py b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_re.py
new file mode 100644
index 0000000000000000000000000000000000000000..994bb7493fd92865e6ab87c277ba5741b44c31a9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_re.py
@@ -0,0 +1,107 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from __future__ import annotations
+
+from datetime import date, datetime, time, timedelta, timezone, tzinfo
+from functools import lru_cache
+import re
+from typing import Any
+
+from ._types import ParseFloat
+
+# E.g.
+# - 00:32:00.999999
+# - 00:32:00
+_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
+
+RE_NUMBER = re.compile(
+    r"""
+0
+(?:
+    x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*   # hex
+    |
+    b[01](?:_?[01])*                 # bin
+    |
+    o[0-7](?:_?[0-7])*               # oct
+)
+|
+[+-]?(?:0|[1-9](?:_?[0-9])*)         # dec, integer part
+(?P
+    (?:\.[0-9](?:_?[0-9])*)?         # optional fractional part
+    (?:[eE][+-]?[0-9](?:_?[0-9])*)?  # optional exponent part
+)
+""",
+    flags=re.VERBOSE,
+)
+RE_LOCALTIME = re.compile(_TIME_RE_STR)
+RE_DATETIME = re.compile(
+    rf"""
+([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27
+(?:
+    [Tt ]
+    {_TIME_RE_STR}
+    (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))?  # optional time offset
+)?
+""",
+    flags=re.VERBOSE,
+)
+
+
+def match_to_datetime(match: re.Match) -> datetime | date:
+    """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
+
+    Raises ValueError if the match does not correspond to a valid date
+    or datetime.
+    """
+    (
+        year_str,
+        month_str,
+        day_str,
+        hour_str,
+        minute_str,
+        sec_str,
+        micros_str,
+        zulu_time,
+        offset_sign_str,
+        offset_hour_str,
+        offset_minute_str,
+    ) = match.groups()
+    year, month, day = int(year_str), int(month_str), int(day_str)
+    if hour_str is None:
+        return date(year, month, day)
+    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
+    micros = int(micros_str.ljust(6, "0")) if micros_str else 0
+    if offset_sign_str:
+        tz: tzinfo | None = cached_tz(
+            offset_hour_str, offset_minute_str, offset_sign_str
+        )
+    elif zulu_time:
+        tz = timezone.utc
+    else:  # local date-time
+        tz = None
+    return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
+
+
+@lru_cache(maxsize=None)
+def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
+    sign = 1 if sign_str == "+" else -1
+    return timezone(
+        timedelta(
+            hours=sign * int(hour_str),
+            minutes=sign * int(minute_str),
+        )
+    )
+
+
+def match_to_localtime(match: re.Match) -> time:
+    hour_str, minute_str, sec_str, micros_str = match.groups()
+    micros = int(micros_str.ljust(6, "0")) if micros_str else 0
+    return time(int(hour_str), int(minute_str), int(sec_str), micros)
+
+
+def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
+    if match.group("floatpart"):
+        return parse_float(match.group())
+    return int(match.group(), 0)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_types.py b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..d949412e03b29d70592c7721fe747e5085c2e280
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/_types.py
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from typing import Any, Callable, Tuple
+
+# Type annotations
+ParseFloat = Callable[[str], Any]
+Key = Tuple[str, ...]
+Pos = int
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..7632ecf77545c5e5501cb3fc5719df0761104ca2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/tomli/py.typed
@@ -0,0 +1 @@
+# Marker file for PEP 561
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..07806f8af9dd3253ebdb5710b67e73124aea4941
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/LICENSE
@@ -0,0 +1,19 @@
+This is the MIT license: http://www.opensource.org/licenses/mit-license.php
+
+Copyright (c) Alex Grönholm
+
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..6e5750b485fd5cbdb25a9ac9b03bc494357546c7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/METADATA
@@ -0,0 +1,81 @@
+Metadata-Version: 2.1
+Name: typeguard
+Version: 4.3.0
+Summary: Run-time type checker for Python
+Author-email: Alex Grönholm 
+License: MIT
+Project-URL: Documentation, https://typeguard.readthedocs.io/en/latest/
+Project-URL: Change log, https://typeguard.readthedocs.io/en/latest/versionhistory.html
+Project-URL: Source code, https://github.com/agronholm/typeguard
+Project-URL: Issue tracker, https://github.com/agronholm/typeguard/issues
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: typing-extensions >=4.10.0
+Requires-Dist: importlib-metadata >=3.6 ; python_version < "3.10"
+Provides-Extra: doc
+Requires-Dist: packaging ; extra == 'doc'
+Requires-Dist: Sphinx >=7 ; extra == 'doc'
+Requires-Dist: sphinx-autodoc-typehints >=1.2.0 ; extra == 'doc'
+Requires-Dist: sphinx-rtd-theme >=1.3.0 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: coverage[toml] >=7 ; extra == 'test'
+Requires-Dist: pytest >=7 ; extra == 'test'
+Requires-Dist: mypy >=1.2.0 ; (platform_python_implementation != "PyPy") and extra == 'test'
+
+.. image:: https://github.com/agronholm/typeguard/actions/workflows/test.yml/badge.svg
+  :target: https://github.com/agronholm/typeguard/actions/workflows/test.yml
+  :alt: Build Status
+.. image:: https://coveralls.io/repos/agronholm/typeguard/badge.svg?branch=master&service=github
+  :target: https://coveralls.io/github/agronholm/typeguard?branch=master
+  :alt: Code Coverage
+.. image:: https://readthedocs.org/projects/typeguard/badge/?version=latest
+  :target: https://typeguard.readthedocs.io/en/latest/?badge=latest
+  :alt: Documentation
+
+This library provides run-time type checking for functions defined with
+`PEP 484 `_ argument (and return) type
+annotations, and any arbitrary objects. It can be used together with static type
+checkers as an additional layer of type safety, to catch type violations that could only
+be detected at run time.
+
+Two principal ways to do type checking are provided:
+
+#. The ``check_type`` function:
+
+   * like ``isinstance()``, but supports arbitrary type annotations (within limits)
+   * can be used as a ``cast()`` replacement, but with actual checking of the value
+#. Code instrumentation:
+
+   * entire modules, or individual functions (via ``@typechecked``) are recompiled, with
+     type checking code injected into them
+   * automatically checks function arguments, return values and assignments to annotated
+     local variables
+   * for generator functions (regular and async), checks yield and send values
+   * requires the original source code of the instrumented module(s) to be accessible
+
+Two options are provided for code instrumentation:
+
+#. the ``@typechecked`` function:
+
+   * can be applied to functions individually
+#. the import hook (``typeguard.install_import_hook()``):
+
+   * automatically instruments targeted modules on import
+   * no manual code changes required in the target modules
+   * requires the import hook to be installed before the targeted modules are imported
+   * may clash with other import hooks
+
+See the documentation_ for further information.
+
+.. _documentation: https://typeguard.readthedocs.io/en/latest/
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..801e73347c4dfdd6c275f53295de748d0aa7049d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/RECORD
@@ -0,0 +1,34 @@
+typeguard-4.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+typeguard-4.3.0.dist-info/LICENSE,sha256=YWP3mH37ONa8MgzitwsvArhivEESZRbVUu8c1DJH51g,1130
+typeguard-4.3.0.dist-info/METADATA,sha256=z2dcHAp0TwhYCFU5Deh8x31nazElgujUz9tbuP0pjSE,3717
+typeguard-4.3.0.dist-info/RECORD,,
+typeguard-4.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+typeguard-4.3.0.dist-info/entry_points.txt,sha256=qp7NQ1aLtiSgMQqo6gWlfGpy0IIXzoMJmeQTLpzqFZQ,48
+typeguard-4.3.0.dist-info/top_level.txt,sha256=4z28AhuDodwRS_c1J_l8H51t5QuwfTseskYzlxp6grs,10
+typeguard/__init__.py,sha256=Onh4w38elPCjtlcU3JY9k3h70NjsxXIkAflmQn-Z0FY,2071
+typeguard/__pycache__/__init__.cpython-312.pyc,,
+typeguard/__pycache__/_checkers.cpython-312.pyc,,
+typeguard/__pycache__/_config.cpython-312.pyc,,
+typeguard/__pycache__/_decorators.cpython-312.pyc,,
+typeguard/__pycache__/_exceptions.cpython-312.pyc,,
+typeguard/__pycache__/_functions.cpython-312.pyc,,
+typeguard/__pycache__/_importhook.cpython-312.pyc,,
+typeguard/__pycache__/_memo.cpython-312.pyc,,
+typeguard/__pycache__/_pytest_plugin.cpython-312.pyc,,
+typeguard/__pycache__/_suppression.cpython-312.pyc,,
+typeguard/__pycache__/_transformer.cpython-312.pyc,,
+typeguard/__pycache__/_union_transformer.cpython-312.pyc,,
+typeguard/__pycache__/_utils.cpython-312.pyc,,
+typeguard/_checkers.py,sha256=JRrgKicdOEfIBoNEtegYCEIlhpad-a1u1Em7GCj0WCI,31360
+typeguard/_config.py,sha256=nIz8QwDa-oFO3L9O8_6srzlmd99pSby2wOM4Wb7F_B0,2846
+typeguard/_decorators.py,sha256=v6dsIeWvPhExGLP_wXF-RmDUyjZf_Ak28g7gBJ_v0-0,9033
+typeguard/_exceptions.py,sha256=ZIPeiV-FBd5Emw2EaWd2Fvlsrwi4ocwT2fVGBIAtHcQ,1121
+typeguard/_functions.py,sha256=ibgSAKa5ptIm1eR9ARG0BSozAFJPFNASZqhPVyQeqig,10393
+typeguard/_importhook.py,sha256=ugjCDvFcdWMU7UugqlJG91IpVNpEIxtRr-99s0h1k7M,6389
+typeguard/_memo.py,sha256=1juQV_vxnD2JYKbSrebiQuj4oKHz6n67v9pYA-CCISg,1303
+typeguard/_pytest_plugin.py,sha256=-fcSqkv54rIfIF8pDavY5YQPkj4OX8GMt_lL7CQSD4I,4416
+typeguard/_suppression.py,sha256=VQfzxcwIbu3if0f7VBkKM7hkYOA7tNFw9a7jMBsmMg4,2266
+typeguard/_transformer.py,sha256=9Ha7_QhdwoUni_6hvdY-hZbuEergowHrNL2vzHIakFY,44937
+typeguard/_union_transformer.py,sha256=v_42r7-6HuRX2SoFwnyJ-E5PlxXpVeUJPJR1-HU9qSo,1354
+typeguard/_utils.py,sha256=5HhO1rPn5f1M6ymkVAEv7Xmlz1cX-j0OnTMlyHqqrR8,5270
+typeguard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..47c9d0bd913e50da44b12013bde2a1df636ef684
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[pytest11]
+typeguard = typeguard._pytest_plugin
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..be5ec23ea2016f69345eaf80c7714777d04988f0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard-4.3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+typeguard
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6781cad094b29db0959df4fb0c29c0fa9d480c0c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/__init__.py
@@ -0,0 +1,48 @@
+import os
+from typing import Any
+
+from ._checkers import TypeCheckerCallable as TypeCheckerCallable
+from ._checkers import TypeCheckLookupCallback as TypeCheckLookupCallback
+from ._checkers import check_type_internal as check_type_internal
+from ._checkers import checker_lookup_functions as checker_lookup_functions
+from ._checkers import load_plugins as load_plugins
+from ._config import CollectionCheckStrategy as CollectionCheckStrategy
+from ._config import ForwardRefPolicy as ForwardRefPolicy
+from ._config import TypeCheckConfiguration as TypeCheckConfiguration
+from ._decorators import typechecked as typechecked
+from ._decorators import typeguard_ignore as typeguard_ignore
+from ._exceptions import InstrumentationWarning as InstrumentationWarning
+from ._exceptions import TypeCheckError as TypeCheckError
+from ._exceptions import TypeCheckWarning as TypeCheckWarning
+from ._exceptions import TypeHintWarning as TypeHintWarning
+from ._functions import TypeCheckFailCallback as TypeCheckFailCallback
+from ._functions import check_type as check_type
+from ._functions import warn_on_error as warn_on_error
+from ._importhook import ImportHookManager as ImportHookManager
+from ._importhook import TypeguardFinder as TypeguardFinder
+from ._importhook import install_import_hook as install_import_hook
+from ._memo import TypeCheckMemo as TypeCheckMemo
+from ._suppression import suppress_type_checks as suppress_type_checks
+from ._utils import Unset as Unset
+
+# Re-export imports so they look like they live directly in this package
+for value in list(locals().values()):
+    if getattr(value, "__module__", "").startswith(f"{__name__}."):
+        value.__module__ = __name__
+
+
+config: TypeCheckConfiguration
+
+
+def __getattr__(name: str) -> Any:
+    if name == "config":
+        from ._config import global_config
+
+        return global_config
+
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+# Automatically load checker lookup functions unless explicitly disabled
+if "TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD" not in os.environ:
+    load_plugins()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_checkers.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_checkers.py
new file mode 100644
index 0000000000000000000000000000000000000000..67dd5ad4dcbda70353b06fc08db962d1a41ba266
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_checkers.py
@@ -0,0 +1,993 @@
+from __future__ import annotations
+
+import collections.abc
+import inspect
+import sys
+import types
+import typing
+import warnings
+from enum import Enum
+from inspect import Parameter, isclass, isfunction
+from io import BufferedIOBase, IOBase, RawIOBase, TextIOBase
+from textwrap import indent
+from typing import (
+    IO,
+    AbstractSet,
+    Any,
+    BinaryIO,
+    Callable,
+    Dict,
+    ForwardRef,
+    List,
+    Mapping,
+    MutableMapping,
+    NewType,
+    Optional,
+    Sequence,
+    Set,
+    TextIO,
+    Tuple,
+    Type,
+    TypeVar,
+    Union,
+)
+from unittest.mock import Mock
+from weakref import WeakKeyDictionary
+
+try:
+    import typing_extensions
+except ImportError:
+    typing_extensions = None  # type: ignore[assignment]
+
+# Must use this because typing.is_typeddict does not recognize
+# TypedDict from typing_extensions, and as of version 4.12.0
+# typing_extensions.TypedDict is different from typing.TypedDict
+# on all versions.
+from typing_extensions import is_typeddict
+
+from ._config import ForwardRefPolicy
+from ._exceptions import TypeCheckError, TypeHintWarning
+from ._memo import TypeCheckMemo
+from ._utils import evaluate_forwardref, get_stacklevel, get_type_name, qualified_name
+
+if sys.version_info >= (3, 11):
+    from typing import (
+        Annotated,
+        NotRequired,
+        TypeAlias,
+        get_args,
+        get_origin,
+    )
+
+    SubclassableAny = Any
+else:
+    from typing_extensions import (
+        Annotated,
+        NotRequired,
+        TypeAlias,
+        get_args,
+        get_origin,
+    )
+    from typing_extensions import Any as SubclassableAny
+
+if sys.version_info >= (3, 10):
+    from importlib.metadata import entry_points
+    from typing import ParamSpec
+else:
+    from importlib_metadata import entry_points
+    from typing_extensions import ParamSpec
+
+TypeCheckerCallable: TypeAlias = Callable[
+    [Any, Any, Tuple[Any, ...], TypeCheckMemo], Any
+]
+TypeCheckLookupCallback: TypeAlias = Callable[
+    [Any, Tuple[Any, ...], Tuple[Any, ...]], Optional[TypeCheckerCallable]
+]
+
+checker_lookup_functions: list[TypeCheckLookupCallback] = []
+generic_alias_types: tuple[type, ...] = (type(List), type(List[Any]))
+if sys.version_info >= (3, 9):
+    generic_alias_types += (types.GenericAlias,)
+
+protocol_check_cache: WeakKeyDictionary[
+    type[Any], dict[type[Any], TypeCheckError | None]
+] = WeakKeyDictionary()
+
+# Sentinel
+_missing = object()
+
+# Lifted from mypy.sharedparse
+BINARY_MAGIC_METHODS = {
+    "__add__",
+    "__and__",
+    "__cmp__",
+    "__divmod__",
+    "__div__",
+    "__eq__",
+    "__floordiv__",
+    "__ge__",
+    "__gt__",
+    "__iadd__",
+    "__iand__",
+    "__idiv__",
+    "__ifloordiv__",
+    "__ilshift__",
+    "__imatmul__",
+    "__imod__",
+    "__imul__",
+    "__ior__",
+    "__ipow__",
+    "__irshift__",
+    "__isub__",
+    "__itruediv__",
+    "__ixor__",
+    "__le__",
+    "__lshift__",
+    "__lt__",
+    "__matmul__",
+    "__mod__",
+    "__mul__",
+    "__ne__",
+    "__or__",
+    "__pow__",
+    "__radd__",
+    "__rand__",
+    "__rdiv__",
+    "__rfloordiv__",
+    "__rlshift__",
+    "__rmatmul__",
+    "__rmod__",
+    "__rmul__",
+    "__ror__",
+    "__rpow__",
+    "__rrshift__",
+    "__rshift__",
+    "__rsub__",
+    "__rtruediv__",
+    "__rxor__",
+    "__sub__",
+    "__truediv__",
+    "__xor__",
+}
+
+
+def check_callable(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not callable(value):
+        raise TypeCheckError("is not callable")
+
+    if args:
+        try:
+            signature = inspect.signature(value)
+        except (TypeError, ValueError):
+            return
+
+        argument_types = args[0]
+        if isinstance(argument_types, list) and not any(
+            type(item) is ParamSpec for item in argument_types
+        ):
+            # The callable must not have keyword-only arguments without defaults
+            unfulfilled_kwonlyargs = [
+                param.name
+                for param in signature.parameters.values()
+                if param.kind == Parameter.KEYWORD_ONLY
+                and param.default == Parameter.empty
+            ]
+            if unfulfilled_kwonlyargs:
+                raise TypeCheckError(
+                    f"has mandatory keyword-only arguments in its declaration: "
+                    f'{", ".join(unfulfilled_kwonlyargs)}'
+                )
+
+            num_positional_args = num_mandatory_pos_args = 0
+            has_varargs = False
+            for param in signature.parameters.values():
+                if param.kind in (
+                    Parameter.POSITIONAL_ONLY,
+                    Parameter.POSITIONAL_OR_KEYWORD,
+                ):
+                    num_positional_args += 1
+                    if param.default is Parameter.empty:
+                        num_mandatory_pos_args += 1
+                elif param.kind == Parameter.VAR_POSITIONAL:
+                    has_varargs = True
+
+            if num_mandatory_pos_args > len(argument_types):
+                raise TypeCheckError(
+                    f"has too many mandatory positional arguments in its declaration; "
+                    f"expected {len(argument_types)} but {num_mandatory_pos_args} "
+                    f"mandatory positional argument(s) declared"
+                )
+            elif not has_varargs and num_positional_args < len(argument_types):
+                raise TypeCheckError(
+                    f"has too few arguments in its declaration; expected "
+                    f"{len(argument_types)} but {num_positional_args} argument(s) "
+                    f"declared"
+                )
+
+
+def check_mapping(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is Dict or origin_type is dict:
+        if not isinstance(value, dict):
+            raise TypeCheckError("is not a dict")
+    if origin_type is MutableMapping or origin_type is collections.abc.MutableMapping:
+        if not isinstance(value, collections.abc.MutableMapping):
+            raise TypeCheckError("is not a mutable mapping")
+    elif not isinstance(value, collections.abc.Mapping):
+        raise TypeCheckError("is not a mapping")
+
+    if args:
+        key_type, value_type = args
+        if key_type is not Any or value_type is not Any:
+            samples = memo.config.collection_check_strategy.iterate_samples(
+                value.items()
+            )
+            for k, v in samples:
+                try:
+                    check_type_internal(k, key_type, memo)
+                except TypeCheckError as exc:
+                    exc.append_path_element(f"key {k!r}")
+                    raise
+
+                try:
+                    check_type_internal(v, value_type, memo)
+                except TypeCheckError as exc:
+                    exc.append_path_element(f"value of key {k!r}")
+                    raise
+
+
+def check_typed_dict(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, dict):
+        raise TypeCheckError("is not a dict")
+
+    declared_keys = frozenset(origin_type.__annotations__)
+    if hasattr(origin_type, "__required_keys__"):
+        required_keys = set(origin_type.__required_keys__)
+    else:  # py3.8 and lower
+        required_keys = set(declared_keys) if origin_type.__total__ else set()
+
+    existing_keys = set(value)
+    extra_keys = existing_keys - declared_keys
+    if extra_keys:
+        keys_formatted = ", ".join(f'"{key}"' for key in sorted(extra_keys, key=repr))
+        raise TypeCheckError(f"has unexpected extra key(s): {keys_formatted}")
+
+    # Detect NotRequired fields which are hidden by get_type_hints()
+    type_hints: dict[str, type] = {}
+    for key, annotation in origin_type.__annotations__.items():
+        if isinstance(annotation, ForwardRef):
+            annotation = evaluate_forwardref(annotation, memo)
+            if get_origin(annotation) is NotRequired:
+                required_keys.discard(key)
+                annotation = get_args(annotation)[0]
+
+        type_hints[key] = annotation
+
+    missing_keys = required_keys - existing_keys
+    if missing_keys:
+        keys_formatted = ", ".join(f'"{key}"' for key in sorted(missing_keys, key=repr))
+        raise TypeCheckError(f"is missing required key(s): {keys_formatted}")
+
+    for key, argtype in type_hints.items():
+        argvalue = value.get(key, _missing)
+        if argvalue is not _missing:
+            try:
+                check_type_internal(argvalue, argtype, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"value of key {key!r}")
+                raise
+
+
+def check_list(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, list):
+        raise TypeCheckError("is not a list")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, v in enumerate(samples):
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_sequence(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, collections.abc.Sequence):
+        raise TypeCheckError("is not a sequence")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, v in enumerate(samples):
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_set(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is frozenset:
+        if not isinstance(value, frozenset):
+            raise TypeCheckError("is not a frozenset")
+    elif not isinstance(value, AbstractSet):
+        raise TypeCheckError("is not a set")
+
+    if args and args != (Any,):
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for v in samples:
+            try:
+                check_type_internal(v, args[0], memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"[{v}]")
+                raise
+
+
+def check_tuple(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    # Specialized check for NamedTuples
+    if field_types := getattr(origin_type, "__annotations__", None):
+        if not isinstance(value, origin_type):
+            raise TypeCheckError(
+                f"is not a named tuple of type {qualified_name(origin_type)}"
+            )
+
+        for name, field_type in field_types.items():
+            try:
+                check_type_internal(getattr(value, name), field_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"attribute {name!r}")
+                raise
+
+        return
+    elif not isinstance(value, tuple):
+        raise TypeCheckError("is not a tuple")
+
+    if args:
+        use_ellipsis = args[-1] is Ellipsis
+        tuple_params = args[: -1 if use_ellipsis else None]
+    else:
+        # Unparametrized Tuple or plain tuple
+        return
+
+    if use_ellipsis:
+        element_type = tuple_params[0]
+        samples = memo.config.collection_check_strategy.iterate_samples(value)
+        for i, element in enumerate(samples):
+            try:
+                check_type_internal(element, element_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+    elif tuple_params == ((),):
+        if value != ():
+            raise TypeCheckError("is not an empty tuple")
+    else:
+        if len(value) != len(tuple_params):
+            raise TypeCheckError(
+                f"has wrong number of elements (expected {len(tuple_params)}, got "
+                f"{len(value)} instead)"
+            )
+
+        for i, (element, element_type) in enumerate(zip(value, tuple_params)):
+            try:
+                check_type_internal(element, element_type, memo)
+            except TypeCheckError as exc:
+                exc.append_path_element(f"item {i}")
+                raise
+
+
+def check_union(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    errors: dict[str, TypeCheckError] = {}
+    try:
+        for type_ in args:
+            try:
+                check_type_internal(value, type_, memo)
+                return
+            except TypeCheckError as exc:
+                errors[get_type_name(type_)] = exc
+
+        formatted_errors = indent(
+            "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+        )
+    finally:
+        del errors  # avoid creating ref cycle
+    raise TypeCheckError(f"did not match any element in the union:\n{formatted_errors}")
+
+
+def check_uniontype(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    errors: dict[str, TypeCheckError] = {}
+    for type_ in args:
+        try:
+            check_type_internal(value, type_, memo)
+            return
+        except TypeCheckError as exc:
+            errors[get_type_name(type_)] = exc
+
+    formatted_errors = indent(
+        "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+    )
+    raise TypeCheckError(f"did not match any element in the union:\n{formatted_errors}")
+
+
+def check_class(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isclass(value) and not isinstance(value, generic_alias_types):
+        raise TypeCheckError("is not a class")
+
+    if not args:
+        return
+
+    if isinstance(args[0], ForwardRef):
+        expected_class = evaluate_forwardref(args[0], memo)
+    else:
+        expected_class = args[0]
+
+    if expected_class is Any:
+        return
+    elif getattr(expected_class, "_is_protocol", False):
+        check_protocol(value, expected_class, (), memo)
+    elif isinstance(expected_class, TypeVar):
+        check_typevar(value, expected_class, (), memo, subclass_check=True)
+    elif get_origin(expected_class) is Union:
+        errors: dict[str, TypeCheckError] = {}
+        for arg in get_args(expected_class):
+            if arg is Any:
+                return
+
+            try:
+                check_class(value, type, (arg,), memo)
+                return
+            except TypeCheckError as exc:
+                errors[get_type_name(arg)] = exc
+        else:
+            formatted_errors = indent(
+                "\n".join(f"{key}: {error}" for key, error in errors.items()), "  "
+            )
+            raise TypeCheckError(
+                f"did not match any element in the union:\n{formatted_errors}"
+            )
+    elif not issubclass(value, expected_class):  # type: ignore[arg-type]
+        raise TypeCheckError(f"is not a subclass of {qualified_name(expected_class)}")
+
+
+def check_newtype(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, origin_type.__supertype__, memo)
+
+
+def check_instance(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, origin_type):
+        raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+
+
+def check_typevar(
+    value: Any,
+    origin_type: TypeVar,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+    *,
+    subclass_check: bool = False,
+) -> None:
+    if origin_type.__bound__ is not None:
+        annotation = (
+            Type[origin_type.__bound__] if subclass_check else origin_type.__bound__
+        )
+        check_type_internal(value, annotation, memo)
+    elif origin_type.__constraints__:
+        for constraint in origin_type.__constraints__:
+            annotation = Type[constraint] if subclass_check else constraint
+            try:
+                check_type_internal(value, annotation, memo)
+            except TypeCheckError:
+                pass
+            else:
+                break
+        else:
+            formatted_constraints = ", ".join(
+                get_type_name(constraint) for constraint in origin_type.__constraints__
+            )
+            raise TypeCheckError(
+                f"does not match any of the constraints " f"({formatted_constraints})"
+            )
+
+
+if typing_extensions is None:
+
+    def _is_literal_type(typ: object) -> bool:
+        return typ is typing.Literal
+
+else:
+
+    def _is_literal_type(typ: object) -> bool:
+        return typ is typing.Literal or typ is typing_extensions.Literal
+
+
+def check_literal(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    def get_literal_args(literal_args: tuple[Any, ...]) -> tuple[Any, ...]:
+        retval: list[Any] = []
+        for arg in literal_args:
+            if _is_literal_type(get_origin(arg)):
+                retval.extend(get_literal_args(arg.__args__))
+            elif arg is None or isinstance(arg, (int, str, bytes, bool, Enum)):
+                retval.append(arg)
+            else:
+                raise TypeError(
+                    f"Illegal literal value: {arg}"
+                )  # TypeError here is deliberate
+
+        return tuple(retval)
+
+    final_args = tuple(get_literal_args(args))
+    try:
+        index = final_args.index(value)
+    except ValueError:
+        pass
+    else:
+        if type(final_args[index]) is type(value):
+            return
+
+    formatted_args = ", ".join(repr(arg) for arg in final_args)
+    raise TypeCheckError(f"is not any of ({formatted_args})") from None
+
+
+def check_literal_string(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, str, memo)
+
+
+def check_typeguard(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    check_type_internal(value, bool, memo)
+
+
+def check_none(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if value is not None:
+        raise TypeCheckError("is not None")
+
+
+def check_number(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is complex and not isinstance(value, (complex, float, int)):
+        raise TypeCheckError("is neither complex, float or int")
+    elif origin_type is float and not isinstance(value, (float, int)):
+        raise TypeCheckError("is neither float or int")
+
+
+def check_io(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if origin_type is TextIO or (origin_type is IO and args == (str,)):
+        if not isinstance(value, TextIOBase):
+            raise TypeCheckError("is not a text based I/O object")
+    elif origin_type is BinaryIO or (origin_type is IO and args == (bytes,)):
+        if not isinstance(value, (RawIOBase, BufferedIOBase)):
+            raise TypeCheckError("is not a binary I/O object")
+    elif not isinstance(value, IOBase):
+        raise TypeCheckError("is not an I/O object")
+
+
+def check_protocol(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    subject: type[Any] = value if isclass(value) else type(value)
+
+    if subject in protocol_check_cache:
+        result_map = protocol_check_cache[subject]
+        if origin_type in result_map:
+            if exc := result_map[origin_type]:
+                raise exc
+            else:
+                return
+
+    # Collect a set of methods and non-method attributes present in the protocol
+    ignored_attrs = set(dir(typing.Protocol)) | {
+        "__annotations__",
+        "__non_callable_proto_members__",
+    }
+    expected_methods: dict[str, tuple[Any, Any]] = {}
+    expected_noncallable_members: dict[str, Any] = {}
+    for attrname in dir(origin_type):
+        # Skip attributes present in typing.Protocol
+        if attrname in ignored_attrs:
+            continue
+
+        member = getattr(origin_type, attrname)
+        if callable(member):
+            signature = inspect.signature(member)
+            argtypes = [
+                (p.annotation if p.annotation is not Parameter.empty else Any)
+                for p in signature.parameters.values()
+                if p.kind is not Parameter.KEYWORD_ONLY
+            ] or Ellipsis
+            return_annotation = (
+                signature.return_annotation
+                if signature.return_annotation is not Parameter.empty
+                else Any
+            )
+            expected_methods[attrname] = argtypes, return_annotation
+        else:
+            expected_noncallable_members[attrname] = member
+
+    for attrname, annotation in typing.get_type_hints(origin_type).items():
+        expected_noncallable_members[attrname] = annotation
+
+    subject_annotations = typing.get_type_hints(subject)
+
+    # Check that all required methods are present and their signatures are compatible
+    result_map = protocol_check_cache.setdefault(subject, {})
+    try:
+        for attrname, callable_args in expected_methods.items():
+            try:
+                method = getattr(subject, attrname)
+            except AttributeError:
+                if attrname in subject_annotations:
+                    raise TypeCheckError(
+                        f"is not compatible with the {origin_type.__qualname__} protocol "
+                        f"because its {attrname!r} attribute is not a method"
+                    ) from None
+                else:
+                    raise TypeCheckError(
+                        f"is not compatible with the {origin_type.__qualname__} protocol "
+                        f"because it has no method named {attrname!r}"
+                    ) from None
+
+            if not callable(method):
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because its {attrname!r} attribute is not a callable"
+                )
+
+            # TODO: raise exception on added keyword-only arguments without defaults
+            try:
+                check_callable(method, Callable, callable_args, memo)
+            except TypeCheckError as exc:
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because its {attrname!r} method {exc}"
+                ) from None
+
+        # Check that all required non-callable members are present
+        for attrname in expected_noncallable_members:
+            # TODO: implement assignability checks for non-callable members
+            if attrname not in subject_annotations and not hasattr(subject, attrname):
+                raise TypeCheckError(
+                    f"is not compatible with the {origin_type.__qualname__} protocol "
+                    f"because it has no attribute named {attrname!r}"
+                )
+    except TypeCheckError as exc:
+        result_map[origin_type] = exc
+        raise
+    else:
+        result_map[origin_type] = None
+
+
+def check_byteslike(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, (bytearray, bytes, memoryview)):
+        raise TypeCheckError("is not bytes-like")
+
+
+def check_self(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if memo.self_type is None:
+        raise TypeCheckError("cannot be checked against Self outside of a method call")
+
+    if isclass(value):
+        if not issubclass(value, memo.self_type):
+            raise TypeCheckError(
+                f"is not an instance of the self type "
+                f"({qualified_name(memo.self_type)})"
+            )
+    elif not isinstance(value, memo.self_type):
+        raise TypeCheckError(
+            f"is not an instance of the self type ({qualified_name(memo.self_type)})"
+        )
+
+
+def check_paramspec(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    pass  # No-op for now
+
+
+def check_instanceof(
+    value: Any,
+    origin_type: Any,
+    args: tuple[Any, ...],
+    memo: TypeCheckMemo,
+) -> None:
+    if not isinstance(value, origin_type):
+        raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+
+
+def check_type_internal(
+    value: Any,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> None:
+    """
+    Check that the given object is compatible with the given type annotation.
+
+    This function should only be used by type checker callables. Applications should use
+    :func:`~.check_type` instead.
+
+    :param value: the value to check
+    :param annotation: the type annotation to check against
+    :param memo: a memo object containing configuration and information necessary for
+        looking up forward references
+    """
+
+    if isinstance(annotation, ForwardRef):
+        try:
+            annotation = evaluate_forwardref(annotation, memo)
+        except NameError:
+            if memo.config.forward_ref_policy is ForwardRefPolicy.ERROR:
+                raise
+            elif memo.config.forward_ref_policy is ForwardRefPolicy.WARN:
+                warnings.warn(
+                    f"Cannot resolve forward reference {annotation.__forward_arg__!r}",
+                    TypeHintWarning,
+                    stacklevel=get_stacklevel(),
+                )
+
+            return
+
+    if annotation is Any or annotation is SubclassableAny or isinstance(value, Mock):
+        return
+
+    # Skip type checks if value is an instance of a class that inherits from Any
+    if not isclass(value) and SubclassableAny in type(value).__bases__:
+        return
+
+    extras: tuple[Any, ...]
+    origin_type = get_origin(annotation)
+    if origin_type is Annotated:
+        annotation, *extras_ = get_args(annotation)
+        extras = tuple(extras_)
+        origin_type = get_origin(annotation)
+    else:
+        extras = ()
+
+    if origin_type is not None:
+        args = get_args(annotation)
+
+        # Compatibility hack to distinguish between unparametrized and empty tuple
+        # (tuple[()]), necessary due to https://github.com/python/cpython/issues/91137
+        if origin_type in (tuple, Tuple) and annotation is not Tuple and not args:
+            args = ((),)
+    else:
+        origin_type = annotation
+        args = ()
+
+    for lookup_func in checker_lookup_functions:
+        checker = lookup_func(origin_type, args, extras)
+        if checker:
+            checker(value, origin_type, args, memo)
+            return
+
+    if isclass(origin_type):
+        if not isinstance(value, origin_type):
+            raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}")
+    elif type(origin_type) is str:  # noqa: E721
+        warnings.warn(
+            f"Skipping type check against {origin_type!r}; this looks like a "
+            f"string-form forward reference imported from another module",
+            TypeHintWarning,
+            stacklevel=get_stacklevel(),
+        )
+
+
+# Equality checks are applied to these
+origin_type_checkers = {
+    bytes: check_byteslike,
+    AbstractSet: check_set,
+    BinaryIO: check_io,
+    Callable: check_callable,
+    collections.abc.Callable: check_callable,
+    complex: check_number,
+    dict: check_mapping,
+    Dict: check_mapping,
+    float: check_number,
+    frozenset: check_set,
+    IO: check_io,
+    list: check_list,
+    List: check_list,
+    typing.Literal: check_literal,
+    Mapping: check_mapping,
+    MutableMapping: check_mapping,
+    None: check_none,
+    collections.abc.Mapping: check_mapping,
+    collections.abc.MutableMapping: check_mapping,
+    Sequence: check_sequence,
+    collections.abc.Sequence: check_sequence,
+    collections.abc.Set: check_set,
+    set: check_set,
+    Set: check_set,
+    TextIO: check_io,
+    tuple: check_tuple,
+    Tuple: check_tuple,
+    type: check_class,
+    Type: check_class,
+    Union: check_union,
+}
+if sys.version_info >= (3, 10):
+    origin_type_checkers[types.UnionType] = check_uniontype
+    origin_type_checkers[typing.TypeGuard] = check_typeguard
+if sys.version_info >= (3, 11):
+    origin_type_checkers.update(
+        {typing.LiteralString: check_literal_string, typing.Self: check_self}
+    )
+if typing_extensions is not None:
+    # On some Python versions, these may simply be re-exports from typing,
+    # but exactly which Python versions is subject to change,
+    # so it's best to err on the safe side
+    # and update the dictionary on all Python versions
+    # if typing_extensions is installed
+    origin_type_checkers[typing_extensions.Literal] = check_literal
+    origin_type_checkers[typing_extensions.LiteralString] = check_literal_string
+    origin_type_checkers[typing_extensions.Self] = check_self
+    origin_type_checkers[typing_extensions.TypeGuard] = check_typeguard
+
+
+def builtin_checker_lookup(
+    origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...]
+) -> TypeCheckerCallable | None:
+    checker = origin_type_checkers.get(origin_type)
+    if checker is not None:
+        return checker
+    elif is_typeddict(origin_type):
+        return check_typed_dict
+    elif isclass(origin_type) and issubclass(
+        origin_type,
+        Tuple,  # type: ignore[arg-type]
+    ):
+        # NamedTuple
+        return check_tuple
+    elif getattr(origin_type, "_is_protocol", False):
+        return check_protocol
+    elif isinstance(origin_type, ParamSpec):
+        return check_paramspec
+    elif isinstance(origin_type, TypeVar):
+        return check_typevar
+    elif origin_type.__class__ is NewType:
+        # typing.NewType on Python 3.10+
+        return check_newtype
+    elif (
+        isfunction(origin_type)
+        and getattr(origin_type, "__module__", None) == "typing"
+        and getattr(origin_type, "__qualname__", "").startswith("NewType.")
+        and hasattr(origin_type, "__supertype__")
+    ):
+        # typing.NewType on Python 3.9 and below
+        return check_newtype
+
+    return None
+
+
+checker_lookup_functions.append(builtin_checker_lookup)
+
+
+def load_plugins() -> None:
+    """
+    Load all type checker lookup functions from entry points.
+
+    All entry points from the ``typeguard.checker_lookup`` group are loaded, and the
+    returned lookup functions are added to :data:`typeguard.checker_lookup_functions`.
+
+    .. note:: This function is called implicitly on import, unless the
+        ``TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD`` environment variable is present.
+    """
+
+    for ep in entry_points(group="typeguard.checker_lookup"):
+        try:
+            plugin = ep.load()
+        except Exception as exc:
+            warnings.warn(
+                f"Failed to load plugin {ep.name!r}: " f"{qualified_name(exc)}: {exc}",
+                stacklevel=2,
+            )
+            continue
+
+        if not callable(plugin):
+            warnings.warn(
+                f"Plugin {ep} returned a non-callable object: {plugin!r}", stacklevel=2
+            )
+            continue
+
+        checker_lookup_functions.insert(0, plugin)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_config.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..36efad53965488e7e003c265262db8d5d902a930
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_config.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from enum import Enum, auto
+from typing import TYPE_CHECKING, TypeVar
+
+if TYPE_CHECKING:
+    from ._functions import TypeCheckFailCallback
+
+T = TypeVar("T")
+
+
+class ForwardRefPolicy(Enum):
+    """
+    Defines how unresolved forward references are handled.
+
+    Members:
+
+    * ``ERROR``: propagate the :exc:`NameError` when the forward reference lookup fails
+    * ``WARN``: emit a :class:`~.TypeHintWarning` if the forward reference lookup fails
+    * ``IGNORE``: silently skip checks for unresolveable forward references
+    """
+
+    ERROR = auto()
+    WARN = auto()
+    IGNORE = auto()
+
+
+class CollectionCheckStrategy(Enum):
+    """
+    Specifies how thoroughly the contents of collections are type checked.
+
+    This has an effect on the following built-in checkers:
+
+    * ``AbstractSet``
+    * ``Dict``
+    * ``List``
+    * ``Mapping``
+    * ``Set``
+    * ``Tuple[, ...]`` (arbitrarily sized tuples)
+
+    Members:
+
+    * ``FIRST_ITEM``: check only the first item
+    * ``ALL_ITEMS``: check all items
+    """
+
+    FIRST_ITEM = auto()
+    ALL_ITEMS = auto()
+
+    def iterate_samples(self, collection: Iterable[T]) -> Iterable[T]:
+        if self is CollectionCheckStrategy.FIRST_ITEM:
+            try:
+                return [next(iter(collection))]
+            except StopIteration:
+                return ()
+        else:
+            return collection
+
+
+@dataclass
+class TypeCheckConfiguration:
+    """
+     You can change Typeguard's behavior with these settings.
+
+    .. attribute:: typecheck_fail_callback
+       :type: Callable[[TypeCheckError, TypeCheckMemo], Any]
+
+         Callable that is called when type checking fails.
+
+         Default: ``None`` (the :exc:`~.TypeCheckError` is raised directly)
+
+    .. attribute:: forward_ref_policy
+       :type: ForwardRefPolicy
+
+         Specifies what to do when a forward reference fails to resolve.
+
+         Default: ``WARN``
+
+    .. attribute:: collection_check_strategy
+       :type: CollectionCheckStrategy
+
+         Specifies how thoroughly the contents of collections (list, dict, etc.) are
+         type checked.
+
+         Default: ``FIRST_ITEM``
+
+    .. attribute:: debug_instrumentation
+       :type: bool
+
+         If set to ``True``, the code of modules or functions instrumented by typeguard
+         is printed to ``sys.stderr`` after the instrumentation is done
+
+         Requires Python 3.9 or newer.
+
+         Default: ``False``
+    """
+
+    forward_ref_policy: ForwardRefPolicy = ForwardRefPolicy.WARN
+    typecheck_fail_callback: TypeCheckFailCallback | None = None
+    collection_check_strategy: CollectionCheckStrategy = (
+        CollectionCheckStrategy.FIRST_ITEM
+    )
+    debug_instrumentation: bool = False
+
+
+global_config = TypeCheckConfiguration()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_decorators.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf3253351fe3b07af0b79f7c1ffac7b2d6127a19
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_decorators.py
@@ -0,0 +1,235 @@
+from __future__ import annotations
+
+import ast
+import inspect
+import sys
+from collections.abc import Sequence
+from functools import partial
+from inspect import isclass, isfunction
+from types import CodeType, FrameType, FunctionType
+from typing import TYPE_CHECKING, Any, Callable, ForwardRef, TypeVar, cast, overload
+from warnings import warn
+
+from ._config import CollectionCheckStrategy, ForwardRefPolicy, global_config
+from ._exceptions import InstrumentationWarning
+from ._functions import TypeCheckFailCallback
+from ._transformer import TypeguardTransformer
+from ._utils import Unset, function_name, get_stacklevel, is_method_of, unset
+
+if TYPE_CHECKING:
+    from typeshed.stdlib.types import _Cell
+
+    _F = TypeVar("_F")
+
+    def typeguard_ignore(f: _F) -> _F:
+        """This decorator is a noop during static type-checking."""
+        return f
+
+else:
+    from typing import no_type_check as typeguard_ignore  # noqa: F401
+
+T_CallableOrType = TypeVar("T_CallableOrType", bound=Callable[..., Any])
+
+
+def make_cell(value: object) -> _Cell:
+    return (lambda: value).__closure__[0]  # type: ignore[index]
+
+
+def find_target_function(
+    new_code: CodeType, target_path: Sequence[str], firstlineno: int
+) -> CodeType | None:
+    target_name = target_path[0]
+    for const in new_code.co_consts:
+        if isinstance(const, CodeType):
+            if const.co_name == target_name:
+                if const.co_firstlineno == firstlineno:
+                    return const
+                elif len(target_path) > 1:
+                    target_code = find_target_function(
+                        const, target_path[1:], firstlineno
+                    )
+                    if target_code:
+                        return target_code
+
+    return None
+
+
+def instrument(f: T_CallableOrType) -> FunctionType | str:
+    if not getattr(f, "__code__", None):
+        return "no code associated"
+    elif not getattr(f, "__module__", None):
+        return "__module__ attribute is not set"
+    elif f.__code__.co_filename == "":
+        return "cannot instrument functions defined in a REPL"
+    elif hasattr(f, "__wrapped__"):
+        return (
+            "@typechecked only supports instrumenting functions wrapped with "
+            "@classmethod, @staticmethod or @property"
+        )
+
+    target_path = [item for item in f.__qualname__.split(".") if item != ""]
+    module_source = inspect.getsource(sys.modules[f.__module__])
+    module_ast = ast.parse(module_source)
+    instrumentor = TypeguardTransformer(target_path, f.__code__.co_firstlineno)
+    instrumentor.visit(module_ast)
+
+    if not instrumentor.target_node or instrumentor.target_lineno is None:
+        return "instrumentor did not find the target function"
+
+    module_code = compile(module_ast, f.__code__.co_filename, "exec", dont_inherit=True)
+    new_code = find_target_function(
+        module_code, target_path, instrumentor.target_lineno
+    )
+    if not new_code:
+        return "cannot find the target function in the AST"
+
+    if global_config.debug_instrumentation and sys.version_info >= (3, 9):
+        # Find the matching AST node, then unparse it to source and print to stdout
+        print(
+            f"Source code of {f.__qualname__}() after instrumentation:"
+            "\n----------------------------------------------",
+            file=sys.stderr,
+        )
+        print(ast.unparse(instrumentor.target_node), file=sys.stderr)
+        print(
+            "----------------------------------------------",
+            file=sys.stderr,
+        )
+
+    closure = f.__closure__
+    if new_code.co_freevars != f.__code__.co_freevars:
+        # Create a new closure and find values for the new free variables
+        frame = cast(FrameType, inspect.currentframe())
+        frame = cast(FrameType, frame.f_back)
+        frame_locals = cast(FrameType, frame.f_back).f_locals
+        cells: list[_Cell] = []
+        for key in new_code.co_freevars:
+            if key in instrumentor.names_used_in_annotations:
+                # Find the value and make a new cell from it
+                value = frame_locals.get(key) or ForwardRef(key)
+                cells.append(make_cell(value))
+            else:
+                # Reuse the cell from the existing closure
+                assert f.__closure__
+                cells.append(f.__closure__[f.__code__.co_freevars.index(key)])
+
+        closure = tuple(cells)
+
+    new_function = FunctionType(new_code, f.__globals__, f.__name__, closure=closure)
+    new_function.__module__ = f.__module__
+    new_function.__name__ = f.__name__
+    new_function.__qualname__ = f.__qualname__
+    new_function.__annotations__ = f.__annotations__
+    new_function.__doc__ = f.__doc__
+    new_function.__defaults__ = f.__defaults__
+    new_function.__kwdefaults__ = f.__kwdefaults__
+    return new_function
+
+
+@overload
+def typechecked(
+    *,
+    forward_ref_policy: ForwardRefPolicy | Unset = unset,
+    typecheck_fail_callback: TypeCheckFailCallback | Unset = unset,
+    collection_check_strategy: CollectionCheckStrategy | Unset = unset,
+    debug_instrumentation: bool | Unset = unset,
+) -> Callable[[T_CallableOrType], T_CallableOrType]: ...
+
+
+@overload
+def typechecked(target: T_CallableOrType) -> T_CallableOrType: ...
+
+
+def typechecked(
+    target: T_CallableOrType | None = None,
+    *,
+    forward_ref_policy: ForwardRefPolicy | Unset = unset,
+    typecheck_fail_callback: TypeCheckFailCallback | Unset = unset,
+    collection_check_strategy: CollectionCheckStrategy | Unset = unset,
+    debug_instrumentation: bool | Unset = unset,
+) -> Any:
+    """
+    Instrument the target function to perform run-time type checking.
+
+    This decorator recompiles the target function, injecting code to type check
+    arguments, return values, yield values (excluding ``yield from``) and assignments to
+    annotated local variables.
+
+    This can also be used as a class decorator. This will instrument all type annotated
+    methods, including :func:`@classmethod `,
+    :func:`@staticmethod `,  and :class:`@property ` decorated
+    methods in the class.
+
+    .. note:: When Python is run in optimized mode (``-O`` or ``-OO``, this decorator
+        is a no-op). This is a feature meant for selectively introducing type checking
+        into a code base where the checks aren't meant to be run in production.
+
+    :param target: the function or class to enable type checking for
+    :param forward_ref_policy: override for
+        :attr:`.TypeCheckConfiguration.forward_ref_policy`
+    :param typecheck_fail_callback: override for
+        :attr:`.TypeCheckConfiguration.typecheck_fail_callback`
+    :param collection_check_strategy: override for
+        :attr:`.TypeCheckConfiguration.collection_check_strategy`
+    :param debug_instrumentation: override for
+        :attr:`.TypeCheckConfiguration.debug_instrumentation`
+
+    """
+    if target is None:
+        return partial(
+            typechecked,
+            forward_ref_policy=forward_ref_policy,
+            typecheck_fail_callback=typecheck_fail_callback,
+            collection_check_strategy=collection_check_strategy,
+            debug_instrumentation=debug_instrumentation,
+        )
+
+    if not __debug__:
+        return target
+
+    if isclass(target):
+        for key, attr in target.__dict__.items():
+            if is_method_of(attr, target):
+                retval = instrument(attr)
+                if isfunction(retval):
+                    setattr(target, key, retval)
+            elif isinstance(attr, (classmethod, staticmethod)):
+                if is_method_of(attr.__func__, target):
+                    retval = instrument(attr.__func__)
+                    if isfunction(retval):
+                        wrapper = attr.__class__(retval)
+                        setattr(target, key, wrapper)
+            elif isinstance(attr, property):
+                kwargs: dict[str, Any] = dict(doc=attr.__doc__)
+                for name in ("fset", "fget", "fdel"):
+                    property_func = kwargs[name] = getattr(attr, name)
+                    if is_method_of(property_func, target):
+                        retval = instrument(property_func)
+                        if isfunction(retval):
+                            kwargs[name] = retval
+
+                setattr(target, key, attr.__class__(**kwargs))
+
+        return target
+
+    # Find either the first Python wrapper or the actual function
+    wrapper_class: (
+        type[classmethod[Any, Any, Any]] | type[staticmethod[Any, Any]] | None
+    ) = None
+    if isinstance(target, (classmethod, staticmethod)):
+        wrapper_class = target.__class__
+        target = target.__func__
+
+    retval = instrument(target)
+    if isinstance(retval, str):
+        warn(
+            f"{retval} -- not typechecking {function_name(target)}",
+            InstrumentationWarning,
+            stacklevel=get_stacklevel(),
+        )
+        return target
+
+    if wrapper_class is None:
+        return retval
+    else:
+        return wrapper_class(retval)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_exceptions.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..625437a64990b5fae898c9c98fe9a7bd6be90cfb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_exceptions.py
@@ -0,0 +1,42 @@
+from collections import deque
+from typing import Deque
+
+
+class TypeHintWarning(UserWarning):
+    """
+    A warning that is emitted when a type hint in string form could not be resolved to
+    an actual type.
+    """
+
+
+class TypeCheckWarning(UserWarning):
+    """Emitted by typeguard's type checkers when a type mismatch is detected."""
+
+    def __init__(self, message: str):
+        super().__init__(message)
+
+
+class InstrumentationWarning(UserWarning):
+    """Emitted when there's a problem with instrumenting a function for type checks."""
+
+    def __init__(self, message: str):
+        super().__init__(message)
+
+
+class TypeCheckError(Exception):
+    """
+    Raised by typeguard's type checkers when a type mismatch is detected.
+    """
+
+    def __init__(self, message: str):
+        super().__init__(message)
+        self._path: Deque[str] = deque()
+
+    def append_path_element(self, element: str) -> None:
+        self._path.append(element)
+
+    def __str__(self) -> str:
+        if self._path:
+            return " of ".join(self._path) + " " + str(self.args[0])
+        else:
+            return str(self.args[0])
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_functions.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..28497856a325e1b00dbe4aadfd2ed1c6082cd23a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_functions.py
@@ -0,0 +1,308 @@
+from __future__ import annotations
+
+import sys
+import warnings
+from typing import Any, Callable, NoReturn, TypeVar, Union, overload
+
+from . import _suppression
+from ._checkers import BINARY_MAGIC_METHODS, check_type_internal
+from ._config import (
+    CollectionCheckStrategy,
+    ForwardRefPolicy,
+    TypeCheckConfiguration,
+)
+from ._exceptions import TypeCheckError, TypeCheckWarning
+from ._memo import TypeCheckMemo
+from ._utils import get_stacklevel, qualified_name
+
+if sys.version_info >= (3, 11):
+    from typing import Literal, Never, TypeAlias
+else:
+    from typing_extensions import Literal, Never, TypeAlias
+
+T = TypeVar("T")
+TypeCheckFailCallback: TypeAlias = Callable[[TypeCheckError, TypeCheckMemo], Any]
+
+
+@overload
+def check_type(
+    value: object,
+    expected_type: type[T],
+    *,
+    forward_ref_policy: ForwardRefPolicy = ...,
+    typecheck_fail_callback: TypeCheckFailCallback | None = ...,
+    collection_check_strategy: CollectionCheckStrategy = ...,
+) -> T: ...
+
+
+@overload
+def check_type(
+    value: object,
+    expected_type: Any,
+    *,
+    forward_ref_policy: ForwardRefPolicy = ...,
+    typecheck_fail_callback: TypeCheckFailCallback | None = ...,
+    collection_check_strategy: CollectionCheckStrategy = ...,
+) -> Any: ...
+
+
+def check_type(
+    value: object,
+    expected_type: Any,
+    *,
+    forward_ref_policy: ForwardRefPolicy = TypeCheckConfiguration().forward_ref_policy,
+    typecheck_fail_callback: TypeCheckFailCallback | None = (
+        TypeCheckConfiguration().typecheck_fail_callback
+    ),
+    collection_check_strategy: CollectionCheckStrategy = (
+        TypeCheckConfiguration().collection_check_strategy
+    ),
+) -> Any:
+    """
+    Ensure that ``value`` matches ``expected_type``.
+
+    The types from the :mod:`typing` module do not support :func:`isinstance` or
+    :func:`issubclass` so a number of type specific checks are required. This function
+    knows which checker to call for which type.
+
+    This function wraps :func:`~.check_type_internal` in the following ways:
+
+    * Respects type checking suppression (:func:`~.suppress_type_checks`)
+    * Forms a :class:`~.TypeCheckMemo` from the current stack frame
+    * Calls the configured type check fail callback if the check fails
+
+    Note that this function is independent of the globally shared configuration in
+    :data:`typeguard.config`. This means that usage within libraries is safe from being
+    affected configuration changes made by other libraries or by the integrating
+    application. Instead, configuration options have the same default values as their
+    corresponding fields in :class:`TypeCheckConfiguration`.
+
+    :param value: value to be checked against ``expected_type``
+    :param expected_type: a class or generic type instance, or a tuple of such things
+    :param forward_ref_policy: see :attr:`TypeCheckConfiguration.forward_ref_policy`
+    :param typecheck_fail_callback:
+        see :attr`TypeCheckConfiguration.typecheck_fail_callback`
+    :param collection_check_strategy:
+        see :attr:`TypeCheckConfiguration.collection_check_strategy`
+    :return: ``value``, unmodified
+    :raises TypeCheckError: if there is a type mismatch
+
+    """
+    if type(expected_type) is tuple:
+        expected_type = Union[expected_type]
+
+    config = TypeCheckConfiguration(
+        forward_ref_policy=forward_ref_policy,
+        typecheck_fail_callback=typecheck_fail_callback,
+        collection_check_strategy=collection_check_strategy,
+    )
+
+    if _suppression.type_checks_suppressed or expected_type is Any:
+        return value
+
+    frame = sys._getframe(1)
+    memo = TypeCheckMemo(frame.f_globals, frame.f_locals, config=config)
+    try:
+        check_type_internal(value, expected_type, memo)
+    except TypeCheckError as exc:
+        exc.append_path_element(qualified_name(value, add_class_prefix=True))
+        if config.typecheck_fail_callback:
+            config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return value
+
+
+def check_argument_types(
+    func_name: str,
+    arguments: dict[str, tuple[Any, Any]],
+    memo: TypeCheckMemo,
+) -> Literal[True]:
+    if _suppression.type_checks_suppressed:
+        return True
+
+    for argname, (value, annotation) in arguments.items():
+        if annotation is NoReturn or annotation is Never:
+            exc = TypeCheckError(
+                f"{func_name}() was declared never to be called but it was"
+            )
+            if memo.config.typecheck_fail_callback:
+                memo.config.typecheck_fail_callback(exc, memo)
+            else:
+                raise exc
+
+        try:
+            check_type_internal(value, annotation, memo)
+        except TypeCheckError as exc:
+            qualname = qualified_name(value, add_class_prefix=True)
+            exc.append_path_element(f'argument "{argname}" ({qualname})')
+            if memo.config.typecheck_fail_callback:
+                memo.config.typecheck_fail_callback(exc, memo)
+            else:
+                raise
+
+    return True
+
+
+def check_return_type(
+    func_name: str,
+    retval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return retval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(f"{func_name}() was declared never to return but it did")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(retval, annotation, memo)
+    except TypeCheckError as exc:
+        # Allow NotImplemented if this is a binary magic method (__eq__() et al)
+        if retval is NotImplemented and annotation is bool:
+            # This does (and cannot) not check if it's actually a method
+            func_name = func_name.rsplit(".", 1)[-1]
+            if func_name in BINARY_MAGIC_METHODS:
+                return retval
+
+        qualname = qualified_name(retval, add_class_prefix=True)
+        exc.append_path_element(f"the return value ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return retval
+
+
+def check_send_type(
+    func_name: str,
+    sendval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return sendval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(
+            f"{func_name}() was declared never to be sent a value to but it was"
+        )
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(sendval, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(sendval, add_class_prefix=True)
+        exc.append_path_element(f"the value sent to generator ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return sendval
+
+
+def check_yield_type(
+    func_name: str,
+    yieldval: T,
+    annotation: Any,
+    memo: TypeCheckMemo,
+) -> T:
+    if _suppression.type_checks_suppressed:
+        return yieldval
+
+    if annotation is NoReturn or annotation is Never:
+        exc = TypeCheckError(f"{func_name}() was declared never to yield but it did")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise exc
+
+    try:
+        check_type_internal(yieldval, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(yieldval, add_class_prefix=True)
+        exc.append_path_element(f"the yielded value ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return yieldval
+
+
+def check_variable_assignment(
+    value: object, varname: str, annotation: Any, memo: TypeCheckMemo
+) -> Any:
+    if _suppression.type_checks_suppressed:
+        return value
+
+    try:
+        check_type_internal(value, annotation, memo)
+    except TypeCheckError as exc:
+        qualname = qualified_name(value, add_class_prefix=True)
+        exc.append_path_element(f"value assigned to {varname} ({qualname})")
+        if memo.config.typecheck_fail_callback:
+            memo.config.typecheck_fail_callback(exc, memo)
+        else:
+            raise
+
+    return value
+
+
+def check_multi_variable_assignment(
+    value: Any, targets: list[dict[str, Any]], memo: TypeCheckMemo
+) -> Any:
+    if max(len(target) for target in targets) == 1:
+        iterated_values = [value]
+    else:
+        iterated_values = list(value)
+
+    if not _suppression.type_checks_suppressed:
+        for expected_types in targets:
+            value_index = 0
+            for ann_index, (varname, expected_type) in enumerate(
+                expected_types.items()
+            ):
+                if varname.startswith("*"):
+                    varname = varname[1:]
+                    keys_left = len(expected_types) - 1 - ann_index
+                    next_value_index = len(iterated_values) - keys_left
+                    obj: object = iterated_values[value_index:next_value_index]
+                    value_index = next_value_index
+                else:
+                    obj = iterated_values[value_index]
+                    value_index += 1
+
+                try:
+                    check_type_internal(obj, expected_type, memo)
+                except TypeCheckError as exc:
+                    qualname = qualified_name(obj, add_class_prefix=True)
+                    exc.append_path_element(f"value assigned to {varname} ({qualname})")
+                    if memo.config.typecheck_fail_callback:
+                        memo.config.typecheck_fail_callback(exc, memo)
+                    else:
+                        raise
+
+    return iterated_values[0] if len(iterated_values) == 1 else iterated_values
+
+
+def warn_on_error(exc: TypeCheckError, memo: TypeCheckMemo) -> None:
+    """
+    Emit a warning on a type mismatch.
+
+    This is intended to be used as an error handler in
+    :attr:`TypeCheckConfiguration.typecheck_fail_callback`.
+
+    """
+    warnings.warn(TypeCheckWarning(str(exc)), stacklevel=get_stacklevel())
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_importhook.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_importhook.py
new file mode 100644
index 0000000000000000000000000000000000000000..8590540a5a2ace23bbfc8272aca8e066740474a6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_importhook.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+import ast
+import sys
+import types
+from collections.abc import Callable, Iterable
+from importlib.abc import MetaPathFinder
+from importlib.machinery import ModuleSpec, SourceFileLoader
+from importlib.util import cache_from_source, decode_source
+from inspect import isclass
+from os import PathLike
+from types import CodeType, ModuleType, TracebackType
+from typing import Sequence, TypeVar
+from unittest.mock import patch
+
+from ._config import global_config
+from ._transformer import TypeguardTransformer
+
+if sys.version_info >= (3, 12):
+    from collections.abc import Buffer
+else:
+    from typing_extensions import Buffer
+
+if sys.version_info >= (3, 11):
+    from typing import ParamSpec
+else:
+    from typing_extensions import ParamSpec
+
+if sys.version_info >= (3, 10):
+    from importlib.metadata import PackageNotFoundError, version
+else:
+    from importlib_metadata import PackageNotFoundError, version
+
+try:
+    OPTIMIZATION = "typeguard" + "".join(version("typeguard").split(".")[:3])
+except PackageNotFoundError:
+    OPTIMIZATION = "typeguard"
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+# The name of this function is magical
+def _call_with_frames_removed(
+    f: Callable[P, T], *args: P.args, **kwargs: P.kwargs
+) -> T:
+    return f(*args, **kwargs)
+
+
+def optimized_cache_from_source(path: str, debug_override: bool | None = None) -> str:
+    return cache_from_source(path, debug_override, optimization=OPTIMIZATION)
+
+
+class TypeguardLoader(SourceFileLoader):
+    @staticmethod
+    def source_to_code(
+        data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
+        path: Buffer | str | PathLike[str] = "",
+    ) -> CodeType:
+        if isinstance(data, (ast.Module, ast.Expression, ast.Interactive)):
+            tree = data
+        else:
+            if isinstance(data, str):
+                source = data
+            else:
+                source = decode_source(data)
+
+            tree = _call_with_frames_removed(
+                ast.parse,
+                source,
+                path,
+                "exec",
+            )
+
+        tree = TypeguardTransformer().visit(tree)
+        ast.fix_missing_locations(tree)
+
+        if global_config.debug_instrumentation and sys.version_info >= (3, 9):
+            print(
+                f"Source code of {path!r} after instrumentation:\n"
+                "----------------------------------------------",
+                file=sys.stderr,
+            )
+            print(ast.unparse(tree), file=sys.stderr)
+            print("----------------------------------------------", file=sys.stderr)
+
+        return _call_with_frames_removed(
+            compile, tree, path, "exec", 0, dont_inherit=True
+        )
+
+    def exec_module(self, module: ModuleType) -> None:
+        # Use a custom optimization marker – the import lock should make this monkey
+        # patch safe
+        with patch(
+            "importlib._bootstrap_external.cache_from_source",
+            optimized_cache_from_source,
+        ):
+            super().exec_module(module)
+
+
+class TypeguardFinder(MetaPathFinder):
+    """
+    Wraps another path finder and instruments the module with
+    :func:`@typechecked ` if :meth:`should_instrument` returns
+    ``True``.
+
+    Should not be used directly, but rather via :func:`~.install_import_hook`.
+
+    .. versionadded:: 2.6
+    """
+
+    def __init__(self, packages: list[str] | None, original_pathfinder: MetaPathFinder):
+        self.packages = packages
+        self._original_pathfinder = original_pathfinder
+
+    def find_spec(
+        self,
+        fullname: str,
+        path: Sequence[str] | None,
+        target: types.ModuleType | None = None,
+    ) -> ModuleSpec | None:
+        if self.should_instrument(fullname):
+            spec = self._original_pathfinder.find_spec(fullname, path, target)
+            if spec is not None and isinstance(spec.loader, SourceFileLoader):
+                spec.loader = TypeguardLoader(spec.loader.name, spec.loader.path)
+                return spec
+
+        return None
+
+    def should_instrument(self, module_name: str) -> bool:
+        """
+        Determine whether the module with the given name should be instrumented.
+
+        :param module_name: full name of the module that is about to be imported (e.g.
+            ``xyz.abc``)
+
+        """
+        if self.packages is None:
+            return True
+
+        for package in self.packages:
+            if module_name == package or module_name.startswith(package + "."):
+                return True
+
+        return False
+
+
+class ImportHookManager:
+    """
+    A handle that can be used to uninstall the Typeguard import hook.
+    """
+
+    def __init__(self, hook: MetaPathFinder):
+        self.hook = hook
+
+    def __enter__(self) -> None:
+        pass
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException],
+        exc_val: BaseException,
+        exc_tb: TracebackType,
+    ) -> None:
+        self.uninstall()
+
+    def uninstall(self) -> None:
+        """Uninstall the import hook."""
+        try:
+            sys.meta_path.remove(self.hook)
+        except ValueError:
+            pass  # already removed
+
+
+def install_import_hook(
+    packages: Iterable[str] | None = None,
+    *,
+    cls: type[TypeguardFinder] = TypeguardFinder,
+) -> ImportHookManager:
+    """
+    Install an import hook that instruments functions for automatic type checking.
+
+    This only affects modules loaded **after** this hook has been installed.
+
+    :param packages: an iterable of package names to instrument, or ``None`` to
+        instrument all packages
+    :param cls: a custom meta path finder class
+    :return: a context manager that uninstalls the hook on exit (or when you call
+        ``.uninstall()``)
+
+    .. versionadded:: 2.6
+
+    """
+    if packages is None:
+        target_packages: list[str] | None = None
+    elif isinstance(packages, str):
+        target_packages = [packages]
+    else:
+        target_packages = list(packages)
+
+    for finder in sys.meta_path:
+        if (
+            isclass(finder)
+            and finder.__name__ == "PathFinder"
+            and hasattr(finder, "find_spec")
+        ):
+            break
+    else:
+        raise RuntimeError("Cannot find a PathFinder in sys.meta_path")
+
+    hook = cls(target_packages, finder)
+    sys.meta_path.insert(0, hook)
+    return ImportHookManager(hook)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_memo.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_memo.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d0d80c66d788e2f8f5e24ce14249319c54054c0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_memo.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import Any
+
+from typeguard._config import TypeCheckConfiguration, global_config
+
+
+class TypeCheckMemo:
+    """
+    Contains information necessary for type checkers to do their work.
+
+    .. attribute:: globals
+       :type: dict[str, Any]
+
+        Dictionary of global variables to use for resolving forward references.
+
+    .. attribute:: locals
+       :type: dict[str, Any]
+
+        Dictionary of local variables to use for resolving forward references.
+
+    .. attribute:: self_type
+       :type: type | None
+
+        When running type checks within an instance method or class method, this is the
+        class object that the first argument (usually named ``self`` or ``cls``) refers
+        to.
+
+    .. attribute:: config
+       :type: TypeCheckConfiguration
+
+         Contains the configuration for a particular set of type checking operations.
+    """
+
+    __slots__ = "globals", "locals", "self_type", "config"
+
+    def __init__(
+        self,
+        globals: dict[str, Any],
+        locals: dict[str, Any],
+        *,
+        self_type: type | None = None,
+        config: TypeCheckConfiguration = global_config,
+    ):
+        self.globals = globals
+        self.locals = locals
+        self.self_type = self_type
+        self.config = config
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b2f494ec7dbe5333c2798c0fcebb83cc3ac9907
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_pytest_plugin.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import sys
+import warnings
+from typing import TYPE_CHECKING, Any, Literal
+
+from typeguard._config import CollectionCheckStrategy, ForwardRefPolicy, global_config
+from typeguard._exceptions import InstrumentationWarning
+from typeguard._importhook import install_import_hook
+from typeguard._utils import qualified_name, resolve_reference
+
+if TYPE_CHECKING:
+    from pytest import Config, Parser
+
+
+def pytest_addoption(parser: Parser) -> None:
+    def add_ini_option(
+        opt_type: (
+            Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None
+        ),
+    ) -> None:
+        parser.addini(
+            group.options[-1].names()[0][2:],
+            group.options[-1].attrs()["help"],
+            opt_type,
+        )
+
+    group = parser.getgroup("typeguard")
+    group.addoption(
+        "--typeguard-packages",
+        action="store",
+        help="comma separated name list of packages and modules to instrument for "
+        "type checking, or :all: to instrument all modules loaded after typeguard",
+    )
+    add_ini_option("linelist")
+
+    group.addoption(
+        "--typeguard-debug-instrumentation",
+        action="store_true",
+        help="print all instrumented code to stderr",
+    )
+    add_ini_option("bool")
+
+    group.addoption(
+        "--typeguard-typecheck-fail-callback",
+        action="store",
+        help=(
+            "a module:varname (e.g. typeguard:warn_on_error) reference to a function "
+            "that is called (with the exception, and memo object as arguments) to "
+            "handle a TypeCheckError"
+        ),
+    )
+    add_ini_option("string")
+
+    group.addoption(
+        "--typeguard-forward-ref-policy",
+        action="store",
+        choices=list(ForwardRefPolicy.__members__),
+        help=(
+            "determines how to deal with unresolveable forward references in type "
+            "annotations"
+        ),
+    )
+    add_ini_option("string")
+
+    group.addoption(
+        "--typeguard-collection-check-strategy",
+        action="store",
+        choices=list(CollectionCheckStrategy.__members__),
+        help="determines how thoroughly to check collections (list, dict, etc)",
+    )
+    add_ini_option("string")
+
+
+def pytest_configure(config: Config) -> None:
+    def getoption(name: str) -> Any:
+        return config.getoption(name.replace("-", "_")) or config.getini(name)
+
+    packages: list[str] | None = []
+    if packages_option := config.getoption("typeguard_packages"):
+        packages = [pkg.strip() for pkg in packages_option.split(",")]
+    elif packages_ini := config.getini("typeguard-packages"):
+        packages = packages_ini
+
+    if packages:
+        if packages == [":all:"]:
+            packages = None
+        else:
+            already_imported_packages = sorted(
+                package for package in packages if package in sys.modules
+            )
+            if already_imported_packages:
+                warnings.warn(
+                    f"typeguard cannot check these packages because they are already "
+                    f"imported: {', '.join(already_imported_packages)}",
+                    InstrumentationWarning,
+                    stacklevel=1,
+                )
+
+        install_import_hook(packages=packages)
+
+    debug_option = getoption("typeguard-debug-instrumentation")
+    if debug_option:
+        global_config.debug_instrumentation = True
+
+    fail_callback_option = getoption("typeguard-typecheck-fail-callback")
+    if fail_callback_option:
+        callback = resolve_reference(fail_callback_option)
+        if not callable(callback):
+            raise TypeError(
+                f"{fail_callback_option} ({qualified_name(callback.__class__)}) is not "
+                f"a callable"
+            )
+
+        global_config.typecheck_fail_callback = callback
+
+    forward_ref_policy_option = getoption("typeguard-forward-ref-policy")
+    if forward_ref_policy_option:
+        forward_ref_policy = ForwardRefPolicy.__members__[forward_ref_policy_option]
+        global_config.forward_ref_policy = forward_ref_policy
+
+    collection_check_strategy_option = getoption("typeguard-collection-check-strategy")
+    if collection_check_strategy_option:
+        collection_check_strategy = CollectionCheckStrategy.__members__[
+            collection_check_strategy_option
+        ]
+        global_config.collection_check_strategy = collection_check_strategy
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_suppression.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_suppression.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbbfbfbe8ef364d45a1db581562c73b323819b84
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_suppression.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import sys
+from collections.abc import Callable, Generator
+from contextlib import contextmanager
+from functools import update_wrapper
+from threading import Lock
+from typing import ContextManager, TypeVar, overload
+
+if sys.version_info >= (3, 10):
+    from typing import ParamSpec
+else:
+    from typing_extensions import ParamSpec
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+type_checks_suppressed = 0
+type_checks_suppress_lock = Lock()
+
+
+@overload
+def suppress_type_checks(func: Callable[P, T]) -> Callable[P, T]: ...
+
+
+@overload
+def suppress_type_checks() -> ContextManager[None]: ...
+
+
+def suppress_type_checks(
+    func: Callable[P, T] | None = None,
+) -> Callable[P, T] | ContextManager[None]:
+    """
+    Temporarily suppress all type checking.
+
+    This function has two operating modes, based on how it's used:
+
+    #. as a context manager (``with suppress_type_checks(): ...``)
+    #. as a decorator (``@suppress_type_checks``)
+
+    When used as a context manager, :func:`check_type` and any automatically
+    instrumented functions skip the actual type checking. These context managers can be
+    nested.
+
+    When used as a decorator, all type checking is suppressed while the function is
+    running.
+
+    Type checking will resume once no more context managers are active and no decorated
+    functions are running.
+
+    Both operating modes are thread-safe.
+
+    """
+
+    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
+        global type_checks_suppressed
+
+        with type_checks_suppress_lock:
+            type_checks_suppressed += 1
+
+        assert func is not None
+        try:
+            return func(*args, **kwargs)
+        finally:
+            with type_checks_suppress_lock:
+                type_checks_suppressed -= 1
+
+    def cm() -> Generator[None, None, None]:
+        global type_checks_suppressed
+
+        with type_checks_suppress_lock:
+            type_checks_suppressed += 1
+
+        try:
+            yield
+        finally:
+            with type_checks_suppress_lock:
+                type_checks_suppressed -= 1
+
+    if func is None:
+        # Context manager mode
+        return contextmanager(cm)()
+    else:
+        # Decorator mode
+        update_wrapper(wrapper, func)
+        return wrapper
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_transformer.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..13ac3630e6c29ca32b2a84a3e6a85665b439cedf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_transformer.py
@@ -0,0 +1,1229 @@
+from __future__ import annotations
+
+import ast
+import builtins
+import sys
+import typing
+from ast import (
+    AST,
+    Add,
+    AnnAssign,
+    Assign,
+    AsyncFunctionDef,
+    Attribute,
+    AugAssign,
+    BinOp,
+    BitAnd,
+    BitOr,
+    BitXor,
+    Call,
+    ClassDef,
+    Constant,
+    Dict,
+    Div,
+    Expr,
+    Expression,
+    FloorDiv,
+    FunctionDef,
+    If,
+    Import,
+    ImportFrom,
+    Index,
+    List,
+    Load,
+    LShift,
+    MatMult,
+    Mod,
+    Module,
+    Mult,
+    Name,
+    NamedExpr,
+    NodeTransformer,
+    NodeVisitor,
+    Pass,
+    Pow,
+    Return,
+    RShift,
+    Starred,
+    Store,
+    Sub,
+    Subscript,
+    Tuple,
+    Yield,
+    YieldFrom,
+    alias,
+    copy_location,
+    expr,
+    fix_missing_locations,
+    keyword,
+    walk,
+)
+from collections import defaultdict
+from collections.abc import Generator, Sequence
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import dataclass, field
+from typing import Any, ClassVar, cast, overload
+
+generator_names = (
+    "typing.Generator",
+    "collections.abc.Generator",
+    "typing.Iterator",
+    "collections.abc.Iterator",
+    "typing.Iterable",
+    "collections.abc.Iterable",
+    "typing.AsyncIterator",
+    "collections.abc.AsyncIterator",
+    "typing.AsyncIterable",
+    "collections.abc.AsyncIterable",
+    "typing.AsyncGenerator",
+    "collections.abc.AsyncGenerator",
+)
+anytype_names = (
+    "typing.Any",
+    "typing_extensions.Any",
+)
+literal_names = (
+    "typing.Literal",
+    "typing_extensions.Literal",
+)
+annotated_names = (
+    "typing.Annotated",
+    "typing_extensions.Annotated",
+)
+ignore_decorators = (
+    "typing.no_type_check",
+    "typeguard.typeguard_ignore",
+)
+aug_assign_functions = {
+    Add: "iadd",
+    Sub: "isub",
+    Mult: "imul",
+    MatMult: "imatmul",
+    Div: "itruediv",
+    FloorDiv: "ifloordiv",
+    Mod: "imod",
+    Pow: "ipow",
+    LShift: "ilshift",
+    RShift: "irshift",
+    BitAnd: "iand",
+    BitXor: "ixor",
+    BitOr: "ior",
+}
+
+
+@dataclass
+class TransformMemo:
+    node: Module | ClassDef | FunctionDef | AsyncFunctionDef | None
+    parent: TransformMemo | None
+    path: tuple[str, ...]
+    joined_path: Constant = field(init=False)
+    return_annotation: expr | None = None
+    yield_annotation: expr | None = None
+    send_annotation: expr | None = None
+    is_async: bool = False
+    local_names: set[str] = field(init=False, default_factory=set)
+    imported_names: dict[str, str] = field(init=False, default_factory=dict)
+    ignored_names: set[str] = field(init=False, default_factory=set)
+    load_names: defaultdict[str, dict[str, Name]] = field(
+        init=False, default_factory=lambda: defaultdict(dict)
+    )
+    has_yield_expressions: bool = field(init=False, default=False)
+    has_return_expressions: bool = field(init=False, default=False)
+    memo_var_name: Name | None = field(init=False, default=None)
+    should_instrument: bool = field(init=False, default=True)
+    variable_annotations: dict[str, expr] = field(init=False, default_factory=dict)
+    configuration_overrides: dict[str, Any] = field(init=False, default_factory=dict)
+    code_inject_index: int = field(init=False, default=0)
+
+    def __post_init__(self) -> None:
+        elements: list[str] = []
+        memo = self
+        while isinstance(memo.node, (ClassDef, FunctionDef, AsyncFunctionDef)):
+            elements.insert(0, memo.node.name)
+            if not memo.parent:
+                break
+
+            memo = memo.parent
+            if isinstance(memo.node, (FunctionDef, AsyncFunctionDef)):
+                elements.insert(0, "")
+
+        self.joined_path = Constant(".".join(elements))
+
+        # Figure out where to insert instrumentation code
+        if self.node:
+            for index, child in enumerate(self.node.body):
+                if isinstance(child, ImportFrom) and child.module == "__future__":
+                    # (module only) __future__ imports must come first
+                    continue
+                elif (
+                    isinstance(child, Expr)
+                    and isinstance(child.value, Constant)
+                    and isinstance(child.value.value, str)
+                ):
+                    continue  # docstring
+
+                self.code_inject_index = index
+                break
+
+    def get_unused_name(self, name: str) -> str:
+        memo: TransformMemo | None = self
+        while memo is not None:
+            if name in memo.local_names:
+                memo = self
+                name += "_"
+            else:
+                memo = memo.parent
+
+        self.local_names.add(name)
+        return name
+
+    def is_ignored_name(self, expression: expr | Expr | None) -> bool:
+        top_expression = (
+            expression.value if isinstance(expression, Expr) else expression
+        )
+
+        if isinstance(top_expression, Attribute) and isinstance(
+            top_expression.value, Name
+        ):
+            name = top_expression.value.id
+        elif isinstance(top_expression, Name):
+            name = top_expression.id
+        else:
+            return False
+
+        memo: TransformMemo | None = self
+        while memo is not None:
+            if name in memo.ignored_names:
+                return True
+
+            memo = memo.parent
+
+        return False
+
+    def get_memo_name(self) -> Name:
+        if not self.memo_var_name:
+            self.memo_var_name = Name(id="memo", ctx=Load())
+
+        return self.memo_var_name
+
+    def get_import(self, module: str, name: str) -> Name:
+        if module in self.load_names and name in self.load_names[module]:
+            return self.load_names[module][name]
+
+        qualified_name = f"{module}.{name}"
+        if name in self.imported_names and self.imported_names[name] == qualified_name:
+            return Name(id=name, ctx=Load())
+
+        alias = self.get_unused_name(name)
+        node = self.load_names[module][name] = Name(id=alias, ctx=Load())
+        self.imported_names[name] = qualified_name
+        return node
+
+    def insert_imports(self, node: Module | FunctionDef | AsyncFunctionDef) -> None:
+        """Insert imports needed by injected code."""
+        if not self.load_names:
+            return
+
+        # Insert imports after any "from __future__ ..." imports and any docstring
+        for modulename, names in self.load_names.items():
+            aliases = [
+                alias(orig_name, new_name.id if orig_name != new_name.id else None)
+                for orig_name, new_name in sorted(names.items())
+            ]
+            node.body.insert(self.code_inject_index, ImportFrom(modulename, aliases, 0))
+
+    def name_matches(self, expression: expr | Expr | None, *names: str) -> bool:
+        if expression is None:
+            return False
+
+        path: list[str] = []
+        top_expression = (
+            expression.value if isinstance(expression, Expr) else expression
+        )
+
+        if isinstance(top_expression, Subscript):
+            top_expression = top_expression.value
+        elif isinstance(top_expression, Call):
+            top_expression = top_expression.func
+
+        while isinstance(top_expression, Attribute):
+            path.insert(0, top_expression.attr)
+            top_expression = top_expression.value
+
+        if not isinstance(top_expression, Name):
+            return False
+
+        if top_expression.id in self.imported_names:
+            translated = self.imported_names[top_expression.id]
+        elif hasattr(builtins, top_expression.id):
+            translated = "builtins." + top_expression.id
+        else:
+            translated = top_expression.id
+
+        path.insert(0, translated)
+        joined_path = ".".join(path)
+        if joined_path in names:
+            return True
+        elif self.parent:
+            return self.parent.name_matches(expression, *names)
+        else:
+            return False
+
+    def get_config_keywords(self) -> list[keyword]:
+        if self.parent and isinstance(self.parent.node, ClassDef):
+            overrides = self.parent.configuration_overrides.copy()
+        else:
+            overrides = {}
+
+        overrides.update(self.configuration_overrides)
+        return [keyword(key, value) for key, value in overrides.items()]
+
+
+class NameCollector(NodeVisitor):
+    def __init__(self) -> None:
+        self.names: set[str] = set()
+
+    def visit_Import(self, node: Import) -> None:
+        for name in node.names:
+            self.names.add(name.asname or name.name)
+
+    def visit_ImportFrom(self, node: ImportFrom) -> None:
+        for name in node.names:
+            self.names.add(name.asname or name.name)
+
+    def visit_Assign(self, node: Assign) -> None:
+        for target in node.targets:
+            if isinstance(target, Name):
+                self.names.add(target.id)
+
+    def visit_NamedExpr(self, node: NamedExpr) -> Any:
+        if isinstance(node.target, Name):
+            self.names.add(node.target.id)
+
+    def visit_FunctionDef(self, node: FunctionDef) -> None:
+        pass
+
+    def visit_ClassDef(self, node: ClassDef) -> None:
+        pass
+
+
+class GeneratorDetector(NodeVisitor):
+    """Detects if a function node is a generator function."""
+
+    contains_yields: bool = False
+    in_root_function: bool = False
+
+    def visit_Yield(self, node: Yield) -> Any:
+        self.contains_yields = True
+
+    def visit_YieldFrom(self, node: YieldFrom) -> Any:
+        self.contains_yields = True
+
+    def visit_ClassDef(self, node: ClassDef) -> Any:
+        pass
+
+    def visit_FunctionDef(self, node: FunctionDef | AsyncFunctionDef) -> Any:
+        if not self.in_root_function:
+            self.in_root_function = True
+            self.generic_visit(node)
+            self.in_root_function = False
+
+    def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any:
+        self.visit_FunctionDef(node)
+
+
+class AnnotationTransformer(NodeTransformer):
+    type_substitutions: ClassVar[dict[str, tuple[str, str]]] = {
+        "builtins.dict": ("typing", "Dict"),
+        "builtins.list": ("typing", "List"),
+        "builtins.tuple": ("typing", "Tuple"),
+        "builtins.set": ("typing", "Set"),
+        "builtins.frozenset": ("typing", "FrozenSet"),
+    }
+
+    def __init__(self, transformer: TypeguardTransformer):
+        self.transformer = transformer
+        self._memo = transformer._memo
+        self._level = 0
+
+    def visit(self, node: AST) -> Any:
+        # Don't process Literals
+        if isinstance(node, expr) and self._memo.name_matches(node, *literal_names):
+            return node
+
+        self._level += 1
+        new_node = super().visit(node)
+        self._level -= 1
+
+        if isinstance(new_node, Expression) and not hasattr(new_node, "body"):
+            return None
+
+        # Return None if this new node matches a variation of typing.Any
+        if (
+            self._level == 0
+            and isinstance(new_node, expr)
+            and self._memo.name_matches(new_node, *anytype_names)
+        ):
+            return None
+
+        return new_node
+
+    def visit_BinOp(self, node: BinOp) -> Any:
+        self.generic_visit(node)
+
+        if isinstance(node.op, BitOr):
+            # If either branch of the BinOp has been transformed to `None`, it means
+            # that a type in the union was ignored, so the entire annotation should e
+            # ignored
+            if not hasattr(node, "left") or not hasattr(node, "right"):
+                return None
+
+            # Return Any if either side is Any
+            if self._memo.name_matches(node.left, *anytype_names):
+                return node.left
+            elif self._memo.name_matches(node.right, *anytype_names):
+                return node.right
+
+            if sys.version_info < (3, 10):
+                union_name = self.transformer._get_import("typing", "Union")
+                return Subscript(
+                    value=union_name,
+                    slice=Index(
+                        Tuple(elts=[node.left, node.right], ctx=Load()), ctx=Load()
+                    ),
+                    ctx=Load(),
+                )
+
+        return node
+
+    def visit_Attribute(self, node: Attribute) -> Any:
+        if self._memo.is_ignored_name(node):
+            return None
+
+        return node
+
+    def visit_Subscript(self, node: Subscript) -> Any:
+        if self._memo.is_ignored_name(node.value):
+            return None
+
+        # The subscript of typing(_extensions).Literal can be any arbitrary string, so
+        # don't try to evaluate it as code
+        if node.slice:
+            if isinstance(node.slice, Index):
+                # Python 3.8
+                slice_value = node.slice.value  # type: ignore[attr-defined]
+            else:
+                slice_value = node.slice
+
+            if isinstance(slice_value, Tuple):
+                if self._memo.name_matches(node.value, *annotated_names):
+                    # Only treat the first argument to typing.Annotated as a potential
+                    # forward reference
+                    items = cast(
+                        typing.List[expr],
+                        [self.visit(slice_value.elts[0])] + slice_value.elts[1:],
+                    )
+                else:
+                    items = cast(
+                        typing.List[expr],
+                        [self.visit(item) for item in slice_value.elts],
+                    )
+
+                # If this is a Union and any of the items is Any, erase the entire
+                # annotation
+                if self._memo.name_matches(node.value, "typing.Union") and any(
+                    item is None
+                    or (
+                        isinstance(item, expr)
+                        and self._memo.name_matches(item, *anytype_names)
+                    )
+                    for item in items
+                ):
+                    return None
+
+                # If all items in the subscript were Any, erase the subscript entirely
+                if all(item is None for item in items):
+                    return node.value
+
+                for index, item in enumerate(items):
+                    if item is None:
+                        items[index] = self.transformer._get_import("typing", "Any")
+
+                slice_value.elts = items
+            else:
+                self.generic_visit(node)
+
+                # If the transformer erased the slice entirely, just return the node
+                # value without the subscript (unless it's Optional, in which case erase
+                # the node entirely
+                if self._memo.name_matches(
+                    node.value, "typing.Optional"
+                ) and not hasattr(node, "slice"):
+                    return None
+                if sys.version_info >= (3, 9) and not hasattr(node, "slice"):
+                    return node.value
+                elif sys.version_info < (3, 9) and not hasattr(node.slice, "value"):
+                    return node.value
+
+        return node
+
+    def visit_Name(self, node: Name) -> Any:
+        if self._memo.is_ignored_name(node):
+            return None
+
+        if sys.version_info < (3, 9):
+            for typename, substitute in self.type_substitutions.items():
+                if self._memo.name_matches(node, typename):
+                    new_node = self.transformer._get_import(*substitute)
+                    return copy_location(new_node, node)
+
+        return node
+
+    def visit_Call(self, node: Call) -> Any:
+        # Don't recurse into calls
+        return node
+
+    def visit_Constant(self, node: Constant) -> Any:
+        if isinstance(node.value, str):
+            expression = ast.parse(node.value, mode="eval")
+            new_node = self.visit(expression)
+            if new_node:
+                return copy_location(new_node.body, node)
+            else:
+                return None
+
+        return node
+
+
+class TypeguardTransformer(NodeTransformer):
+    def __init__(
+        self, target_path: Sequence[str] | None = None, target_lineno: int | None = None
+    ) -> None:
+        self._target_path = tuple(target_path) if target_path else None
+        self._memo = self._module_memo = TransformMemo(None, None, ())
+        self.names_used_in_annotations: set[str] = set()
+        self.target_node: FunctionDef | AsyncFunctionDef | None = None
+        self.target_lineno = target_lineno
+
+    def generic_visit(self, node: AST) -> AST:
+        has_non_empty_body_initially = bool(getattr(node, "body", None))
+        initial_type = type(node)
+
+        node = super().generic_visit(node)
+
+        if (
+            type(node) is initial_type
+            and has_non_empty_body_initially
+            and hasattr(node, "body")
+            and not node.body
+        ):
+            # If we have still the same node type after transformation
+            # but we've optimised it's body away, we add a `pass` statement.
+            node.body = [Pass()]
+
+        return node
+
+    @contextmanager
+    def _use_memo(
+        self, node: ClassDef | FunctionDef | AsyncFunctionDef
+    ) -> Generator[None, Any, None]:
+        new_memo = TransformMemo(node, self._memo, self._memo.path + (node.name,))
+        old_memo = self._memo
+        self._memo = new_memo
+
+        if isinstance(node, (FunctionDef, AsyncFunctionDef)):
+            new_memo.should_instrument = (
+                self._target_path is None or new_memo.path == self._target_path
+            )
+            if new_memo.should_instrument:
+                # Check if the function is a generator function
+                detector = GeneratorDetector()
+                detector.visit(node)
+
+                # Extract yield, send and return types where possible from a subscripted
+                # annotation like Generator[int, str, bool]
+                return_annotation = deepcopy(node.returns)
+                if detector.contains_yields and new_memo.name_matches(
+                    return_annotation, *generator_names
+                ):
+                    if isinstance(return_annotation, Subscript):
+                        annotation_slice = return_annotation.slice
+
+                        # Python < 3.9
+                        if isinstance(annotation_slice, Index):
+                            annotation_slice = (
+                                annotation_slice.value  # type: ignore[attr-defined]
+                            )
+
+                        if isinstance(annotation_slice, Tuple):
+                            items = annotation_slice.elts
+                        else:
+                            items = [annotation_slice]
+
+                        if len(items) > 0:
+                            new_memo.yield_annotation = self._convert_annotation(
+                                items[0]
+                            )
+
+                        if len(items) > 1:
+                            new_memo.send_annotation = self._convert_annotation(
+                                items[1]
+                            )
+
+                        if len(items) > 2:
+                            new_memo.return_annotation = self._convert_annotation(
+                                items[2]
+                            )
+                else:
+                    new_memo.return_annotation = self._convert_annotation(
+                        return_annotation
+                    )
+
+        if isinstance(node, AsyncFunctionDef):
+            new_memo.is_async = True
+
+        yield
+        self._memo = old_memo
+
+    def _get_import(self, module: str, name: str) -> Name:
+        memo = self._memo if self._target_path else self._module_memo
+        return memo.get_import(module, name)
+
+    @overload
+    def _convert_annotation(self, annotation: None) -> None: ...
+
+    @overload
+    def _convert_annotation(self, annotation: expr) -> expr: ...
+
+    def _convert_annotation(self, annotation: expr | None) -> expr | None:
+        if annotation is None:
+            return None
+
+        # Convert PEP 604 unions (x | y) and generic built-in collections where
+        # necessary, and undo forward references
+        new_annotation = cast(expr, AnnotationTransformer(self).visit(annotation))
+        if isinstance(new_annotation, expr):
+            new_annotation = ast.copy_location(new_annotation, annotation)
+
+            # Store names used in the annotation
+            names = {node.id for node in walk(new_annotation) if isinstance(node, Name)}
+            self.names_used_in_annotations.update(names)
+
+        return new_annotation
+
+    def visit_Name(self, node: Name) -> Name:
+        self._memo.local_names.add(node.id)
+        return node
+
+    def visit_Module(self, node: Module) -> Module:
+        self._module_memo = self._memo = TransformMemo(node, None, ())
+        self.generic_visit(node)
+        self._module_memo.insert_imports(node)
+
+        fix_missing_locations(node)
+        return node
+
+    def visit_Import(self, node: Import) -> Import:
+        for name in node.names:
+            self._memo.local_names.add(name.asname or name.name)
+            self._memo.imported_names[name.asname or name.name] = name.name
+
+        return node
+
+    def visit_ImportFrom(self, node: ImportFrom) -> ImportFrom:
+        for name in node.names:
+            if name.name != "*":
+                alias = name.asname or name.name
+                self._memo.local_names.add(alias)
+                self._memo.imported_names[alias] = f"{node.module}.{name.name}"
+
+        return node
+
+    def visit_ClassDef(self, node: ClassDef) -> ClassDef | None:
+        self._memo.local_names.add(node.name)
+
+        # Eliminate top level classes not belonging to the target path
+        if (
+            self._target_path is not None
+            and not self._memo.path
+            and node.name != self._target_path[0]
+        ):
+            return None
+
+        with self._use_memo(node):
+            for decorator in node.decorator_list.copy():
+                if self._memo.name_matches(decorator, "typeguard.typechecked"):
+                    # Remove the decorator to prevent duplicate instrumentation
+                    node.decorator_list.remove(decorator)
+
+                    # Store any configuration overrides
+                    if isinstance(decorator, Call) and decorator.keywords:
+                        self._memo.configuration_overrides.update(
+                            {kw.arg: kw.value for kw in decorator.keywords if kw.arg}
+                        )
+
+            self.generic_visit(node)
+            return node
+
+    def visit_FunctionDef(
+        self, node: FunctionDef | AsyncFunctionDef
+    ) -> FunctionDef | AsyncFunctionDef | None:
+        """
+        Injects type checks for function arguments, and for a return of None if the
+        function is annotated to return something else than Any or None, and the body
+        ends without an explicit "return".
+
+        """
+        self._memo.local_names.add(node.name)
+
+        # Eliminate top level functions not belonging to the target path
+        if (
+            self._target_path is not None
+            and not self._memo.path
+            and node.name != self._target_path[0]
+        ):
+            return None
+
+        # Skip instrumentation if we're instrumenting the whole module and the function
+        # contains either @no_type_check or @typeguard_ignore
+        if self._target_path is None:
+            for decorator in node.decorator_list:
+                if self._memo.name_matches(decorator, *ignore_decorators):
+                    return node
+
+        with self._use_memo(node):
+            arg_annotations: dict[str, Any] = {}
+            if self._target_path is None or self._memo.path == self._target_path:
+                # Find line number we're supposed to match against
+                if node.decorator_list:
+                    first_lineno = node.decorator_list[0].lineno
+                else:
+                    first_lineno = node.lineno
+
+                for decorator in node.decorator_list.copy():
+                    if self._memo.name_matches(decorator, "typing.overload"):
+                        # Remove overloads entirely
+                        return None
+                    elif self._memo.name_matches(decorator, "typeguard.typechecked"):
+                        # Remove the decorator to prevent duplicate instrumentation
+                        node.decorator_list.remove(decorator)
+
+                        # Store any configuration overrides
+                        if isinstance(decorator, Call) and decorator.keywords:
+                            self._memo.configuration_overrides = {
+                                kw.arg: kw.value for kw in decorator.keywords if kw.arg
+                            }
+
+                if self.target_lineno == first_lineno:
+                    assert self.target_node is None
+                    self.target_node = node
+                    if node.decorator_list:
+                        self.target_lineno = node.decorator_list[0].lineno
+                    else:
+                        self.target_lineno = node.lineno
+
+                all_args = node.args.args + node.args.kwonlyargs + node.args.posonlyargs
+
+                # Ensure that any type shadowed by the positional or keyword-only
+                # argument names are ignored in this function
+                for arg in all_args:
+                    self._memo.ignored_names.add(arg.arg)
+
+                # Ensure that any type shadowed by the variable positional argument name
+                # (e.g. "args" in *args) is ignored this function
+                if node.args.vararg:
+                    self._memo.ignored_names.add(node.args.vararg.arg)
+
+                # Ensure that any type shadowed by the variable keywrod argument name
+                # (e.g. "kwargs" in *kwargs) is ignored this function
+                if node.args.kwarg:
+                    self._memo.ignored_names.add(node.args.kwarg.arg)
+
+                for arg in all_args:
+                    annotation = self._convert_annotation(deepcopy(arg.annotation))
+                    if annotation:
+                        arg_annotations[arg.arg] = annotation
+
+                if node.args.vararg:
+                    annotation_ = self._convert_annotation(node.args.vararg.annotation)
+                    if annotation_:
+                        if sys.version_info >= (3, 9):
+                            container = Name("tuple", ctx=Load())
+                        else:
+                            container = self._get_import("typing", "Tuple")
+
+                        subscript_slice: Tuple | Index = Tuple(
+                            [
+                                annotation_,
+                                Constant(Ellipsis),
+                            ],
+                            ctx=Load(),
+                        )
+                        if sys.version_info < (3, 9):
+                            subscript_slice = Index(subscript_slice, ctx=Load())
+
+                        arg_annotations[node.args.vararg.arg] = Subscript(
+                            container, subscript_slice, ctx=Load()
+                        )
+
+                if node.args.kwarg:
+                    annotation_ = self._convert_annotation(node.args.kwarg.annotation)
+                    if annotation_:
+                        if sys.version_info >= (3, 9):
+                            container = Name("dict", ctx=Load())
+                        else:
+                            container = self._get_import("typing", "Dict")
+
+                        subscript_slice = Tuple(
+                            [
+                                Name("str", ctx=Load()),
+                                annotation_,
+                            ],
+                            ctx=Load(),
+                        )
+                        if sys.version_info < (3, 9):
+                            subscript_slice = Index(subscript_slice, ctx=Load())
+
+                        arg_annotations[node.args.kwarg.arg] = Subscript(
+                            container, subscript_slice, ctx=Load()
+                        )
+
+                if arg_annotations:
+                    self._memo.variable_annotations.update(arg_annotations)
+
+            self.generic_visit(node)
+
+            if arg_annotations:
+                annotations_dict = Dict(
+                    keys=[Constant(key) for key in arg_annotations.keys()],
+                    values=[
+                        Tuple([Name(key, ctx=Load()), annotation], ctx=Load())
+                        for key, annotation in arg_annotations.items()
+                    ],
+                )
+                func_name = self._get_import(
+                    "typeguard._functions", "check_argument_types"
+                )
+                args = [
+                    self._memo.joined_path,
+                    annotations_dict,
+                    self._memo.get_memo_name(),
+                ]
+                node.body.insert(
+                    self._memo.code_inject_index, Expr(Call(func_name, args, []))
+                )
+
+            # Add a checked "return None" to the end if there's no explicit return
+            # Skip if the return annotation is None or Any
+            if (
+                self._memo.return_annotation
+                and (not self._memo.is_async or not self._memo.has_yield_expressions)
+                and not isinstance(node.body[-1], Return)
+                and (
+                    not isinstance(self._memo.return_annotation, Constant)
+                    or self._memo.return_annotation.value is not None
+                )
+            ):
+                func_name = self._get_import(
+                    "typeguard._functions", "check_return_type"
+                )
+                return_node = Return(
+                    Call(
+                        func_name,
+                        [
+                            self._memo.joined_path,
+                            Constant(None),
+                            self._memo.return_annotation,
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+                )
+
+                # Replace a placeholder "pass" at the end
+                if isinstance(node.body[-1], Pass):
+                    copy_location(return_node, node.body[-1])
+                    del node.body[-1]
+
+                node.body.append(return_node)
+
+            # Insert code to create the call memo, if it was ever needed for this
+            # function
+            if self._memo.memo_var_name:
+                memo_kwargs: dict[str, Any] = {}
+                if self._memo.parent and isinstance(self._memo.parent.node, ClassDef):
+                    for decorator in node.decorator_list:
+                        if (
+                            isinstance(decorator, Name)
+                            and decorator.id == "staticmethod"
+                        ):
+                            break
+                        elif (
+                            isinstance(decorator, Name)
+                            and decorator.id == "classmethod"
+                        ):
+                            memo_kwargs["self_type"] = Name(
+                                id=node.args.args[0].arg, ctx=Load()
+                            )
+                            break
+                    else:
+                        if node.args.args:
+                            if node.name == "__new__":
+                                memo_kwargs["self_type"] = Name(
+                                    id=node.args.args[0].arg, ctx=Load()
+                                )
+                            else:
+                                memo_kwargs["self_type"] = Attribute(
+                                    Name(id=node.args.args[0].arg, ctx=Load()),
+                                    "__class__",
+                                    ctx=Load(),
+                                )
+
+                # Construct the function reference
+                # Nested functions get special treatment: the function name is added
+                # to free variables (and the closure of the resulting function)
+                names: list[str] = [node.name]
+                memo = self._memo.parent
+                while memo:
+                    if isinstance(memo.node, (FunctionDef, AsyncFunctionDef)):
+                        # This is a nested function. Use the function name as-is.
+                        del names[:-1]
+                        break
+                    elif not isinstance(memo.node, ClassDef):
+                        break
+
+                    names.insert(0, memo.node.name)
+                    memo = memo.parent
+
+                config_keywords = self._memo.get_config_keywords()
+                if config_keywords:
+                    memo_kwargs["config"] = Call(
+                        self._get_import("dataclasses", "replace"),
+                        [self._get_import("typeguard._config", "global_config")],
+                        config_keywords,
+                    )
+
+                self._memo.memo_var_name.id = self._memo.get_unused_name("memo")
+                memo_store_name = Name(id=self._memo.memo_var_name.id, ctx=Store())
+                globals_call = Call(Name(id="globals", ctx=Load()), [], [])
+                locals_call = Call(Name(id="locals", ctx=Load()), [], [])
+                memo_expr = Call(
+                    self._get_import("typeguard", "TypeCheckMemo"),
+                    [globals_call, locals_call],
+                    [keyword(key, value) for key, value in memo_kwargs.items()],
+                )
+                node.body.insert(
+                    self._memo.code_inject_index,
+                    Assign([memo_store_name], memo_expr),
+                )
+
+                self._memo.insert_imports(node)
+
+                # Special case the __new__() method to create a local alias from the
+                # class name to the first argument (usually "cls")
+                if (
+                    isinstance(node, FunctionDef)
+                    and node.args
+                    and self._memo.parent is not None
+                    and isinstance(self._memo.parent.node, ClassDef)
+                    and node.name == "__new__"
+                ):
+                    first_args_expr = Name(node.args.args[0].arg, ctx=Load())
+                    cls_name = Name(self._memo.parent.node.name, ctx=Store())
+                    node.body.insert(
+                        self._memo.code_inject_index,
+                        Assign([cls_name], first_args_expr),
+                    )
+
+                # Rmove any placeholder "pass" at the end
+                if isinstance(node.body[-1], Pass):
+                    del node.body[-1]
+
+        return node
+
+    def visit_AsyncFunctionDef(
+        self, node: AsyncFunctionDef
+    ) -> FunctionDef | AsyncFunctionDef | None:
+        return self.visit_FunctionDef(node)
+
+    def visit_Return(self, node: Return) -> Return:
+        """This injects type checks into "return" statements."""
+        self.generic_visit(node)
+        if (
+            self._memo.return_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.return_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_return_type")
+            old_node = node
+            retval = old_node.value or Constant(None)
+            node = Return(
+                Call(
+                    func_name,
+                    [
+                        self._memo.joined_path,
+                        retval,
+                        self._memo.return_annotation,
+                        self._memo.get_memo_name(),
+                    ],
+                    [],
+                )
+            )
+            copy_location(node, old_node)
+
+        return node
+
+    def visit_Yield(self, node: Yield) -> Yield | Call:
+        """
+        This injects type checks into "yield" expressions, checking both the yielded
+        value and the value sent back to the generator, when appropriate.
+
+        """
+        self._memo.has_yield_expressions = True
+        self.generic_visit(node)
+
+        if (
+            self._memo.yield_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.yield_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_yield_type")
+            yieldval = node.value or Constant(None)
+            node.value = Call(
+                func_name,
+                [
+                    self._memo.joined_path,
+                    yieldval,
+                    self._memo.yield_annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+
+        if (
+            self._memo.send_annotation
+            and self._memo.should_instrument
+            and not self._memo.is_ignored_name(self._memo.send_annotation)
+        ):
+            func_name = self._get_import("typeguard._functions", "check_send_type")
+            old_node = node
+            call_node = Call(
+                func_name,
+                [
+                    self._memo.joined_path,
+                    old_node,
+                    self._memo.send_annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+            copy_location(call_node, old_node)
+            return call_node
+
+        return node
+
+    def visit_AnnAssign(self, node: AnnAssign) -> Any:
+        """
+        This injects a type check into a local variable annotation-assignment within a
+        function body.
+
+        """
+        self.generic_visit(node)
+
+        if (
+            isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef))
+            and node.annotation
+            and isinstance(node.target, Name)
+        ):
+            self._memo.ignored_names.add(node.target.id)
+            annotation = self._convert_annotation(deepcopy(node.annotation))
+            if annotation:
+                self._memo.variable_annotations[node.target.id] = annotation
+                if node.value:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_variable_assignment"
+                    )
+                    node.value = Call(
+                        func_name,
+                        [
+                            node.value,
+                            Constant(node.target.id),
+                            annotation,
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+
+        return node
+
+    def visit_Assign(self, node: Assign) -> Any:
+        """
+        This injects a type check into a local variable assignment within a function
+        body. The variable must have been annotated earlier in the function body.
+
+        """
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)):
+            targets: list[dict[Constant, expr | None]] = []
+            check_required = False
+            for target in node.targets:
+                elts: Sequence[expr]
+                if isinstance(target, Name):
+                    elts = [target]
+                elif isinstance(target, Tuple):
+                    elts = target.elts
+                else:
+                    continue
+
+                annotations_: dict[Constant, expr | None] = {}
+                for exp in elts:
+                    prefix = ""
+                    if isinstance(exp, Starred):
+                        exp = exp.value
+                        prefix = "*"
+
+                    if isinstance(exp, Name):
+                        self._memo.ignored_names.add(exp.id)
+                        name = prefix + exp.id
+                        annotation = self._memo.variable_annotations.get(exp.id)
+                        if annotation:
+                            annotations_[Constant(name)] = annotation
+                            check_required = True
+                        else:
+                            annotations_[Constant(name)] = None
+
+                targets.append(annotations_)
+
+            if check_required:
+                # Replace missing annotations with typing.Any
+                for item in targets:
+                    for key, expression in item.items():
+                        if expression is None:
+                            item[key] = self._get_import("typing", "Any")
+
+                if len(targets) == 1 and len(targets[0]) == 1:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_variable_assignment"
+                    )
+                    target_varname = next(iter(targets[0]))
+                    node.value = Call(
+                        func_name,
+                        [
+                            node.value,
+                            target_varname,
+                            targets[0][target_varname],
+                            self._memo.get_memo_name(),
+                        ],
+                        [],
+                    )
+                elif targets:
+                    func_name = self._get_import(
+                        "typeguard._functions", "check_multi_variable_assignment"
+                    )
+                    targets_arg = List(
+                        [
+                            Dict(keys=list(target), values=list(target.values()))
+                            for target in targets
+                        ],
+                        ctx=Load(),
+                    )
+                    node.value = Call(
+                        func_name,
+                        [node.value, targets_arg, self._memo.get_memo_name()],
+                        [],
+                    )
+
+        return node
+
+    def visit_NamedExpr(self, node: NamedExpr) -> Any:
+        """This injects a type check into an assignment expression (a := foo())."""
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)) and isinstance(
+            node.target, Name
+        ):
+            self._memo.ignored_names.add(node.target.id)
+
+            # Bail out if no matching annotation is found
+            annotation = self._memo.variable_annotations.get(node.target.id)
+            if annotation is None:
+                return node
+
+            func_name = self._get_import(
+                "typeguard._functions", "check_variable_assignment"
+            )
+            node.value = Call(
+                func_name,
+                [
+                    node.value,
+                    Constant(node.target.id),
+                    annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+
+        return node
+
+    def visit_AugAssign(self, node: AugAssign) -> Any:
+        """
+        This injects a type check into an augmented assignment expression (a += 1).
+
+        """
+        self.generic_visit(node)
+
+        # Only instrument function-local assignments
+        if isinstance(self._memo.node, (FunctionDef, AsyncFunctionDef)) and isinstance(
+            node.target, Name
+        ):
+            # Bail out if no matching annotation is found
+            annotation = self._memo.variable_annotations.get(node.target.id)
+            if annotation is None:
+                return node
+
+            # Bail out if the operator is not found (newer Python version?)
+            try:
+                operator_func_name = aug_assign_functions[node.op.__class__]
+            except KeyError:
+                return node
+
+            operator_func = self._get_import("operator", operator_func_name)
+            operator_call = Call(
+                operator_func, [Name(node.target.id, ctx=Load()), node.value], []
+            )
+            check_call = Call(
+                self._get_import("typeguard._functions", "check_variable_assignment"),
+                [
+                    operator_call,
+                    Constant(node.target.id),
+                    annotation,
+                    self._memo.get_memo_name(),
+                ],
+                [],
+            )
+            return Assign(targets=[node.target], value=check_call)
+
+        return node
+
+    def visit_If(self, node: If) -> Any:
+        """
+        This blocks names from being collected from a module-level
+        "if typing.TYPE_CHECKING:" block, so that they won't be type checked.
+
+        """
+        self.generic_visit(node)
+
+        if (
+            self._memo is self._module_memo
+            and isinstance(node.test, Name)
+            and self._memo.name_matches(node.test, "typing.TYPE_CHECKING")
+        ):
+            collector = NameCollector()
+            collector.visit(node)
+            self._memo.ignored_names.update(collector.names)
+
+        return node
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_union_transformer.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_union_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..19617e6af5a0fd691b9d3793f9486ade2868d5bf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_union_transformer.py
@@ -0,0 +1,55 @@
+"""
+Transforms lazily evaluated PEP 604 unions into typing.Unions, for compatibility with
+Python versions older than 3.10.
+"""
+
+from __future__ import annotations
+
+from ast import (
+    BinOp,
+    BitOr,
+    Index,
+    Load,
+    Name,
+    NodeTransformer,
+    Subscript,
+    fix_missing_locations,
+    parse,
+)
+from ast import Tuple as ASTTuple
+from types import CodeType
+from typing import Any, Dict, FrozenSet, List, Set, Tuple, Union
+
+type_substitutions = {
+    "dict": Dict,
+    "list": List,
+    "tuple": Tuple,
+    "set": Set,
+    "frozenset": FrozenSet,
+    "Union": Union,
+}
+
+
+class UnionTransformer(NodeTransformer):
+    def __init__(self, union_name: Name | None = None):
+        self.union_name = union_name or Name(id="Union", ctx=Load())
+
+    def visit_BinOp(self, node: BinOp) -> Any:
+        self.generic_visit(node)
+        if isinstance(node.op, BitOr):
+            return Subscript(
+                value=self.union_name,
+                slice=Index(
+                    ASTTuple(elts=[node.left, node.right], ctx=Load()), ctx=Load()
+                ),
+                ctx=Load(),
+            )
+
+        return node
+
+
+def compile_type_hint(hint: str) -> CodeType:
+    parsed = parse(hint, "", "eval")
+    UnionTransformer().visit(parsed)
+    fix_missing_locations(parsed)
+    return compile(parsed, "", "eval", flags=0)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_utils.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bcc8417f8773115de078d307682b457af848052
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/_utils.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+import inspect
+import sys
+from importlib import import_module
+from inspect import currentframe
+from types import CodeType, FrameType, FunctionType
+from typing import TYPE_CHECKING, Any, Callable, ForwardRef, Union, cast, final
+from weakref import WeakValueDictionary
+
+if TYPE_CHECKING:
+    from ._memo import TypeCheckMemo
+
+if sys.version_info >= (3, 13):
+    from typing import get_args, get_origin
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        return forwardref._evaluate(
+            memo.globals, memo.locals, type_params=(), recursive_guard=frozenset()
+        )
+
+elif sys.version_info >= (3, 10):
+    from typing import get_args, get_origin
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        return forwardref._evaluate(
+            memo.globals, memo.locals, recursive_guard=frozenset()
+        )
+
+else:
+    from typing_extensions import get_args, get_origin
+
+    evaluate_extra_args: tuple[frozenset[Any], ...] = (
+        (frozenset(),) if sys.version_info >= (3, 9) else ()
+    )
+
+    def evaluate_forwardref(forwardref: ForwardRef, memo: TypeCheckMemo) -> Any:
+        from ._union_transformer import compile_type_hint, type_substitutions
+
+        if not forwardref.__forward_evaluated__:
+            forwardref.__forward_code__ = compile_type_hint(forwardref.__forward_arg__)
+
+        try:
+            return forwardref._evaluate(memo.globals, memo.locals, *evaluate_extra_args)
+        except NameError:
+            if sys.version_info < (3, 10):
+                # Try again, with the type substitutions (list -> List etc.) in place
+                new_globals = memo.globals.copy()
+                new_globals.setdefault("Union", Union)
+                if sys.version_info < (3, 9):
+                    new_globals.update(type_substitutions)
+
+                return forwardref._evaluate(
+                    new_globals, memo.locals or new_globals, *evaluate_extra_args
+                )
+
+            raise
+
+
+_functions_map: WeakValueDictionary[CodeType, FunctionType] = WeakValueDictionary()
+
+
+def get_type_name(type_: Any) -> str:
+    name: str
+    for attrname in "__name__", "_name", "__forward_arg__":
+        candidate = getattr(type_, attrname, None)
+        if isinstance(candidate, str):
+            name = candidate
+            break
+    else:
+        origin = get_origin(type_)
+        candidate = getattr(origin, "_name", None)
+        if candidate is None:
+            candidate = type_.__class__.__name__.strip("_")
+
+        if isinstance(candidate, str):
+            name = candidate
+        else:
+            return "(unknown)"
+
+    args = get_args(type_)
+    if args:
+        if name == "Literal":
+            formatted_args = ", ".join(repr(arg) for arg in args)
+        else:
+            formatted_args = ", ".join(get_type_name(arg) for arg in args)
+
+        name += f"[{formatted_args}]"
+
+    module = getattr(type_, "__module__", None)
+    if module and module not in (None, "typing", "typing_extensions", "builtins"):
+        name = module + "." + name
+
+    return name
+
+
+def qualified_name(obj: Any, *, add_class_prefix: bool = False) -> str:
+    """
+    Return the qualified name (e.g. package.module.Type) for the given object.
+
+    Builtins and types from the :mod:`typing` package get special treatment by having
+    the module name stripped from the generated name.
+
+    """
+    if obj is None:
+        return "None"
+    elif inspect.isclass(obj):
+        prefix = "class " if add_class_prefix else ""
+        type_ = obj
+    else:
+        prefix = ""
+        type_ = type(obj)
+
+    module = type_.__module__
+    qualname = type_.__qualname__
+    name = qualname if module in ("typing", "builtins") else f"{module}.{qualname}"
+    return prefix + name
+
+
+def function_name(func: Callable[..., Any]) -> str:
+    """
+    Return the qualified name of the given function.
+
+    Builtins and types from the :mod:`typing` package get special treatment by having
+    the module name stripped from the generated name.
+
+    """
+    # For partial functions and objects with __call__ defined, __qualname__ does not
+    # exist
+    module = getattr(func, "__module__", "")
+    qualname = (module + ".") if module not in ("builtins", "") else ""
+    return qualname + getattr(func, "__qualname__", repr(func))
+
+
+def resolve_reference(reference: str) -> Any:
+    modulename, varname = reference.partition(":")[::2]
+    if not modulename or not varname:
+        raise ValueError(f"{reference!r} is not a module:varname reference")
+
+    obj = import_module(modulename)
+    for attr in varname.split("."):
+        obj = getattr(obj, attr)
+
+    return obj
+
+
+def is_method_of(obj: object, cls: type) -> bool:
+    return (
+        inspect.isfunction(obj)
+        and obj.__module__ == cls.__module__
+        and obj.__qualname__.startswith(cls.__qualname__ + ".")
+    )
+
+
+def get_stacklevel() -> int:
+    level = 1
+    frame = cast(FrameType, currentframe()).f_back
+    while frame and frame.f_globals.get("__name__", "").startswith("typeguard."):
+        level += 1
+        frame = frame.f_back
+
+    return level
+
+
+@final
+class Unset:
+    __slots__ = ()
+
+    def __repr__(self) -> str:
+        return ""
+
+
+unset = Unset()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/py.typed b/python_embeded/Lib/site-packages/setuptools/_vendor/typeguard/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/LICENSE
@@ -0,0 +1,279 @@
+A. HISTORY OF THE SOFTWARE
+==========================
+
+Python was created in the early 1990s by Guido van Rossum at Stichting
+Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
+as a successor of a language called ABC.  Guido remains Python's
+principal author, although it includes many contributions from others.
+
+In 1995, Guido continued his work on Python at the Corporation for
+National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
+in Reston, Virginia where he released several versions of the
+software.
+
+In May 2000, Guido and the Python core development team moved to
+BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
+year, the PythonLabs team moved to Digital Creations, which became
+Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
+https://www.python.org/psf/) was formed, a non-profit organization
+created specifically to own Python-related Intellectual Property.
+Zope Corporation was a sponsoring member of the PSF.
+
+All Python releases are Open Source (see https://opensource.org for
+the Open Source Definition).  Historically, most, but not all, Python
+releases have also been GPL-compatible; the table below summarizes
+the various releases.
+
+    Release         Derived     Year        Owner       GPL-
+                    from                                compatible? (1)
+
+    0.9.0 thru 1.2              1991-1995   CWI         yes
+    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
+    1.6             1.5.2       2000        CNRI        no
+    2.0             1.6         2000        BeOpen.com  no
+    1.6.1           1.6         2001        CNRI        yes (2)
+    2.1             2.0+1.6.1   2001        PSF         no
+    2.0.1           2.0+1.6.1   2001        PSF         yes
+    2.1.1           2.1+2.0.1   2001        PSF         yes
+    2.1.2           2.1.1       2002        PSF         yes
+    2.1.3           2.1.2       2002        PSF         yes
+    2.2 and above   2.1.1       2001-now    PSF         yes
+
+Footnotes:
+
+(1) GPL-compatible doesn't mean that we're distributing Python under
+    the GPL.  All Python licenses, unlike the GPL, let you distribute
+    a modified version without making your changes open source.  The
+    GPL-compatible licenses make it possible to combine Python with
+    other software that is released under the GPL; the others don't.
+
+(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
+    because its license has a choice of law clause.  According to
+    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
+    is "not incompatible" with the GPL.
+
+Thanks to the many outside volunteers who have worked under Guido's
+direction to make these releases possible.
+
+
+B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
+===============================================================
+
+Python software and documentation are licensed under the
+Python Software Foundation License Version 2.
+
+Starting with Python 3.8.6, examples, recipes, and other code in
+the documentation are dual licensed under the PSF License Version 2
+and the Zero-Clause BSD license.
+
+Some software incorporated into Python is under different licenses.
+The licenses are listed with code falling under that license.
+
+
+PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+--------------------------------------------
+
+1. This LICENSE AGREEMENT is between the Python Software Foundation
+("PSF"), and the Individual or Organization ("Licensee") accessing and
+otherwise using this software ("Python") in source or binary form and
+its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
+All Rights Reserved" are retained in Python alone or in any derivative version
+prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python.
+
+4. PSF is making Python available to Licensee on an "AS IS"
+basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between PSF and
+Licensee.  This License Agreement does not grant permission to use PSF
+trademarks or trade name in a trademark sense to endorse or promote
+products or services of Licensee, or any third party.
+
+8. By copying, installing or otherwise using Python, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
+-------------------------------------------
+
+BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
+
+1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
+office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
+Individual or Organization ("Licensee") accessing and otherwise using
+this software in source or binary form and its associated
+documentation ("the Software").
+
+2. Subject to the terms and conditions of this BeOpen Python License
+Agreement, BeOpen hereby grants Licensee a non-exclusive,
+royalty-free, world-wide license to reproduce, analyze, test, perform
+and/or display publicly, prepare derivative works, distribute, and
+otherwise use the Software alone or in any derivative version,
+provided, however, that the BeOpen Python License is retained in the
+Software, alone or in any derivative version prepared by Licensee.
+
+3. BeOpen is making the Software available to Licensee on an "AS IS"
+basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
+SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
+AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
+DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+5. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+6. This License Agreement shall be governed by and interpreted in all
+respects by the law of the State of California, excluding conflict of
+law provisions.  Nothing in this License Agreement shall be deemed to
+create any relationship of agency, partnership, or joint venture
+between BeOpen and Licensee.  This License Agreement does not grant
+permission to use BeOpen trademarks or trade names in a trademark
+sense to endorse or promote products or services of Licensee, or any
+third party.  As an exception, the "BeOpen Python" logos available at
+http://www.pythonlabs.com/logos.html may be used according to the
+permissions granted on that web page.
+
+7. By copying, installing or otherwise using the software, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
+---------------------------------------
+
+1. This LICENSE AGREEMENT is between the Corporation for National
+Research Initiatives, having an office at 1895 Preston White Drive,
+Reston, VA 20191 ("CNRI"), and the Individual or Organization
+("Licensee") accessing and otherwise using Python 1.6.1 software in
+source or binary form and its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, CNRI
+hereby grants Licensee a nonexclusive, royalty-free, world-wide
+license to reproduce, analyze, test, perform and/or display publicly,
+prepare derivative works, distribute, and otherwise use Python 1.6.1
+alone or in any derivative version, provided, however, that CNRI's
+License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
+1995-2001 Corporation for National Research Initiatives; All Rights
+Reserved" are retained in Python 1.6.1 alone or in any derivative
+version prepared by Licensee.  Alternately, in lieu of CNRI's License
+Agreement, Licensee may substitute the following text (omitting the
+quotes): "Python 1.6.1 is made available subject to the terms and
+conditions in CNRI's License Agreement.  This Agreement together with
+Python 1.6.1 may be located on the internet using the following
+unique, persistent identifier (known as a handle): 1895.22/1013.  This
+Agreement may also be obtained from a proxy server on the internet
+using the following URL: http://hdl.handle.net/1895.22/1013".
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python 1.6.1 or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python 1.6.1.
+
+4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
+basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. This License Agreement shall be governed by the federal
+intellectual property law of the United States, including without
+limitation the federal copyright law, and, to the extent such
+U.S. federal law does not apply, by the law of the Commonwealth of
+Virginia, excluding Virginia's conflict of law provisions.
+Notwithstanding the foregoing, with regard to derivative works based
+on Python 1.6.1 that incorporate non-separable material that was
+previously distributed under the GNU General Public License (GPL), the
+law of the Commonwealth of Virginia shall govern this License
+Agreement only as to issues arising under or with respect to
+Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
+License Agreement shall be deemed to create any relationship of
+agency, partnership, or joint venture between CNRI and Licensee.  This
+License Agreement does not grant permission to use CNRI trademarks or
+trade name in a trademark sense to endorse or promote products or
+services of Licensee, or any third party.
+
+8. By clicking on the "ACCEPT" button where indicated, or by copying,
+installing or otherwise using Python 1.6.1, Licensee agrees to be
+bound by the terms and conditions of this License Agreement.
+
+        ACCEPT
+
+
+CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
+--------------------------------------------------
+
+Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
+The Netherlands.  All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the name of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
+FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
+----------------------------------------------------------------------
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f15e2b387737b14e013a83b32a766fe4eb0da611
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/METADATA
@@ -0,0 +1,67 @@
+Metadata-Version: 2.1
+Name: typing_extensions
+Version: 4.12.2
+Summary: Backported and Experimental Type Hints for Python 3.8+
+Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
+Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" 
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Python Software Foundation License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Topic :: Software Development
+Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues
+Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md
+Project-URL: Documentation, https://typing-extensions.readthedocs.io/
+Project-URL: Home, https://github.com/python/typing_extensions
+Project-URL: Q & A, https://github.com/python/typing/discussions
+Project-URL: Repository, https://github.com/python/typing_extensions
+
+# Typing Extensions
+
+[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing)
+
+[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –
+[PyPI](https://pypi.org/project/typing-extensions/)
+
+## Overview
+
+The `typing_extensions` module serves two related purposes:
+
+- Enable use of new type system features on older Python versions. For example,
+  `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows
+  users on previous Python versions to use it too.
+- Enable experimentation with new type system PEPs before they are accepted and
+  added to the `typing` module.
+
+`typing_extensions` is treated specially by static type checkers such as
+mypy and pyright. Objects defined in `typing_extensions` are treated the same
+way as equivalent forms in `typing`.
+
+`typing_extensions` uses
+[Semantic Versioning](https://semver.org/). The
+major version will be incremented only for backwards-incompatible changes.
+Therefore, it's safe to depend
+on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`,
+where `x.y` is the first version that includes all features you need.
+
+## Included items
+
+See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a
+complete listing of module contents.
+
+## Contributing
+
+See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)
+for how to contribute to `typing_extensions`.
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..bc7b45334dd59e2c386632c238648ed3cb5031bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/RECORD
@@ -0,0 +1,7 @@
+__pycache__/typing_extensions.cpython-312.pyc,,
+typing_extensions-4.12.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+typing_extensions-4.12.2.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936
+typing_extensions-4.12.2.dist-info/METADATA,sha256=BeUQIa8cnYbrjWx-N8TOznM9UGW5Gm2DicVpDtRA8W0,3018
+typing_extensions-4.12.2.dist-info/RECORD,,
+typing_extensions-4.12.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
+typing_extensions.py,sha256=gwekpyG9DVG3lxWKX4ni8u7nk3We5slG98mA9F3DJQw,134451
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions-4.12.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.9.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions.py b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions.py
new file mode 100644
index 0000000000000000000000000000000000000000..dec429ca8723950097217d2140dd8daccb064e2d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/typing_extensions.py
@@ -0,0 +1,3641 @@
+import abc
+import collections
+import collections.abc
+import contextlib
+import functools
+import inspect
+import operator
+import sys
+import types as _types
+import typing
+import warnings
+
+__all__ = [
+    # Super-special typing primitives.
+    'Any',
+    'ClassVar',
+    'Concatenate',
+    'Final',
+    'LiteralString',
+    'ParamSpec',
+    'ParamSpecArgs',
+    'ParamSpecKwargs',
+    'Self',
+    'Type',
+    'TypeVar',
+    'TypeVarTuple',
+    'Unpack',
+
+    # ABCs (from collections.abc).
+    'Awaitable',
+    'AsyncIterator',
+    'AsyncIterable',
+    'Coroutine',
+    'AsyncGenerator',
+    'AsyncContextManager',
+    'Buffer',
+    'ChainMap',
+
+    # Concrete collection types.
+    'ContextManager',
+    'Counter',
+    'Deque',
+    'DefaultDict',
+    'NamedTuple',
+    'OrderedDict',
+    'TypedDict',
+
+    # Structural checks, a.k.a. protocols.
+    'SupportsAbs',
+    'SupportsBytes',
+    'SupportsComplex',
+    'SupportsFloat',
+    'SupportsIndex',
+    'SupportsInt',
+    'SupportsRound',
+
+    # One-off things.
+    'Annotated',
+    'assert_never',
+    'assert_type',
+    'clear_overloads',
+    'dataclass_transform',
+    'deprecated',
+    'Doc',
+    'get_overloads',
+    'final',
+    'get_args',
+    'get_origin',
+    'get_original_bases',
+    'get_protocol_members',
+    'get_type_hints',
+    'IntVar',
+    'is_protocol',
+    'is_typeddict',
+    'Literal',
+    'NewType',
+    'overload',
+    'override',
+    'Protocol',
+    'reveal_type',
+    'runtime',
+    'runtime_checkable',
+    'Text',
+    'TypeAlias',
+    'TypeAliasType',
+    'TypeGuard',
+    'TypeIs',
+    'TYPE_CHECKING',
+    'Never',
+    'NoReturn',
+    'ReadOnly',
+    'Required',
+    'NotRequired',
+
+    # Pure aliases, have always been in typing
+    'AbstractSet',
+    'AnyStr',
+    'BinaryIO',
+    'Callable',
+    'Collection',
+    'Container',
+    'Dict',
+    'ForwardRef',
+    'FrozenSet',
+    'Generator',
+    'Generic',
+    'Hashable',
+    'IO',
+    'ItemsView',
+    'Iterable',
+    'Iterator',
+    'KeysView',
+    'List',
+    'Mapping',
+    'MappingView',
+    'Match',
+    'MutableMapping',
+    'MutableSequence',
+    'MutableSet',
+    'NoDefault',
+    'Optional',
+    'Pattern',
+    'Reversible',
+    'Sequence',
+    'Set',
+    'Sized',
+    'TextIO',
+    'Tuple',
+    'Union',
+    'ValuesView',
+    'cast',
+    'no_type_check',
+    'no_type_check_decorator',
+]
+
+# for backward compatibility
+PEP_560 = True
+GenericMeta = type
+_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta")
+
+# The functions below are modified copies of typing internal helpers.
+# They are needed by _ProtocolMeta and they provide support for PEP 646.
+
+
+class _Sentinel:
+    def __repr__(self):
+        return ""
+
+
+_marker = _Sentinel()
+
+
+if sys.version_info >= (3, 10):
+    def _should_collect_from_parameters(t):
+        return isinstance(
+            t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
+        )
+elif sys.version_info >= (3, 9):
+    def _should_collect_from_parameters(t):
+        return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
+else:
+    def _should_collect_from_parameters(t):
+        return isinstance(t, typing._GenericAlias) and not t._special
+
+
+NoReturn = typing.NoReturn
+
+# Some unconstrained type variables.  These are used by the container types.
+# (These are not for export.)
+T = typing.TypeVar('T')  # Any type.
+KT = typing.TypeVar('KT')  # Key type.
+VT = typing.TypeVar('VT')  # Value type.
+T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
+T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
+
+
+if sys.version_info >= (3, 11):
+    from typing import Any
+else:
+
+    class _AnyMeta(type):
+        def __instancecheck__(self, obj):
+            if self is Any:
+                raise TypeError("typing_extensions.Any cannot be used with isinstance()")
+            return super().__instancecheck__(obj)
+
+        def __repr__(self):
+            if self is Any:
+                return "typing_extensions.Any"
+            return super().__repr__()
+
+    class Any(metaclass=_AnyMeta):
+        """Special type indicating an unconstrained type.
+        - Any is compatible with every type.
+        - Any assumed to have all methods.
+        - All values assumed to be instances of Any.
+        Note that all the above statements are true from the point of view of
+        static type checkers. At runtime, Any should not be used with instance
+        checks.
+        """
+        def __new__(cls, *args, **kwargs):
+            if cls is Any:
+                raise TypeError("Any cannot be instantiated")
+            return super().__new__(cls, *args, **kwargs)
+
+
+ClassVar = typing.ClassVar
+
+
+class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
+    def __repr__(self):
+        return 'typing_extensions.' + self._name
+
+
+Final = typing.Final
+
+if sys.version_info >= (3, 11):
+    final = typing.final
+else:
+    # @final exists in 3.8+, but we backport it for all versions
+    # before 3.11 to keep support for the __final__ attribute.
+    # See https://bugs.python.org/issue46342
+    def final(f):
+        """This decorator can be used to indicate to type checkers that
+        the decorated method cannot be overridden, and decorated class
+        cannot be subclassed. For example:
+
+            class Base:
+                @final
+                def done(self) -> None:
+                    ...
+            class Sub(Base):
+                def done(self) -> None:  # Error reported by type checker
+                    ...
+            @final
+            class Leaf:
+                ...
+            class Other(Leaf):  # Error reported by type checker
+                ...
+
+        There is no runtime checking of these properties. The decorator
+        sets the ``__final__`` attribute to ``True`` on the decorated object
+        to allow runtime introspection.
+        """
+        try:
+            f.__final__ = True
+        except (AttributeError, TypeError):
+            # Skip the attribute silently if it is not writable.
+            # AttributeError happens if the object has __slots__ or a
+            # read-only property, TypeError if it's a builtin class.
+            pass
+        return f
+
+
+def IntVar(name):
+    return typing.TypeVar(name)
+
+
+# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
+if sys.version_info >= (3, 10, 1):
+    Literal = typing.Literal
+else:
+    def _flatten_literal_params(parameters):
+        """An internal helper for Literal creation: flatten Literals among parameters"""
+        params = []
+        for p in parameters:
+            if isinstance(p, _LiteralGenericAlias):
+                params.extend(p.__args__)
+            else:
+                params.append(p)
+        return tuple(params)
+
+    def _value_and_type_iter(params):
+        for p in params:
+            yield p, type(p)
+
+    class _LiteralGenericAlias(typing._GenericAlias, _root=True):
+        def __eq__(self, other):
+            if not isinstance(other, _LiteralGenericAlias):
+                return NotImplemented
+            these_args_deduped = set(_value_and_type_iter(self.__args__))
+            other_args_deduped = set(_value_and_type_iter(other.__args__))
+            return these_args_deduped == other_args_deduped
+
+        def __hash__(self):
+            return hash(frozenset(_value_and_type_iter(self.__args__)))
+
+    class _LiteralForm(_ExtensionsSpecialForm, _root=True):
+        def __init__(self, doc: str):
+            self._name = 'Literal'
+            self._doc = self.__doc__ = doc
+
+        def __getitem__(self, parameters):
+            if not isinstance(parameters, tuple):
+                parameters = (parameters,)
+
+            parameters = _flatten_literal_params(parameters)
+
+            val_type_pairs = list(_value_and_type_iter(parameters))
+            try:
+                deduped_pairs = set(val_type_pairs)
+            except TypeError:
+                # unhashable parameters
+                pass
+            else:
+                # similar logic to typing._deduplicate on Python 3.9+
+                if len(deduped_pairs) < len(val_type_pairs):
+                    new_parameters = []
+                    for pair in val_type_pairs:
+                        if pair in deduped_pairs:
+                            new_parameters.append(pair[0])
+                            deduped_pairs.remove(pair)
+                    assert not deduped_pairs, deduped_pairs
+                    parameters = tuple(new_parameters)
+
+            return _LiteralGenericAlias(self, parameters)
+
+    Literal = _LiteralForm(doc="""\
+                           A type that can be used to indicate to type checkers
+                           that the corresponding value has a value literally equivalent
+                           to the provided parameter. For example:
+
+                               var: Literal[4] = 4
+
+                           The type checker understands that 'var' is literally equal to
+                           the value 4 and no other value.
+
+                           Literal[...] cannot be subclassed. There is no runtime
+                           checking verifying that the parameter is actually a value
+                           instead of a type.""")
+
+
+_overload_dummy = typing._overload_dummy
+
+
+if hasattr(typing, "get_overloads"):  # 3.11+
+    overload = typing.overload
+    get_overloads = typing.get_overloads
+    clear_overloads = typing.clear_overloads
+else:
+    # {module: {qualname: {firstlineno: func}}}
+    _overload_registry = collections.defaultdict(
+        functools.partial(collections.defaultdict, dict)
+    )
+
+    def overload(func):
+        """Decorator for overloaded functions/methods.
+
+        In a stub file, place two or more stub definitions for the same
+        function in a row, each decorated with @overload.  For example:
+
+        @overload
+        def utf8(value: None) -> None: ...
+        @overload
+        def utf8(value: bytes) -> bytes: ...
+        @overload
+        def utf8(value: str) -> bytes: ...
+
+        In a non-stub file (i.e. a regular .py file), do the same but
+        follow it with an implementation.  The implementation should *not*
+        be decorated with @overload.  For example:
+
+        @overload
+        def utf8(value: None) -> None: ...
+        @overload
+        def utf8(value: bytes) -> bytes: ...
+        @overload
+        def utf8(value: str) -> bytes: ...
+        def utf8(value):
+            # implementation goes here
+
+        The overloads for a function can be retrieved at runtime using the
+        get_overloads() function.
+        """
+        # classmethod and staticmethod
+        f = getattr(func, "__func__", func)
+        try:
+            _overload_registry[f.__module__][f.__qualname__][
+                f.__code__.co_firstlineno
+            ] = func
+        except AttributeError:
+            # Not a normal function; ignore.
+            pass
+        return _overload_dummy
+
+    def get_overloads(func):
+        """Return all defined overloads for *func* as a sequence."""
+        # classmethod and staticmethod
+        f = getattr(func, "__func__", func)
+        if f.__module__ not in _overload_registry:
+            return []
+        mod_dict = _overload_registry[f.__module__]
+        if f.__qualname__ not in mod_dict:
+            return []
+        return list(mod_dict[f.__qualname__].values())
+
+    def clear_overloads():
+        """Clear all overloads in the registry."""
+        _overload_registry.clear()
+
+
+# This is not a real generic class.  Don't use outside annotations.
+Type = typing.Type
+
+# Various ABCs mimicking those in collections.abc.
+# A few are simply re-exported for completeness.
+Awaitable = typing.Awaitable
+Coroutine = typing.Coroutine
+AsyncIterable = typing.AsyncIterable
+AsyncIterator = typing.AsyncIterator
+Deque = typing.Deque
+DefaultDict = typing.DefaultDict
+OrderedDict = typing.OrderedDict
+Counter = typing.Counter
+ChainMap = typing.ChainMap
+Text = typing.Text
+TYPE_CHECKING = typing.TYPE_CHECKING
+
+
+if sys.version_info >= (3, 13, 0, "beta"):
+    from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
+else:
+    def _is_dunder(attr):
+        return attr.startswith('__') and attr.endswith('__')
+
+    # Python <3.9 doesn't have typing._SpecialGenericAlias
+    _special_generic_alias_base = getattr(
+        typing, "_SpecialGenericAlias", typing._GenericAlias
+    )
+
+    class _SpecialGenericAlias(_special_generic_alias_base, _root=True):
+        def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
+            if _special_generic_alias_base is typing._GenericAlias:
+                # Python <3.9
+                self.__origin__ = origin
+                self._nparams = nparams
+                super().__init__(origin, nparams, special=True, inst=inst, name=name)
+            else:
+                # Python >= 3.9
+                super().__init__(origin, nparams, inst=inst, name=name)
+            self._defaults = defaults
+
+        def __setattr__(self, attr, val):
+            allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'}
+            if _special_generic_alias_base is typing._GenericAlias:
+                # Python <3.9
+                allowed_attrs.add("__origin__")
+            if _is_dunder(attr) or attr in allowed_attrs:
+                object.__setattr__(self, attr, val)
+            else:
+                setattr(self.__origin__, attr, val)
+
+        @typing._tp_cache
+        def __getitem__(self, params):
+            if not isinstance(params, tuple):
+                params = (params,)
+            msg = "Parameters to generic types must be types."
+            params = tuple(typing._type_check(p, msg) for p in params)
+            if (
+                self._defaults
+                and len(params) < self._nparams
+                and len(params) + len(self._defaults) >= self._nparams
+            ):
+                params = (*params, *self._defaults[len(params) - self._nparams:])
+            actual_len = len(params)
+
+            if actual_len != self._nparams:
+                if self._defaults:
+                    expected = f"at least {self._nparams - len(self._defaults)}"
+                else:
+                    expected = str(self._nparams)
+                if not self._nparams:
+                    raise TypeError(f"{self} is not a generic class")
+                raise TypeError(
+                    f"Too {'many' if actual_len > self._nparams else 'few'}"
+                    f" arguments for {self};"
+                    f" actual {actual_len}, expected {expected}"
+                )
+            return self.copy_with(params)
+
+    _NoneType = type(None)
+    Generator = _SpecialGenericAlias(
+        collections.abc.Generator, 3, defaults=(_NoneType, _NoneType)
+    )
+    AsyncGenerator = _SpecialGenericAlias(
+        collections.abc.AsyncGenerator, 2, defaults=(_NoneType,)
+    )
+    ContextManager = _SpecialGenericAlias(
+        contextlib.AbstractContextManager,
+        2,
+        name="ContextManager",
+        defaults=(typing.Optional[bool],)
+    )
+    AsyncContextManager = _SpecialGenericAlias(
+        contextlib.AbstractAsyncContextManager,
+        2,
+        name="AsyncContextManager",
+        defaults=(typing.Optional[bool],)
+    )
+
+
+_PROTO_ALLOWLIST = {
+    'collections.abc': [
+        'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
+        'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
+    ],
+    'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
+    'typing_extensions': ['Buffer'],
+}
+
+
+_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
+    "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
+    "__final__",
+}
+
+
+def _get_protocol_attrs(cls):
+    attrs = set()
+    for base in cls.__mro__[:-1]:  # without object
+        if base.__name__ in {'Protocol', 'Generic'}:
+            continue
+        annotations = getattr(base, '__annotations__', {})
+        for attr in (*base.__dict__, *annotations):
+            if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
+                attrs.add(attr)
+    return attrs
+
+
+def _caller(depth=2):
+    try:
+        return sys._getframe(depth).f_globals.get('__name__', '__main__')
+    except (AttributeError, ValueError):  # For platforms without _getframe()
+        return None
+
+
+# `__match_args__` attribute was removed from protocol members in 3.13,
+# we want to backport this change to older Python versions.
+if sys.version_info >= (3, 13):
+    Protocol = typing.Protocol
+else:
+    def _allow_reckless_class_checks(depth=3):
+        """Allow instance and class checks for special stdlib modules.
+        The abc and functools modules indiscriminately call isinstance() and
+        issubclass() on the whole MRO of a user class, which may contain protocols.
+        """
+        return _caller(depth) in {'abc', 'functools', None}
+
+    def _no_init(self, *args, **kwargs):
+        if type(self)._is_protocol:
+            raise TypeError('Protocols cannot be instantiated')
+
+    def _type_check_issubclass_arg_1(arg):
+        """Raise TypeError if `arg` is not an instance of `type`
+        in `issubclass(arg, )`.
+
+        In most cases, this is verified by type.__subclasscheck__.
+        Checking it again unnecessarily would slow down issubclass() checks,
+        so, we don't perform this check unless we absolutely have to.
+
+        For various error paths, however,
+        we want to ensure that *this* error message is shown to the user
+        where relevant, rather than a typing.py-specific error message.
+        """
+        if not isinstance(arg, type):
+            # Same error message as for issubclass(1, int).
+            raise TypeError('issubclass() arg 1 must be a class')
+
+    # Inheriting from typing._ProtocolMeta isn't actually desirable,
+    # but is necessary to allow typing.Protocol and typing_extensions.Protocol
+    # to mix without getting TypeErrors about "metaclass conflict"
+    class _ProtocolMeta(type(typing.Protocol)):
+        # This metaclass is somewhat unfortunate,
+        # but is necessary for several reasons...
+        #
+        # NOTE: DO NOT call super() in any methods in this class
+        # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
+        # and those are slow
+        def __new__(mcls, name, bases, namespace, **kwargs):
+            if name == "Protocol" and len(bases) < 2:
+                pass
+            elif {Protocol, typing.Protocol} & set(bases):
+                for base in bases:
+                    if not (
+                        base in {object, typing.Generic, Protocol, typing.Protocol}
+                        or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
+                        or is_protocol(base)
+                    ):
+                        raise TypeError(
+                            f"Protocols can only inherit from other protocols, "
+                            f"got {base!r}"
+                        )
+            return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
+
+        def __init__(cls, *args, **kwargs):
+            abc.ABCMeta.__init__(cls, *args, **kwargs)
+            if getattr(cls, "_is_protocol", False):
+                cls.__protocol_attrs__ = _get_protocol_attrs(cls)
+
+        def __subclasscheck__(cls, other):
+            if cls is Protocol:
+                return type.__subclasscheck__(cls, other)
+            if (
+                getattr(cls, '_is_protocol', False)
+                and not _allow_reckless_class_checks()
+            ):
+                if not getattr(cls, '_is_runtime_protocol', False):
+                    _type_check_issubclass_arg_1(other)
+                    raise TypeError(
+                        "Instance and class checks can only be used with "
+                        "@runtime_checkable protocols"
+                    )
+                if (
+                    # this attribute is set by @runtime_checkable:
+                    cls.__non_callable_proto_members__
+                    and cls.__dict__.get("__subclasshook__") is _proto_hook
+                ):
+                    _type_check_issubclass_arg_1(other)
+                    non_method_attrs = sorted(cls.__non_callable_proto_members__)
+                    raise TypeError(
+                        "Protocols with non-method members don't support issubclass()."
+                        f" Non-method members: {str(non_method_attrs)[1:-1]}."
+                    )
+            return abc.ABCMeta.__subclasscheck__(cls, other)
+
+        def __instancecheck__(cls, instance):
+            # We need this method for situations where attributes are
+            # assigned in __init__.
+            if cls is Protocol:
+                return type.__instancecheck__(cls, instance)
+            if not getattr(cls, "_is_protocol", False):
+                # i.e., it's a concrete subclass of a protocol
+                return abc.ABCMeta.__instancecheck__(cls, instance)
+
+            if (
+                not getattr(cls, '_is_runtime_protocol', False) and
+                not _allow_reckless_class_checks()
+            ):
+                raise TypeError("Instance and class checks can only be used with"
+                                " @runtime_checkable protocols")
+
+            if abc.ABCMeta.__instancecheck__(cls, instance):
+                return True
+
+            for attr in cls.__protocol_attrs__:
+                try:
+                    val = inspect.getattr_static(instance, attr)
+                except AttributeError:
+                    break
+                # this attribute is set by @runtime_checkable:
+                if val is None and attr not in cls.__non_callable_proto_members__:
+                    break
+            else:
+                return True
+
+            return False
+
+        def __eq__(cls, other):
+            # Hack so that typing.Generic.__class_getitem__
+            # treats typing_extensions.Protocol
+            # as equivalent to typing.Protocol
+            if abc.ABCMeta.__eq__(cls, other) is True:
+                return True
+            return cls is Protocol and other is typing.Protocol
+
+        # This has to be defined, or the abc-module cache
+        # complains about classes with this metaclass being unhashable,
+        # if we define only __eq__!
+        def __hash__(cls) -> int:
+            return type.__hash__(cls)
+
+    @classmethod
+    def _proto_hook(cls, other):
+        if not cls.__dict__.get('_is_protocol', False):
+            return NotImplemented
+
+        for attr in cls.__protocol_attrs__:
+            for base in other.__mro__:
+                # Check if the members appears in the class dictionary...
+                if attr in base.__dict__:
+                    if base.__dict__[attr] is None:
+                        return NotImplemented
+                    break
+
+                # ...or in annotations, if it is a sub-protocol.
+                annotations = getattr(base, '__annotations__', {})
+                if (
+                    isinstance(annotations, collections.abc.Mapping)
+                    and attr in annotations
+                    and is_protocol(other)
+                ):
+                    break
+            else:
+                return NotImplemented
+        return True
+
+    class Protocol(typing.Generic, metaclass=_ProtocolMeta):
+        __doc__ = typing.Protocol.__doc__
+        __slots__ = ()
+        _is_protocol = True
+        _is_runtime_protocol = False
+
+        def __init_subclass__(cls, *args, **kwargs):
+            super().__init_subclass__(*args, **kwargs)
+
+            # Determine if this is a protocol or a concrete subclass.
+            if not cls.__dict__.get('_is_protocol', False):
+                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
+
+            # Set (or override) the protocol subclass hook.
+            if '__subclasshook__' not in cls.__dict__:
+                cls.__subclasshook__ = _proto_hook
+
+            # Prohibit instantiation for protocol classes
+            if cls._is_protocol and cls.__init__ is Protocol.__init__:
+                cls.__init__ = _no_init
+
+
+if sys.version_info >= (3, 13):
+    runtime_checkable = typing.runtime_checkable
+else:
+    def runtime_checkable(cls):
+        """Mark a protocol class as a runtime protocol.
+
+        Such protocol can be used with isinstance() and issubclass().
+        Raise TypeError if applied to a non-protocol class.
+        This allows a simple-minded structural check very similar to
+        one trick ponies in collections.abc such as Iterable.
+
+        For example::
+
+            @runtime_checkable
+            class Closable(Protocol):
+                def close(self): ...
+
+            assert isinstance(open('/some/file'), Closable)
+
+        Warning: this will check only the presence of the required methods,
+        not their type signatures!
+        """
+        if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
+            raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
+                            f' got {cls!r}')
+        cls._is_runtime_protocol = True
+
+        # typing.Protocol classes on <=3.11 break if we execute this block,
+        # because typing.Protocol classes on <=3.11 don't have a
+        # `__protocol_attrs__` attribute, and this block relies on the
+        # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+
+        # break if we *don't* execute this block, because *they* assume that all
+        # protocol classes have a `__non_callable_proto_members__` attribute
+        # (which this block sets)
+        if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2):
+            # PEP 544 prohibits using issubclass()
+            # with protocols that have non-method members.
+            # See gh-113320 for why we compute this attribute here,
+            # rather than in `_ProtocolMeta.__init__`
+            cls.__non_callable_proto_members__ = set()
+            for attr in cls.__protocol_attrs__:
+                try:
+                    is_callable = callable(getattr(cls, attr, None))
+                except Exception as e:
+                    raise TypeError(
+                        f"Failed to determine whether protocol member {attr!r} "
+                        "is a method member"
+                    ) from e
+                else:
+                    if not is_callable:
+                        cls.__non_callable_proto_members__.add(attr)
+
+        return cls
+
+
+# The "runtime" alias exists for backwards compatibility.
+runtime = runtime_checkable
+
+
+# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
+if sys.version_info >= (3, 12):
+    SupportsInt = typing.SupportsInt
+    SupportsFloat = typing.SupportsFloat
+    SupportsComplex = typing.SupportsComplex
+    SupportsBytes = typing.SupportsBytes
+    SupportsIndex = typing.SupportsIndex
+    SupportsAbs = typing.SupportsAbs
+    SupportsRound = typing.SupportsRound
+else:
+    @runtime_checkable
+    class SupportsInt(Protocol):
+        """An ABC with one abstract method __int__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __int__(self) -> int:
+            pass
+
+    @runtime_checkable
+    class SupportsFloat(Protocol):
+        """An ABC with one abstract method __float__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __float__(self) -> float:
+            pass
+
+    @runtime_checkable
+    class SupportsComplex(Protocol):
+        """An ABC with one abstract method __complex__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __complex__(self) -> complex:
+            pass
+
+    @runtime_checkable
+    class SupportsBytes(Protocol):
+        """An ABC with one abstract method __bytes__."""
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __bytes__(self) -> bytes:
+            pass
+
+    @runtime_checkable
+    class SupportsIndex(Protocol):
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __index__(self) -> int:
+            pass
+
+    @runtime_checkable
+    class SupportsAbs(Protocol[T_co]):
+        """
+        An ABC with one abstract method __abs__ that is covariant in its return type.
+        """
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __abs__(self) -> T_co:
+            pass
+
+    @runtime_checkable
+    class SupportsRound(Protocol[T_co]):
+        """
+        An ABC with one abstract method __round__ that is covariant in its return type.
+        """
+        __slots__ = ()
+
+        @abc.abstractmethod
+        def __round__(self, ndigits: int = 0) -> T_co:
+            pass
+
+
+def _ensure_subclassable(mro_entries):
+    def inner(func):
+        if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
+            cls_dict = {
+                "__call__": staticmethod(func),
+                "__mro_entries__": staticmethod(mro_entries)
+            }
+            t = type(func.__name__, (), cls_dict)
+            return functools.update_wrapper(t(), func)
+        else:
+            func.__mro_entries__ = mro_entries
+            return func
+    return inner
+
+
+# Update this to something like >=3.13.0b1 if and when
+# PEP 728 is implemented in CPython
+_PEP_728_IMPLEMENTED = False
+
+if _PEP_728_IMPLEMENTED:
+    # The standard library TypedDict in Python 3.8 does not store runtime information
+    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
+    # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
+    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059
+    # The standard library TypedDict below Python 3.11 does not store runtime
+    # information about optional and required keys when using Required or NotRequired.
+    # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
+    # Aaaand on 3.12 we add __orig_bases__ to TypedDict
+    # to enable better runtime introspection.
+    # On 3.13 we deprecate some odd ways of creating TypedDicts.
+    # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
+    # PEP 728 (still pending) makes more changes.
+    TypedDict = typing.TypedDict
+    _TypedDictMeta = typing._TypedDictMeta
+    is_typeddict = typing.is_typeddict
+else:
+    # 3.10.0 and later
+    _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
+
+    def _get_typeddict_qualifiers(annotation_type):
+        while True:
+            annotation_origin = get_origin(annotation_type)
+            if annotation_origin is Annotated:
+                annotation_args = get_args(annotation_type)
+                if annotation_args:
+                    annotation_type = annotation_args[0]
+                else:
+                    break
+            elif annotation_origin is Required:
+                yield Required
+                annotation_type, = get_args(annotation_type)
+            elif annotation_origin is NotRequired:
+                yield NotRequired
+                annotation_type, = get_args(annotation_type)
+            elif annotation_origin is ReadOnly:
+                yield ReadOnly
+                annotation_type, = get_args(annotation_type)
+            else:
+                break
+
+    class _TypedDictMeta(type):
+        def __new__(cls, name, bases, ns, *, total=True, closed=False):
+            """Create new typed dict class object.
+
+            This method is called when TypedDict is subclassed,
+            or when TypedDict is instantiated. This way
+            TypedDict supports all three syntax forms described in its docstring.
+            Subclasses and instances of TypedDict return actual dictionaries.
+            """
+            for base in bases:
+                if type(base) is not _TypedDictMeta and base is not typing.Generic:
+                    raise TypeError('cannot inherit from both a TypedDict type '
+                                    'and a non-TypedDict base class')
+
+            if any(issubclass(b, typing.Generic) for b in bases):
+                generic_base = (typing.Generic,)
+            else:
+                generic_base = ()
+
+            # typing.py generally doesn't let you inherit from plain Generic, unless
+            # the name of the class happens to be "Protocol"
+            tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
+            tp_dict.__name__ = name
+            if tp_dict.__qualname__ == "Protocol":
+                tp_dict.__qualname__ = name
+
+            if not hasattr(tp_dict, '__orig_bases__'):
+                tp_dict.__orig_bases__ = bases
+
+            annotations = {}
+            if "__annotations__" in ns:
+                own_annotations = ns["__annotations__"]
+            elif "__annotate__" in ns:
+                # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
+                own_annotations = ns["__annotate__"](1)
+            else:
+                own_annotations = {}
+            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
+            if _TAKES_MODULE:
+                own_annotations = {
+                    n: typing._type_check(tp, msg, module=tp_dict.__module__)
+                    for n, tp in own_annotations.items()
+                }
+            else:
+                own_annotations = {
+                    n: typing._type_check(tp, msg)
+                    for n, tp in own_annotations.items()
+                }
+            required_keys = set()
+            optional_keys = set()
+            readonly_keys = set()
+            mutable_keys = set()
+            extra_items_type = None
+
+            for base in bases:
+                base_dict = base.__dict__
+
+                annotations.update(base_dict.get('__annotations__', {}))
+                required_keys.update(base_dict.get('__required_keys__', ()))
+                optional_keys.update(base_dict.get('__optional_keys__', ()))
+                readonly_keys.update(base_dict.get('__readonly_keys__', ()))
+                mutable_keys.update(base_dict.get('__mutable_keys__', ()))
+                base_extra_items_type = base_dict.get('__extra_items__', None)
+                if base_extra_items_type is not None:
+                    extra_items_type = base_extra_items_type
+
+            if closed and extra_items_type is None:
+                extra_items_type = Never
+            if closed and "__extra_items__" in own_annotations:
+                annotation_type = own_annotations.pop("__extra_items__")
+                qualifiers = set(_get_typeddict_qualifiers(annotation_type))
+                if Required in qualifiers:
+                    raise TypeError(
+                        "Special key __extra_items__ does not support "
+                        "Required"
+                    )
+                if NotRequired in qualifiers:
+                    raise TypeError(
+                        "Special key __extra_items__ does not support "
+                        "NotRequired"
+                    )
+                extra_items_type = annotation_type
+
+            annotations.update(own_annotations)
+            for annotation_key, annotation_type in own_annotations.items():
+                qualifiers = set(_get_typeddict_qualifiers(annotation_type))
+
+                if Required in qualifiers:
+                    required_keys.add(annotation_key)
+                elif NotRequired in qualifiers:
+                    optional_keys.add(annotation_key)
+                elif total:
+                    required_keys.add(annotation_key)
+                else:
+                    optional_keys.add(annotation_key)
+                if ReadOnly in qualifiers:
+                    mutable_keys.discard(annotation_key)
+                    readonly_keys.add(annotation_key)
+                else:
+                    mutable_keys.add(annotation_key)
+                    readonly_keys.discard(annotation_key)
+
+            tp_dict.__annotations__ = annotations
+            tp_dict.__required_keys__ = frozenset(required_keys)
+            tp_dict.__optional_keys__ = frozenset(optional_keys)
+            tp_dict.__readonly_keys__ = frozenset(readonly_keys)
+            tp_dict.__mutable_keys__ = frozenset(mutable_keys)
+            if not hasattr(tp_dict, '__total__'):
+                tp_dict.__total__ = total
+            tp_dict.__closed__ = closed
+            tp_dict.__extra_items__ = extra_items_type
+            return tp_dict
+
+        __call__ = dict  # static method
+
+        def __subclasscheck__(cls, other):
+            # Typed dicts are only for static structural subtyping.
+            raise TypeError('TypedDict does not support instance and class checks')
+
+        __instancecheck__ = __subclasscheck__
+
+    _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
+
+    @_ensure_subclassable(lambda bases: (_TypedDict,))
+    def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs):
+        """A simple typed namespace. At runtime it is equivalent to a plain dict.
+
+        TypedDict creates a dictionary type such that a type checker will expect all
+        instances to have a certain set of keys, where each key is
+        associated with a value of a consistent type. This expectation
+        is not checked at runtime.
+
+        Usage::
+
+            class Point2D(TypedDict):
+                x: int
+                y: int
+                label: str
+
+            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
+            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
+
+            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
+
+        The type info can be accessed via the Point2D.__annotations__ dict, and
+        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
+        TypedDict supports an additional equivalent form::
+
+            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
+
+        By default, all keys must be present in a TypedDict. It is possible
+        to override this by specifying totality::
+
+            class Point2D(TypedDict, total=False):
+                x: int
+                y: int
+
+        This means that a Point2D TypedDict can have any of the keys omitted. A type
+        checker is only expected to support a literal False or True as the value of
+        the total argument. True is the default, and makes all items defined in the
+        class body be required.
+
+        The Required and NotRequired special forms can also be used to mark
+        individual keys as being required or not required::
+
+            class Point2D(TypedDict):
+                x: int  # the "x" key must always be present (Required is the default)
+                y: NotRequired[int]  # the "y" key can be omitted
+
+        See PEP 655 for more details on Required and NotRequired.
+        """
+        if fields is _marker or fields is None:
+            if fields is _marker:
+                deprecated_thing = "Failing to pass a value for the 'fields' parameter"
+            else:
+                deprecated_thing = "Passing `None` as the 'fields' parameter"
+
+            example = f"`{typename} = TypedDict({typename!r}, {{}})`"
+            deprecation_msg = (
+                f"{deprecated_thing} is deprecated and will be disallowed in "
+                "Python 3.15. To create a TypedDict class with 0 fields "
+                "using the functional syntax, pass an empty dictionary, e.g. "
+            ) + example + "."
+            warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
+            if closed is not False and closed is not True:
+                kwargs["closed"] = closed
+                closed = False
+            fields = kwargs
+        elif kwargs:
+            raise TypeError("TypedDict takes either a dict or keyword arguments,"
+                            " but not both")
+        if kwargs:
+            if sys.version_info >= (3, 13):
+                raise TypeError("TypedDict takes no keyword arguments")
+            warnings.warn(
+                "The kwargs-based syntax for TypedDict definitions is deprecated "
+                "in Python 3.11, will be removed in Python 3.13, and may not be "
+                "understood by third-party type checkers.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+
+        ns = {'__annotations__': dict(fields)}
+        module = _caller()
+        if module is not None:
+            # Setting correct module is necessary to make typed dict classes pickleable.
+            ns['__module__'] = module
+
+        td = _TypedDictMeta(typename, (), ns, total=total, closed=closed)
+        td.__orig_bases__ = (TypedDict,)
+        return td
+
+    if hasattr(typing, "_TypedDictMeta"):
+        _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
+    else:
+        _TYPEDDICT_TYPES = (_TypedDictMeta,)
+
+    def is_typeddict(tp):
+        """Check if an annotation is a TypedDict class
+
+        For example::
+            class Film(TypedDict):
+                title: str
+                year: int
+
+            is_typeddict(Film)  # => True
+            is_typeddict(Union[list, str])  # => False
+        """
+        # On 3.8, this would otherwise return True
+        if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
+            return False
+        return isinstance(tp, _TYPEDDICT_TYPES)
+
+
+if hasattr(typing, "assert_type"):
+    assert_type = typing.assert_type
+
+else:
+    def assert_type(val, typ, /):
+        """Assert (to the type checker) that the value is of the given type.
+
+        When the type checker encounters a call to assert_type(), it
+        emits an error if the value is not of the specified type::
+
+            def greet(name: str) -> None:
+                assert_type(name, str)  # ok
+                assert_type(name, int)  # type checker error
+
+        At runtime this returns the first argument unchanged and otherwise
+        does nothing.
+        """
+        return val
+
+
+if hasattr(typing, "ReadOnly"):  # 3.13+
+    get_type_hints = typing.get_type_hints
+else:  # <=3.13
+    # replaces _strip_annotations()
+    def _strip_extras(t):
+        """Strips Annotated, Required and NotRequired from a given type."""
+        if isinstance(t, _AnnotatedAlias):
+            return _strip_extras(t.__origin__)
+        if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
+            return _strip_extras(t.__args__[0])
+        if isinstance(t, typing._GenericAlias):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return t.copy_with(stripped_args)
+        if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return _types.GenericAlias(t.__origin__, stripped_args)
+        if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
+            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
+            if stripped_args == t.__args__:
+                return t
+            return functools.reduce(operator.or_, stripped_args)
+
+        return t
+
+    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
+        """Return type hints for an object.
+
+        This is often the same as obj.__annotations__, but it handles
+        forward references encoded as string literals, adds Optional[t] if a
+        default value equal to None is set and recursively replaces all
+        'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
+        (unless 'include_extras=True').
+
+        The argument may be a module, class, method, or function. The annotations
+        are returned as a dictionary. For classes, annotations include also
+        inherited members.
+
+        TypeError is raised if the argument is not of a type that can contain
+        annotations, and an empty dictionary is returned if no annotations are
+        present.
+
+        BEWARE -- the behavior of globalns and localns is counterintuitive
+        (unless you are familiar with how eval() and exec() work).  The
+        search order is locals first, then globals.
+
+        - If no dict arguments are passed, an attempt is made to use the
+          globals from obj (or the respective module's globals for classes),
+          and these are also used as the locals.  If the object does not appear
+          to have globals, an empty dictionary is used.
+
+        - If one dict argument is passed, it is used for both globals and
+          locals.
+
+        - If two dict arguments are passed, they specify globals and
+          locals, respectively.
+        """
+        if hasattr(typing, "Annotated"):  # 3.9+
+            hint = typing.get_type_hints(
+                obj, globalns=globalns, localns=localns, include_extras=True
+            )
+        else:  # 3.8
+            hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
+        if include_extras:
+            return hint
+        return {k: _strip_extras(t) for k, t in hint.items()}
+
+
+# Python 3.9+ has PEP 593 (Annotated)
+if hasattr(typing, 'Annotated'):
+    Annotated = typing.Annotated
+    # Not exported and not a public API, but needed for get_origin() and get_args()
+    # to work.
+    _AnnotatedAlias = typing._AnnotatedAlias
+# 3.8
+else:
+    class _AnnotatedAlias(typing._GenericAlias, _root=True):
+        """Runtime representation of an annotated type.
+
+        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
+        with extra annotations. The alias behaves like a normal typing alias,
+        instantiating is the same as instantiating the underlying type, binding
+        it to types is also the same.
+        """
+        def __init__(self, origin, metadata):
+            if isinstance(origin, _AnnotatedAlias):
+                metadata = origin.__metadata__ + metadata
+                origin = origin.__origin__
+            super().__init__(origin, origin)
+            self.__metadata__ = metadata
+
+        def copy_with(self, params):
+            assert len(params) == 1
+            new_type = params[0]
+            return _AnnotatedAlias(new_type, self.__metadata__)
+
+        def __repr__(self):
+            return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
+                    f"{', '.join(repr(a) for a in self.__metadata__)}]")
+
+        def __reduce__(self):
+            return operator.getitem, (
+                Annotated, (self.__origin__, *self.__metadata__)
+            )
+
+        def __eq__(self, other):
+            if not isinstance(other, _AnnotatedAlias):
+                return NotImplemented
+            if self.__origin__ != other.__origin__:
+                return False
+            return self.__metadata__ == other.__metadata__
+
+        def __hash__(self):
+            return hash((self.__origin__, self.__metadata__))
+
+    class Annotated:
+        """Add context specific metadata to a type.
+
+        Example: Annotated[int, runtime_check.Unsigned] indicates to the
+        hypothetical runtime_check module that this type is an unsigned int.
+        Every other consumer of this type can ignore this metadata and treat
+        this type as int.
+
+        The first argument to Annotated must be a valid type (and will be in
+        the __origin__ field), the remaining arguments are kept as a tuple in
+        the __extra__ field.
+
+        Details:
+
+        - It's an error to call `Annotated` with less than two arguments.
+        - Nested Annotated are flattened::
+
+            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
+
+        - Instantiating an annotated type is equivalent to instantiating the
+        underlying type::
+
+            Annotated[C, Ann1](5) == C(5)
+
+        - Annotated can be used as a generic type alias::
+
+            Optimized = Annotated[T, runtime.Optimize()]
+            Optimized[int] == Annotated[int, runtime.Optimize()]
+
+            OptimizedList = Annotated[List[T], runtime.Optimize()]
+            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
+        """
+
+        __slots__ = ()
+
+        def __new__(cls, *args, **kwargs):
+            raise TypeError("Type Annotated cannot be instantiated.")
+
+        @typing._tp_cache
+        def __class_getitem__(cls, params):
+            if not isinstance(params, tuple) or len(params) < 2:
+                raise TypeError("Annotated[...] should be used "
+                                "with at least two arguments (a type and an "
+                                "annotation).")
+            allowed_special_forms = (ClassVar, Final)
+            if get_origin(params[0]) in allowed_special_forms:
+                origin = params[0]
+            else:
+                msg = "Annotated[t, ...]: t must be a type."
+                origin = typing._type_check(params[0], msg)
+            metadata = tuple(params[1:])
+            return _AnnotatedAlias(origin, metadata)
+
+        def __init_subclass__(cls, *args, **kwargs):
+            raise TypeError(
+                f"Cannot subclass {cls.__module__}.Annotated"
+            )
+
+# Python 3.8 has get_origin() and get_args() but those implementations aren't
+# Annotated-aware, so we can't use those. Python 3.9's versions don't support
+# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
+if sys.version_info[:2] >= (3, 10):
+    get_origin = typing.get_origin
+    get_args = typing.get_args
+# 3.8-3.9
+else:
+    try:
+        # 3.9+
+        from typing import _BaseGenericAlias
+    except ImportError:
+        _BaseGenericAlias = typing._GenericAlias
+    try:
+        # 3.9+
+        from typing import GenericAlias as _typing_GenericAlias
+    except ImportError:
+        _typing_GenericAlias = typing._GenericAlias
+
+    def get_origin(tp):
+        """Get the unsubscripted version of a type.
+
+        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
+        and Annotated. Return None for unsupported types. Examples::
+
+            get_origin(Literal[42]) is Literal
+            get_origin(int) is None
+            get_origin(ClassVar[int]) is ClassVar
+            get_origin(Generic) is Generic
+            get_origin(Generic[T]) is Generic
+            get_origin(Union[T, int]) is Union
+            get_origin(List[Tuple[T, T]][int]) == list
+            get_origin(P.args) is P
+        """
+        if isinstance(tp, _AnnotatedAlias):
+            return Annotated
+        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
+                           ParamSpecArgs, ParamSpecKwargs)):
+            return tp.__origin__
+        if tp is typing.Generic:
+            return typing.Generic
+        return None
+
+    def get_args(tp):
+        """Get type arguments with all substitutions performed.
+
+        For unions, basic simplifications used by Union constructor are performed.
+        Examples::
+            get_args(Dict[str, int]) == (str, int)
+            get_args(int) == ()
+            get_args(Union[int, Union[T, int], str][int]) == (int, str)
+            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
+            get_args(Callable[[], T][int]) == ([], int)
+        """
+        if isinstance(tp, _AnnotatedAlias):
+            return (tp.__origin__, *tp.__metadata__)
+        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
+            if getattr(tp, "_special", False):
+                return ()
+            res = tp.__args__
+            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
+                res = (list(res[:-1]), res[-1])
+            return res
+        return ()
+
+
+# 3.10+
+if hasattr(typing, 'TypeAlias'):
+    TypeAlias = typing.TypeAlias
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeAlias(self, parameters):
+        """Special marker indicating that an assignment should
+        be recognized as a proper type alias definition by type
+        checkers.
+
+        For example::
+
+            Predicate: TypeAlias = Callable[..., bool]
+
+        It's invalid when used anywhere except as in the example above.
+        """
+        raise TypeError(f"{self} is not subscriptable")
+# 3.8
+else:
+    TypeAlias = _ExtensionsSpecialForm(
+        'TypeAlias',
+        doc="""Special marker indicating that an assignment should
+        be recognized as a proper type alias definition by type
+        checkers.
+
+        For example::
+
+            Predicate: TypeAlias = Callable[..., bool]
+
+        It's invalid when used anywhere except as in the example
+        above."""
+    )
+
+
+if hasattr(typing, "NoDefault"):
+    NoDefault = typing.NoDefault
+else:
+    class NoDefaultTypeMeta(type):
+        def __setattr__(cls, attr, value):
+            # TypeError is consistent with the behavior of NoneType
+            raise TypeError(
+                f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
+            )
+
+    class NoDefaultType(metaclass=NoDefaultTypeMeta):
+        """The type of the NoDefault singleton."""
+
+        __slots__ = ()
+
+        def __new__(cls):
+            return globals().get("NoDefault") or object.__new__(cls)
+
+        def __repr__(self):
+            return "typing_extensions.NoDefault"
+
+        def __reduce__(self):
+            return "NoDefault"
+
+    NoDefault = NoDefaultType()
+    del NoDefaultType, NoDefaultTypeMeta
+
+
+def _set_default(type_param, default):
+    type_param.has_default = lambda: default is not NoDefault
+    type_param.__default__ = default
+
+
+def _set_module(typevarlike):
+    # for pickling:
+    def_mod = _caller(depth=3)
+    if def_mod != 'typing_extensions':
+        typevarlike.__module__ = def_mod
+
+
+class _DefaultMixin:
+    """Mixin for TypeVarLike defaults."""
+
+    __slots__ = ()
+    __init__ = _set_default
+
+
+# Classes using this metaclass must provide a _backported_typevarlike ClassVar
+class _TypeVarLikeMeta(type):
+    def __instancecheck__(cls, __instance: Any) -> bool:
+        return isinstance(__instance, cls._backported_typevarlike)
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import TypeVar
+else:
+    # Add default and infer_variance parameters from PEP 696 and 695
+    class TypeVar(metaclass=_TypeVarLikeMeta):
+        """Type variable."""
+
+        _backported_typevarlike = typing.TypeVar
+
+        def __new__(cls, name, *constraints, bound=None,
+                    covariant=False, contravariant=False,
+                    default=NoDefault, infer_variance=False):
+            if hasattr(typing, "TypeAliasType"):
+                # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
+                typevar = typing.TypeVar(name, *constraints, bound=bound,
+                                         covariant=covariant, contravariant=contravariant,
+                                         infer_variance=infer_variance)
+            else:
+                typevar = typing.TypeVar(name, *constraints, bound=bound,
+                                         covariant=covariant, contravariant=contravariant)
+                if infer_variance and (covariant or contravariant):
+                    raise ValueError("Variance cannot be specified with infer_variance.")
+                typevar.__infer_variance__ = infer_variance
+
+            _set_default(typevar, default)
+            _set_module(typevar)
+
+            def _tvar_prepare_subst(alias, args):
+                if (
+                    typevar.has_default()
+                    and alias.__parameters__.index(typevar) == len(args)
+                ):
+                    args += (typevar.__default__,)
+                return args
+
+            typevar.__typing_prepare_subst__ = _tvar_prepare_subst
+            return typevar
+
+        def __init_subclass__(cls) -> None:
+            raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
+
+
+# Python 3.10+ has PEP 612
+if hasattr(typing, 'ParamSpecArgs'):
+    ParamSpecArgs = typing.ParamSpecArgs
+    ParamSpecKwargs = typing.ParamSpecKwargs
+# 3.8-3.9
+else:
+    class _Immutable:
+        """Mixin to indicate that object should not be copied."""
+        __slots__ = ()
+
+        def __copy__(self):
+            return self
+
+        def __deepcopy__(self, memo):
+            return self
+
+    class ParamSpecArgs(_Immutable):
+        """The args for a ParamSpec object.
+
+        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
+
+        ParamSpecArgs objects have a reference back to their ParamSpec:
+
+        P.args.__origin__ is P
+
+        This type is meant for runtime introspection and has no special meaning to
+        static type checkers.
+        """
+        def __init__(self, origin):
+            self.__origin__ = origin
+
+        def __repr__(self):
+            return f"{self.__origin__.__name__}.args"
+
+        def __eq__(self, other):
+            if not isinstance(other, ParamSpecArgs):
+                return NotImplemented
+            return self.__origin__ == other.__origin__
+
+    class ParamSpecKwargs(_Immutable):
+        """The kwargs for a ParamSpec object.
+
+        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
+
+        ParamSpecKwargs objects have a reference back to their ParamSpec:
+
+        P.kwargs.__origin__ is P
+
+        This type is meant for runtime introspection and has no special meaning to
+        static type checkers.
+        """
+        def __init__(self, origin):
+            self.__origin__ = origin
+
+        def __repr__(self):
+            return f"{self.__origin__.__name__}.kwargs"
+
+        def __eq__(self, other):
+            if not isinstance(other, ParamSpecKwargs):
+                return NotImplemented
+            return self.__origin__ == other.__origin__
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import ParamSpec
+
+# 3.10+
+elif hasattr(typing, 'ParamSpec'):
+
+    # Add default parameter - PEP 696
+    class ParamSpec(metaclass=_TypeVarLikeMeta):
+        """Parameter specification."""
+
+        _backported_typevarlike = typing.ParamSpec
+
+        def __new__(cls, name, *, bound=None,
+                    covariant=False, contravariant=False,
+                    infer_variance=False, default=NoDefault):
+            if hasattr(typing, "TypeAliasType"):
+                # PEP 695 implemented, can pass infer_variance to typing.TypeVar
+                paramspec = typing.ParamSpec(name, bound=bound,
+                                             covariant=covariant,
+                                             contravariant=contravariant,
+                                             infer_variance=infer_variance)
+            else:
+                paramspec = typing.ParamSpec(name, bound=bound,
+                                             covariant=covariant,
+                                             contravariant=contravariant)
+                paramspec.__infer_variance__ = infer_variance
+
+            _set_default(paramspec, default)
+            _set_module(paramspec)
+
+            def _paramspec_prepare_subst(alias, args):
+                params = alias.__parameters__
+                i = params.index(paramspec)
+                if i == len(args) and paramspec.has_default():
+                    args = [*args, paramspec.__default__]
+                if i >= len(args):
+                    raise TypeError(f"Too few arguments for {alias}")
+                # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
+                if len(params) == 1 and not typing._is_param_expr(args[0]):
+                    assert i == 0
+                    args = (args,)
+                # Convert lists to tuples to help other libraries cache the results.
+                elif isinstance(args[i], list):
+                    args = (*args[:i], tuple(args[i]), *args[i + 1:])
+                return args
+
+            paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
+            return paramspec
+
+        def __init_subclass__(cls) -> None:
+            raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
+
+# 3.8-3.9
+else:
+
+    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
+    class ParamSpec(list, _DefaultMixin):
+        """Parameter specification variable.
+
+        Usage::
+
+           P = ParamSpec('P')
+
+        Parameter specification variables exist primarily for the benefit of static
+        type checkers.  They are used to forward the parameter types of one
+        callable to another callable, a pattern commonly found in higher order
+        functions and decorators.  They are only valid when used in ``Concatenate``,
+        or s the first argument to ``Callable``. In Python 3.10 and higher,
+        they are also supported in user-defined Generics at runtime.
+        See class Generic for more information on generic types.  An
+        example for annotating a decorator::
+
+           T = TypeVar('T')
+           P = ParamSpec('P')
+
+           def add_logging(f: Callable[P, T]) -> Callable[P, T]:
+               '''A type-safe decorator to add logging to a function.'''
+               def inner(*args: P.args, **kwargs: P.kwargs) -> T:
+                   logging.info(f'{f.__name__} was called')
+                   return f(*args, **kwargs)
+               return inner
+
+           @add_logging
+           def add_two(x: float, y: float) -> float:
+               '''Add two numbers together.'''
+               return x + y
+
+        Parameter specification variables defined with covariant=True or
+        contravariant=True can be used to declare covariant or contravariant
+        generic types.  These keyword arguments are valid, but their actual semantics
+        are yet to be decided.  See PEP 612 for details.
+
+        Parameter specification variables can be introspected. e.g.:
+
+           P.__name__ == 'T'
+           P.__bound__ == None
+           P.__covariant__ == False
+           P.__contravariant__ == False
+
+        Note that only parameter specification variables defined in global scope can
+        be pickled.
+        """
+
+        # Trick Generic __parameters__.
+        __class__ = typing.TypeVar
+
+        @property
+        def args(self):
+            return ParamSpecArgs(self)
+
+        @property
+        def kwargs(self):
+            return ParamSpecKwargs(self)
+
+        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
+                     infer_variance=False, default=NoDefault):
+            list.__init__(self, [self])
+            self.__name__ = name
+            self.__covariant__ = bool(covariant)
+            self.__contravariant__ = bool(contravariant)
+            self.__infer_variance__ = bool(infer_variance)
+            if bound:
+                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
+            else:
+                self.__bound__ = None
+            _DefaultMixin.__init__(self, default)
+
+            # for pickling:
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+        def __repr__(self):
+            if self.__infer_variance__:
+                prefix = ''
+            elif self.__covariant__:
+                prefix = '+'
+            elif self.__contravariant__:
+                prefix = '-'
+            else:
+                prefix = '~'
+            return prefix + self.__name__
+
+        def __hash__(self):
+            return object.__hash__(self)
+
+        def __eq__(self, other):
+            return self is other
+
+        def __reduce__(self):
+            return self.__name__
+
+        # Hack to get typing._type_check to pass.
+        def __call__(self, *args, **kwargs):
+            pass
+
+
+# 3.8-3.9
+if not hasattr(typing, 'Concatenate'):
+    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
+    class _ConcatenateGenericAlias(list):
+
+        # Trick Generic into looking into this for __parameters__.
+        __class__ = typing._GenericAlias
+
+        # Flag in 3.8.
+        _special = False
+
+        def __init__(self, origin, args):
+            super().__init__(args)
+            self.__origin__ = origin
+            self.__args__ = args
+
+        def __repr__(self):
+            _type_repr = typing._type_repr
+            return (f'{_type_repr(self.__origin__)}'
+                    f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
+
+        def __hash__(self):
+            return hash((self.__origin__, self.__args__))
+
+        # Hack to get typing._type_check to pass in Generic.
+        def __call__(self, *args, **kwargs):
+            pass
+
+        @property
+        def __parameters__(self):
+            return tuple(
+                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
+            )
+
+
+# 3.8-3.9
+@typing._tp_cache
+def _concatenate_getitem(self, parameters):
+    if parameters == ():
+        raise TypeError("Cannot take a Concatenate of no types.")
+    if not isinstance(parameters, tuple):
+        parameters = (parameters,)
+    if not isinstance(parameters[-1], ParamSpec):
+        raise TypeError("The last parameter to Concatenate should be a "
+                        "ParamSpec variable.")
+    msg = "Concatenate[arg, ...]: each arg must be a type."
+    parameters = tuple(typing._type_check(p, msg) for p in parameters)
+    return _ConcatenateGenericAlias(self, parameters)
+
+
+# 3.10+
+if hasattr(typing, 'Concatenate'):
+    Concatenate = typing.Concatenate
+    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def Concatenate(self, parameters):
+        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
+        higher order function which adds, removes or transforms parameters of a
+        callable.
+
+        For example::
+
+           Callable[Concatenate[int, P], int]
+
+        See PEP 612 for detailed information.
+        """
+        return _concatenate_getitem(self, parameters)
+# 3.8
+else:
+    class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            return _concatenate_getitem(self, parameters)
+
+    Concatenate = _ConcatenateForm(
+        'Concatenate',
+        doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
+        higher order function which adds, removes or transforms parameters of a
+        callable.
+
+        For example::
+
+           Callable[Concatenate[int, P], int]
+
+        See PEP 612 for detailed information.
+        """)
+
+# 3.10+
+if hasattr(typing, 'TypeGuard'):
+    TypeGuard = typing.TypeGuard
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeGuard(self, parameters):
+        """Special typing form used to annotate the return type of a user-defined
+        type guard function.  ``TypeGuard`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeGuard`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the type inside ``TypeGuard``.
+
+        For example::
+
+            def is_str(val: Union[str, float]):
+                # "isinstance" type guard
+                if isinstance(val, str):
+                    # Type of ``val`` is narrowed to ``str``
+                    ...
+                else:
+                    # Else, type of ``val`` is narrowed to ``float``.
+                    ...
+
+        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
+        form of ``TypeA`` (it can even be a wider form) and this may lead to
+        type-unsafe results.  The main reason is to allow for things like
+        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
+        a subtype of the former, since ``List`` is invariant.  The responsibility of
+        writing type-safe type guards is left to the user.
+
+        ``TypeGuard`` also works with type variables.  For more information, see
+        PEP 647 (User-Defined Type Guards).
+        """
+        item = typing._type_check(parameters, f'{self} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+# 3.8
+else:
+    class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type')
+            return typing._GenericAlias(self, (item,))
+
+    TypeGuard = _TypeGuardForm(
+        'TypeGuard',
+        doc="""Special typing form used to annotate the return type of a user-defined
+        type guard function.  ``TypeGuard`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeGuard`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the type inside ``TypeGuard``.
+
+        For example::
+
+            def is_str(val: Union[str, float]):
+                # "isinstance" type guard
+                if isinstance(val, str):
+                    # Type of ``val`` is narrowed to ``str``
+                    ...
+                else:
+                    # Else, type of ``val`` is narrowed to ``float``.
+                    ...
+
+        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
+        form of ``TypeA`` (it can even be a wider form) and this may lead to
+        type-unsafe results.  The main reason is to allow for things like
+        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
+        a subtype of the former, since ``List`` is invariant.  The responsibility of
+        writing type-safe type guards is left to the user.
+
+        ``TypeGuard`` also works with type variables.  For more information, see
+        PEP 647 (User-Defined Type Guards).
+        """)
+
+# 3.13+
+if hasattr(typing, 'TypeIs'):
+    TypeIs = typing.TypeIs
+# 3.9
+elif sys.version_info[:2] >= (3, 9):
+    @_ExtensionsSpecialForm
+    def TypeIs(self, parameters):
+        """Special typing form used to annotate the return type of a user-defined
+        type narrower function.  ``TypeIs`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeIs[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeIs`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the intersection of the type inside ``TypeGuard`` and the argument's
+        previously known type.
+
+        For example::
+
+            def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
+                return hasattr(val, '__await__')
+
+            def f(val: Union[int, Awaitable[int]]) -> int:
+                if is_awaitable(val):
+                    assert_type(val, Awaitable[int])
+                else:
+                    assert_type(val, int)
+
+        ``TypeIs`` also works with type variables.  For more information, see
+        PEP 742 (Narrowing types with TypeIs).
+        """
+        item = typing._type_check(parameters, f'{self} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+# 3.8
+else:
+    class _TypeIsForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type')
+            return typing._GenericAlias(self, (item,))
+
+    TypeIs = _TypeIsForm(
+        'TypeIs',
+        doc="""Special typing form used to annotate the return type of a user-defined
+        type narrower function.  ``TypeIs`` only accepts a single type argument.
+        At runtime, functions marked this way should return a boolean.
+
+        ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
+        type checkers to determine a more precise type of an expression within a
+        program's code flow.  Usually type narrowing is done by analyzing
+        conditional code flow and applying the narrowing to a block of code.  The
+        conditional expression here is sometimes referred to as a "type guard".
+
+        Sometimes it would be convenient to use a user-defined boolean function
+        as a type guard.  Such a function should use ``TypeIs[...]`` as its
+        return type to alert static type checkers to this intention.
+
+        Using  ``-> TypeIs`` tells the static type checker that for a given
+        function:
+
+        1. The return value is a boolean.
+        2. If the return value is ``True``, the type of its argument
+        is the intersection of the type inside ``TypeGuard`` and the argument's
+        previously known type.
+
+        For example::
+
+            def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
+                return hasattr(val, '__await__')
+
+            def f(val: Union[int, Awaitable[int]]) -> int:
+                if is_awaitable(val):
+                    assert_type(val, Awaitable[int])
+                else:
+                    assert_type(val, int)
+
+        ``TypeIs`` also works with type variables.  For more information, see
+        PEP 742 (Narrowing types with TypeIs).
+        """)
+
+
+# Vendored from cpython typing._SpecialFrom
+class _SpecialForm(typing._Final, _root=True):
+    __slots__ = ('_name', '__doc__', '_getitem')
+
+    def __init__(self, getitem):
+        self._getitem = getitem
+        self._name = getitem.__name__
+        self.__doc__ = getitem.__doc__
+
+    def __getattr__(self, item):
+        if item in {'__name__', '__qualname__'}:
+            return self._name
+
+        raise AttributeError(item)
+
+    def __mro_entries__(self, bases):
+        raise TypeError(f"Cannot subclass {self!r}")
+
+    def __repr__(self):
+        return f'typing_extensions.{self._name}'
+
+    def __reduce__(self):
+        return self._name
+
+    def __call__(self, *args, **kwds):
+        raise TypeError(f"Cannot instantiate {self!r}")
+
+    def __or__(self, other):
+        return typing.Union[self, other]
+
+    def __ror__(self, other):
+        return typing.Union[other, self]
+
+    def __instancecheck__(self, obj):
+        raise TypeError(f"{self} cannot be used with isinstance()")
+
+    def __subclasscheck__(self, cls):
+        raise TypeError(f"{self} cannot be used with issubclass()")
+
+    @typing._tp_cache
+    def __getitem__(self, parameters):
+        return self._getitem(self, parameters)
+
+
+if hasattr(typing, "LiteralString"):  # 3.11+
+    LiteralString = typing.LiteralString
+else:
+    @_SpecialForm
+    def LiteralString(self, params):
+        """Represents an arbitrary literal string.
+
+        Example::
+
+          from typing_extensions import LiteralString
+
+          def query(sql: LiteralString) -> ...:
+              ...
+
+          query("SELECT * FROM table")  # ok
+          query(f"SELECT * FROM {input()}")  # not ok
+
+        See PEP 675 for details.
+
+        """
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, "Self"):  # 3.11+
+    Self = typing.Self
+else:
+    @_SpecialForm
+    def Self(self, params):
+        """Used to spell the type of "self" in classes.
+
+        Example::
+
+          from typing import Self
+
+          class ReturnsSelf:
+              def parse(self, data: bytes) -> Self:
+                  ...
+                  return self
+
+        """
+
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, "Never"):  # 3.11+
+    Never = typing.Never
+else:
+    @_SpecialForm
+    def Never(self, params):
+        """The bottom type, a type that has no members.
+
+        This can be used to define a function that should never be
+        called, or a function that never returns::
+
+            from typing_extensions import Never
+
+            def never_call_me(arg: Never) -> None:
+                pass
+
+            def int_or_str(arg: int | str) -> None:
+                never_call_me(arg)  # type checker error
+                match arg:
+                    case int():
+                        print("It's an int")
+                    case str():
+                        print("It's a str")
+                    case _:
+                        never_call_me(arg)  # ok, arg is of type Never
+
+        """
+
+        raise TypeError(f"{self} is not subscriptable")
+
+
+if hasattr(typing, 'Required'):  # 3.11+
+    Required = typing.Required
+    NotRequired = typing.NotRequired
+elif sys.version_info[:2] >= (3, 9):  # 3.9-3.10
+    @_ExtensionsSpecialForm
+    def Required(self, parameters):
+        """A special typing construct to mark a key of a total=False TypedDict
+        as required. For example:
+
+            class Movie(TypedDict, total=False):
+                title: Required[str]
+                year: int
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+
+        There is no runtime checking that a required key is actually provided
+        when instantiating a related TypedDict.
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+    @_ExtensionsSpecialForm
+    def NotRequired(self, parameters):
+        """A special typing construct to mark a key of a TypedDict as
+        potentially missing. For example:
+
+            class Movie(TypedDict):
+                title: str
+                year: NotRequired[int]
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+else:  # 3.8
+    class _RequiredForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return typing._GenericAlias(self, (item,))
+
+    Required = _RequiredForm(
+        'Required',
+        doc="""A special typing construct to mark a key of a total=False TypedDict
+        as required. For example:
+
+            class Movie(TypedDict, total=False):
+                title: Required[str]
+                year: int
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+
+        There is no runtime checking that a required key is actually provided
+        when instantiating a related TypedDict.
+        """)
+    NotRequired = _RequiredForm(
+        'NotRequired',
+        doc="""A special typing construct to mark a key of a TypedDict as
+        potentially missing. For example:
+
+            class Movie(TypedDict):
+                title: str
+                year: NotRequired[int]
+
+            m = Movie(
+                title='The Matrix',  # typechecker error if key is omitted
+                year=1999,
+            )
+        """)
+
+
+if hasattr(typing, 'ReadOnly'):
+    ReadOnly = typing.ReadOnly
+elif sys.version_info[:2] >= (3, 9):  # 3.9-3.12
+    @_ExtensionsSpecialForm
+    def ReadOnly(self, parameters):
+        """A special typing construct to mark an item of a TypedDict as read-only.
+
+        For example:
+
+            class Movie(TypedDict):
+                title: ReadOnly[str]
+                year: int
+
+            def mutate_movie(m: Movie) -> None:
+                m["year"] = 1992  # allowed
+                m["title"] = "The Matrix"  # typechecker error
+
+        There is no runtime checking for this property.
+        """
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return typing._GenericAlias(self, (item,))
+
+else:  # 3.8
+    class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return typing._GenericAlias(self, (item,))
+
+    ReadOnly = _ReadOnlyForm(
+        'ReadOnly',
+        doc="""A special typing construct to mark a key of a TypedDict as read-only.
+
+        For example:
+
+            class Movie(TypedDict):
+                title: ReadOnly[str]
+                year: int
+
+            def mutate_movie(m: Movie) -> None:
+                m["year"] = 1992  # allowed
+                m["title"] = "The Matrix"  # typechecker error
+
+        There is no runtime checking for this propery.
+        """)
+
+
+_UNPACK_DOC = """\
+Type unpack operator.
+
+The type unpack operator takes the child types from some container type,
+such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
+example:
+
+  # For some generic class `Foo`:
+  Foo[Unpack[tuple[int, str]]]  # Equivalent to Foo[int, str]
+
+  Ts = TypeVarTuple('Ts')
+  # Specifies that `Bar` is generic in an arbitrary number of types.
+  # (Think of `Ts` as a tuple of an arbitrary number of individual
+  #  `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
+  #  `Generic[]`.)
+  class Bar(Generic[Unpack[Ts]]): ...
+  Bar[int]  # Valid
+  Bar[int, str]  # Also valid
+
+From Python 3.11, this can also be done using the `*` operator:
+
+    Foo[*tuple[int, str]]
+    class Bar(Generic[*Ts]): ...
+
+The operator can also be used along with a `TypedDict` to annotate
+`**kwargs` in a function signature. For instance:
+
+  class Movie(TypedDict):
+    name: str
+    year: int
+
+  # This function expects two keyword arguments - *name* of type `str` and
+  # *year* of type `int`.
+  def foo(**kwargs: Unpack[Movie]): ...
+
+Note that there is only some runtime checking of this operator. Not
+everything the runtime allows may be accepted by static type checkers.
+
+For more information, see PEP 646 and PEP 692.
+"""
+
+
+if sys.version_info >= (3, 12):  # PEP 692 changed the repr of Unpack[]
+    Unpack = typing.Unpack
+
+    def _is_unpack(obj):
+        return get_origin(obj) is Unpack
+
+elif sys.version_info[:2] >= (3, 9):  # 3.9+
+    class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
+        def __init__(self, getitem):
+            super().__init__(getitem)
+            self.__doc__ = _UNPACK_DOC
+
+    class _UnpackAlias(typing._GenericAlias, _root=True):
+        __class__ = typing.TypeVar
+
+        @property
+        def __typing_unpacked_tuple_args__(self):
+            assert self.__origin__ is Unpack
+            assert len(self.__args__) == 1
+            arg, = self.__args__
+            if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
+                if arg.__origin__ is not tuple:
+                    raise TypeError("Unpack[...] must be used with a tuple type")
+                return arg.__args__
+            return None
+
+    @_UnpackSpecialForm
+    def Unpack(self, parameters):
+        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
+        return _UnpackAlias(self, (item,))
+
+    def _is_unpack(obj):
+        return isinstance(obj, _UnpackAlias)
+
+else:  # 3.8
+    class _UnpackAlias(typing._GenericAlias, _root=True):
+        __class__ = typing.TypeVar
+
+    class _UnpackForm(_ExtensionsSpecialForm, _root=True):
+        def __getitem__(self, parameters):
+            item = typing._type_check(parameters,
+                                      f'{self._name} accepts only a single type.')
+            return _UnpackAlias(self, (item,))
+
+    Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
+
+    def _is_unpack(obj):
+        return isinstance(obj, _UnpackAlias)
+
+
+if _PEP_696_IMPLEMENTED:
+    from typing import TypeVarTuple
+
+elif hasattr(typing, "TypeVarTuple"):  # 3.11+
+
+    def _unpack_args(*args):
+        newargs = []
+        for arg in args:
+            subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
+            if subargs is not None and not (subargs and subargs[-1] is ...):
+                newargs.extend(subargs)
+            else:
+                newargs.append(arg)
+        return newargs
+
+    # Add default parameter - PEP 696
+    class TypeVarTuple(metaclass=_TypeVarLikeMeta):
+        """Type variable tuple."""
+
+        _backported_typevarlike = typing.TypeVarTuple
+
+        def __new__(cls, name, *, default=NoDefault):
+            tvt = typing.TypeVarTuple(name)
+            _set_default(tvt, default)
+            _set_module(tvt)
+
+            def _typevartuple_prepare_subst(alias, args):
+                params = alias.__parameters__
+                typevartuple_index = params.index(tvt)
+                for param in params[typevartuple_index + 1:]:
+                    if isinstance(param, TypeVarTuple):
+                        raise TypeError(
+                            f"More than one TypeVarTuple parameter in {alias}"
+                        )
+
+                alen = len(args)
+                plen = len(params)
+                left = typevartuple_index
+                right = plen - typevartuple_index - 1
+                var_tuple_index = None
+                fillarg = None
+                for k, arg in enumerate(args):
+                    if not isinstance(arg, type):
+                        subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
+                        if subargs and len(subargs) == 2 and subargs[-1] is ...:
+                            if var_tuple_index is not None:
+                                raise TypeError(
+                                    "More than one unpacked "
+                                    "arbitrary-length tuple argument"
+                                )
+                            var_tuple_index = k
+                            fillarg = subargs[0]
+                if var_tuple_index is not None:
+                    left = min(left, var_tuple_index)
+                    right = min(right, alen - var_tuple_index - 1)
+                elif left + right > alen:
+                    raise TypeError(f"Too few arguments for {alias};"
+                                    f" actual {alen}, expected at least {plen - 1}")
+                if left == alen - right and tvt.has_default():
+                    replacement = _unpack_args(tvt.__default__)
+                else:
+                    replacement = args[left: alen - right]
+
+                return (
+                    *args[:left],
+                    *([fillarg] * (typevartuple_index - left)),
+                    replacement,
+                    *([fillarg] * (plen - right - left - typevartuple_index - 1)),
+                    *args[alen - right:],
+                )
+
+            tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
+            return tvt
+
+        def __init_subclass__(self, *args, **kwds):
+            raise TypeError("Cannot subclass special typing classes")
+
+else:  # <=3.10
+    class TypeVarTuple(_DefaultMixin):
+        """Type variable tuple.
+
+        Usage::
+
+            Ts = TypeVarTuple('Ts')
+
+        In the same way that a normal type variable is a stand-in for a single
+        type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
+        type such as ``Tuple[int, str]``.
+
+        Type variable tuples can be used in ``Generic`` declarations.
+        Consider the following example::
+
+            class Array(Generic[*Ts]): ...
+
+        The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
+        where ``T1`` and ``T2`` are type variables. To use these type variables
+        as type parameters of ``Array``, we must *unpack* the type variable tuple using
+        the star operator: ``*Ts``. The signature of ``Array`` then behaves
+        as if we had simply written ``class Array(Generic[T1, T2]): ...``.
+        In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
+        us to parameterise the class with an *arbitrary* number of type parameters.
+
+        Type variable tuples can be used anywhere a normal ``TypeVar`` can.
+        This includes class definitions, as shown above, as well as function
+        signatures and variable annotations::
+
+            class Array(Generic[*Ts]):
+
+                def __init__(self, shape: Tuple[*Ts]):
+                    self._shape: Tuple[*Ts] = shape
+
+                def get_shape(self) -> Tuple[*Ts]:
+                    return self._shape
+
+            shape = (Height(480), Width(640))
+            x: Array[Height, Width] = Array(shape)
+            y = abs(x)  # Inferred type is Array[Height, Width]
+            z = x + x   #        ...    is Array[Height, Width]
+            x.get_shape()  #     ...    is tuple[Height, Width]
+
+        """
+
+        # Trick Generic __parameters__.
+        __class__ = typing.TypeVar
+
+        def __iter__(self):
+            yield self.__unpacked__
+
+        def __init__(self, name, *, default=NoDefault):
+            self.__name__ = name
+            _DefaultMixin.__init__(self, default)
+
+            # for pickling:
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+            self.__unpacked__ = Unpack[self]
+
+        def __repr__(self):
+            return self.__name__
+
+        def __hash__(self):
+            return object.__hash__(self)
+
+        def __eq__(self, other):
+            return self is other
+
+        def __reduce__(self):
+            return self.__name__
+
+        def __init_subclass__(self, *args, **kwds):
+            if '_root' not in kwds:
+                raise TypeError("Cannot subclass special typing classes")
+
+
+if hasattr(typing, "reveal_type"):  # 3.11+
+    reveal_type = typing.reveal_type
+else:  # <=3.10
+    def reveal_type(obj: T, /) -> T:
+        """Reveal the inferred type of a variable.
+
+        When a static type checker encounters a call to ``reveal_type()``,
+        it will emit the inferred type of the argument::
+
+            x: int = 1
+            reveal_type(x)
+
+        Running a static type checker (e.g., ``mypy``) on this example
+        will produce output similar to 'Revealed type is "builtins.int"'.
+
+        At runtime, the function prints the runtime type of the
+        argument and returns it unchanged.
+
+        """
+        print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
+        return obj
+
+
+if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"):  # 3.11+
+    _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
+else:  # <=3.10
+    _ASSERT_NEVER_REPR_MAX_LENGTH = 100
+
+
+if hasattr(typing, "assert_never"):  # 3.11+
+    assert_never = typing.assert_never
+else:  # <=3.10
+    def assert_never(arg: Never, /) -> Never:
+        """Assert to the type checker that a line of code is unreachable.
+
+        Example::
+
+            def int_or_str(arg: int | str) -> None:
+                match arg:
+                    case int():
+                        print("It's an int")
+                    case str():
+                        print("It's a str")
+                    case _:
+                        assert_never(arg)
+
+        If a type checker finds that a call to assert_never() is
+        reachable, it will emit an error.
+
+        At runtime, this throws an exception when called.
+
+        """
+        value = repr(arg)
+        if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
+            value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
+        raise AssertionError(f"Expected code to be unreachable, but got: {value}")
+
+
+if sys.version_info >= (3, 12):  # 3.12+
+    # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
+    dataclass_transform = typing.dataclass_transform
+else:  # <=3.11
+    def dataclass_transform(
+        *,
+        eq_default: bool = True,
+        order_default: bool = False,
+        kw_only_default: bool = False,
+        frozen_default: bool = False,
+        field_specifiers: typing.Tuple[
+            typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
+            ...
+        ] = (),
+        **kwargs: typing.Any,
+    ) -> typing.Callable[[T], T]:
+        """Decorator that marks a function, class, or metaclass as providing
+        dataclass-like behavior.
+
+        Example:
+
+            from typing_extensions import dataclass_transform
+
+            _T = TypeVar("_T")
+
+            # Used on a decorator function
+            @dataclass_transform()
+            def create_model(cls: type[_T]) -> type[_T]:
+                ...
+                return cls
+
+            @create_model
+            class CustomerModel:
+                id: int
+                name: str
+
+            # Used on a base class
+            @dataclass_transform()
+            class ModelBase: ...
+
+            class CustomerModel(ModelBase):
+                id: int
+                name: str
+
+            # Used on a metaclass
+            @dataclass_transform()
+            class ModelMeta(type): ...
+
+            class ModelBase(metaclass=ModelMeta): ...
+
+            class CustomerModel(ModelBase):
+                id: int
+                name: str
+
+        Each of the ``CustomerModel`` classes defined in this example will now
+        behave similarly to a dataclass created with the ``@dataclasses.dataclass``
+        decorator. For example, the type checker will synthesize an ``__init__``
+        method.
+
+        The arguments to this decorator can be used to customize this behavior:
+        - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
+          True or False if it is omitted by the caller.
+        - ``order_default`` indicates whether the ``order`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``frozen_default`` indicates whether the ``frozen`` parameter is
+          assumed to be True or False if it is omitted by the caller.
+        - ``field_specifiers`` specifies a static list of supported classes
+          or functions that describe fields, similar to ``dataclasses.field()``.
+
+        At runtime, this decorator records its arguments in the
+        ``__dataclass_transform__`` attribute on the decorated object.
+
+        See PEP 681 for details.
+
+        """
+        def decorator(cls_or_fn):
+            cls_or_fn.__dataclass_transform__ = {
+                "eq_default": eq_default,
+                "order_default": order_default,
+                "kw_only_default": kw_only_default,
+                "frozen_default": frozen_default,
+                "field_specifiers": field_specifiers,
+                "kwargs": kwargs,
+            }
+            return cls_or_fn
+        return decorator
+
+
+if hasattr(typing, "override"):  # 3.12+
+    override = typing.override
+else:  # <=3.11
+    _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
+
+    def override(arg: _F, /) -> _F:
+        """Indicate that a method is intended to override a method in a base class.
+
+        Usage:
+
+            class Base:
+                def method(self) -> None:
+                    pass
+
+            class Child(Base):
+                @override
+                def method(self) -> None:
+                    super().method()
+
+        When this decorator is applied to a method, the type checker will
+        validate that it overrides a method with the same name on a base class.
+        This helps prevent bugs that may occur when a base class is changed
+        without an equivalent change to a child class.
+
+        There is no runtime checking of these properties. The decorator
+        sets the ``__override__`` attribute to ``True`` on the decorated object
+        to allow runtime introspection.
+
+        See PEP 698 for details.
+
+        """
+        try:
+            arg.__override__ = True
+        except (AttributeError, TypeError):
+            # Skip the attribute silently if it is not writable.
+            # AttributeError happens if the object has __slots__ or a
+            # read-only property, TypeError if it's a builtin class.
+            pass
+        return arg
+
+
+if hasattr(warnings, "deprecated"):
+    deprecated = warnings.deprecated
+else:
+    _T = typing.TypeVar("_T")
+
+    class deprecated:
+        """Indicate that a class, function or overload is deprecated.
+
+        When this decorator is applied to an object, the type checker
+        will generate a diagnostic on usage of the deprecated object.
+
+        Usage:
+
+            @deprecated("Use B instead")
+            class A:
+                pass
+
+            @deprecated("Use g instead")
+            def f():
+                pass
+
+            @overload
+            @deprecated("int support is deprecated")
+            def g(x: int) -> int: ...
+            @overload
+            def g(x: str) -> int: ...
+
+        The warning specified by *category* will be emitted at runtime
+        on use of deprecated objects. For functions, that happens on calls;
+        for classes, on instantiation and on creation of subclasses.
+        If the *category* is ``None``, no warning is emitted at runtime.
+        The *stacklevel* determines where the
+        warning is emitted. If it is ``1`` (the default), the warning
+        is emitted at the direct caller of the deprecated object; if it
+        is higher, it is emitted further up the stack.
+        Static type checker behavior is not affected by the *category*
+        and *stacklevel* arguments.
+
+        The deprecation message passed to the decorator is saved in the
+        ``__deprecated__`` attribute on the decorated object.
+        If applied to an overload, the decorator
+        must be after the ``@overload`` decorator for the attribute to
+        exist on the overload as returned by ``get_overloads()``.
+
+        See PEP 702 for details.
+
+        """
+        def __init__(
+            self,
+            message: str,
+            /,
+            *,
+            category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
+            stacklevel: int = 1,
+        ) -> None:
+            if not isinstance(message, str):
+                raise TypeError(
+                    "Expected an object of type str for 'message', not "
+                    f"{type(message).__name__!r}"
+                )
+            self.message = message
+            self.category = category
+            self.stacklevel = stacklevel
+
+        def __call__(self, arg: _T, /) -> _T:
+            # Make sure the inner functions created below don't
+            # retain a reference to self.
+            msg = self.message
+            category = self.category
+            stacklevel = self.stacklevel
+            if category is None:
+                arg.__deprecated__ = msg
+                return arg
+            elif isinstance(arg, type):
+                import functools
+                from types import MethodType
+
+                original_new = arg.__new__
+
+                @functools.wraps(original_new)
+                def __new__(cls, *args, **kwargs):
+                    if cls is arg:
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                    if original_new is not object.__new__:
+                        return original_new(cls, *args, **kwargs)
+                    # Mirrors a similar check in object.__new__.
+                    elif cls.__init__ is object.__init__ and (args or kwargs):
+                        raise TypeError(f"{cls.__name__}() takes no arguments")
+                    else:
+                        return original_new(cls)
+
+                arg.__new__ = staticmethod(__new__)
+
+                original_init_subclass = arg.__init_subclass__
+                # We need slightly different behavior if __init_subclass__
+                # is a bound method (likely if it was implemented in Python)
+                if isinstance(original_init_subclass, MethodType):
+                    original_init_subclass = original_init_subclass.__func__
+
+                    @functools.wraps(original_init_subclass)
+                    def __init_subclass__(*args, **kwargs):
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                        return original_init_subclass(*args, **kwargs)
+
+                    arg.__init_subclass__ = classmethod(__init_subclass__)
+                # Or otherwise, which likely means it's a builtin such as
+                # object's implementation of __init_subclass__.
+                else:
+                    @functools.wraps(original_init_subclass)
+                    def __init_subclass__(*args, **kwargs):
+                        warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                        return original_init_subclass(*args, **kwargs)
+
+                    arg.__init_subclass__ = __init_subclass__
+
+                arg.__deprecated__ = __new__.__deprecated__ = msg
+                __init_subclass__.__deprecated__ = msg
+                return arg
+            elif callable(arg):
+                import functools
+
+                @functools.wraps(arg)
+                def wrapper(*args, **kwargs):
+                    warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
+                    return arg(*args, **kwargs)
+
+                arg.__deprecated__ = wrapper.__deprecated__ = msg
+                return wrapper
+            else:
+                raise TypeError(
+                    "@deprecated decorator with non-None category must be applied to "
+                    f"a class or callable, not {arg!r}"
+                )
+
+
+# We have to do some monkey patching to deal with the dual nature of
+# Unpack/TypeVarTuple:
+# - We want Unpack to be a kind of TypeVar so it gets accepted in
+#   Generic[Unpack[Ts]]
+# - We want it to *not* be treated as a TypeVar for the purposes of
+#   counting generic parameters, so that when we subscript a generic,
+#   the runtime doesn't try to substitute the Unpack with the subscripted type.
+if not hasattr(typing, "TypeVarTuple"):
+    def _check_generic(cls, parameters, elen=_marker):
+        """Check correct count for parameters of a generic cls (internal helper).
+
+        This gives a nice error message in case of count mismatch.
+        """
+        if not elen:
+            raise TypeError(f"{cls} is not a generic class")
+        if elen is _marker:
+            if not hasattr(cls, "__parameters__") or not cls.__parameters__:
+                raise TypeError(f"{cls} is not a generic class")
+            elen = len(cls.__parameters__)
+        alen = len(parameters)
+        if alen != elen:
+            expect_val = elen
+            if hasattr(cls, "__parameters__"):
+                parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
+                num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
+                if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
+                    return
+
+                # deal with TypeVarLike defaults
+                # required TypeVarLikes cannot appear after a defaulted one.
+                if alen < elen:
+                    # since we validate TypeVarLike default in _collect_type_vars
+                    # or _collect_parameters we can safely check parameters[alen]
+                    if (
+                        getattr(parameters[alen], '__default__', NoDefault)
+                        is not NoDefault
+                    ):
+                        return
+
+                    num_default_tv = sum(getattr(p, '__default__', NoDefault)
+                                         is not NoDefault for p in parameters)
+
+                    elen -= num_default_tv
+
+                    expect_val = f"at least {elen}"
+
+            things = "arguments" if sys.version_info >= (3, 10) else "parameters"
+            raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
+                            f" for {cls}; actual {alen}, expected {expect_val}")
+else:
+    # Python 3.11+
+
+    def _check_generic(cls, parameters, elen):
+        """Check correct count for parameters of a generic cls (internal helper).
+
+        This gives a nice error message in case of count mismatch.
+        """
+        if not elen:
+            raise TypeError(f"{cls} is not a generic class")
+        alen = len(parameters)
+        if alen != elen:
+            expect_val = elen
+            if hasattr(cls, "__parameters__"):
+                parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
+
+                # deal with TypeVarLike defaults
+                # required TypeVarLikes cannot appear after a defaulted one.
+                if alen < elen:
+                    # since we validate TypeVarLike default in _collect_type_vars
+                    # or _collect_parameters we can safely check parameters[alen]
+                    if (
+                        getattr(parameters[alen], '__default__', NoDefault)
+                        is not NoDefault
+                    ):
+                        return
+
+                    num_default_tv = sum(getattr(p, '__default__', NoDefault)
+                                         is not NoDefault for p in parameters)
+
+                    elen -= num_default_tv
+
+                    expect_val = f"at least {elen}"
+
+            raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
+                            f" for {cls}; actual {alen}, expected {expect_val}")
+
+if not _PEP_696_IMPLEMENTED:
+    typing._check_generic = _check_generic
+
+
+def _has_generic_or_protocol_as_origin() -> bool:
+    try:
+        frame = sys._getframe(2)
+    # - Catch AttributeError: not all Python implementations have sys._getframe()
+    # - Catch ValueError: maybe we're called from an unexpected module
+    #   and the call stack isn't deep enough
+    except (AttributeError, ValueError):
+        return False  # err on the side of leniency
+    else:
+        # If we somehow get invoked from outside typing.py,
+        # also err on the side of leniency
+        if frame.f_globals.get("__name__") != "typing":
+            return False
+        origin = frame.f_locals.get("origin")
+        # Cannot use "in" because origin may be an object with a buggy __eq__ that
+        # throws an error.
+        return origin is typing.Generic or origin is Protocol or origin is typing.Protocol
+
+
+_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)}
+
+
+def _is_unpacked_typevartuple(x) -> bool:
+    if get_origin(x) is not Unpack:
+        return False
+    args = get_args(x)
+    return (
+        bool(args)
+        and len(args) == 1
+        and type(args[0]) in _TYPEVARTUPLE_TYPES
+    )
+
+
+# Python 3.11+ _collect_type_vars was renamed to _collect_parameters
+if hasattr(typing, '_collect_type_vars'):
+    def _collect_type_vars(types, typevar_types=None):
+        """Collect all type variable contained in types in order of
+        first appearance (lexicographic order). For example::
+
+            _collect_type_vars((T, List[S, T])) == (T, S)
+        """
+        if typevar_types is None:
+            typevar_types = typing.TypeVar
+        tvars = []
+
+        # A required TypeVarLike cannot appear after a TypeVarLike with a default
+        # if it was a direct call to `Generic[]` or `Protocol[]`
+        enforce_default_ordering = _has_generic_or_protocol_as_origin()
+        default_encountered = False
+
+        # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
+        type_var_tuple_encountered = False
+
+        for t in types:
+            if _is_unpacked_typevartuple(t):
+                type_var_tuple_encountered = True
+            elif isinstance(t, typevar_types) and t not in tvars:
+                if enforce_default_ordering:
+                    has_default = getattr(t, '__default__', NoDefault) is not NoDefault
+                    if has_default:
+                        if type_var_tuple_encountered:
+                            raise TypeError('Type parameter with a default'
+                                            ' follows TypeVarTuple')
+                        default_encountered = True
+                    elif default_encountered:
+                        raise TypeError(f'Type parameter {t!r} without a default'
+                                        ' follows type parameter with a default')
+
+                tvars.append(t)
+            if _should_collect_from_parameters(t):
+                tvars.extend([t for t in t.__parameters__ if t not in tvars])
+        return tuple(tvars)
+
+    typing._collect_type_vars = _collect_type_vars
+else:
+    def _collect_parameters(args):
+        """Collect all type variables and parameter specifications in args
+        in order of first appearance (lexicographic order).
+
+        For example::
+
+            assert _collect_parameters((T, Callable[P, T])) == (T, P)
+        """
+        parameters = []
+
+        # A required TypeVarLike cannot appear after a TypeVarLike with default
+        # if it was a direct call to `Generic[]` or `Protocol[]`
+        enforce_default_ordering = _has_generic_or_protocol_as_origin()
+        default_encountered = False
+
+        # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
+        type_var_tuple_encountered = False
+
+        for t in args:
+            if isinstance(t, type):
+                # We don't want __parameters__ descriptor of a bare Python class.
+                pass
+            elif isinstance(t, tuple):
+                # `t` might be a tuple, when `ParamSpec` is substituted with
+                # `[T, int]`, or `[int, *Ts]`, etc.
+                for x in t:
+                    for collected in _collect_parameters([x]):
+                        if collected not in parameters:
+                            parameters.append(collected)
+            elif hasattr(t, '__typing_subst__'):
+                if t not in parameters:
+                    if enforce_default_ordering:
+                        has_default = (
+                            getattr(t, '__default__', NoDefault) is not NoDefault
+                        )
+
+                        if type_var_tuple_encountered and has_default:
+                            raise TypeError('Type parameter with a default'
+                                            ' follows TypeVarTuple')
+
+                        if has_default:
+                            default_encountered = True
+                        elif default_encountered:
+                            raise TypeError(f'Type parameter {t!r} without a default'
+                                            ' follows type parameter with a default')
+
+                    parameters.append(t)
+            else:
+                if _is_unpacked_typevartuple(t):
+                    type_var_tuple_encountered = True
+                for x in getattr(t, '__parameters__', ()):
+                    if x not in parameters:
+                        parameters.append(x)
+
+        return tuple(parameters)
+
+    if not _PEP_696_IMPLEMENTED:
+        typing._collect_parameters = _collect_parameters
+
+# Backport typing.NamedTuple as it exists in Python 3.13.
+# In 3.11, the ability to define generic `NamedTuple`s was supported.
+# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
+# On 3.12, we added __orig_bases__ to call-based NamedTuples
+# On 3.13, we deprecated kwargs-based NamedTuples
+if sys.version_info >= (3, 13):
+    NamedTuple = typing.NamedTuple
+else:
+    def _make_nmtuple(name, types, module, defaults=()):
+        fields = [n for n, t in types]
+        annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
+                       for n, t in types}
+        nm_tpl = collections.namedtuple(name, fields,
+                                        defaults=defaults, module=module)
+        nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
+        # The `_field_types` attribute was removed in 3.9;
+        # in earlier versions, it is the same as the `__annotations__` attribute
+        if sys.version_info < (3, 9):
+            nm_tpl._field_types = annotations
+        return nm_tpl
+
+    _prohibited_namedtuple_fields = typing._prohibited
+    _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
+
+    class _NamedTupleMeta(type):
+        def __new__(cls, typename, bases, ns):
+            assert _NamedTuple in bases
+            for base in bases:
+                if base is not _NamedTuple and base is not typing.Generic:
+                    raise TypeError(
+                        'can only inherit from a NamedTuple type and Generic')
+            bases = tuple(tuple if base is _NamedTuple else base for base in bases)
+            if "__annotations__" in ns:
+                types = ns["__annotations__"]
+            elif "__annotate__" in ns:
+                # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
+                types = ns["__annotate__"](1)
+            else:
+                types = {}
+            default_names = []
+            for field_name in types:
+                if field_name in ns:
+                    default_names.append(field_name)
+                elif default_names:
+                    raise TypeError(f"Non-default namedtuple field {field_name} "
+                                    f"cannot follow default field"
+                                    f"{'s' if len(default_names) > 1 else ''} "
+                                    f"{', '.join(default_names)}")
+            nm_tpl = _make_nmtuple(
+                typename, types.items(),
+                defaults=[ns[n] for n in default_names],
+                module=ns['__module__']
+            )
+            nm_tpl.__bases__ = bases
+            if typing.Generic in bases:
+                if hasattr(typing, '_generic_class_getitem'):  # 3.12+
+                    nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
+                else:
+                    class_getitem = typing.Generic.__class_getitem__.__func__
+                    nm_tpl.__class_getitem__ = classmethod(class_getitem)
+            # update from user namespace without overriding special namedtuple attributes
+            for key, val in ns.items():
+                if key in _prohibited_namedtuple_fields:
+                    raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
+                elif key not in _special_namedtuple_fields:
+                    if key not in nm_tpl._fields:
+                        setattr(nm_tpl, key, ns[key])
+                    try:
+                        set_name = type(val).__set_name__
+                    except AttributeError:
+                        pass
+                    else:
+                        try:
+                            set_name(val, nm_tpl, key)
+                        except BaseException as e:
+                            msg = (
+                                f"Error calling __set_name__ on {type(val).__name__!r} "
+                                f"instance {key!r} in {typename!r}"
+                            )
+                            # BaseException.add_note() existed on py311,
+                            # but the __set_name__ machinery didn't start
+                            # using add_note() until py312.
+                            # Making sure exceptions are raised in the same way
+                            # as in "normal" classes seems most important here.
+                            if sys.version_info >= (3, 12):
+                                e.add_note(msg)
+                                raise
+                            else:
+                                raise RuntimeError(msg) from e
+
+            if typing.Generic in bases:
+                nm_tpl.__init_subclass__()
+            return nm_tpl
+
+    _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
+
+    def _namedtuple_mro_entries(bases):
+        assert NamedTuple in bases
+        return (_NamedTuple,)
+
+    @_ensure_subclassable(_namedtuple_mro_entries)
+    def NamedTuple(typename, fields=_marker, /, **kwargs):
+        """Typed version of namedtuple.
+
+        Usage::
+
+            class Employee(NamedTuple):
+                name: str
+                id: int
+
+        This is equivalent to::
+
+            Employee = collections.namedtuple('Employee', ['name', 'id'])
+
+        The resulting class has an extra __annotations__ attribute, giving a
+        dict that maps field names to types.  (The field names are also in
+        the _fields attribute, which is part of the namedtuple API.)
+        An alternative equivalent functional syntax is also accepted::
+
+            Employee = NamedTuple('Employee', [('name', str), ('id', int)])
+        """
+        if fields is _marker:
+            if kwargs:
+                deprecated_thing = "Creating NamedTuple classes using keyword arguments"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "Use the class-based or functional syntax instead."
+                )
+            else:
+                deprecated_thing = "Failing to pass a value for the 'fields' parameter"
+                example = f"`{typename} = NamedTuple({typename!r}, [])`"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "To create a NamedTuple class with 0 fields "
+                    "using the functional syntax, "
+                    "pass an empty list, e.g. "
+                ) + example + "."
+        elif fields is None:
+            if kwargs:
+                raise TypeError(
+                    "Cannot pass `None` as the 'fields' parameter "
+                    "and also specify fields using keyword arguments"
+                )
+            else:
+                deprecated_thing = "Passing `None` as the 'fields' parameter"
+                example = f"`{typename} = NamedTuple({typename!r}, [])`"
+                deprecation_msg = (
+                    "{name} is deprecated and will be disallowed in Python {remove}. "
+                    "To create a NamedTuple class with 0 fields "
+                    "using the functional syntax, "
+                    "pass an empty list, e.g. "
+                ) + example + "."
+        elif kwargs:
+            raise TypeError("Either list of fields or keywords"
+                            " can be provided to NamedTuple, not both")
+        if fields is _marker or fields is None:
+            warnings.warn(
+                deprecation_msg.format(name=deprecated_thing, remove="3.15"),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            fields = kwargs.items()
+        nt = _make_nmtuple(typename, fields, module=_caller())
+        nt.__orig_bases__ = (NamedTuple,)
+        return nt
+
+
+if hasattr(collections.abc, "Buffer"):
+    Buffer = collections.abc.Buffer
+else:
+    class Buffer(abc.ABC):  # noqa: B024
+        """Base class for classes that implement the buffer protocol.
+
+        The buffer protocol allows Python objects to expose a low-level
+        memory buffer interface. Before Python 3.12, it is not possible
+        to implement the buffer protocol in pure Python code, or even
+        to check whether a class implements the buffer protocol. In
+        Python 3.12 and higher, the ``__buffer__`` method allows access
+        to the buffer protocol from Python code, and the
+        ``collections.abc.Buffer`` ABC allows checking whether a class
+        implements the buffer protocol.
+
+        To indicate support for the buffer protocol in earlier versions,
+        inherit from this ABC, either in a stub file or at runtime,
+        or use ABC registration. This ABC provides no methods, because
+        there is no Python-accessible methods shared by pre-3.12 buffer
+        classes. It is useful primarily for static checks.
+
+        """
+
+    # As a courtesy, register the most common stdlib buffer classes.
+    Buffer.register(memoryview)
+    Buffer.register(bytearray)
+    Buffer.register(bytes)
+
+
+# Backport of types.get_original_bases, available on 3.12+ in CPython
+if hasattr(_types, "get_original_bases"):
+    get_original_bases = _types.get_original_bases
+else:
+    def get_original_bases(cls, /):
+        """Return the class's "original" bases prior to modification by `__mro_entries__`.
+
+        Examples::
+
+            from typing import TypeVar, Generic
+            from typing_extensions import NamedTuple, TypedDict
+
+            T = TypeVar("T")
+            class Foo(Generic[T]): ...
+            class Bar(Foo[int], float): ...
+            class Baz(list[str]): ...
+            Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
+            Spam = TypedDict("Spam", {"a": int, "b": str})
+
+            assert get_original_bases(Bar) == (Foo[int], float)
+            assert get_original_bases(Baz) == (list[str],)
+            assert get_original_bases(Eggs) == (NamedTuple,)
+            assert get_original_bases(Spam) == (TypedDict,)
+            assert get_original_bases(int) == (object,)
+        """
+        try:
+            return cls.__dict__.get("__orig_bases__", cls.__bases__)
+        except AttributeError:
+            raise TypeError(
+                f'Expected an instance of type, not {type(cls).__name__!r}'
+            ) from None
+
+
+# NewType is a class on Python 3.10+, making it pickleable
+# The error message for subclassing instances of NewType was improved on 3.11+
+if sys.version_info >= (3, 11):
+    NewType = typing.NewType
+else:
+    class NewType:
+        """NewType creates simple unique types with almost zero
+        runtime overhead. NewType(name, tp) is considered a subtype of tp
+        by static type checkers. At runtime, NewType(name, tp) returns
+        a dummy callable that simply returns its argument. Usage::
+            UserId = NewType('UserId', int)
+            def name_by_id(user_id: UserId) -> str:
+                ...
+            UserId('user')          # Fails type check
+            name_by_id(42)          # Fails type check
+            name_by_id(UserId(42))  # OK
+            num = UserId(5) + 1     # type: int
+        """
+
+        def __call__(self, obj, /):
+            return obj
+
+        def __init__(self, name, tp):
+            self.__qualname__ = name
+            if '.' in name:
+                name = name.rpartition('.')[-1]
+            self.__name__ = name
+            self.__supertype__ = tp
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+
+        def __mro_entries__(self, bases):
+            # We defined __mro_entries__ to get a better error message
+            # if a user attempts to subclass a NewType instance. bpo-46170
+            supercls_name = self.__name__
+
+            class Dummy:
+                def __init_subclass__(cls):
+                    subcls_name = cls.__name__
+                    raise TypeError(
+                        f"Cannot subclass an instance of NewType. "
+                        f"Perhaps you were looking for: "
+                        f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
+                    )
+
+            return (Dummy,)
+
+        def __repr__(self):
+            return f'{self.__module__}.{self.__qualname__}'
+
+        def __reduce__(self):
+            return self.__qualname__
+
+        if sys.version_info >= (3, 10):
+            # PEP 604 methods
+            # It doesn't make sense to have these methods on Python <3.10
+
+            def __or__(self, other):
+                return typing.Union[self, other]
+
+            def __ror__(self, other):
+                return typing.Union[other, self]
+
+
+if hasattr(typing, "TypeAliasType"):
+    TypeAliasType = typing.TypeAliasType
+else:
+    def _is_unionable(obj):
+        """Corresponds to is_unionable() in unionobject.c in CPython."""
+        return obj is None or isinstance(obj, (
+            type,
+            _types.GenericAlias,
+            _types.UnionType,
+            TypeAliasType,
+        ))
+
+    class TypeAliasType:
+        """Create named, parameterized type aliases.
+
+        This provides a backport of the new `type` statement in Python 3.12:
+
+            type ListOrSet[T] = list[T] | set[T]
+
+        is equivalent to:
+
+            T = TypeVar("T")
+            ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
+
+        The name ListOrSet can then be used as an alias for the type it refers to.
+
+        The type_params argument should contain all the type parameters used
+        in the value of the type alias. If the alias is not generic, this
+        argument is omitted.
+
+        Static type checkers should only support type aliases declared using
+        TypeAliasType that follow these rules:
+
+        - The first argument (the name) must be a string literal.
+        - The TypeAliasType instance must be immediately assigned to a variable
+          of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
+          as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
+
+        """
+
+        def __init__(self, name: str, value, *, type_params=()):
+            if not isinstance(name, str):
+                raise TypeError("TypeAliasType name must be a string")
+            self.__value__ = value
+            self.__type_params__ = type_params
+
+            parameters = []
+            for type_param in type_params:
+                if isinstance(type_param, TypeVarTuple):
+                    parameters.extend(type_param)
+                else:
+                    parameters.append(type_param)
+            self.__parameters__ = tuple(parameters)
+            def_mod = _caller()
+            if def_mod != 'typing_extensions':
+                self.__module__ = def_mod
+            # Setting this attribute closes the TypeAliasType from further modification
+            self.__name__ = name
+
+        def __setattr__(self, name: str, value: object, /) -> None:
+            if hasattr(self, "__name__"):
+                self._raise_attribute_error(name)
+            super().__setattr__(name, value)
+
+        def __delattr__(self, name: str, /) -> Never:
+            self._raise_attribute_error(name)
+
+        def _raise_attribute_error(self, name: str) -> Never:
+            # Match the Python 3.12 error messages exactly
+            if name == "__name__":
+                raise AttributeError("readonly attribute")
+            elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
+                raise AttributeError(
+                    f"attribute '{name}' of 'typing.TypeAliasType' objects "
+                    "is not writable"
+                )
+            else:
+                raise AttributeError(
+                    f"'typing.TypeAliasType' object has no attribute '{name}'"
+                )
+
+        def __repr__(self) -> str:
+            return self.__name__
+
+        def __getitem__(self, parameters):
+            if not isinstance(parameters, tuple):
+                parameters = (parameters,)
+            parameters = [
+                typing._type_check(
+                    item, f'Subscripting {self.__name__} requires a type.'
+                )
+                for item in parameters
+            ]
+            return typing._GenericAlias(self, tuple(parameters))
+
+        def __reduce__(self):
+            return self.__name__
+
+        def __init_subclass__(cls, *args, **kwargs):
+            raise TypeError(
+                "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
+            )
+
+        # The presence of this method convinces typing._type_check
+        # that TypeAliasTypes are types.
+        def __call__(self):
+            raise TypeError("Type alias is not callable")
+
+        if sys.version_info >= (3, 10):
+            def __or__(self, right):
+                # For forward compatibility with 3.12, reject Unions
+                # that are not accepted by the built-in Union.
+                if not _is_unionable(right):
+                    return NotImplemented
+                return typing.Union[self, right]
+
+            def __ror__(self, left):
+                if not _is_unionable(left):
+                    return NotImplemented
+                return typing.Union[left, self]
+
+
+if hasattr(typing, "is_protocol"):
+    is_protocol = typing.is_protocol
+    get_protocol_members = typing.get_protocol_members
+else:
+    def is_protocol(tp: type, /) -> bool:
+        """Return True if the given type is a Protocol.
+
+        Example::
+
+            >>> from typing_extensions import Protocol, is_protocol
+            >>> class P(Protocol):
+            ...     def a(self) -> str: ...
+            ...     b: int
+            >>> is_protocol(P)
+            True
+            >>> is_protocol(int)
+            False
+        """
+        return (
+            isinstance(tp, type)
+            and getattr(tp, '_is_protocol', False)
+            and tp is not Protocol
+            and tp is not typing.Protocol
+        )
+
+    def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
+        """Return the set of members defined in a Protocol.
+
+        Example::
+
+            >>> from typing_extensions import Protocol, get_protocol_members
+            >>> class P(Protocol):
+            ...     def a(self) -> str: ...
+            ...     b: int
+            >>> get_protocol_members(P)
+            frozenset({'a', 'b'})
+
+        Raise a TypeError for arguments that are not Protocols.
+        """
+        if not is_protocol(tp):
+            raise TypeError(f'{tp!r} is not a Protocol')
+        if hasattr(tp, '__protocol_attrs__'):
+            return frozenset(tp.__protocol_attrs__)
+        return frozenset(_get_protocol_attrs(tp))
+
+
+if hasattr(typing, "Doc"):
+    Doc = typing.Doc
+else:
+    class Doc:
+        """Define the documentation of a type annotation using ``Annotated``, to be
+         used in class attributes, function and method parameters, return values,
+         and variables.
+
+        The value should be a positional-only string literal to allow static tools
+        like editors and documentation generators to use it.
+
+        This complements docstrings.
+
+        The string value passed is available in the attribute ``documentation``.
+
+        Example::
+
+            >>> from typing_extensions import Annotated, Doc
+            >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
+        """
+        def __init__(self, documentation: str, /) -> None:
+            self.documentation = documentation
+
+        def __repr__(self) -> str:
+            return f"Doc({self.documentation!r})"
+
+        def __hash__(self) -> int:
+            return hash(self.documentation)
+
+        def __eq__(self, other: object) -> bool:
+            if not isinstance(other, Doc):
+                return NotImplemented
+            return self.documentation == other.documentation
+
+
+_CapsuleType = getattr(_types, "CapsuleType", None)
+
+if _CapsuleType is None:
+    try:
+        import _socket
+    except ImportError:
+        pass
+    else:
+        _CAPI = getattr(_socket, "CAPI", None)
+        if _CAPI is not None:
+            _CapsuleType = type(_CAPI)
+
+if _CapsuleType is not None:
+    CapsuleType = _CapsuleType
+    __all__.append("CapsuleType")
+
+
+# Aliases for items that have always been in typing.
+# Explicitly assign these (rather than using `from typing import *` at the top),
+# so that we get a CI error if one of these is deleted from typing.py
+# in a future version of Python
+AbstractSet = typing.AbstractSet
+AnyStr = typing.AnyStr
+BinaryIO = typing.BinaryIO
+Callable = typing.Callable
+Collection = typing.Collection
+Container = typing.Container
+Dict = typing.Dict
+ForwardRef = typing.ForwardRef
+FrozenSet = typing.FrozenSet
+Generic = typing.Generic
+Hashable = typing.Hashable
+IO = typing.IO
+ItemsView = typing.ItemsView
+Iterable = typing.Iterable
+Iterator = typing.Iterator
+KeysView = typing.KeysView
+List = typing.List
+Mapping = typing.Mapping
+MappingView = typing.MappingView
+Match = typing.Match
+MutableMapping = typing.MutableMapping
+MutableSequence = typing.MutableSequence
+MutableSet = typing.MutableSet
+Optional = typing.Optional
+Pattern = typing.Pattern
+Reversible = typing.Reversible
+Sequence = typing.Sequence
+Set = typing.Set
+Sized = typing.Sized
+TextIO = typing.TextIO
+Tuple = typing.Tuple
+Union = typing.Union
+ValuesView = typing.ValuesView
+cast = typing.cast
+no_type_check = typing.no_type_check
+no_type_check_decorator = typing.no_type_check_decorator
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a31470f14c5978d5fcc3bc173b8399b6c9a6443f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2012 Daniel Holth  and contributors
+
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f645dcb673aaa7e3e7e054d57af5e8c0992b70e8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/METADATA
@@ -0,0 +1,66 @@
+Metadata-Version: 2.3
+Name: wheel
+Version: 0.45.1
+Summary: A built-package format for Python
+Keywords: wheel,packaging
+Author-email: Daniel Holth 
+Maintainer-email: Alex Grönholm 
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: System :: Archiving :: Packaging
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Requires-Dist: pytest >= 6.0.0 ; extra == "test"
+Requires-Dist: setuptools >= 65 ; extra == "test"
+Project-URL: Changelog, https://wheel.readthedocs.io/en/stable/news.html
+Project-URL: Documentation, https://wheel.readthedocs.io/
+Project-URL: Issue Tracker, https://github.com/pypa/wheel/issues
+Project-URL: Source, https://github.com/pypa/wheel
+Provides-Extra: test
+
+wheel
+=====
+
+This is a command line tool for manipulating Python wheel files, as defined in
+`PEP 427`_. It contains the following functionality:
+
+* Convert ``.egg`` archives into ``.whl``
+* Unpack wheel archives
+* Repack wheel archives
+* Add or remove tags in existing wheel archives
+
+.. _PEP 427: https://www.python.org/dev/peps/pep-0427/
+
+Historical note
+---------------
+
+This project used to contain the implementation of the setuptools_ ``bdist_wheel``
+command, but as of setuptools v70.1, it no longer needs ``wheel`` installed for that to
+work. Thus, you should install this **only** if you intend to use the ``wheel`` command
+line tool!
+
+.. _setuptools: https://pypi.org/project/setuptools/
+
+Documentation
+-------------
+
+The documentation_ can be found on Read The Docs.
+
+.. _documentation: https://wheel.readthedocs.io/
+
+Code of Conduct
+---------------
+
+Everyone interacting in the wheel project's codebases, issue trackers, chat
+rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
+
+.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..c1535b697f8dd60212541f637c69c9dfb4f1c8f1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/RECORD
@@ -0,0 +1,68 @@
+../../bin/wheel,sha256=pBhV19bQIgjS-r541fG3kLU6QtcyKaKdQ2RE9YIzeiU,249
+wheel-0.45.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+wheel-0.45.1.dist-info/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107
+wheel-0.45.1.dist-info/METADATA,sha256=mKz84H7m7jsxJyzeIcTVORiTb0NPMV39KvOIYhGgmjA,2313
+wheel-0.45.1.dist-info/RECORD,,
+wheel-0.45.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel-0.45.1.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82
+wheel-0.45.1.dist-info/entry_points.txt,sha256=rTY1BbkPHhkGMm4Q3F0pIzJBzW2kMxoG1oriffvGdA0,104
+wheel/__init__.py,sha256=mrxMnvdXACur_LWegbUfh5g5ysWZrd63UJn890wvGNk,59
+wheel/__main__.py,sha256=NkMUnuTCGcOkgY0IBLgBCVC_BGGcWORx2K8jYGS12UE,455
+wheel/__pycache__/__init__.cpython-311.pyc,,
+wheel/__pycache__/__main__.cpython-311.pyc,,
+wheel/__pycache__/_bdist_wheel.cpython-311.pyc,,
+wheel/__pycache__/_setuptools_logging.cpython-311.pyc,,
+wheel/__pycache__/bdist_wheel.cpython-311.pyc,,
+wheel/__pycache__/macosx_libfile.cpython-311.pyc,,
+wheel/__pycache__/metadata.cpython-311.pyc,,
+wheel/__pycache__/util.cpython-311.pyc,,
+wheel/__pycache__/wheelfile.cpython-311.pyc,,
+wheel/_bdist_wheel.py,sha256=UghCQjSH_pVfcZh6oRjzSw_TQhcf3anSx1OkiLSL82M,21694
+wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781
+wheel/bdist_wheel.py,sha256=tpf9WufiSO1RuEMg5oPhIfSG8DMziCZ_4muCKF69Cqo,1107
+wheel/cli/__init__.py,sha256=Npq6_jKi03dhIcRnmbuFhwviVJxwO0tYEnEhWMv9cJo,4402
+wheel/cli/__pycache__/__init__.cpython-311.pyc,,
+wheel/cli/__pycache__/convert.cpython-311.pyc,,
+wheel/cli/__pycache__/pack.cpython-311.pyc,,
+wheel/cli/__pycache__/tags.cpython-311.pyc,,
+wheel/cli/__pycache__/unpack.cpython-311.pyc,,
+wheel/cli/convert.py,sha256=Bi0ntEXb9nTllCxWeTRQ4j-nPs3szWSEKipG_GgnMkQ,12634
+wheel/cli/pack.py,sha256=CAFcHdBVulvsHYJlndKVO7KMI9JqBTZz5ii0PKxxCOs,3103
+wheel/cli/tags.py,sha256=lHw-LaWrkS5Jy_qWcw-6pSjeNM6yAjDnqKI3E5JTTCU,4760
+wheel/cli/unpack.py,sha256=Y_J7ynxPSoFFTT7H0fMgbBlVErwyDGcObgme5MBuz58,1021
+wheel/macosx_libfile.py,sha256=k1x7CE3LPtOVGqj6NXQ1nTGYVPaeRrhVzUG_KPq3zDs,16572
+wheel/metadata.py,sha256=JC4p7jlQZu2bUTAQ2fevkqLjg_X6gnNyRhLn6OUO1tc,6171
+wheel/util.py,sha256=aL7aibHwYUgfc8WlolL5tXdkV4DatbJxZHb1kwHFJAU,423
+wheel/vendored/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel/vendored/__pycache__/__init__.cpython-311.pyc,,
+wheel/vendored/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+wheel/vendored/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+wheel/vendored/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+wheel/vendored/packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel/vendored/packaging/__pycache__/__init__.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_elffile.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_manylinux.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_musllinux.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_parser.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_structures.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/_tokenizer.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/markers.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/requirements.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/specifiers.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/tags.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/utils.cpython-311.pyc,,
+wheel/vendored/packaging/__pycache__/version.cpython-311.pyc,,
+wheel/vendored/packaging/_elffile.py,sha256=hbmK8OD6Z7fY6hwinHEUcD1by7czkGiNYu7ShnFEk2k,3266
+wheel/vendored/packaging/_manylinux.py,sha256=P7sdR5_7XBY09LVYYPhHmydMJIIwPXWsh4olk74Uuj4,9588
+wheel/vendored/packaging/_musllinux.py,sha256=z1s8To2hQ0vpn_d-O2i5qxGwEK8WmGlLt3d_26V7NeY,2674
+wheel/vendored/packaging/_parser.py,sha256=4tT4emSl2qTaU7VTQE1Xa9o1jMPCsBezsYBxyNMUN-s,10347
+wheel/vendored/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431
+wheel/vendored/packaging/_tokenizer.py,sha256=alCtbwXhOFAmFGZ6BQ-wCTSFoRAJ2z-ysIf7__MTJ_k,5292
+wheel/vendored/packaging/markers.py,sha256=_TSPI1BhJYO7Bp9AzTmHQxIqHEVXaTjmDh9G-w8qzPA,8232
+wheel/vendored/packaging/requirements.py,sha256=dgoBeVprPu2YE6Q8nGfwOPTjATHbRa_ZGLyXhFEln6Q,2933
+wheel/vendored/packaging/specifiers.py,sha256=IWSt0SrLSP72heWhAC8UL0eGvas7XIQHjqiViVfmPKE,39778
+wheel/vendored/packaging/tags.py,sha256=fedHXiOHkBxNZTXotXv8uXPmMFU9ae-TKBujgYHigcA,18950
+wheel/vendored/packaging/utils.py,sha256=XgdmP3yx9-wQEFjO7OvMj9RjEf5JlR5HFFR69v7SQ9E,5268
+wheel/vendored/packaging/version.py,sha256=PFJaYZDxBgyxkfYhH3SQw4qfE9ICCWrTmitvq14y3bs,16234
+wheel/vendored/vendor.txt,sha256=Z2ENjB1i5prfez8CdM1Sdr3c6Zxv2rRRolMpLmBncAE,16
+wheel/wheelfile.py,sha256=USCttNlJwafxt51YYFFKG7jnxz8dfhbyqAZL6jMTA9s,8411
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e3c6feefa22927866e3fd5575379ea972b432aaf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.10.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..06c9f69debd05e53c3b6053a905805e616c61fad
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel-0.45.1.dist-info/entry_points.txt
@@ -0,0 +1,6 @@
+[console_scripts]
+wheel=wheel.cli:main
+
+[distutils.commands]
+bdist_wheel=wheel.bdist_wheel:bdist_wheel
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ab8f72d8b2e31b1cb8456ee1c4b8e62d4aba252
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import annotations
+
+__version__ = "0.45.1"
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__main__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0be74537494dc2cf18c2e3b318ffd22b886aef6b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/__main__.py
@@ -0,0 +1,23 @@
+"""
+Wheel command line tool (enable python -m wheel syntax)
+"""
+
+from __future__ import annotations
+
+import sys
+
+
+def main():  # needed for console script
+    if __package__ == "":
+        # To be able to run 'python wheel-0.9.whl/wheel':
+        import os.path
+
+        path = os.path.dirname(os.path.dirname(__file__))
+        sys.path[0:0] = [path]
+    import wheel.cli
+
+    sys.exit(wheel.cli.main())
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..88973ebfb88f9521e5f0613b5cedf1204d10a8f1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
@@ -0,0 +1,613 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import stat
+import struct
+import sys
+import sysconfig
+import warnings
+from email.generator import BytesGenerator, Generator
+from email.policy import EmailPolicy
+from glob import iglob
+from shutil import rmtree
+from typing import TYPE_CHECKING, Callable, Iterable, Literal, Sequence, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+import setuptools
+from setuptools import Command
+
+from . import __version__ as wheel_version
+from .metadata import pkginfo_to_metadata
+from .util import log
+from .vendored.packaging import tags
+from .vendored.packaging import version as _packaging_version
+from .wheelfile import WheelFile
+
+if TYPE_CHECKING:
+    import types
+
+# ensure Python logging is configured
+try:
+    __import__("setuptools.logging")
+except ImportError:
+    # setuptools < ??
+    from . import _setuptools_logging
+
+    _setuptools_logging.configure()
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(_packaging_version.Version(version))
+    except _packaging_version.InvalidVersion:
+        version = version.replace(" ", ".")
+        return re.sub("[^A-Za-z0-9.]+", "-", version)
+
+
+setuptools_major_version = int(setuptools.__version__.split(".")[0])
+
+PY_LIMITED_API_PATTERN = r"cp3\d"
+
+
+def _is_32bit_interpreter() -> bool:
+    return struct.calcsize("P") == 4
+
+
+def python_tag() -> str:
+    return f"py{sys.version_info[0]}"
+
+
+def get_platform(archive_root: str | None) -> str:
+    """Return our platform name 'win32', 'linux_x86_64'"""
+    result = sysconfig.get_platform()
+    if result.startswith("macosx") and archive_root is not None:
+        from .macosx_libfile import calculate_macosx_platform_tag
+
+        result = calculate_macosx_platform_tag(archive_root, result)
+    elif _is_32bit_interpreter():
+        if result == "linux-x86_64":
+            # pip pull request #3497
+            result = "linux-i686"
+        elif result == "linux-aarch64":
+            # packaging pull request #234
+            # TODO armv8l, packaging pull request #690 => this did not land
+            # in pip/packaging yet
+            result = "linux-armv7l"
+
+    return result.replace("-", "_")
+
+
+def get_flag(
+    var: str, fallback: bool, expected: bool = True, warn: bool = True
+) -> bool:
+    """Use a fallback value for determining SOABI flags if the needed config
+    var is unset or unavailable."""
+    val = sysconfig.get_config_var(var)
+    if val is None:
+        if warn:
+            warnings.warn(
+                f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
+                RuntimeWarning,
+                stacklevel=2,
+            )
+        return fallback
+    return val == expected
+
+
+def get_abi_tag() -> str | None:
+    """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
+    soabi: str = sysconfig.get_config_var("SOABI")
+    impl = tags.interpreter_name()
+    if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
+        d = ""
+        m = ""
+        u = ""
+        if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
+            d = "d"
+
+        if get_flag(
+            "WITH_PYMALLOC",
+            impl == "cp",
+            warn=(impl == "cp" and sys.version_info < (3, 8)),
+        ) and sys.version_info < (3, 8):
+            m = "m"
+
+        abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}"
+    elif soabi and impl == "cp" and soabi.startswith("cpython"):
+        # non-Windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi and impl == "cp" and soabi.startswith("cp"):
+        # Windows
+        abi = soabi.split("-")[0]
+    elif soabi and impl == "pp":
+        # we want something like pypy36-pp73
+        abi = "-".join(soabi.split("-")[:2])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi and impl == "graalpy":
+        abi = "-".join(soabi.split("-")[:3])
+        abi = abi.replace(".", "_").replace("-", "_")
+    elif soabi:
+        abi = soabi.replace(".", "_").replace("-", "_")
+    else:
+        abi = None
+
+    return abi
+
+
+def safer_name(name: str) -> str:
+    return safe_name(name).replace("-", "_")
+
+
+def safer_version(version: str) -> str:
+    return safe_version(version).replace("-", "_")
+
+
+def remove_readonly(
+    func: Callable[..., object],
+    path: str,
+    excinfo: tuple[type[Exception], Exception, types.TracebackType],
+) -> None:
+    remove_readonly_exc(func, path, excinfo[1])
+
+
+def remove_readonly_exc(func: Callable[..., object], path: str, exc: Exception) -> None:
+    os.chmod(path, stat.S_IWRITE)
+    func(path)
+
+
+class bdist_wheel(Command):
+    description = "create a wheel distribution"
+
+    supported_compressions = {
+        "stored": ZIP_STORED,
+        "deflated": ZIP_DEFLATED,
+    }
+
+    user_options = [
+        ("bdist-dir=", "b", "temporary directory for creating the distribution"),
+        (
+            "plat-name=",
+            "p",
+            "platform name to embed in generated filenames "
+            f"(default: {get_platform(None)})",
+        ),
+        (
+            "keep-temp",
+            "k",
+            "keep the pseudo-installation tree around after "
+            "creating the distribution archive",
+        ),
+        ("dist-dir=", "d", "directory to put final built distributions in"),
+        ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
+        (
+            "relative",
+            None,
+            "build the archive using relative paths (default: false)",
+        ),
+        (
+            "owner=",
+            "u",
+            "Owner name used when creating a tar file [default: current user]",
+        ),
+        (
+            "group=",
+            "g",
+            "Group name used when creating a tar file [default: current group]",
+        ),
+        ("universal", None, "make a universal wheel (default: false)"),
+        (
+            "compression=",
+            None,
+            "zipfile compression (one of: {}) (default: 'deflated')".format(
+                ", ".join(supported_compressions)
+            ),
+        ),
+        (
+            "python-tag=",
+            None,
+            f"Python implementation compatibility tag (default: '{python_tag()}')",
+        ),
+        (
+            "build-number=",
+            None,
+            "Build number for this particular version. "
+            "As specified in PEP-0427, this must start with a digit. "
+            "[default: None]",
+        ),
+        (
+            "py-limited-api=",
+            None,
+            "Python tag (cp32|cp33|cpNN) for abi3 wheel tag (default: false)",
+        ),
+    ]
+
+    boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
+
+    def initialize_options(self):
+        self.bdist_dir: str = None
+        self.data_dir = None
+        self.plat_name: str | None = None
+        self.plat_tag = None
+        self.format = "zip"
+        self.keep_temp = False
+        self.dist_dir: str | None = None
+        self.egginfo_dir = None
+        self.root_is_pure: bool | None = None
+        self.skip_build = None
+        self.relative = False
+        self.owner = None
+        self.group = None
+        self.universal: bool = False
+        self.compression: str | int = "deflated"
+        self.python_tag: str = python_tag()
+        self.build_number: str | None = None
+        self.py_limited_api: str | Literal[False] = False
+        self.plat_name_supplied = False
+
+    def finalize_options(self):
+        if self.bdist_dir is None:
+            bdist_base = self.get_finalized_command("bdist").bdist_base
+            self.bdist_dir = os.path.join(bdist_base, "wheel")
+
+        egg_info = self.distribution.get_command_obj("egg_info")
+        egg_info.ensure_finalized()  # needed for correct `wheel_dist_name`
+
+        self.data_dir = self.wheel_dist_name + ".data"
+        self.plat_name_supplied = self.plat_name is not None
+
+        try:
+            self.compression = self.supported_compressions[self.compression]
+        except KeyError:
+            raise ValueError(f"Unsupported compression: {self.compression}") from None
+
+        need_options = ("dist_dir", "plat_name", "skip_build")
+
+        self.set_undefined_options("bdist", *zip(need_options, need_options))
+
+        self.root_is_pure = not (
+            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
+        )
+
+        if self.py_limited_api and not re.match(
+            PY_LIMITED_API_PATTERN, self.py_limited_api
+        ):
+            raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
+
+        # Support legacy [wheel] section for setting universal
+        wheel = self.distribution.get_option_dict("wheel")
+        if "universal" in wheel:
+            # please don't define this in your global configs
+            log.warning(
+                "The [wheel] section is deprecated. Use [bdist_wheel] instead.",
+            )
+            val = wheel["universal"][1].strip()
+            if val.lower() in ("1", "true", "yes"):
+                self.universal = True
+
+        if self.build_number is not None and not self.build_number[:1].isdigit():
+            raise ValueError("Build tag (build-number) must start with a digit.")
+
+    @property
+    def wheel_dist_name(self):
+        """Return distribution full name with - replaced with _"""
+        components = (
+            safer_name(self.distribution.get_name()),
+            safer_version(self.distribution.get_version()),
+        )
+        if self.build_number:
+            components += (self.build_number,)
+        return "-".join(components)
+
+    def get_tag(self) -> tuple[str, str, str]:
+        # bdist sets self.plat_name if unset, we should only use it for purepy
+        # wheels if the user supplied it.
+        if self.plat_name_supplied:
+            plat_name = cast(str, self.plat_name)
+        elif self.root_is_pure:
+            plat_name = "any"
+        else:
+            # macosx contains system version in platform name so need special handle
+            if self.plat_name and not self.plat_name.startswith("macosx"):
+                plat_name = self.plat_name
+            else:
+                # on macosx always limit the platform name to comply with any
+                # c-extension modules in bdist_dir, since the user can specify
+                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
+
+                # on other platforms, and on macosx if there are no c-extension
+                # modules, use the default platform name.
+                plat_name = get_platform(self.bdist_dir)
+
+            if _is_32bit_interpreter():
+                if plat_name in ("linux-x86_64", "linux_x86_64"):
+                    plat_name = "linux_i686"
+                if plat_name in ("linux-aarch64", "linux_aarch64"):
+                    # TODO armv8l, packaging pull request #690 => this did not land
+                    # in pip/packaging yet
+                    plat_name = "linux_armv7l"
+
+        plat_name = (
+            plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
+        )
+
+        if self.root_is_pure:
+            if self.universal:
+                impl = "py2.py3"
+            else:
+                impl = self.python_tag
+            tag = (impl, "none", plat_name)
+        else:
+            impl_name = tags.interpreter_name()
+            impl_ver = tags.interpreter_version()
+            impl = impl_name + impl_ver
+            # We don't work on CPython 3.1, 3.0.
+            if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
+                impl = self.py_limited_api
+                abi_tag = "abi3"
+            else:
+                abi_tag = str(get_abi_tag()).lower()
+            tag = (impl, abi_tag, plat_name)
+            # issue gh-374: allow overriding plat_name
+            supported_tags = [
+                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
+            ]
+            assert (
+                tag in supported_tags
+            ), f"would build wheel with unsupported tag {tag}"
+        return tag
+
+    def run(self):
+        build_scripts = self.reinitialize_command("build_scripts")
+        build_scripts.executable = "python"
+        build_scripts.force = True
+
+        build_ext = self.reinitialize_command("build_ext")
+        build_ext.inplace = False
+
+        if not self.skip_build:
+            self.run_command("build")
+
+        install = self.reinitialize_command("install", reinit_subcommands=True)
+        install.root = self.bdist_dir
+        install.compile = False
+        install.skip_build = self.skip_build
+        install.warn_dir = False
+
+        # A wheel without setuptools scripts is more cross-platform.
+        # Use the (undocumented) `no_ep` option to setuptools'
+        # install_scripts command to avoid creating entry point scripts.
+        install_scripts = self.reinitialize_command("install_scripts")
+        install_scripts.no_ep = True
+
+        # Use a custom scheme for the archive, because we have to decide
+        # at installation time which scheme to use.
+        for key in ("headers", "scripts", "data", "purelib", "platlib"):
+            setattr(install, "install_" + key, os.path.join(self.data_dir, key))
+
+        basedir_observed = ""
+
+        if os.name == "nt":
+            # win32 barfs if any of these are ''; could be '.'?
+            # (distutils.command.install:change_roots bug)
+            basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
+            self.install_libbase = self.install_lib = basedir_observed
+
+        setattr(
+            install,
+            "install_purelib" if self.root_is_pure else "install_platlib",
+            basedir_observed,
+        )
+
+        log.info(f"installing to {self.bdist_dir}")
+
+        self.run_command("install")
+
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
+        if not self.relative:
+            archive_root = self.bdist_dir
+        else:
+            archive_root = os.path.join(
+                self.bdist_dir, self._ensure_relative(install.install_base)
+            )
+
+        self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
+        distinfo_dirname = (
+            f"{safer_name(self.distribution.get_name())}-"
+            f"{safer_version(self.distribution.get_version())}.dist-info"
+        )
+        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
+        self.egg2dist(self.egginfo_dir, distinfo_dir)
+
+        self.write_wheelfile(distinfo_dir)
+
+        # Make the archive
+        if not os.path.exists(self.dist_dir):
+            os.makedirs(self.dist_dir)
+
+        wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
+        with WheelFile(wheel_path, "w", self.compression) as wf:
+            wf.write_files(archive_root)
+
+        # Add to 'Distribution.dist_files' so that the "upload" command works
+        getattr(self.distribution, "dist_files", []).append(
+            (
+                "bdist_wheel",
+                "{}.{}".format(*sys.version_info[:2]),  # like 3.7
+                wheel_path,
+            )
+        )
+
+        if not self.keep_temp:
+            log.info(f"removing {self.bdist_dir}")
+            if not self.dry_run:
+                if sys.version_info < (3, 12):
+                    rmtree(self.bdist_dir, onerror=remove_readonly)
+                else:
+                    rmtree(self.bdist_dir, onexc=remove_readonly_exc)
+
+    def write_wheelfile(
+        self, wheelfile_base: str, generator: str = f"bdist_wheel ({wheel_version})"
+    ):
+        from email.message import Message
+
+        msg = Message()
+        msg["Wheel-Version"] = "1.0"  # of the spec
+        msg["Generator"] = generator
+        msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
+        if self.build_number is not None:
+            msg["Build"] = self.build_number
+
+        # Doesn't work for bdist_wininst
+        impl_tag, abi_tag, plat_tag = self.get_tag()
+        for impl in impl_tag.split("."):
+            for abi in abi_tag.split("."):
+                for plat in plat_tag.split("."):
+                    msg["Tag"] = "-".join((impl, abi, plat))
+
+        wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
+        log.info(f"creating {wheelfile_path}")
+        with open(wheelfile_path, "wb") as f:
+            BytesGenerator(f, maxheaderlen=0).flatten(msg)
+
+    def _ensure_relative(self, path: str) -> str:
+        # copied from dir_util, deleted
+        drive, path = os.path.splitdrive(path)
+        if path[0:1] == os.sep:
+            path = drive + path[1:]
+        return path
+
+    @property
+    def license_paths(self) -> Iterable[str]:
+        if setuptools_major_version >= 57:
+            # Setuptools has resolved any patterns to actual file names
+            return self.distribution.metadata.license_files or ()
+
+        files: set[str] = set()
+        metadata = self.distribution.get_option_dict("metadata")
+        if setuptools_major_version >= 42:
+            # Setuptools recognizes the license_files option but does not do globbing
+            patterns = cast(Sequence[str], self.distribution.metadata.license_files)
+        else:
+            # Prior to those, wheel is entirely responsible for handling license files
+            if "license_files" in metadata:
+                patterns = metadata["license_files"][1].split()
+            else:
+                patterns = ()
+
+        if "license_file" in metadata:
+            warnings.warn(
+                'The "license_file" option is deprecated. Use "license_files" instead.',
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            files.add(metadata["license_file"][1])
+
+        if not files and not patterns and not isinstance(patterns, list):
+            patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
+
+        for pattern in patterns:
+            for path in iglob(pattern):
+                if path.endswith("~"):
+                    log.debug(
+                        f'ignoring license file "{path}" as it looks like a backup'
+                    )
+                    continue
+
+                if path not in files and os.path.isfile(path):
+                    log.info(
+                        f'adding license file "{path}" (matched pattern "{pattern}")'
+                    )
+                    files.add(path)
+
+        return files
+
+    def egg2dist(self, egginfo_path: str, distinfo_path: str):
+        """Convert an .egg-info directory into a .dist-info directory"""
+
+        def adios(p: str) -> None:
+            """Appropriately delete directory, file or link."""
+            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
+                shutil.rmtree(p)
+            elif os.path.exists(p):
+                os.unlink(p)
+
+        adios(distinfo_path)
+
+        if not os.path.exists(egginfo_path):
+            # There is no egg-info. This is probably because the egg-info
+            # file/directory is not named matching the distribution name used
+            # to name the archive file. Check for this case and report
+            # accordingly.
+            import glob
+
+            pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
+            possible = glob.glob(pat)
+            err = f"Egg metadata expected at {egginfo_path} but not found"
+            if possible:
+                alt = os.path.basename(possible[0])
+                err += f" ({alt} found - possible misnamed archive file?)"
+
+            raise ValueError(err)
+
+        if os.path.isfile(egginfo_path):
+            # .egg-info is a single file
+            pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path)
+            os.mkdir(distinfo_path)
+        else:
+            # .egg-info is a directory
+            pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
+            pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path)
+
+            # ignore common egg metadata that is useless to wheel
+            shutil.copytree(
+                egginfo_path,
+                distinfo_path,
+                ignore=lambda x, y: {
+                    "PKG-INFO",
+                    "requires.txt",
+                    "SOURCES.txt",
+                    "not-zip-safe",
+                },
+            )
+
+            # delete dependency_links if it is only whitespace
+            dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
+            with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
+                dependency_links = dependency_links_file.read().strip()
+            if not dependency_links:
+                adios(dependency_links_path)
+
+        pkg_info_path = os.path.join(distinfo_path, "METADATA")
+        serialization_policy = EmailPolicy(
+            utf8=True,
+            mangle_from_=False,
+            max_line_length=0,
+        )
+        with open(pkg_info_path, "w", encoding="utf-8") as out:
+            Generator(out, policy=serialization_policy).flatten(pkg_info)
+
+        for license_path in self.license_paths:
+            filename = os.path.basename(license_path)
+            shutil.copy(license_path, os.path.join(distinfo_path, filename))
+
+        adios(egginfo_path)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1a2482ba29ac5290c8f7d7688452ec3faf59332
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py
@@ -0,0 +1,26 @@
+# copied from setuptools.logging, omitting monkeypatching
+from __future__ import annotations
+
+import logging
+import sys
+
+
+def _not_warning(record: logging.LogRecord) -> bool:
+    return record.levelno < logging.WARNING
+
+
+def configure() -> None:
+    """
+    Configure logging to emit warning and above to stderr
+    and everything else to stdout. This behavior is provided
+    for compatibility with distutils.log but may change in
+    the future.
+    """
+    err_handler = logging.StreamHandler()
+    err_handler.setLevel(logging.WARNING)
+    out_handler = logging.StreamHandler(sys.stdout)
+    out_handler.addFilter(_not_warning)
+    handlers = err_handler, out_handler
+    logging.basicConfig(
+        format="{message}", style="{", handlers=handlers, level=logging.DEBUG
+    )
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/bdist_wheel.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd7b8629e5087fe35a2ea7ab6d3cbbb4cacf0031
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/bdist_wheel.py
@@ -0,0 +1,26 @@
+from typing import TYPE_CHECKING
+from warnings import warn
+
+warn(
+    "The 'wheel' package is no longer the canonical location of the 'bdist_wheel' "
+    "command, and will be removed in a future release. Please update to setuptools "
+    "v70.1 or later which contains an integrated version of this command.",
+    DeprecationWarning,
+    stacklevel=1,
+)
+
+if TYPE_CHECKING:
+    from ._bdist_wheel import bdist_wheel as bdist_wheel
+else:
+    try:
+        # Better integration/compatibility with setuptools:
+        # in the case new fixes or PEPs are implemented in setuptools
+        # there is no need to backport them to the deprecated code base.
+        # This is useful in the case of old packages in the ecosystem
+        # that are still used but have low maintenance.
+        from setuptools.command.bdist_wheel import bdist_wheel
+    except ImportError:
+        # Only used in the case of old setuptools versions.
+        # If the user wants to get the latest fixes/PEPs,
+        # they are encouraged to address the deprecation warning.
+        from ._bdist_wheel import bdist_wheel as bdist_wheel
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ba1217f5bdb6106c37ecc2be74d53ef2237b717
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/__init__.py
@@ -0,0 +1,155 @@
+"""
+Wheel command-line utility.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from argparse import ArgumentTypeError
+
+
+class WheelError(Exception):
+    pass
+
+
+def unpack_f(args: argparse.Namespace) -> None:
+    from .unpack import unpack
+
+    unpack(args.wheelfile, args.dest)
+
+
+def pack_f(args: argparse.Namespace) -> None:
+    from .pack import pack
+
+    pack(args.directory, args.dest_dir, args.build_number)
+
+
+def convert_f(args: argparse.Namespace) -> None:
+    from .convert import convert
+
+    convert(args.files, args.dest_dir, args.verbose)
+
+
+def tags_f(args: argparse.Namespace) -> None:
+    from .tags import tags
+
+    names = (
+        tags(
+            wheel,
+            args.python_tag,
+            args.abi_tag,
+            args.platform_tag,
+            args.build,
+            args.remove,
+        )
+        for wheel in args.wheel
+    )
+
+    for name in names:
+        print(name)
+
+
+def version_f(args: argparse.Namespace) -> None:
+    from .. import __version__
+
+    print(f"wheel {__version__}")
+
+
+def parse_build_tag(build_tag: str) -> str:
+    if build_tag and not build_tag[0].isdigit():
+        raise ArgumentTypeError("build tag must begin with a digit")
+    elif "-" in build_tag:
+        raise ArgumentTypeError("invalid character ('-') in build tag")
+
+    return build_tag
+
+
+TAGS_HELP = """\
+Make a new wheel with given tags. Any tags unspecified will remain the same.
+Starting the tags with a "+" will append to the existing tags. Starting with a
+"-" will remove a tag (use --option=-TAG syntax). Multiple tags can be
+separated by ".". The original file will remain unless --remove is given.  The
+output filename(s) will be displayed on stdout for further processing.
+"""
+
+
+def parser():
+    p = argparse.ArgumentParser()
+    s = p.add_subparsers(help="commands")
+
+    unpack_parser = s.add_parser("unpack", help="Unpack wheel")
+    unpack_parser.add_argument(
+        "--dest", "-d", help="Destination directory", default="."
+    )
+    unpack_parser.add_argument("wheelfile", help="Wheel file")
+    unpack_parser.set_defaults(func=unpack_f)
+
+    repack_parser = s.add_parser("pack", help="Repack wheel")
+    repack_parser.add_argument("directory", help="Root directory of the unpacked wheel")
+    repack_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store the wheel (default %(default)s)",
+    )
+    repack_parser.add_argument(
+        "--build-number", help="Build tag to use in the wheel name"
+    )
+    repack_parser.set_defaults(func=pack_f)
+
+    convert_parser = s.add_parser("convert", help="Convert egg or wininst to wheel")
+    convert_parser.add_argument("files", nargs="*", help="Files to convert")
+    convert_parser.add_argument(
+        "--dest-dir",
+        "-d",
+        default=os.path.curdir,
+        help="Directory to store wheels (default %(default)s)",
+    )
+    convert_parser.add_argument("--verbose", "-v", action="store_true")
+    convert_parser.set_defaults(func=convert_f)
+
+    tags_parser = s.add_parser(
+        "tags", help="Add or replace the tags on a wheel", description=TAGS_HELP
+    )
+    tags_parser.add_argument("wheel", nargs="*", help="Existing wheel(s) to retag")
+    tags_parser.add_argument(
+        "--remove",
+        action="store_true",
+        help="Remove the original files, keeping only the renamed ones",
+    )
+    tags_parser.add_argument(
+        "--python-tag", metavar="TAG", help="Specify an interpreter tag(s)"
+    )
+    tags_parser.add_argument("--abi-tag", metavar="TAG", help="Specify an ABI tag(s)")
+    tags_parser.add_argument(
+        "--platform-tag", metavar="TAG", help="Specify a platform tag(s)"
+    )
+    tags_parser.add_argument(
+        "--build", type=parse_build_tag, metavar="BUILD", help="Specify a build tag"
+    )
+    tags_parser.set_defaults(func=tags_f)
+
+    version_parser = s.add_parser("version", help="Print version and exit")
+    version_parser.set_defaults(func=version_f)
+
+    help_parser = s.add_parser("help", help="Show this help")
+    help_parser.set_defaults(func=lambda args: p.print_help())
+
+    return p
+
+
+def main():
+    p = parser()
+    args = p.parse_args()
+    if not hasattr(args, "func"):
+        p.print_help()
+    else:
+        try:
+            args.func(args)
+            return 0
+        except WheelError as e:
+            print(e, file=sys.stderr)
+
+    return 1
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/convert.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..61d4775c58596ec12a0c4d4a548de430dee579bf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/convert.py
@@ -0,0 +1,332 @@
+from __future__ import annotations
+
+import os.path
+import re
+from abc import ABCMeta, abstractmethod
+from collections import defaultdict
+from collections.abc import Iterator
+from email.message import Message
+from email.parser import Parser
+from email.policy import EmailPolicy
+from glob import iglob
+from pathlib import Path
+from textwrap import dedent
+from zipfile import ZipFile
+
+from .. import __version__
+from ..metadata import generate_requirements
+from ..vendored.packaging.tags import parse_tag
+from ..wheelfile import WheelFile
+
+egg_filename_re = re.compile(
+    r"""
+    (?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+     (-(?P.+?))?
+    )?.egg$""",
+    re.VERBOSE,
+)
+egg_info_re = re.compile(
+    r"""
+    ^(?P.+?)-(?P.+?)
+    (-(?Ppy\d\.\d+)
+    )?.egg-info/""",
+    re.VERBOSE,
+)
+wininst_re = re.compile(
+    r"\.(?Pwin32|win-amd64)(?:-(?Ppy\d\.\d))?\.exe$"
+)
+pyd_re = re.compile(r"\.(?P[a-z0-9]+)-(?Pwin32|win_amd64)\.pyd$")
+serialization_policy = EmailPolicy(
+    utf8=True,
+    mangle_from_=False,
+    max_line_length=0,
+)
+GENERATOR = f"wheel {__version__}"
+
+
+def convert_requires(requires: str, metadata: Message) -> None:
+    extra: str | None = None
+    requirements: dict[str | None, list[str]] = defaultdict(list)
+    for line in requires.splitlines():
+        line = line.strip()
+        if not line:
+            continue
+
+        if line.startswith("[") and line.endswith("]"):
+            extra = line[1:-1]
+            continue
+
+        requirements[extra].append(line)
+
+    for key, value in generate_requirements(requirements):
+        metadata.add_header(key, value)
+
+
+def convert_pkg_info(pkginfo: str, metadata: Message):
+    parsed_message = Parser().parsestr(pkginfo)
+    for key, value in parsed_message.items():
+        key_lower = key.lower()
+        if value == "UNKNOWN":
+            continue
+
+        if key_lower == "description":
+            description_lines = value.splitlines()
+            value = "\n".join(
+                (
+                    description_lines[0].lstrip(),
+                    dedent("\n".join(description_lines[1:])),
+                    "\n",
+                )
+            )
+            metadata.set_payload(value)
+        elif key_lower == "home-page":
+            metadata.add_header("Project-URL", f"Homepage, {value}")
+        elif key_lower == "download-url":
+            metadata.add_header("Project-URL", f"Download, {value}")
+        else:
+            metadata.add_header(key, value)
+
+    metadata.replace_header("Metadata-Version", "2.4")
+
+
+def normalize(name: str) -> str:
+    return re.sub(r"[-_.]+", "-", name).lower().replace("-", "_")
+
+
+class ConvertSource(metaclass=ABCMeta):
+    name: str
+    version: str
+    pyver: str = "py2.py3"
+    abi: str = "none"
+    platform: str = "any"
+    metadata: Message
+
+    @property
+    def dist_info_dir(self) -> str:
+        return f"{self.name}-{self.version}.dist-info"
+
+    @abstractmethod
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        pass
+
+
+class EggFileSource(ConvertSource):
+    def __init__(self, path: Path):
+        if not (match := egg_filename_re.match(path.name)):
+            raise ValueError(f"Invalid egg file name: {path.name}")
+
+        # Binary wheels are assumed to be for CPython
+        self.path = path
+        self.name = normalize(match.group("name"))
+        self.version = match.group("ver")
+        if pyver := match.group("pyver"):
+            self.pyver = pyver.replace(".", "")
+            if arch := match.group("arch"):
+                self.abi = self.pyver.replace("py", "cp")
+                self.platform = normalize(arch)
+
+        self.metadata = Message()
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                if filename.startswith("EGG-INFO/"):
+                    if filename == "EGG-INFO/requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif filename == "EGG-INFO/PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif filename == "EGG-INFO/entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield filename, zip_file.read(filename)
+
+
+class EggDirectorySource(EggFileSource):
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        for dirpath, _, filenames in os.walk(self.path):
+            for filename in sorted(filenames):
+                path = Path(dirpath, filename)
+                if path.parent.name == "EGG-INFO":
+                    if path.name == "requires.txt":
+                        requires = path.read_text("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif path.name == "PKG-INFO":
+                        pkginfo = path.read_text("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                        if name := self.metadata.get("Name"):
+                            self.name = normalize(name)
+
+                        if version := self.metadata.get("Version"):
+                            self.version = version
+                    elif path.name == "entry_points.txt":
+                        yield (
+                            f"{self.dist_info_dir}/entry_points.txt",
+                            path.read_bytes(),
+                        )
+
+                    continue
+
+                # For any other file, just pass it through
+                yield str(path.relative_to(self.path)), path.read_bytes()
+
+
+class WininstFileSource(ConvertSource):
+    """
+    Handles distributions created with ``bdist_wininst``.
+
+    The egginfo filename has the format::
+
+        name-ver(-pyver)(-arch).egg-info
+
+    The installer filename has the format::
+
+        name-ver.arch(-pyver).exe
+
+    Some things to note:
+
+    1. The installer filename is not definitive. An installer can be renamed
+       and work perfectly well as an installer. So more reliable data should
+       be used whenever possible.
+    2. The egg-info data should be preferred for the name and version, because
+       these come straight from the distutils metadata, and are mandatory.
+    3. The pyver from the egg-info data should be ignored, as it is
+       constructed from the version of Python used to build the installer,
+       which is irrelevant - the installer filename is correct here (even to
+       the point that when it's not there, any version is implied).
+    4. The architecture must be taken from the installer filename, as it is
+       not included in the egg-info data.
+    5. Architecture-neutral installers still have an architecture because the
+       installer format itself (being executable) is architecture-specific. We
+       should therefore ignore the architecture if the content is pure-python.
+    """
+
+    def __init__(self, path: Path):
+        self.path = path
+        self.metadata = Message()
+
+        # Determine the initial architecture and Python version from the file name
+        # (if possible)
+        if match := wininst_re.search(path.name):
+            self.platform = normalize(match.group("platform"))
+            if pyver := match.group("pyver"):
+                self.pyver = pyver.replace(".", "")
+
+        # Look for an .egg-info directory and any .pyd files for more precise info
+        egg_info_found = pyd_found = False
+        with ZipFile(self.path) as zip_file:
+            for filename in zip_file.namelist():
+                prefix, filename = filename.split("/", 1)
+                if not egg_info_found and (match := egg_info_re.match(filename)):
+                    egg_info_found = True
+                    self.name = normalize(match.group("name"))
+                    self.version = match.group("ver")
+                    if pyver := match.group("pyver"):
+                        self.pyver = pyver.replace(".", "")
+                elif not pyd_found and (match := pyd_re.search(filename)):
+                    pyd_found = True
+                    self.abi = match.group("abi")
+                    self.platform = match.group("platform")
+
+                if egg_info_found and pyd_found:
+                    break
+
+    def generate_contents(self) -> Iterator[tuple[str, bytes]]:
+        dist_info_dir = f"{self.name}-{self.version}.dist-info"
+        data_dir = f"{self.name}-{self.version}.data"
+        with ZipFile(self.path, "r") as zip_file:
+            for filename in sorted(zip_file.namelist()):
+                # Skip pure directory entries
+                if filename.endswith("/"):
+                    continue
+
+                # Handle files in the egg-info directory specially, selectively moving
+                # them to the dist-info directory while converting as needed
+                prefix, target_filename = filename.split("/", 1)
+                if egg_info_re.search(target_filename):
+                    basename = target_filename.rsplit("/", 1)[-1]
+                    if basename == "requires.txt":
+                        requires = zip_file.read(filename).decode("utf-8")
+                        convert_requires(requires, self.metadata)
+                    elif basename == "PKG-INFO":
+                        pkginfo = zip_file.read(filename).decode("utf-8")
+                        convert_pkg_info(pkginfo, self.metadata)
+                    elif basename == "entry_points.txt":
+                        yield (
+                            f"{dist_info_dir}/entry_points.txt",
+                            zip_file.read(filename),
+                        )
+
+                    continue
+                elif prefix == "SCRIPTS":
+                    target_filename = f"{data_dir}/scripts/{target_filename}"
+
+                # For any other file, just pass it through
+                yield target_filename, zip_file.read(filename)
+
+
+def convert(files: list[str], dest_dir: str, verbose: bool) -> None:
+    for pat in files:
+        for archive in iglob(pat):
+            path = Path(archive)
+            if path.suffix == ".egg":
+                if path.is_dir():
+                    source: ConvertSource = EggDirectorySource(path)
+                else:
+                    source = EggFileSource(path)
+            else:
+                source = WininstFileSource(path)
+
+            if verbose:
+                print(f"{archive}...", flush=True, end="")
+
+            dest_path = Path(dest_dir) / (
+                f"{source.name}-{source.version}-{source.pyver}-{source.abi}"
+                f"-{source.platform}.whl"
+            )
+            with WheelFile(dest_path, "w") as wheelfile:
+                for name_or_zinfo, contents in source.generate_contents():
+                    wheelfile.writestr(name_or_zinfo, contents)
+
+                # Write the METADATA file
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/METADATA",
+                    source.metadata.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+                # Write the WHEEL file
+                wheel_message = Message()
+                wheel_message.add_header("Wheel-Version", "1.0")
+                wheel_message.add_header("Generator", GENERATOR)
+                wheel_message.add_header(
+                    "Root-Is-Purelib", str(source.platform == "any").lower()
+                )
+                tags = parse_tag(f"{source.pyver}-{source.abi}-{source.platform}")
+                for tag in sorted(tags, key=lambda tag: tag.interpreter):
+                    wheel_message.add_header("Tag", str(tag))
+
+                wheelfile.writestr(
+                    f"{source.dist_info_dir}/WHEEL",
+                    wheel_message.as_string(policy=serialization_policy).encode(
+                        "utf-8"
+                    ),
+                )
+
+            if verbose:
+                print("OK")
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/pack.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/pack.py
new file mode 100644
index 0000000000000000000000000000000000000000..64469c0c730c24449e77c23f46d0e3f68d647d67
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/pack.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import email.policy
+import os.path
+import re
+from email.generator import BytesGenerator
+from email.parser import BytesParser
+
+from wheel.cli import WheelError
+from wheel.wheelfile import WheelFile
+
+DIST_INFO_RE = re.compile(r"^(?P(?P.+?)-(?P\d.*?))\.dist-info$")
+
+
+def pack(directory: str, dest_dir: str, build_number: str | None) -> None:
+    """Repack a previously unpacked wheel directory into a new wheel file.
+
+    The .dist-info/WHEEL file must contain one or more tags so that the target
+    wheel file name can be determined.
+
+    :param directory: The unpacked wheel directory
+    :param dest_dir: Destination directory (defaults to the current directory)
+    """
+    # Find the .dist-info directory
+    dist_info_dirs = [
+        fn
+        for fn in os.listdir(directory)
+        if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)
+    ]
+    if len(dist_info_dirs) > 1:
+        raise WheelError(f"Multiple .dist-info directories found in {directory}")
+    elif not dist_info_dirs:
+        raise WheelError(f"No .dist-info directories found in {directory}")
+
+    # Determine the target wheel filename
+    dist_info_dir = dist_info_dirs[0]
+    name_version = DIST_INFO_RE.match(dist_info_dir).group("namever")
+
+    # Read the tags and the existing build number from .dist-info/WHEEL
+    wheel_file_path = os.path.join(directory, dist_info_dir, "WHEEL")
+    with open(wheel_file_path, "rb") as f:
+        info = BytesParser(policy=email.policy.compat32).parse(f)
+        tags: list[str] = info.get_all("Tag", [])
+        existing_build_number = info.get("Build")
+
+        if not tags:
+            raise WheelError(
+                f"No tags present in {dist_info_dir}/WHEEL; cannot determine target "
+                f"wheel filename"
+            )
+
+    # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL
+    build_number = build_number if build_number is not None else existing_build_number
+    if build_number is not None:
+        del info["Build"]
+        if build_number:
+            info["Build"] = build_number
+            name_version += "-" + build_number
+
+        if build_number != existing_build_number:
+            with open(wheel_file_path, "wb") as f:
+                BytesGenerator(f, maxheaderlen=0).flatten(info)
+
+    # Reassemble the tags for the wheel file
+    tagline = compute_tagline(tags)
+
+    # Repack the wheel
+    wheel_path = os.path.join(dest_dir, f"{name_version}-{tagline}.whl")
+    with WheelFile(wheel_path, "w") as wf:
+        print(f"Repacking wheel as {wheel_path}...", end="", flush=True)
+        wf.write_files(directory)
+
+    print("OK")
+
+
+def compute_tagline(tags: list[str]) -> str:
+    """Compute a tagline from a list of tags.
+
+    :param tags: A list of tags
+    :return: A tagline
+    """
+    impls = sorted({tag.split("-")[0] for tag in tags})
+    abivers = sorted({tag.split("-")[1] for tag in tags})
+    platforms = sorted({tag.split("-")[2] for tag in tags})
+    return "-".join([".".join(impls), ".".join(abivers), ".".join(platforms)])
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/tags.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..88da72e9ec4a31e2427bdb2bcf2b3e0ce3c0beb0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/tags.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import email.policy
+import itertools
+import os
+from collections.abc import Iterable
+from email.parser import BytesParser
+
+from ..wheelfile import WheelFile
+
+
+def _compute_tags(original_tags: Iterable[str], new_tags: str | None) -> set[str]:
+    """Add or replace tags. Supports dot-separated tags"""
+    if new_tags is None:
+        return set(original_tags)
+
+    if new_tags.startswith("+"):
+        return {*original_tags, *new_tags[1:].split(".")}
+
+    if new_tags.startswith("-"):
+        return set(original_tags) - set(new_tags[1:].split("."))
+
+    return set(new_tags.split("."))
+
+
+def tags(
+    wheel: str,
+    python_tags: str | None = None,
+    abi_tags: str | None = None,
+    platform_tags: str | None = None,
+    build_tag: str | None = None,
+    remove: bool = False,
+) -> str:
+    """Change the tags on a wheel file.
+
+    The tags are left unchanged if they are not specified. To specify "none",
+    use ["none"]. To append to the previous tags, a tag should start with a
+    "+".  If a tag starts with "-", it will be removed from existing tags.
+    Processing is done left to right.
+
+    :param wheel: The paths to the wheels
+    :param python_tags: The Python tags to set
+    :param abi_tags: The ABI tags to set
+    :param platform_tags: The platform tags to set
+    :param build_tag: The build tag to set
+    :param remove: Remove the original wheel
+    """
+    with WheelFile(wheel, "r") as f:
+        assert f.filename, f"{f.filename} must be available"
+
+        wheel_info = f.read(f.dist_info_path + "/WHEEL")
+        info = BytesParser(policy=email.policy.compat32).parsebytes(wheel_info)
+
+        original_wheel_name = os.path.basename(f.filename)
+        namever = f.parsed_filename.group("namever")
+        build = f.parsed_filename.group("build")
+        original_python_tags = f.parsed_filename.group("pyver").split(".")
+        original_abi_tags = f.parsed_filename.group("abi").split(".")
+        original_plat_tags = f.parsed_filename.group("plat").split(".")
+
+    tags: list[str] = info.get_all("Tag", [])
+    existing_build_tag = info.get("Build")
+
+    impls = {tag.split("-")[0] for tag in tags}
+    abivers = {tag.split("-")[1] for tag in tags}
+    platforms = {tag.split("-")[2] for tag in tags}
+
+    if impls != set(original_python_tags):
+        msg = f"Wheel internal tags {impls!r} != filename tags {original_python_tags!r}"
+        raise AssertionError(msg)
+
+    if abivers != set(original_abi_tags):
+        msg = f"Wheel internal tags {abivers!r} != filename tags {original_abi_tags!r}"
+        raise AssertionError(msg)
+
+    if platforms != set(original_plat_tags):
+        msg = (
+            f"Wheel internal tags {platforms!r} != filename tags {original_plat_tags!r}"
+        )
+        raise AssertionError(msg)
+
+    if existing_build_tag != build:
+        msg = (
+            f"Incorrect filename '{build}' "
+            f"& *.dist-info/WHEEL '{existing_build_tag}' build numbers"
+        )
+        raise AssertionError(msg)
+
+    # Start changing as needed
+    if build_tag is not None:
+        build = build_tag
+
+    final_python_tags = sorted(_compute_tags(original_python_tags, python_tags))
+    final_abi_tags = sorted(_compute_tags(original_abi_tags, abi_tags))
+    final_plat_tags = sorted(_compute_tags(original_plat_tags, platform_tags))
+
+    final_tags = [
+        namever,
+        ".".join(final_python_tags),
+        ".".join(final_abi_tags),
+        ".".join(final_plat_tags),
+    ]
+    if build:
+        final_tags.insert(1, build)
+
+    final_wheel_name = "-".join(final_tags) + ".whl"
+
+    if original_wheel_name != final_wheel_name:
+        del info["Tag"], info["Build"]
+        for a, b, c in itertools.product(
+            final_python_tags, final_abi_tags, final_plat_tags
+        ):
+            info["Tag"] = f"{a}-{b}-{c}"
+        if build:
+            info["Build"] = build
+
+        original_wheel_path = os.path.join(
+            os.path.dirname(f.filename), original_wheel_name
+        )
+        final_wheel_path = os.path.join(os.path.dirname(f.filename), final_wheel_name)
+
+        with WheelFile(original_wheel_path, "r") as fin, WheelFile(
+            final_wheel_path, "w"
+        ) as fout:
+            fout.comment = fin.comment  # preserve the comment
+            for item in fin.infolist():
+                if item.is_dir():
+                    continue
+                if item.filename == f.dist_info_path + "/RECORD":
+                    continue
+                if item.filename == f.dist_info_path + "/WHEEL":
+                    fout.writestr(item, info.as_bytes())
+                else:
+                    fout.writestr(item, fin.read(item))
+
+        if remove:
+            os.remove(original_wheel_path)
+
+    return final_wheel_name
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/unpack.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/unpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d48840e6ec0512225233bf02d1d7ce203415b04c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/cli/unpack.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from ..wheelfile import WheelFile
+
+
+def unpack(path: str, dest: str = ".") -> None:
+    """Unpack a wheel.
+
+    Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
+    is the package name and {ver} its version.
+
+    :param path: The path to the wheel.
+    :param dest: Destination directory (default to current directory).
+    """
+    with WheelFile(path) as wf:
+        namever = wf.parsed_filename.group("namever")
+        destination = Path(dest) / namever
+        print(f"Unpacking to: {destination}...", end="", flush=True)
+        for zinfo in wf.filelist:
+            wf.extract(zinfo, destination)
+
+            # Set permissions to the same values as they were set in the archive
+            # We have to do this manually due to
+            # https://github.com/python/cpython/issues/59999
+            permissions = zinfo.external_attr >> 16 & 0o777
+            destination.joinpath(zinfo.filename).chmod(permissions)
+
+    print("OK")
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/macosx_libfile.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..abdfc9eda1d4c1f33270c155e1610fe73bd54263
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
@@ -0,0 +1,482 @@
+"""
+This module contains function to analyse dynamic library
+headers to extract system information
+
+Currently only for MacOSX
+
+Library file on macosx system starts with Mach-O or Fat field.
+This can be distinguish by first 32 bites and it is called magic number.
+Proper value of magic number is with suffix _MAGIC. Suffix _CIGAM means
+reversed bytes order.
+Both fields can occur in two types: 32 and 64 bytes.
+
+FAT field inform that this library contains few version of library
+(typically for different types version). It contains
+information where Mach-O headers starts.
+
+Each section started with Mach-O header contains one library
+(So if file starts with this field it contains only one version).
+
+After filed Mach-O there are section fields.
+Each of them starts with two fields:
+cmd - magic number for this command
+cmdsize - total size occupied by this section information.
+
+In this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier)
+and LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting,
+because them contains information about minimal system version.
+
+Important remarks:
+- For fat files this implementation looks for maximum number version.
+  It not check if it is 32 or 64 and do not compare it with currently built package.
+  So it is possible to false report higher version that needed.
+- All structures signatures are taken form macosx header files.
+- I think that binary format will be more stable than `otool` output.
+  and if apple introduce some changes both implementation will need to be updated.
+- The system compile will set the deployment target no lower than
+  11.0 for arm64 builds. For "Universal 2" builds use the x86_64 deployment
+  target when the arm64 target is 11.0.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import os
+import sys
+from io import BufferedIOBase
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Union
+
+    StrPath = Union[str, os.PathLike[str]]
+
+"""here the needed const and struct from mach-o header files"""
+
+FAT_MAGIC = 0xCAFEBABE
+FAT_CIGAM = 0xBEBAFECA
+FAT_MAGIC_64 = 0xCAFEBABF
+FAT_CIGAM_64 = 0xBFBAFECA
+MH_MAGIC = 0xFEEDFACE
+MH_CIGAM = 0xCEFAEDFE
+MH_MAGIC_64 = 0xFEEDFACF
+MH_CIGAM_64 = 0xCFFAEDFE
+
+LC_VERSION_MIN_MACOSX = 0x24
+LC_BUILD_VERSION = 0x32
+
+CPU_TYPE_ARM64 = 0x0100000C
+
+mach_header_fields = [
+    ("magic", ctypes.c_uint32),
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("filetype", ctypes.c_uint32),
+    ("ncmds", ctypes.c_uint32),
+    ("sizeofcmds", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct mach_header {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+};
+typedef integer_t cpu_type_t;
+typedef integer_t cpu_subtype_t;
+"""
+
+mach_header_fields_64 = mach_header_fields + [("reserved", ctypes.c_uint32)]
+"""
+struct mach_header_64 {
+    uint32_t	magic;		/* mach magic number identifier */
+    cpu_type_t	cputype;	/* cpu specifier */
+    cpu_subtype_t	cpusubtype;	/* machine specifier */
+    uint32_t	filetype;	/* type of file */
+    uint32_t	ncmds;		/* number of load commands */
+    uint32_t	sizeofcmds;	/* the size of all the load commands */
+    uint32_t	flags;		/* flags */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+fat_header_fields = [("magic", ctypes.c_uint32), ("nfat_arch", ctypes.c_uint32)]
+"""
+struct fat_header {
+    uint32_t	magic;		/* FAT_MAGIC or FAT_MAGIC_64 */
+    uint32_t	nfat_arch;	/* number of structs that follow */
+};
+"""
+
+fat_arch_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint32),
+    ("size", ctypes.c_uint32),
+    ("align", ctypes.c_uint32),
+]
+"""
+struct fat_arch {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint32_t	offset;		/* file offset to this object file */
+    uint32_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+};
+"""
+
+fat_arch_64_fields = [
+    ("cputype", ctypes.c_int),
+    ("cpusubtype", ctypes.c_int),
+    ("offset", ctypes.c_uint64),
+    ("size", ctypes.c_uint64),
+    ("align", ctypes.c_uint32),
+    ("reserved", ctypes.c_uint32),
+]
+"""
+struct fat_arch_64 {
+    cpu_type_t	cputype;	/* cpu specifier (int) */
+    cpu_subtype_t	cpusubtype;	/* machine specifier (int) */
+    uint64_t	offset;		/* file offset to this object file */
+    uint64_t	size;		/* size of this object file */
+    uint32_t	align;		/* alignment as a power of 2 */
+    uint32_t	reserved;	/* reserved */
+};
+"""
+
+segment_base_fields = [("cmd", ctypes.c_uint32), ("cmdsize", ctypes.c_uint32)]
+"""base for reading segment info"""
+
+segment_command_fields = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint32),
+    ("vmsize", ctypes.c_uint32),
+    ("fileoff", ctypes.c_uint32),
+    ("filesize", ctypes.c_uint32),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command { /* for 32-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT */
+    uint32_t	cmdsize;	/* includes sizeof section structs */
+    char		segname[16];	/* segment name */
+    uint32_t	vmaddr;		/* memory address of this segment */
+    uint32_t	vmsize;		/* memory size of this segment */
+    uint32_t	fileoff;	/* file offset of this segment */
+    uint32_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+typedef int vm_prot_t;
+"""
+
+segment_command_fields_64 = [
+    ("cmd", ctypes.c_uint32),
+    ("cmdsize", ctypes.c_uint32),
+    ("segname", ctypes.c_char * 16),
+    ("vmaddr", ctypes.c_uint64),
+    ("vmsize", ctypes.c_uint64),
+    ("fileoff", ctypes.c_uint64),
+    ("filesize", ctypes.c_uint64),
+    ("maxprot", ctypes.c_int),
+    ("initprot", ctypes.c_int),
+    ("nsects", ctypes.c_uint32),
+    ("flags", ctypes.c_uint32),
+]
+"""
+struct segment_command_64 { /* for 64-bit architectures */
+    uint32_t	cmd;		/* LC_SEGMENT_64 */
+    uint32_t	cmdsize;	/* includes sizeof section_64 structs */
+    char		segname[16];	/* segment name */
+    uint64_t	vmaddr;		/* memory address of this segment */
+    uint64_t	vmsize;		/* memory size of this segment */
+    uint64_t	fileoff;	/* file offset of this segment */
+    uint64_t	filesize;	/* amount to map from the file */
+    vm_prot_t	maxprot;	/* maximum VM protection */
+    vm_prot_t	initprot;	/* initial VM protection */
+    uint32_t	nsects;		/* number of sections in segment */
+    uint32_t	flags;		/* flags */
+};
+"""
+
+version_min_command_fields = segment_base_fields + [
+    ("version", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+]
+"""
+struct version_min_command {
+    uint32_t	cmd;		/* LC_VERSION_MIN_MACOSX or
+                               LC_VERSION_MIN_IPHONEOS or
+                               LC_VERSION_MIN_WATCHOS or
+                               LC_VERSION_MIN_TVOS */
+    uint32_t	cmdsize;	/* sizeof(struct min_version_command) */
+    uint32_t	version;	/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+};
+"""
+
+build_version_command_fields = segment_base_fields + [
+    ("platform", ctypes.c_uint32),
+    ("minos", ctypes.c_uint32),
+    ("sdk", ctypes.c_uint32),
+    ("ntools", ctypes.c_uint32),
+]
+"""
+struct build_version_command {
+    uint32_t	cmd;		/* LC_BUILD_VERSION */
+    uint32_t	cmdsize;	/* sizeof(struct build_version_command) plus */
+                                /* ntools * sizeof(struct build_tool_version) */
+    uint32_t	platform;	/* platform */
+    uint32_t	minos;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	sdk;		/* X.Y.Z is encoded in nibbles xxxx.yy.zz */
+    uint32_t	ntools;		/* number of tool entries following this */
+};
+"""
+
+
+def swap32(x: int) -> int:
+    return (
+        ((x << 24) & 0xFF000000)
+        | ((x << 8) & 0x00FF0000)
+        | ((x >> 8) & 0x0000FF00)
+        | ((x >> 24) & 0x000000FF)
+    )
+
+
+def get_base_class_and_magic_number(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[type[ctypes.Structure], int]:
+    if seek is None:
+        seek = lib_file.tell()
+    else:
+        lib_file.seek(seek)
+    magic_number = ctypes.c_uint32.from_buffer_copy(
+        lib_file.read(ctypes.sizeof(ctypes.c_uint32))
+    ).value
+
+    # Handle wrong byte order
+    if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]:
+        if sys.byteorder == "little":
+            BaseClass = ctypes.BigEndianStructure
+        else:
+            BaseClass = ctypes.LittleEndianStructure
+
+        magic_number = swap32(magic_number)
+    else:
+        BaseClass = ctypes.Structure
+
+    lib_file.seek(seek)
+    return BaseClass, magic_number
+
+
+def read_data(struct_class: type[ctypes.Structure], lib_file: BufferedIOBase):
+    return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class)))
+
+
+def extract_macosx_min_system_version(path_to_lib: str):
+    with open(path_to_lib, "rb") as lib_file:
+        BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0)
+        if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]:
+            return
+
+        if magic_number in [FAT_MAGIC, FAT_CIGAM_64]:
+
+            class FatHeader(BaseClass):
+                _fields_ = fat_header_fields
+
+            fat_header = read_data(FatHeader, lib_file)
+            if magic_number == FAT_MAGIC:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_fields
+
+            else:
+
+                class FatArch(BaseClass):
+                    _fields_ = fat_arch_64_fields
+
+            fat_arch_list = [
+                read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch)
+            ]
+
+            versions_list: list[tuple[int, int, int]] = []
+            for el in fat_arch_list:
+                try:
+                    version = read_mach_header(lib_file, el.offset)
+                    if version is not None:
+                        if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1:
+                            # Xcode will not set the deployment target below 11.0.0
+                            # for the arm64 architecture. Ignore the arm64 deployment
+                            # in fat binaries when the target is 11.0.0, that way
+                            # the other architectures can select a lower deployment
+                            # target.
+                            # This is safe because there is no arm64 variant for
+                            # macOS 10.15 or earlier.
+                            if version == (11, 0, 0):
+                                continue
+                        versions_list.append(version)
+                except ValueError:
+                    pass
+
+            if len(versions_list) > 0:
+                return max(versions_list)
+            else:
+                return None
+
+        else:
+            try:
+                return read_mach_header(lib_file, 0)
+            except ValueError:
+                """when some error during read library files"""
+                return None
+
+
+def read_mach_header(
+    lib_file: BufferedIOBase,
+    seek: int | None = None,
+) -> tuple[int, int, int] | None:
+    """
+    This function parses a Mach-O header and extracts
+    information about the minimal macOS version.
+
+    :param lib_file: reference to opened library file with pointer
+    """
+    base_class, magic_number = get_base_class_and_magic_number(lib_file, seek)
+    arch = "32" if magic_number == MH_MAGIC else "64"
+
+    class SegmentBase(base_class):
+        _fields_ = segment_base_fields
+
+    if arch == "32":
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields
+
+    else:
+
+        class MachHeader(base_class):
+            _fields_ = mach_header_fields_64
+
+    mach_header = read_data(MachHeader, lib_file)
+    for _i in range(mach_header.ncmds):
+        pos = lib_file.tell()
+        segment_base = read_data(SegmentBase, lib_file)
+        lib_file.seek(pos)
+        if segment_base.cmd == LC_VERSION_MIN_MACOSX:
+
+            class VersionMinCommand(base_class):
+                _fields_ = version_min_command_fields
+
+            version_info = read_data(VersionMinCommand, lib_file)
+            return parse_version(version_info.version)
+        elif segment_base.cmd == LC_BUILD_VERSION:
+
+            class VersionBuild(base_class):
+                _fields_ = build_version_command_fields
+
+            version_info = read_data(VersionBuild, lib_file)
+            return parse_version(version_info.minos)
+        else:
+            lib_file.seek(pos + segment_base.cmdsize)
+            continue
+
+
+def parse_version(version: int) -> tuple[int, int, int]:
+    x = (version & 0xFFFF0000) >> 16
+    y = (version & 0x0000FF00) >> 8
+    z = version & 0x000000FF
+    return x, y, z
+
+
+def calculate_macosx_platform_tag(archive_root: StrPath, platform_tag: str) -> str:
+    """
+    Calculate proper macosx platform tag basing on files which are included to wheel
+
+    Example platform tag `macosx-10.14-x86_64`
+    """
+    prefix, base_version, suffix = platform_tag.split("-")
+    base_version = tuple(int(x) for x in base_version.split("."))
+    base_version = base_version[:2]
+    if base_version[0] > 10:
+        base_version = (base_version[0], 0)
+    assert len(base_version) == 2
+    if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+        deploy_target = tuple(
+            int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".")
+        )
+        deploy_target = deploy_target[:2]
+        if deploy_target[0] > 10:
+            deploy_target = (deploy_target[0], 0)
+        if deploy_target < base_version:
+            sys.stderr.write(
+                "[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than "
+                "the version on which the Python interpreter was compiled ({}), and "
+                "will be ignored.\n".format(
+                    ".".join(str(x) for x in deploy_target),
+                    ".".join(str(x) for x in base_version),
+                )
+            )
+        else:
+            base_version = deploy_target
+
+    assert len(base_version) == 2
+    start_version = base_version
+    versions_dict: dict[str, tuple[int, int]] = {}
+    for dirpath, _dirnames, filenames in os.walk(archive_root):
+        for filename in filenames:
+            if filename.endswith(".dylib") or filename.endswith(".so"):
+                lib_path = os.path.join(dirpath, filename)
+                min_ver = extract_macosx_min_system_version(lib_path)
+                if min_ver is not None:
+                    min_ver = min_ver[0:2]
+                    if min_ver[0] > 10:
+                        min_ver = (min_ver[0], 0)
+                    versions_dict[lib_path] = min_ver
+
+    if len(versions_dict) > 0:
+        base_version = max(base_version, max(versions_dict.values()))
+
+    # macosx platform tag do not support minor bugfix release
+    fin_base_version = "_".join([str(x) for x in base_version])
+    if start_version < base_version:
+        problematic_files = [k for k, v in versions_dict.items() if v > start_version]
+        problematic_files = "\n".join(problematic_files)
+        if len(problematic_files) == 1:
+            files_form = "this file"
+        else:
+            files_form = "these files"
+        error_message = (
+            "[WARNING] This wheel needs a higher macOS version than {}  "
+            "To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least "
+            + fin_base_version
+            + " or recreate "
+            + files_form
+            + " with lower "
+            "MACOSX_DEPLOYMENT_TARGET:  \n" + problematic_files
+        )
+
+        if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
+            error_message = error_message.format(
+                "is set in MACOSX_DEPLOYMENT_TARGET variable."
+            )
+        else:
+            error_message = error_message.format(
+                "the version your Python interpreter is compiled against."
+            )
+
+        sys.stderr.write(error_message)
+
+    platform_tag = prefix + "_" + fin_base_version + "_" + suffix
+    return platform_tag
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/metadata.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8098fa8599a1f142ee33ee551b7a874f5f98840
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/metadata.py
@@ -0,0 +1,183 @@
+"""
+Tools for converting old- to new-style metadata.
+"""
+
+from __future__ import annotations
+
+import functools
+import itertools
+import os.path
+import re
+import textwrap
+from email.message import Message
+from email.parser import Parser
+from typing import Generator, Iterable, Iterator, Literal
+
+from .vendored.packaging.requirements import Requirement
+
+
+def _nonblank(str: str) -> bool | Literal[""]:
+    return str and not str.startswith("#")
+
+
+@functools.singledispatch
+def yield_lines(iterable: Iterable[str]) -> Iterator[str]:
+    r"""
+    Yield valid lines of a string or iterable.
+    >>> list(yield_lines(''))
+    []
+    >>> list(yield_lines(['foo', 'bar']))
+    ['foo', 'bar']
+    >>> list(yield_lines('foo\nbar'))
+    ['foo', 'bar']
+    >>> list(yield_lines('\nfoo\n#bar\nbaz #comment'))
+    ['foo', 'baz #comment']
+    >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n']))
+    ['foo', 'bar', 'baz', 'bing']
+    """
+    return itertools.chain.from_iterable(map(yield_lines, iterable))
+
+
+@yield_lines.register(str)
+def _(text: str) -> Iterator[str]:
+    return filter(_nonblank, map(str.strip, text.splitlines()))
+
+
+def split_sections(
+    s: str | Iterator[str],
+) -> Generator[tuple[str | None, list[str]], None, None]:
+    """Split a string or iterable thereof into (section, content) pairs
+    Each ``section`` is a stripped version of the section header ("[section]")
+    and each ``content`` is a list of stripped lines excluding blank lines and
+    comment-only lines.  If there are any such lines before the first section
+    header, they're returned in a first ``section`` of ``None``.
+    """
+    section = None
+    content: list[str] = []
+    for line in yield_lines(s):
+        if line.startswith("["):
+            if line.endswith("]"):
+                if section or content:
+                    yield section, content
+                section = line[1:-1].strip()
+                content = []
+            else:
+                raise ValueError("Invalid section heading", line)
+        else:
+            content.append(line)
+
+    # wrap up last segment
+    yield section, content
+
+
+def safe_extra(extra: str) -> str:
+    """Convert an arbitrary string to a standard 'extra' name
+    Any runs of non-alphanumeric characters are replaced with a single '_',
+    and the result is always lowercased.
+    """
+    return re.sub("[^A-Za-z0-9.-]+", "_", extra).lower()
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub("[^A-Za-z0-9.]+", "-", name)
+
+
+def requires_to_requires_dist(requirement: Requirement) -> str:
+    """Return the version specifier for a requirement in PEP 345/566 fashion."""
+    if requirement.url:
+        return " @ " + requirement.url
+
+    requires_dist: list[str] = []
+    for spec in requirement.specifier:
+        requires_dist.append(spec.operator + spec.version)
+
+    if requires_dist:
+        return " " + ",".join(sorted(requires_dist))
+    else:
+        return ""
+
+
+def convert_requirements(requirements: list[str]) -> Iterator[str]:
+    """Yield Requires-Dist: strings for parsed requirements strings."""
+    for req in requirements:
+        parsed_requirement = Requirement(req)
+        spec = requires_to_requires_dist(parsed_requirement)
+        extras = ",".join(sorted(safe_extra(e) for e in parsed_requirement.extras))
+        if extras:
+            extras = f"[{extras}]"
+
+        yield safe_name(parsed_requirement.name) + extras + spec
+
+
+def generate_requirements(
+    extras_require: dict[str | None, list[str]],
+) -> Iterator[tuple[str, str]]:
+    """
+    Convert requirements from a setup()-style dictionary to
+    ('Requires-Dist', 'requirement') and ('Provides-Extra', 'extra') tuples.
+
+    extras_require is a dictionary of {extra: [requirements]} as passed to setup(),
+    using the empty extra {'': [requirements]} to hold install_requires.
+    """
+    for extra, depends in extras_require.items():
+        condition = ""
+        extra = extra or ""
+        if ":" in extra:  # setuptools extra:condition syntax
+            extra, condition = extra.split(":", 1)
+
+        extra = safe_extra(extra)
+        if extra:
+            yield "Provides-Extra", extra
+            if condition:
+                condition = "(" + condition + ") and "
+            condition += f"extra == '{extra}'"
+
+        if condition:
+            condition = " ; " + condition
+
+        for new_req in convert_requirements(depends):
+            canonical_req = str(Requirement(new_req + condition))
+            yield "Requires-Dist", canonical_req
+
+
+def pkginfo_to_metadata(egg_info_path: str, pkginfo_path: str) -> Message:
+    """
+    Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format
+    """
+    with open(pkginfo_path, encoding="utf-8") as headers:
+        pkg_info = Parser().parse(headers)
+
+    pkg_info.replace_header("Metadata-Version", "2.1")
+    # Those will be regenerated from `requires.txt`.
+    del pkg_info["Provides-Extra"]
+    del pkg_info["Requires-Dist"]
+    requires_path = os.path.join(egg_info_path, "requires.txt")
+    if os.path.exists(requires_path):
+        with open(requires_path, encoding="utf-8") as requires_file:
+            requires = requires_file.read()
+
+        parsed_requirements = sorted(split_sections(requires), key=lambda x: x[0] or "")
+        for extra, reqs in parsed_requirements:
+            for key, value in generate_requirements({extra: reqs}):
+                if (key, value) not in pkg_info.items():
+                    pkg_info[key] = value
+
+    description = pkg_info["Description"]
+    if description:
+        description_lines = pkg_info["Description"].splitlines()
+        dedented_description = "\n".join(
+            # if the first line of long_description is blank,
+            # the first line here will be indented.
+            (
+                description_lines[0].lstrip(),
+                textwrap.dedent("\n".join(description_lines[1:])),
+                "\n",
+            )
+        )
+        pkg_info.set_payload(dedented_description)
+        del pkg_info["Description"]
+
+    return pkg_info
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/util.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..c928aa403b75e1ae392b4af5fe13147a095bbd30
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/util.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+import base64
+import logging
+
+log = logging.getLogger("wheel")
+
+
+def urlsafe_b64encode(data: bytes) -> bytes:
+    """urlsafe_b64encode without padding"""
+    return base64.urlsafe_b64encode(data).rstrip(b"=")
+
+
+def urlsafe_b64decode(data: bytes) -> bytes:
+    """urlsafe_b64decode without padding"""
+    pad = b"=" * (4 - (len(data) & 3))
+    return base64.urlsafe_b64decode(data + pad)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE
@@ -0,0 +1,3 @@
+This software is made available under the terms of *either* of the licenses
+found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
+under the terms of *both* these licenses.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE
new file mode 100644
index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.APACHE
@@ -0,0 +1,177 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD
new file mode 100644
index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/LICENSE.BSD
@@ -0,0 +1,23 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fb19b30bb53c18f38a9ef02dd7c4478670fb962
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_elffile.py
@@ -0,0 +1,108 @@
+"""
+ELF file parser.
+
+This provides a class ``ELFFile`` that parses an ELF executable in a similar
+interface to ``ZipFile``. Only the read interface is implemented.
+
+Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
+ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
+"""
+
+import enum
+import os
+import struct
+from typing import IO, Optional, Tuple
+
+
+class ELFInvalid(ValueError):
+    pass
+
+
+class EIClass(enum.IntEnum):
+    C32 = 1
+    C64 = 2
+
+
+class EIData(enum.IntEnum):
+    Lsb = 1
+    Msb = 2
+
+
+class EMachine(enum.IntEnum):
+    I386 = 3
+    S390 = 22
+    Arm = 40
+    X8664 = 62
+    AArc64 = 183
+
+
+class ELFFile:
+    """
+    Representation of an ELF executable.
+    """
+
+    def __init__(self, f: IO[bytes]) -> None:
+        self._f = f
+
+        try:
+            ident = self._read("16B")
+        except struct.error:
+            raise ELFInvalid("unable to parse identification")
+        magic = bytes(ident[:4])
+        if magic != b"\x7fELF":
+            raise ELFInvalid(f"invalid magic: {magic!r}")
+
+        self.capacity = ident[4]  # Format for program header (bitness).
+        self.encoding = ident[5]  # Data structure encoding (endianness).
+
+        try:
+            # e_fmt: Format for program header.
+            # p_fmt: Format for section header.
+            # p_idx: Indexes to find p_type, p_offset, and p_filesz.
+            e_fmt, self._p_fmt, self._p_idx = {
+                (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)),  # 32-bit MSB.
+                (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
+            }[(self.capacity, self.encoding)]
+        except KeyError:
+            raise ELFInvalid(
+                f"unrecognized capacity ({self.capacity}) or "
+                f"encoding ({self.encoding})"
+            )
+
+        try:
+            (
+                _,
+                self.machine,  # Architecture type.
+                _,
+                _,
+                self._e_phoff,  # Offset of program header.
+                _,
+                self.flags,  # Processor-specific flags.
+                _,
+                self._e_phentsize,  # Size of section.
+                self._e_phnum,  # Number of sections.
+            ) = self._read(e_fmt)
+        except struct.error as e:
+            raise ELFInvalid("unable to parse machine and section information") from e
+
+    def _read(self, fmt: str) -> Tuple[int, ...]:
+        return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
+
+    @property
+    def interpreter(self) -> Optional[str]:
+        """
+        The path recorded in the ``PT_INTERP`` section header.
+        """
+        for index in range(self._e_phnum):
+            self._f.seek(self._e_phoff + self._e_phentsize * index)
+            try:
+                data = self._read(self._p_fmt)
+            except struct.error:
+                continue
+            if data[self._p_idx[0]] != 3:  # Not PT_INTERP.
+                continue
+            self._f.seek(data[self._p_idx[1]])
+            return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
+        return None
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f5f4ab3e514d1846d3bd189bf081fdb1528ba08
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_manylinux.py
@@ -0,0 +1,260 @@
+import collections
+import contextlib
+import functools
+import os
+import re
+import sys
+import warnings
+from typing import Dict, Generator, Iterator, NamedTuple, Optional, Sequence, Tuple
+
+from ._elffile import EIClass, EIData, ELFFile, EMachine
+
+EF_ARM_ABIMASK = 0xFF000000
+EF_ARM_ABI_VER5 = 0x05000000
+EF_ARM_ABI_FLOAT_HARD = 0x00000400
+
+
+# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
+# as the type for `path` until then.
+@contextlib.contextmanager
+def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]:
+    try:
+        with open(path, "rb") as f:
+            yield ELFFile(f)
+    except (OSError, TypeError, ValueError):
+        yield None
+
+
+def _is_linux_armhf(executable: str) -> bool:
+    # hard-float ABI can be detected from the ELF header of the running
+    # process
+    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
+    with _parse_elf(executable) as f:
+        return (
+            f is not None
+            and f.capacity == EIClass.C32
+            and f.encoding == EIData.Lsb
+            and f.machine == EMachine.Arm
+            and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
+            and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
+        )
+
+
+def _is_linux_i686(executable: str) -> bool:
+    with _parse_elf(executable) as f:
+        return (
+            f is not None
+            and f.capacity == EIClass.C32
+            and f.encoding == EIData.Lsb
+            and f.machine == EMachine.I386
+        )
+
+
+def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
+    if "armv7l" in archs:
+        return _is_linux_armhf(executable)
+    if "i686" in archs:
+        return _is_linux_i686(executable)
+    allowed_archs = {
+        "x86_64",
+        "aarch64",
+        "ppc64",
+        "ppc64le",
+        "s390x",
+        "loongarch64",
+        "riscv64",
+    }
+    return any(arch in allowed_archs for arch in archs)
+
+
+# If glibc ever changes its major version, we need to know what the last
+# minor version was, so we can build the complete list of all versions.
+# For now, guess what the highest minor version might be, assume it will
+# be 50 for testing. Once this actually happens, update the dictionary
+# with the actual value.
+_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)
+
+
+class _GLibCVersion(NamedTuple):
+    major: int
+    minor: int
+
+
+def _glibc_version_string_confstr() -> Optional[str]:
+    """
+    Primary implementation of glibc_version_string using os.confstr.
+    """
+    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
+    # to be broken or missing. This strategy is used in the standard library
+    # platform module.
+    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
+    try:
+        # Should be a string like "glibc 2.17".
+        version_string: Optional[str] = os.confstr("CS_GNU_LIBC_VERSION")
+        assert version_string is not None
+        _, version = version_string.rsplit()
+    except (AssertionError, AttributeError, OSError, ValueError):
+        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
+        return None
+    return version
+
+
+def _glibc_version_string_ctypes() -> Optional[str]:
+    """
+    Fallback implementation of glibc_version_string using ctypes.
+    """
+    try:
+        import ctypes
+    except ImportError:
+        return None
+
+    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
+    # manpage says, "If filename is NULL, then the returned handle is for the
+    # main program". This way we can let the linker do the work to figure out
+    # which libc our process is actually using.
+    #
+    # We must also handle the special case where the executable is not a
+    # dynamically linked executable. This can occur when using musl libc,
+    # for example. In this situation, dlopen() will error, leading to an
+    # OSError. Interestingly, at least in the case of musl, there is no
+    # errno set on the OSError. The single string argument used to construct
+    # OSError comes from libc itself and is therefore not portable to
+    # hard code here. In any case, failure to call dlopen() means we
+    # can proceed, so we bail on our attempt.
+    try:
+        process_namespace = ctypes.CDLL(None)
+    except OSError:
+        return None
+
+    try:
+        gnu_get_libc_version = process_namespace.gnu_get_libc_version
+    except AttributeError:
+        # Symbol doesn't exist -> therefore, we are not linked to
+        # glibc.
+        return None
+
+    # Call gnu_get_libc_version, which returns a string like "2.5"
+    gnu_get_libc_version.restype = ctypes.c_char_p
+    version_str: str = gnu_get_libc_version()
+    # py2 / py3 compatibility:
+    if not isinstance(version_str, str):
+        version_str = version_str.decode("ascii")
+
+    return version_str
+
+
+def _glibc_version_string() -> Optional[str]:
+    """Returns glibc version string, or None if not using glibc."""
+    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
+
+
+def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
+    """Parse glibc version.
+
+    We use a regexp instead of str.split because we want to discard any
+    random junk that might come after the minor version -- this might happen
+    in patched/forked versions of glibc (e.g. Linaro's version of glibc
+    uses version strings like "2.20-2014.11"). See gh-3588.
+    """
+    m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str)
+    if not m:
+        warnings.warn(
+            f"Expected glibc version with 2 components major.minor,"
+            f" got: {version_str}",
+            RuntimeWarning,
+        )
+        return -1, -1
+    return int(m.group("major")), int(m.group("minor"))
+
+
+@functools.lru_cache
+def _get_glibc_version() -> Tuple[int, int]:
+    version_str = _glibc_version_string()
+    if version_str is None:
+        return (-1, -1)
+    return _parse_glibc_version(version_str)
+
+
+# From PEP 513, PEP 600
+def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
+    sys_glibc = _get_glibc_version()
+    if sys_glibc < version:
+        return False
+    # Check for presence of _manylinux module.
+    try:
+        import _manylinux
+    except ImportError:
+        return True
+    if hasattr(_manylinux, "manylinux_compatible"):
+        result = _manylinux.manylinux_compatible(version[0], version[1], arch)
+        if result is not None:
+            return bool(result)
+        return True
+    if version == _GLibCVersion(2, 5):
+        if hasattr(_manylinux, "manylinux1_compatible"):
+            return bool(_manylinux.manylinux1_compatible)
+    if version == _GLibCVersion(2, 12):
+        if hasattr(_manylinux, "manylinux2010_compatible"):
+            return bool(_manylinux.manylinux2010_compatible)
+    if version == _GLibCVersion(2, 17):
+        if hasattr(_manylinux, "manylinux2014_compatible"):
+            return bool(_manylinux.manylinux2014_compatible)
+    return True
+
+
+_LEGACY_MANYLINUX_MAP = {
+    # CentOS 7 w/ glibc 2.17 (PEP 599)
+    (2, 17): "manylinux2014",
+    # CentOS 6 w/ glibc 2.12 (PEP 571)
+    (2, 12): "manylinux2010",
+    # CentOS 5 w/ glibc 2.5 (PEP 513)
+    (2, 5): "manylinux1",
+}
+
+
+def platform_tags(archs: Sequence[str]) -> Iterator[str]:
+    """Generate manylinux tags compatible to the current platform.
+
+    :param archs: Sequence of compatible architectures.
+        The first one shall be the closest to the actual architecture and be the part of
+        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
+        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
+        be manylinux-compatible.
+
+    :returns: An iterator of compatible manylinux tags.
+    """
+    if not _have_compatible_abi(sys.executable, archs):
+        return
+    # Oldest glibc to be supported regardless of architecture is (2, 17).
+    too_old_glibc2 = _GLibCVersion(2, 16)
+    if set(archs) & {"x86_64", "i686"}:
+        # On x86/i686 also oldest glibc to be supported is (2, 5).
+        too_old_glibc2 = _GLibCVersion(2, 4)
+    current_glibc = _GLibCVersion(*_get_glibc_version())
+    glibc_max_list = [current_glibc]
+    # We can assume compatibility across glibc major versions.
+    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
+    #
+    # Build a list of maximum glibc versions so that we can
+    # output the canonical list of all glibc from current_glibc
+    # down to too_old_glibc2, including all intermediary versions.
+    for glibc_major in range(current_glibc.major - 1, 1, -1):
+        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
+        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
+    for arch in archs:
+        for glibc_max in glibc_max_list:
+            if glibc_max.major == too_old_glibc2.major:
+                min_minor = too_old_glibc2.minor
+            else:
+                # For other glibc major versions oldest supported is (x, 0).
+                min_minor = -1
+            for glibc_minor in range(glibc_max.minor, min_minor, -1):
+                glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
+                tag = "manylinux_{}_{}".format(*glibc_version)
+                if _is_compatible(arch, glibc_version):
+                    yield f"{tag}_{arch}"
+                # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
+                if glibc_version in _LEGACY_MANYLINUX_MAP:
+                    legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
+                    if _is_compatible(arch, glibc_version):
+                        yield f"{legacy_tag}_{arch}"
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb4251b5c1e82772b2b0ea539943da5141fd55ec
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_musllinux.py
@@ -0,0 +1,83 @@
+"""PEP 656 support.
+
+This module implements logic to detect if the currently running Python is
+linked against musl, and what musl version is used.
+"""
+
+import functools
+import re
+import subprocess
+import sys
+from typing import Iterator, NamedTuple, Optional, Sequence
+
+from ._elffile import ELFFile
+
+
+class _MuslVersion(NamedTuple):
+    major: int
+    minor: int
+
+
+def _parse_musl_version(output: str) -> Optional[_MuslVersion]:
+    lines = [n for n in (n.strip() for n in output.splitlines()) if n]
+    if len(lines) < 2 or lines[0][:4] != "musl":
+        return None
+    m = re.match(r"Version (\d+)\.(\d+)", lines[1])
+    if not m:
+        return None
+    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
+
+
+@functools.lru_cache
+def _get_musl_version(executable: str) -> Optional[_MuslVersion]:
+    """Detect currently-running musl runtime version.
+
+    This is done by checking the specified executable's dynamic linking
+    information, and invoking the loader to parse its output for a version
+    string. If the loader is musl, the output would be something like::
+
+        musl libc (x86_64)
+        Version 1.2.2
+        Dynamic Program Loader
+    """
+    try:
+        with open(executable, "rb") as f:
+            ld = ELFFile(f).interpreter
+    except (OSError, TypeError, ValueError):
+        return None
+    if ld is None or "musl" not in ld:
+        return None
+    proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True)
+    return _parse_musl_version(proc.stderr)
+
+
+def platform_tags(archs: Sequence[str]) -> Iterator[str]:
+    """Generate musllinux tags compatible to the current platform.
+
+    :param archs: Sequence of compatible architectures.
+        The first one shall be the closest to the actual architecture and be the part of
+        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
+        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
+        be musllinux-compatible.
+
+    :returns: An iterator of compatible musllinux tags.
+    """
+    sys_musl = _get_musl_version(sys.executable)
+    if sys_musl is None:  # Python not dynamically linked against musl.
+        return
+    for arch in archs:
+        for minor in range(sys_musl.minor, -1, -1):
+            yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
+
+
+if __name__ == "__main__":  # pragma: no cover
+    import sysconfig
+
+    plat = sysconfig.get_platform()
+    assert plat.startswith("linux-"), "not linux"
+
+    print("plat:", plat)
+    print("musl:", _get_musl_version(sys.executable))
+    print("tags:", end=" ")
+    for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
+        print(t, end="\n      ")
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..513686a2190f9911c08ca1ca263f37b799f44702
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_parser.py
@@ -0,0 +1,356 @@
+"""Handwritten parser of dependency specifiers.
+
+The docstring for each __parse_* function contains EBNF-inspired grammar representing
+the implementation.
+"""
+
+import ast
+from typing import Any, List, NamedTuple, Optional, Tuple, Union
+
+from ._tokenizer import DEFAULT_RULES, Tokenizer
+
+
+class Node:
+    def __init__(self, value: str) -> None:
+        self.value = value
+
+    def __str__(self) -> str:
+        return self.value
+
+    def __repr__(self) -> str:
+        return f"<{self.__class__.__name__}('{self}')>"
+
+    def serialize(self) -> str:
+        raise NotImplementedError
+
+
+class Variable(Node):
+    def serialize(self) -> str:
+        return str(self)
+
+
+class Value(Node):
+    def serialize(self) -> str:
+        return f'"{self}"'
+
+
+class Op(Node):
+    def serialize(self) -> str:
+        return str(self)
+
+
+MarkerVar = Union[Variable, Value]
+MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
+# MarkerAtom = Union[MarkerItem, List["MarkerAtom"]]
+# MarkerList = List[Union["MarkerList", MarkerAtom, str]]
+# mypy does not support recursive type definition
+# https://github.com/python/mypy/issues/731
+MarkerAtom = Any
+MarkerList = List[Any]
+
+
+class ParsedRequirement(NamedTuple):
+    name: str
+    url: str
+    extras: List[str]
+    specifier: str
+    marker: Optional[MarkerList]
+
+
+# --------------------------------------------------------------------------------------
+# Recursive descent parser for dependency specifier
+# --------------------------------------------------------------------------------------
+def parse_requirement(source: str) -> ParsedRequirement:
+    return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
+
+
+def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
+    """
+    requirement = WS? IDENTIFIER WS? extras WS? requirement_details
+    """
+    tokenizer.consume("WS")
+
+    name_token = tokenizer.expect(
+        "IDENTIFIER", expected="package name at the start of dependency specifier"
+    )
+    name = name_token.text
+    tokenizer.consume("WS")
+
+    extras = _parse_extras(tokenizer)
+    tokenizer.consume("WS")
+
+    url, specifier, marker = _parse_requirement_details(tokenizer)
+    tokenizer.expect("END", expected="end of dependency specifier")
+
+    return ParsedRequirement(name, url, extras, specifier, marker)
+
+
+def _parse_requirement_details(
+    tokenizer: Tokenizer,
+) -> Tuple[str, str, Optional[MarkerList]]:
+    """
+    requirement_details = AT URL (WS requirement_marker?)?
+                        | specifier WS? (requirement_marker)?
+    """
+
+    specifier = ""
+    url = ""
+    marker = None
+
+    if tokenizer.check("AT"):
+        tokenizer.read()
+        tokenizer.consume("WS")
+
+        url_start = tokenizer.position
+        url = tokenizer.expect("URL", expected="URL after @").text
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        tokenizer.expect("WS", expected="whitespace after URL")
+
+        # The input might end after whitespace.
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        marker = _parse_requirement_marker(
+            tokenizer, span_start=url_start, after="URL and whitespace"
+        )
+    else:
+        specifier_start = tokenizer.position
+        specifier = _parse_specifier(tokenizer)
+        tokenizer.consume("WS")
+
+        if tokenizer.check("END", peek=True):
+            return (url, specifier, marker)
+
+        marker = _parse_requirement_marker(
+            tokenizer,
+            span_start=specifier_start,
+            after=(
+                "version specifier"
+                if specifier
+                else "name and no valid version specifier"
+            ),
+        )
+
+    return (url, specifier, marker)
+
+
+def _parse_requirement_marker(
+    tokenizer: Tokenizer, *, span_start: int, after: str
+) -> MarkerList:
+    """
+    requirement_marker = SEMICOLON marker WS?
+    """
+
+    if not tokenizer.check("SEMICOLON"):
+        tokenizer.raise_syntax_error(
+            f"Expected end or semicolon (after {after})",
+            span_start=span_start,
+        )
+    tokenizer.read()
+
+    marker = _parse_marker(tokenizer)
+    tokenizer.consume("WS")
+
+    return marker
+
+
+def _parse_extras(tokenizer: Tokenizer) -> List[str]:
+    """
+    extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
+    """
+    if not tokenizer.check("LEFT_BRACKET", peek=True):
+        return []
+
+    with tokenizer.enclosing_tokens(
+        "LEFT_BRACKET",
+        "RIGHT_BRACKET",
+        around="extras",
+    ):
+        tokenizer.consume("WS")
+        extras = _parse_extras_list(tokenizer)
+        tokenizer.consume("WS")
+
+    return extras
+
+
+def _parse_extras_list(tokenizer: Tokenizer) -> List[str]:
+    """
+    extras_list = identifier (wsp* ',' wsp* identifier)*
+    """
+    extras: List[str] = []
+
+    if not tokenizer.check("IDENTIFIER"):
+        return extras
+
+    extras.append(tokenizer.read().text)
+
+    while True:
+        tokenizer.consume("WS")
+        if tokenizer.check("IDENTIFIER", peek=True):
+            tokenizer.raise_syntax_error("Expected comma between extra names")
+        elif not tokenizer.check("COMMA"):
+            break
+
+        tokenizer.read()
+        tokenizer.consume("WS")
+
+        extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
+        extras.append(extra_token.text)
+
+    return extras
+
+
+def _parse_specifier(tokenizer: Tokenizer) -> str:
+    """
+    specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
+              | WS? version_many WS?
+    """
+    with tokenizer.enclosing_tokens(
+        "LEFT_PARENTHESIS",
+        "RIGHT_PARENTHESIS",
+        around="version specifier",
+    ):
+        tokenizer.consume("WS")
+        parsed_specifiers = _parse_version_many(tokenizer)
+        tokenizer.consume("WS")
+
+    return parsed_specifiers
+
+
+def _parse_version_many(tokenizer: Tokenizer) -> str:
+    """
+    version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
+    """
+    parsed_specifiers = ""
+    while tokenizer.check("SPECIFIER"):
+        span_start = tokenizer.position
+        parsed_specifiers += tokenizer.read().text
+        if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
+            tokenizer.raise_syntax_error(
+                ".* suffix can only be used with `==` or `!=` operators",
+                span_start=span_start,
+                span_end=tokenizer.position + 1,
+            )
+        if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
+            tokenizer.raise_syntax_error(
+                "Local version label can only be used with `==` or `!=` operators",
+                span_start=span_start,
+                span_end=tokenizer.position,
+            )
+        tokenizer.consume("WS")
+        if not tokenizer.check("COMMA"):
+            break
+        parsed_specifiers += tokenizer.read().text
+        tokenizer.consume("WS")
+
+    return parsed_specifiers
+
+
+# --------------------------------------------------------------------------------------
+# Recursive descent parser for marker expression
+# --------------------------------------------------------------------------------------
+def parse_marker(source: str) -> MarkerList:
+    return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
+
+
+def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
+    retval = _parse_marker(tokenizer)
+    tokenizer.expect("END", expected="end of marker expression")
+    return retval
+
+
+def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
+    """
+    marker = marker_atom (BOOLOP marker_atom)+
+    """
+    expression = [_parse_marker_atom(tokenizer)]
+    while tokenizer.check("BOOLOP"):
+        token = tokenizer.read()
+        expr_right = _parse_marker_atom(tokenizer)
+        expression.extend((token.text, expr_right))
+    return expression
+
+
+def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
+    """
+    marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
+                | WS? marker_item WS?
+    """
+
+    tokenizer.consume("WS")
+    if tokenizer.check("LEFT_PARENTHESIS", peek=True):
+        with tokenizer.enclosing_tokens(
+            "LEFT_PARENTHESIS",
+            "RIGHT_PARENTHESIS",
+            around="marker expression",
+        ):
+            tokenizer.consume("WS")
+            marker: MarkerAtom = _parse_marker(tokenizer)
+            tokenizer.consume("WS")
+    else:
+        marker = _parse_marker_item(tokenizer)
+    tokenizer.consume("WS")
+    return marker
+
+
+def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
+    """
+    marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
+    """
+    tokenizer.consume("WS")
+    marker_var_left = _parse_marker_var(tokenizer)
+    tokenizer.consume("WS")
+    marker_op = _parse_marker_op(tokenizer)
+    tokenizer.consume("WS")
+    marker_var_right = _parse_marker_var(tokenizer)
+    tokenizer.consume("WS")
+    return (marker_var_left, marker_op, marker_var_right)
+
+
+def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:
+    """
+    marker_var = VARIABLE | QUOTED_STRING
+    """
+    if tokenizer.check("VARIABLE"):
+        return process_env_var(tokenizer.read().text.replace(".", "_"))
+    elif tokenizer.check("QUOTED_STRING"):
+        return process_python_str(tokenizer.read().text)
+    else:
+        tokenizer.raise_syntax_error(
+            message="Expected a marker variable or quoted string"
+        )
+
+
+def process_env_var(env_var: str) -> Variable:
+    if env_var in ("platform_python_implementation", "python_implementation"):
+        return Variable("platform_python_implementation")
+    else:
+        return Variable(env_var)
+
+
+def process_python_str(python_str: str) -> Value:
+    value = ast.literal_eval(python_str)
+    return Value(str(value))
+
+
+def _parse_marker_op(tokenizer: Tokenizer) -> Op:
+    """
+    marker_op = IN | NOT IN | OP
+    """
+    if tokenizer.check("IN"):
+        tokenizer.read()
+        return Op("in")
+    elif tokenizer.check("NOT"):
+        tokenizer.read()
+        tokenizer.expect("WS", expected="whitespace after 'not'")
+        tokenizer.expect("IN", expected="'in' after 'not'")
+        return Op("not in")
+    elif tokenizer.check("OP"):
+        return Op(tokenizer.read().text)
+    else:
+        return tokenizer.raise_syntax_error(
+            "Expected marker operator, one of "
+            "<=, <, !=, ==, >=, >, ~=, ===, in, not in"
+        )
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py
new file mode 100644
index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_structures.py
@@ -0,0 +1,61 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+
+class InfinityType:
+    def __repr__(self) -> str:
+        return "Infinity"
+
+    def __hash__(self) -> int:
+        return hash(repr(self))
+
+    def __lt__(self, other: object) -> bool:
+        return False
+
+    def __le__(self, other: object) -> bool:
+        return False
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, self.__class__)
+
+    def __gt__(self, other: object) -> bool:
+        return True
+
+    def __ge__(self, other: object) -> bool:
+        return True
+
+    def __neg__(self: object) -> "NegativeInfinityType":
+        return NegativeInfinity
+
+
+Infinity = InfinityType()
+
+
+class NegativeInfinityType:
+    def __repr__(self) -> str:
+        return "-Infinity"
+
+    def __hash__(self) -> int:
+        return hash(repr(self))
+
+    def __lt__(self, other: object) -> bool:
+        return True
+
+    def __le__(self, other: object) -> bool:
+        return True
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, self.__class__)
+
+    def __gt__(self, other: object) -> bool:
+        return False
+
+    def __ge__(self, other: object) -> bool:
+        return False
+
+    def __neg__(self: object) -> InfinityType:
+        return Infinity
+
+
+NegativeInfinity = NegativeInfinityType()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd0d648d49a7c1a62d25ce5c9107aa448a8a22d1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/_tokenizer.py
@@ -0,0 +1,192 @@
+import contextlib
+import re
+from dataclasses import dataclass
+from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union
+
+from .specifiers import Specifier
+
+
+@dataclass
+class Token:
+    name: str
+    text: str
+    position: int
+
+
+class ParserSyntaxError(Exception):
+    """The provided source text could not be parsed correctly."""
+
+    def __init__(
+        self,
+        message: str,
+        *,
+        source: str,
+        span: Tuple[int, int],
+    ) -> None:
+        self.span = span
+        self.message = message
+        self.source = source
+
+        super().__init__()
+
+    def __str__(self) -> str:
+        marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
+        return "\n    ".join([self.message, self.source, marker])
+
+
+DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = {
+    "LEFT_PARENTHESIS": r"\(",
+    "RIGHT_PARENTHESIS": r"\)",
+    "LEFT_BRACKET": r"\[",
+    "RIGHT_BRACKET": r"\]",
+    "SEMICOLON": r";",
+    "COMMA": r",",
+    "QUOTED_STRING": re.compile(
+        r"""
+            (
+                ('[^']*')
+                |
+                ("[^"]*")
+            )
+        """,
+        re.VERBOSE,
+    ),
+    "OP": r"(===|==|~=|!=|<=|>=|<|>)",
+    "BOOLOP": r"\b(or|and)\b",
+    "IN": r"\bin\b",
+    "NOT": r"\bnot\b",
+    "VARIABLE": re.compile(
+        r"""
+            \b(
+                python_version
+                |python_full_version
+                |os[._]name
+                |sys[._]platform
+                |platform_(release|system)
+                |platform[._](version|machine|python_implementation)
+                |python_implementation
+                |implementation_(name|version)
+                |extra
+            )\b
+        """,
+        re.VERBOSE,
+    ),
+    "SPECIFIER": re.compile(
+        Specifier._operator_regex_str + Specifier._version_regex_str,
+        re.VERBOSE | re.IGNORECASE,
+    ),
+    "AT": r"\@",
+    "URL": r"[^ \t]+",
+    "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b",
+    "VERSION_PREFIX_TRAIL": r"\.\*",
+    "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*",
+    "WS": r"[ \t]+",
+    "END": r"$",
+}
+
+
+class Tokenizer:
+    """Context-sensitive token parsing.
+
+    Provides methods to examine the input stream to check whether the next token
+    matches.
+    """
+
+    def __init__(
+        self,
+        source: str,
+        *,
+        rules: "Dict[str, Union[str, re.Pattern[str]]]",
+    ) -> None:
+        self.source = source
+        self.rules: Dict[str, re.Pattern[str]] = {
+            name: re.compile(pattern) for name, pattern in rules.items()
+        }
+        self.next_token: Optional[Token] = None
+        self.position = 0
+
+    def consume(self, name: str) -> None:
+        """Move beyond provided token name, if at current position."""
+        if self.check(name):
+            self.read()
+
+    def check(self, name: str, *, peek: bool = False) -> bool:
+        """Check whether the next token has the provided name.
+
+        By default, if the check succeeds, the token *must* be read before
+        another check. If `peek` is set to `True`, the token is not loaded and
+        would need to be checked again.
+        """
+        assert (
+            self.next_token is None
+        ), f"Cannot check for {name!r}, already have {self.next_token!r}"
+        assert name in self.rules, f"Unknown token name: {name!r}"
+
+        expression = self.rules[name]
+
+        match = expression.match(self.source, self.position)
+        if match is None:
+            return False
+        if not peek:
+            self.next_token = Token(name, match[0], self.position)
+        return True
+
+    def expect(self, name: str, *, expected: str) -> Token:
+        """Expect a certain token name next, failing with a syntax error otherwise.
+
+        The token is *not* read.
+        """
+        if not self.check(name):
+            raise self.raise_syntax_error(f"Expected {expected}")
+        return self.read()
+
+    def read(self) -> Token:
+        """Consume the next token and return it."""
+        token = self.next_token
+        assert token is not None
+
+        self.position += len(token.text)
+        self.next_token = None
+
+        return token
+
+    def raise_syntax_error(
+        self,
+        message: str,
+        *,
+        span_start: Optional[int] = None,
+        span_end: Optional[int] = None,
+    ) -> NoReturn:
+        """Raise ParserSyntaxError at the given position."""
+        span = (
+            self.position if span_start is None else span_start,
+            self.position if span_end is None else span_end,
+        )
+        raise ParserSyntaxError(
+            message,
+            source=self.source,
+            span=span,
+        )
+
+    @contextlib.contextmanager
+    def enclosing_tokens(
+        self, open_token: str, close_token: str, *, around: str
+    ) -> Iterator[None]:
+        if self.check(open_token):
+            open_position = self.position
+            self.read()
+        else:
+            open_position = None
+
+        yield
+
+        if open_position is None:
+            return
+
+        if not self.check(close_token):
+            self.raise_syntax_error(
+                f"Expected matching {close_token} for {open_token}, after {around}",
+                span_start=open_position,
+            )
+
+        self.read()
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c96d22a5a445e7353cd2454dec4255d3785c07b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/markers.py
@@ -0,0 +1,253 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import operator
+import os
+import platform
+import sys
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from ._parser import (
+    MarkerAtom,
+    MarkerList,
+    Op,
+    Value,
+    Variable,
+)
+from ._parser import (
+    parse_marker as _parse_marker,
+)
+from ._tokenizer import ParserSyntaxError
+from .specifiers import InvalidSpecifier, Specifier
+from .utils import canonicalize_name
+
+__all__ = [
+    "InvalidMarker",
+    "UndefinedComparison",
+    "UndefinedEnvironmentName",
+    "Marker",
+    "default_environment",
+]
+
+Operator = Callable[[str, str], bool]
+
+
+class InvalidMarker(ValueError):
+    """
+    An invalid marker was found, users should refer to PEP 508.
+    """
+
+
+class UndefinedComparison(ValueError):
+    """
+    An invalid operation was attempted on a value that doesn't support it.
+    """
+
+
+class UndefinedEnvironmentName(ValueError):
+    """
+    A name was attempted to be used that does not exist inside of the
+    environment.
+    """
+
+
+def _normalize_extra_values(results: Any) -> Any:
+    """
+    Normalize extra values.
+    """
+    if isinstance(results[0], tuple):
+        lhs, op, rhs = results[0]
+        if isinstance(lhs, Variable) and lhs.value == "extra":
+            normalized_extra = canonicalize_name(rhs.value)
+            rhs = Value(normalized_extra)
+        elif isinstance(rhs, Variable) and rhs.value == "extra":
+            normalized_extra = canonicalize_name(lhs.value)
+            lhs = Value(normalized_extra)
+        results[0] = lhs, op, rhs
+    return results
+
+
+def _format_marker(
+    marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True
+) -> str:
+    assert isinstance(marker, (list, tuple, str))
+
+    # Sometimes we have a structure like [[...]] which is a single item list
+    # where the single item is itself it's own list. In that case we want skip
+    # the rest of this function so that we don't get extraneous () on the
+    # outside.
+    if (
+        isinstance(marker, list)
+        and len(marker) == 1
+        and isinstance(marker[0], (list, tuple))
+    ):
+        return _format_marker(marker[0])
+
+    if isinstance(marker, list):
+        inner = (_format_marker(m, first=False) for m in marker)
+        if first:
+            return " ".join(inner)
+        else:
+            return "(" + " ".join(inner) + ")"
+    elif isinstance(marker, tuple):
+        return " ".join([m.serialize() for m in marker])
+    else:
+        return marker
+
+
+_operators: Dict[str, Operator] = {
+    "in": lambda lhs, rhs: lhs in rhs,
+    "not in": lambda lhs, rhs: lhs not in rhs,
+    "<": operator.lt,
+    "<=": operator.le,
+    "==": operator.eq,
+    "!=": operator.ne,
+    ">=": operator.ge,
+    ">": operator.gt,
+}
+
+
+def _eval_op(lhs: str, op: Op, rhs: str) -> bool:
+    try:
+        spec = Specifier("".join([op.serialize(), rhs]))
+    except InvalidSpecifier:
+        pass
+    else:
+        return spec.contains(lhs, prereleases=True)
+
+    oper: Optional[Operator] = _operators.get(op.serialize())
+    if oper is None:
+        raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
+
+    return oper(lhs, rhs)
+
+
+def _normalize(*values: str, key: str) -> Tuple[str, ...]:
+    # PEP 685 – Comparison of extra names for optional distribution dependencies
+    # https://peps.python.org/pep-0685/
+    # > When comparing extra names, tools MUST normalize the names being
+    # > compared using the semantics outlined in PEP 503 for names
+    if key == "extra":
+        return tuple(canonicalize_name(v) for v in values)
+
+    # other environment markers don't have such standards
+    return values
+
+
+def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool:
+    groups: List[List[bool]] = [[]]
+
+    for marker in markers:
+        assert isinstance(marker, (list, tuple, str))
+
+        if isinstance(marker, list):
+            groups[-1].append(_evaluate_markers(marker, environment))
+        elif isinstance(marker, tuple):
+            lhs, op, rhs = marker
+
+            if isinstance(lhs, Variable):
+                environment_key = lhs.value
+                lhs_value = environment[environment_key]
+                rhs_value = rhs.value
+            else:
+                lhs_value = lhs.value
+                environment_key = rhs.value
+                rhs_value = environment[environment_key]
+
+            lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
+            groups[-1].append(_eval_op(lhs_value, op, rhs_value))
+        else:
+            assert marker in ["and", "or"]
+            if marker == "or":
+                groups.append([])
+
+    return any(all(item) for item in groups)
+
+
+def format_full_version(info: "sys._version_info") -> str:
+    version = "{0.major}.{0.minor}.{0.micro}".format(info)
+    kind = info.releaselevel
+    if kind != "final":
+        version += kind[0] + str(info.serial)
+    return version
+
+
+def default_environment() -> Dict[str, str]:
+    iver = format_full_version(sys.implementation.version)
+    implementation_name = sys.implementation.name
+    return {
+        "implementation_name": implementation_name,
+        "implementation_version": iver,
+        "os_name": os.name,
+        "platform_machine": platform.machine(),
+        "platform_release": platform.release(),
+        "platform_system": platform.system(),
+        "platform_version": platform.version(),
+        "python_full_version": platform.python_version(),
+        "platform_python_implementation": platform.python_implementation(),
+        "python_version": ".".join(platform.python_version_tuple()[:2]),
+        "sys_platform": sys.platform,
+    }
+
+
+class Marker:
+    def __init__(self, marker: str) -> None:
+        # Note: We create a Marker object without calling this constructor in
+        #       packaging.requirements.Requirement. If any additional logic is
+        #       added here, make sure to mirror/adapt Requirement.
+        try:
+            self._markers = _normalize_extra_values(_parse_marker(marker))
+            # The attribute `_markers` can be described in terms of a recursive type:
+            # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
+            #
+            # For example, the following expression:
+            # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
+            #
+            # is parsed into:
+            # [
+            #     (, ')>, ),
+            #     'and',
+            #     [
+            #         (, , ),
+            #         'or',
+            #         (, , )
+            #     ]
+            # ]
+        except ParserSyntaxError as e:
+            raise InvalidMarker(str(e)) from e
+
+    def __str__(self) -> str:
+        return _format_marker(self._markers)
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __hash__(self) -> int:
+        return hash((self.__class__.__name__, str(self)))
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, Marker):
+            return NotImplemented
+
+        return str(self) == str(other)
+
+    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:
+        """Evaluate a marker.
+
+        Return the boolean from evaluating the given marker against the
+        environment. environment is an optional argument to override all or
+        part of the determined environment.
+
+        The environment is determined from the current Python process.
+        """
+        current_environment = default_environment()
+        current_environment["extra"] = ""
+        if environment is not None:
+            current_environment.update(environment)
+            # The API used to allow setting extra to None. We need to handle this
+            # case for backwards compatibility.
+            if current_environment["extra"] is None:
+                current_environment["extra"] = ""
+
+        return _evaluate_markers(self._markers, current_environment)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdc43a7e98d87dba0c2069bfb4554f71d228cad4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/requirements.py
@@ -0,0 +1,90 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+from typing import Any, Iterator, Optional, Set
+
+from ._parser import parse_requirement as _parse_requirement
+from ._tokenizer import ParserSyntaxError
+from .markers import Marker, _normalize_extra_values
+from .specifiers import SpecifierSet
+from .utils import canonicalize_name
+
+
+class InvalidRequirement(ValueError):
+    """
+    An invalid requirement was found, users should refer to PEP 508.
+    """
+
+
+class Requirement:
+    """Parse a requirement.
+
+    Parse a given requirement string into its parts, such as name, specifier,
+    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
+    string.
+    """
+
+    # TODO: Can we test whether something is contained within a requirement?
+    #       If so how do we do that? Do we need to test against the _name_ of
+    #       the thing as well as the version? What about the markers?
+    # TODO: Can we normalize the name and extra name?
+
+    def __init__(self, requirement_string: str) -> None:
+        try:
+            parsed = _parse_requirement(requirement_string)
+        except ParserSyntaxError as e:
+            raise InvalidRequirement(str(e)) from e
+
+        self.name: str = parsed.name
+        self.url: Optional[str] = parsed.url or None
+        self.extras: Set[str] = set(parsed.extras or [])
+        self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
+        self.marker: Optional[Marker] = None
+        if parsed.marker is not None:
+            self.marker = Marker.__new__(Marker)
+            self.marker._markers = _normalize_extra_values(parsed.marker)
+
+    def _iter_parts(self, name: str) -> Iterator[str]:
+        yield name
+
+        if self.extras:
+            formatted_extras = ",".join(sorted(self.extras))
+            yield f"[{formatted_extras}]"
+
+        if self.specifier:
+            yield str(self.specifier)
+
+        if self.url:
+            yield f"@ {self.url}"
+            if self.marker:
+                yield " "
+
+        if self.marker:
+            yield f"; {self.marker}"
+
+    def __str__(self) -> str:
+        return "".join(self._iter_parts(self.name))
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __hash__(self) -> int:
+        return hash(
+            (
+                self.__class__.__name__,
+                *self._iter_parts(canonicalize_name(self.name)),
+            )
+        )
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, Requirement):
+            return NotImplemented
+
+        return (
+            canonicalize_name(self.name) == canonicalize_name(other.name)
+            and self.extras == other.extras
+            and self.specifier == other.specifier
+            and self.url == other.url
+            and self.marker == other.marker
+        )
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d4066ae2770a3112f37d0e30d9a98fe59c4861f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/specifiers.py
@@ -0,0 +1,1011 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+"""
+.. testsetup::
+
+    from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
+    from packaging.version import Version
+"""
+
+import abc
+import itertools
+import re
+from typing import Callable, Iterable, Iterator, List, Optional, Tuple, TypeVar, Union
+
+from .utils import canonicalize_version
+from .version import Version
+
+UnparsedVersion = Union[Version, str]
+UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
+CallableOperator = Callable[[Version, str], bool]
+
+
+def _coerce_version(version: UnparsedVersion) -> Version:
+    if not isinstance(version, Version):
+        version = Version(version)
+    return version
+
+
+class InvalidSpecifier(ValueError):
+    """
+    Raised when attempting to create a :class:`Specifier` with a specifier
+    string that is invalid.
+
+    >>> Specifier("lolwat")
+    Traceback (most recent call last):
+        ...
+    packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
+    """
+
+
+class BaseSpecifier(metaclass=abc.ABCMeta):
+    @abc.abstractmethod
+    def __str__(self) -> str:
+        """
+        Returns the str representation of this Specifier-like object. This
+        should be representative of the Specifier itself.
+        """
+
+    @abc.abstractmethod
+    def __hash__(self) -> int:
+        """
+        Returns a hash value for this Specifier-like object.
+        """
+
+    @abc.abstractmethod
+    def __eq__(self, other: object) -> bool:
+        """
+        Returns a boolean representing whether or not the two Specifier-like
+        objects are equal.
+
+        :param other: The other object to check against.
+        """
+
+    @property
+    @abc.abstractmethod
+    def prereleases(self) -> Optional[bool]:
+        """Whether or not pre-releases as a whole are allowed.
+
+        This can be set to either ``True`` or ``False`` to explicitly enable or disable
+        prereleases or it can be set to ``None`` (the default) to use default semantics.
+        """
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        """Setter for :attr:`prereleases`.
+
+        :param value: The value to set.
+        """
+
+    @abc.abstractmethod
+    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
+        """
+        Determines if the given item is contained within this specifier.
+        """
+
+    @abc.abstractmethod
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """
+        Takes an iterable of items and filters them so that only items which
+        are contained within this specifier are allowed in it.
+        """
+
+
+class Specifier(BaseSpecifier):
+    """This class abstracts handling of version specifiers.
+
+    .. tip::
+
+        It is generally not required to instantiate this manually. You should instead
+        prefer to work with :class:`SpecifierSet` instead, which can parse
+        comma-separated version specifiers (which is what package metadata contains).
+    """
+
+    _operator_regex_str = r"""
+        (?P(~=|==|!=|<=|>=|<|>|===))
+        """
+    _version_regex_str = r"""
+        (?P
+            (?:
+                # The identity operators allow for an escape hatch that will
+                # do an exact string match of the version you wish to install.
+                # This will not be parsed by PEP 440 and we cannot determine
+                # any semantic meaning from it. This operator is discouraged
+                # but included entirely as an escape hatch.
+                (?<====)  # Only match for the identity operator
+                \s*
+                [^\s;)]*  # The arbitrary version can be just about anything,
+                          # we match everything except for whitespace, a
+                          # semi-colon for marker support, and a closing paren
+                          # since versions can be enclosed in them.
+            )
+            |
+            (?:
+                # The (non)equality operators allow for wild card and local
+                # versions to be specified so we have to define these two
+                # operators separately to enable that.
+                (?<===|!=)            # Only match for equals and not equals
+
+                \s*
+                v?
+                (?:[0-9]+!)?          # epoch
+                [0-9]+(?:\.[0-9]+)*   # release
+
+                # You cannot use a wild card and a pre-release, post-release, a dev or
+                # local version together so group them with a | and make them optional.
+                (?:
+                    \.\*  # Wild card syntax of .*
+                    |
+                    (?:                                  # pre release
+                        [-_\.]?
+                        (alpha|beta|preview|pre|a|b|c|rc)
+                        [-_\.]?
+                        [0-9]*
+                    )?
+                    (?:                                  # post release
+                        (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
+                    )?
+                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
+                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
+                )?
+            )
+            |
+            (?:
+                # The compatible operator requires at least two digits in the
+                # release segment.
+                (?<=~=)               # Only match for the compatible operator
+
+                \s*
+                v?
+                (?:[0-9]+!)?          # epoch
+                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
+                (?:                   # pre release
+                    [-_\.]?
+                    (alpha|beta|preview|pre|a|b|c|rc)
+                    [-_\.]?
+                    [0-9]*
+                )?
+                (?:                                   # post release
+                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
+                )?
+                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
+            )
+            |
+            (?:
+                # All other operators only allow a sub set of what the
+                # (non)equality operators do. Specifically they do not allow
+                # local versions to be specified nor do they allow the prefix
+                # matching wild cards.
+                (?=": "greater_than_equal",
+        "<": "less_than",
+        ">": "greater_than",
+        "===": "arbitrary",
+    }
+
+    def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
+        """Initialize a Specifier instance.
+
+        :param spec:
+            The string representation of a specifier which will be parsed and
+            normalized before use.
+        :param prereleases:
+            This tells the specifier if it should accept prerelease versions if
+            applicable or not. The default of ``None`` will autodetect it from the
+            given specifiers.
+        :raises InvalidSpecifier:
+            If the given specifier is invalid (i.e. bad syntax).
+        """
+        match = self._regex.search(spec)
+        if not match:
+            raise InvalidSpecifier(f"Invalid specifier: '{spec}'")
+
+        self._spec: Tuple[str, str] = (
+            match.group("operator").strip(),
+            match.group("version").strip(),
+        )
+
+        # Store whether or not this Specifier should accept prereleases
+        self._prereleases = prereleases
+
+    # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515
+    @property  # type: ignore[override]
+    def prereleases(self) -> bool:
+        # If there is an explicit prereleases set for this, then we'll just
+        # blindly use that.
+        if self._prereleases is not None:
+            return self._prereleases
+
+        # Look at all of our specifiers and determine if they are inclusive
+        # operators, and if they are if they are including an explicit
+        # prerelease.
+        operator, version = self._spec
+        if operator in ["==", ">=", "<=", "~=", "==="]:
+            # The == specifier can include a trailing .*, if it does we
+            # want to remove before parsing.
+            if operator == "==" and version.endswith(".*"):
+                version = version[:-2]
+
+            # Parse the version, and if it is a pre-release than this
+            # specifier allows pre-releases.
+            if Version(version).is_prerelease:
+                return True
+
+        return False
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        self._prereleases = value
+
+    @property
+    def operator(self) -> str:
+        """The operator of this specifier.
+
+        >>> Specifier("==1.2.3").operator
+        '=='
+        """
+        return self._spec[0]
+
+    @property
+    def version(self) -> str:
+        """The version of this specifier.
+
+        >>> Specifier("==1.2.3").version
+        '1.2.3'
+        """
+        return self._spec[1]
+
+    def __repr__(self) -> str:
+        """A representation of the Specifier that shows all internal state.
+
+        >>> Specifier('>=1.0.0')
+        =1.0.0')>
+        >>> Specifier('>=1.0.0', prereleases=False)
+        =1.0.0', prereleases=False)>
+        >>> Specifier('>=1.0.0', prereleases=True)
+        =1.0.0', prereleases=True)>
+        """
+        pre = (
+            f", prereleases={self.prereleases!r}"
+            if self._prereleases is not None
+            else ""
+        )
+
+        return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
+
+    def __str__(self) -> str:
+        """A string representation of the Specifier that can be round-tripped.
+
+        >>> str(Specifier('>=1.0.0'))
+        '>=1.0.0'
+        >>> str(Specifier('>=1.0.0', prereleases=False))
+        '>=1.0.0'
+        """
+        return "{}{}".format(*self._spec)
+
+    @property
+    def _canonical_spec(self) -> Tuple[str, str]:
+        canonical_version = canonicalize_version(
+            self._spec[1],
+            strip_trailing_zero=(self._spec[0] != "~="),
+        )
+        return self._spec[0], canonical_version
+
+    def __hash__(self) -> int:
+        return hash(self._canonical_spec)
+
+    def __eq__(self, other: object) -> bool:
+        """Whether or not the two Specifier-like objects are equal.
+
+        :param other: The other object to check against.
+
+        The value of :attr:`prereleases` is ignored.
+
+        >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
+        True
+        >>> (Specifier("==1.2.3", prereleases=False) ==
+        ...  Specifier("==1.2.3", prereleases=True))
+        True
+        >>> Specifier("==1.2.3") == "==1.2.3"
+        True
+        >>> Specifier("==1.2.3") == Specifier("==1.2.4")
+        False
+        >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
+        False
+        """
+        if isinstance(other, str):
+            try:
+                other = self.__class__(str(other))
+            except InvalidSpecifier:
+                return NotImplemented
+        elif not isinstance(other, self.__class__):
+            return NotImplemented
+
+        return self._canonical_spec == other._canonical_spec
+
+    def _get_operator(self, op: str) -> CallableOperator:
+        operator_callable: CallableOperator = getattr(
+            self, f"_compare_{self._operators[op]}"
+        )
+        return operator_callable
+
+    def _compare_compatible(self, prospective: Version, spec: str) -> bool:
+        # Compatible releases have an equivalent combination of >= and ==. That
+        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
+        # implement this in terms of the other specifiers instead of
+        # implementing it ourselves. The only thing we need to do is construct
+        # the other specifiers.
+
+        # We want everything but the last item in the version, but we want to
+        # ignore suffix segments.
+        prefix = _version_join(
+            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
+        )
+
+        # Add the prefix notation to the end of our string
+        prefix += ".*"
+
+        return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
+            prospective, prefix
+        )
+
+    def _compare_equal(self, prospective: Version, spec: str) -> bool:
+        # We need special logic to handle prefix matching
+        if spec.endswith(".*"):
+            # In the case of prefix matching we want to ignore local segment.
+            normalized_prospective = canonicalize_version(
+                prospective.public, strip_trailing_zero=False
+            )
+            # Get the normalized version string ignoring the trailing .*
+            normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
+            # Split the spec out by bangs and dots, and pretend that there is
+            # an implicit dot in between a release segment and a pre-release segment.
+            split_spec = _version_split(normalized_spec)
+
+            # Split the prospective version out by bangs and dots, and pretend
+            # that there is an implicit dot in between a release segment and
+            # a pre-release segment.
+            split_prospective = _version_split(normalized_prospective)
+
+            # 0-pad the prospective version before shortening it to get the correct
+            # shortened version.
+            padded_prospective, _ = _pad_version(split_prospective, split_spec)
+
+            # Shorten the prospective version to be the same length as the spec
+            # so that we can determine if the specifier is a prefix of the
+            # prospective version or not.
+            shortened_prospective = padded_prospective[: len(split_spec)]
+
+            return shortened_prospective == split_spec
+        else:
+            # Convert our spec string into a Version
+            spec_version = Version(spec)
+
+            # If the specifier does not have a local segment, then we want to
+            # act as if the prospective version also does not have a local
+            # segment.
+            if not spec_version.local:
+                prospective = Version(prospective.public)
+
+            return prospective == spec_version
+
+    def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
+        return not self._compare_equal(prospective, spec)
+
+    def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
+        # NB: Local version identifiers are NOT permitted in the version
+        # specifier, so local version labels can be universally removed from
+        # the prospective version.
+        return Version(prospective.public) <= Version(spec)
+
+    def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
+        # NB: Local version identifiers are NOT permitted in the version
+        # specifier, so local version labels can be universally removed from
+        # the prospective version.
+        return Version(prospective.public) >= Version(spec)
+
+    def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
+        # Convert our spec to a Version instance, since we'll want to work with
+        # it as a version.
+        spec = Version(spec_str)
+
+        # Check to see if the prospective version is less than the spec
+        # version. If it's not we can short circuit and just return False now
+        # instead of doing extra unneeded work.
+        if not prospective < spec:
+            return False
+
+        # This special case is here so that, unless the specifier itself
+        # includes is a pre-release version, that we do not accept pre-release
+        # versions for the version mentioned in the specifier (e.g. <3.1 should
+        # not match 3.1.dev0, but should match 3.0.dev0).
+        if not spec.is_prerelease and prospective.is_prerelease:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # If we've gotten to here, it means that prospective version is both
+        # less than the spec version *and* it's not a pre-release of the same
+        # version in the spec.
+        return True
+
+    def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
+        # Convert our spec to a Version instance, since we'll want to work with
+        # it as a version.
+        spec = Version(spec_str)
+
+        # Check to see if the prospective version is greater than the spec
+        # version. If it's not we can short circuit and just return False now
+        # instead of doing extra unneeded work.
+        if not prospective > spec:
+            return False
+
+        # This special case is here so that, unless the specifier itself
+        # includes is a post-release version, that we do not accept
+        # post-release versions for the version mentioned in the specifier
+        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
+        if not spec.is_postrelease and prospective.is_postrelease:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # Ensure that we do not allow a local version of the version mentioned
+        # in the specifier, which is technically greater than, to match.
+        if prospective.local is not None:
+            if Version(prospective.base_version) == Version(spec.base_version):
+                return False
+
+        # If we've gotten to here, it means that prospective version is both
+        # greater than the spec version *and* it's not a pre-release of the
+        # same version in the spec.
+        return True
+
+    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
+        return str(prospective).lower() == str(spec).lower()
+
+    def __contains__(self, item: Union[str, Version]) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item: The item to check for.
+
+        This is used for the ``in`` operator and behaves the same as
+        :meth:`contains` with no ``prereleases`` argument passed.
+
+        >>> "1.2.3" in Specifier(">=1.2.3")
+        True
+        >>> Version("1.2.3") in Specifier(">=1.2.3")
+        True
+        >>> "1.0.0" in Specifier(">=1.2.3")
+        False
+        >>> "1.3.0a1" in Specifier(">=1.2.3")
+        False
+        >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
+        True
+        """
+        return self.contains(item)
+
+    def contains(
+        self, item: UnparsedVersion, prereleases: Optional[bool] = None
+    ) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item:
+            The item to check for, which can be a version string or a
+            :class:`Version` instance.
+        :param prereleases:
+            Whether or not to match prereleases with this Specifier. If set to
+            ``None`` (the default), it uses :attr:`prereleases` to determine
+            whether or not prereleases are allowed.
+
+        >>> Specifier(">=1.2.3").contains("1.2.3")
+        True
+        >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
+        True
+        >>> Specifier(">=1.2.3").contains("1.0.0")
+        False
+        >>> Specifier(">=1.2.3").contains("1.3.0a1")
+        False
+        >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1")
+        True
+        >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True)
+        True
+        """
+
+        # Determine if prereleases are to be allowed or not.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # Normalize item to a Version, this allows us to have a shortcut for
+        # "2.0" in Specifier(">=2")
+        normalized_item = _coerce_version(item)
+
+        # Determine if we should be supporting prereleases in this specifier
+        # or not, if we do not support prereleases than we can short circuit
+        # logic if this version is a prereleases.
+        if normalized_item.is_prerelease and not prereleases:
+            return False
+
+        # Actually do the comparison to determine if this item is contained
+        # within this Specifier or not.
+        operator_callable: CallableOperator = self._get_operator(self.operator)
+        return operator_callable(normalized_item, self.version)
+
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """Filter items in the given iterable, that match the specifier.
+
+        :param iterable:
+            An iterable that can contain version strings and :class:`Version` instances.
+            The items in the iterable will be filtered according to the specifier.
+        :param prereleases:
+            Whether or not to allow prereleases in the returned iterator. If set to
+            ``None`` (the default), it will be intelligently decide whether to allow
+            prereleases or not (based on the :attr:`prereleases` attribute, and
+            whether the only versions matching are prereleases).
+
+        This method is smarter than just ``filter(Specifier().contains, [...])``
+        because it implements the rule from :pep:`440` that a prerelease item
+        SHOULD be accepted if no other versions match the given specifier.
+
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
+        ['1.2.3', '1.3', ]
+        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
+        ['1.5a1']
+        >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+        """
+
+        yielded = False
+        found_prereleases = []
+
+        kw = {"prereleases": prereleases if prereleases is not None else True}
+
+        # Attempt to iterate over all the values in the iterable and if any of
+        # them match, yield them.
+        for version in iterable:
+            parsed_version = _coerce_version(version)
+
+            if self.contains(parsed_version, **kw):
+                # If our version is a prerelease, and we were not set to allow
+                # prereleases, then we'll store it for later in case nothing
+                # else matches this specifier.
+                if parsed_version.is_prerelease and not (
+                    prereleases or self.prereleases
+                ):
+                    found_prereleases.append(version)
+                # Either this is not a prerelease, or we should have been
+                # accepting prereleases from the beginning.
+                else:
+                    yielded = True
+                    yield version
+
+        # Now that we've iterated over everything, determine if we've yielded
+        # any values, and if we have not and we have any prereleases stored up
+        # then we will go ahead and yield the prereleases.
+        if not yielded and found_prereleases:
+            for version in found_prereleases:
+                yield version
+
+
+_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
+
+
+def _version_split(version: str) -> List[str]:
+    """Split version into components.
+
+    The split components are intended for version comparison. The logic does
+    not attempt to retain the original version string, so joining the
+    components back with :func:`_version_join` may not produce the original
+    version string.
+    """
+    result: List[str] = []
+
+    epoch, _, rest = version.rpartition("!")
+    result.append(epoch or "0")
+
+    for item in rest.split("."):
+        match = _prefix_regex.search(item)
+        if match:
+            result.extend(match.groups())
+        else:
+            result.append(item)
+    return result
+
+
+def _version_join(components: List[str]) -> str:
+    """Join split version components into a version string.
+
+    This function assumes the input came from :func:`_version_split`, where the
+    first component must be the epoch (either empty or numeric), and all other
+    components numeric.
+    """
+    epoch, *rest = components
+    return f"{epoch}!{'.'.join(rest)}"
+
+
+def _is_not_suffix(segment: str) -> bool:
+    return not any(
+        segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
+    )
+
+
+def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
+    left_split, right_split = [], []
+
+    # Get the release segment of our versions
+    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
+    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
+
+    # Get the rest of our versions
+    left_split.append(left[len(left_split[0]) :])
+    right_split.append(right[len(right_split[0]) :])
+
+    # Insert our padding
+    left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
+    right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
+
+    return (
+        list(itertools.chain.from_iterable(left_split)),
+        list(itertools.chain.from_iterable(right_split)),
+    )
+
+
+class SpecifierSet(BaseSpecifier):
+    """This class abstracts handling of a set of version specifiers.
+
+    It can be passed a single specifier (``>=3.0``), a comma-separated list of
+    specifiers (``>=3.0,!=3.1``), or no specifier at all.
+    """
+
+    def __init__(
+        self, specifiers: str = "", prereleases: Optional[bool] = None
+    ) -> None:
+        """Initialize a SpecifierSet instance.
+
+        :param specifiers:
+            The string representation of a specifier or a comma-separated list of
+            specifiers which will be parsed and normalized before use.
+        :param prereleases:
+            This tells the SpecifierSet if it should accept prerelease versions if
+            applicable or not. The default of ``None`` will autodetect it from the
+            given specifiers.
+
+        :raises InvalidSpecifier:
+            If the given ``specifiers`` are not parseable than this exception will be
+            raised.
+        """
+
+        # Split on `,` to break each individual specifier into it's own item, and
+        # strip each item to remove leading/trailing whitespace.
+        split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
+
+        # Make each individual specifier a Specifier and save in a frozen set for later.
+        self._specs = frozenset(map(Specifier, split_specifiers))
+
+        # Store our prereleases value so we can use it later to determine if
+        # we accept prereleases or not.
+        self._prereleases = prereleases
+
+    @property
+    def prereleases(self) -> Optional[bool]:
+        # If we have been given an explicit prerelease modifier, then we'll
+        # pass that through here.
+        if self._prereleases is not None:
+            return self._prereleases
+
+        # If we don't have any specifiers, and we don't have a forced value,
+        # then we'll just return None since we don't know if this should have
+        # pre-releases or not.
+        if not self._specs:
+            return None
+
+        # Otherwise we'll see if any of the given specifiers accept
+        # prereleases, if any of them do we'll return True, otherwise False.
+        return any(s.prereleases for s in self._specs)
+
+    @prereleases.setter
+    def prereleases(self, value: bool) -> None:
+        self._prereleases = value
+
+    def __repr__(self) -> str:
+        """A representation of the specifier set that shows all internal state.
+
+        Note that the ordering of the individual specifiers within the set may not
+        match the input string.
+
+        >>> SpecifierSet('>=1.0.0,!=2.0.0')
+        =1.0.0')>
+        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
+        =1.0.0', prereleases=False)>
+        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
+        =1.0.0', prereleases=True)>
+        """
+        pre = (
+            f", prereleases={self.prereleases!r}"
+            if self._prereleases is not None
+            else ""
+        )
+
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the specifier set that can be round-tripped.
+
+        Note that the ordering of the individual specifiers within the set may not
+        match the input string.
+
+        >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
+        '!=1.0.1,>=1.0.0'
+        >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
+        '!=1.0.1,>=1.0.0'
+        """
+        return ",".join(sorted(str(s) for s in self._specs))
+
+    def __hash__(self) -> int:
+        return hash(self._specs)
+
+    def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
+        """Return a SpecifierSet which is a combination of the two sets.
+
+        :param other: The other object to combine with.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
+        =1.0.0')>
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
+        =1.0.0')>
+        """
+        if isinstance(other, str):
+            other = SpecifierSet(other)
+        elif not isinstance(other, SpecifierSet):
+            return NotImplemented
+
+        specifier = SpecifierSet()
+        specifier._specs = frozenset(self._specs | other._specs)
+
+        if self._prereleases is None and other._prereleases is not None:
+            specifier._prereleases = other._prereleases
+        elif self._prereleases is not None and other._prereleases is None:
+            specifier._prereleases = self._prereleases
+        elif self._prereleases == other._prereleases:
+            specifier._prereleases = self._prereleases
+        else:
+            raise ValueError(
+                "Cannot combine SpecifierSets with True and False prerelease "
+                "overrides."
+            )
+
+        return specifier
+
+    def __eq__(self, other: object) -> bool:
+        """Whether or not the two SpecifierSet-like objects are equal.
+
+        :param other: The other object to check against.
+
+        The value of :attr:`prereleases` is ignored.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
+        ...  SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
+        False
+        """
+        if isinstance(other, (str, Specifier)):
+            other = SpecifierSet(str(other))
+        elif not isinstance(other, SpecifierSet):
+            return NotImplemented
+
+        return self._specs == other._specs
+
+    def __len__(self) -> int:
+        """Returns the number of specifiers in this specifier set."""
+        return len(self._specs)
+
+    def __iter__(self) -> Iterator[Specifier]:
+        """
+        Returns an iterator over all the underlying :class:`Specifier` instances
+        in this specifier set.
+
+        >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
+        [, =1.0.0')>]
+        """
+        return iter(self._specs)
+
+    def __contains__(self, item: UnparsedVersion) -> bool:
+        """Return whether or not the item is contained in this specifier.
+
+        :param item: The item to check for.
+
+        This is used for the ``in`` operator and behaves the same as
+        :meth:`contains` with no ``prereleases`` argument passed.
+
+        >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
+        True
+        >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
+        False
+        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
+        False
+        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
+        True
+        """
+        return self.contains(item)
+
+    def contains(
+        self,
+        item: UnparsedVersion,
+        prereleases: Optional[bool] = None,
+        installed: Optional[bool] = None,
+    ) -> bool:
+        """Return whether or not the item is contained in this SpecifierSet.
+
+        :param item:
+            The item to check for, which can be a version string or a
+            :class:`Version` instance.
+        :param prereleases:
+            Whether or not to match prereleases with this SpecifierSet. If set to
+            ``None`` (the default), it uses :attr:`prereleases` to determine
+            whether or not prereleases are allowed.
+
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
+        False
+        >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1")
+        True
+        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
+        True
+        """
+        # Ensure that our item is a Version instance.
+        if not isinstance(item, Version):
+            item = Version(item)
+
+        # Determine if we're forcing a prerelease or not, if we're not forcing
+        # one for this particular filter call, then we'll use whatever the
+        # SpecifierSet thinks for whether or not we should support prereleases.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # We can determine if we're going to allow pre-releases by looking to
+        # see if any of the underlying items supports them. If none of them do
+        # and this item is a pre-release then we do not allow it and we can
+        # short circuit that here.
+        # Note: This means that 1.0.dev1 would not be contained in something
+        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
+        if not prereleases and item.is_prerelease:
+            return False
+
+        if installed and item.is_prerelease:
+            item = Version(item.base_version)
+
+        # We simply dispatch to the underlying specs here to make sure that the
+        # given version is contained within all of them.
+        # Note: This use of all() here means that an empty set of specifiers
+        #       will always return True, this is an explicit design decision.
+        return all(s.contains(item, prereleases=prereleases) for s in self._specs)
+
+    def filter(
+        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
+    ) -> Iterator[UnparsedVersionVar]:
+        """Filter items in the given iterable, that match the specifiers in this set.
+
+        :param iterable:
+            An iterable that can contain version strings and :class:`Version` instances.
+            The items in the iterable will be filtered according to the specifier.
+        :param prereleases:
+            Whether or not to allow prereleases in the returned iterator. If set to
+            ``None`` (the default), it will be intelligently decide whether to allow
+            prereleases or not (based on the :attr:`prereleases` attribute, and
+            whether the only versions matching are prereleases).
+
+        This method is smarter than just ``filter(SpecifierSet(...).contains, [...])``
+        because it implements the rule from :pep:`440` that a prerelease item
+        SHOULD be accepted if no other versions match the given specifier.
+
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
+        ['1.3', ]
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
+        []
+        >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+
+        An "empty" SpecifierSet will filter items based on the presence of prerelease
+        versions in the set.
+
+        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
+        ['1.3']
+        >>> list(SpecifierSet("").filter(["1.5a1"]))
+        ['1.5a1']
+        >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
+        ['1.3', '1.5a1']
+        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
+        ['1.3', '1.5a1']
+        """
+        # Determine if we're forcing a prerelease or not, if we're not forcing
+        # one for this particular filter call, then we'll use whatever the
+        # SpecifierSet thinks for whether or not we should support prereleases.
+        if prereleases is None:
+            prereleases = self.prereleases
+
+        # If we have any specifiers, then we want to wrap our iterable in the
+        # filter method for each one, this will act as a logical AND amongst
+        # each specifier.
+        if self._specs:
+            for spec in self._specs:
+                iterable = spec.filter(iterable, prereleases=bool(prereleases))
+            return iter(iterable)
+        # If we do not have any specifiers, then we need to have a rough filter
+        # which will filter out any pre-releases, unless there are no final
+        # releases.
+        else:
+            filtered: List[UnparsedVersionVar] = []
+            found_prereleases: List[UnparsedVersionVar] = []
+
+            for item in iterable:
+                parsed_version = _coerce_version(item)
+
+                # Store any item which is a pre-release for later unless we've
+                # already found a final version or we are accepting prereleases
+                if parsed_version.is_prerelease and not prereleases:
+                    if not filtered:
+                        found_prereleases.append(item)
+                else:
+                    filtered.append(item)
+
+            # If we've found no items except for pre-releases, then we'll go
+            # ahead and use the pre-releases
+            if not filtered and found_prereleases and prereleases is None:
+                return iter(found_prereleases)
+
+            return iter(filtered)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..89f1926137dd2d2a6bd63616bf5b9f722fc8d584
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/tags.py
@@ -0,0 +1,571 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import logging
+import platform
+import re
+import struct
+import subprocess
+import sys
+import sysconfig
+from importlib.machinery import EXTENSION_SUFFIXES
+from typing import (
+    Dict,
+    FrozenSet,
+    Iterable,
+    Iterator,
+    List,
+    Optional,
+    Sequence,
+    Tuple,
+    Union,
+    cast,
+)
+
+from . import _manylinux, _musllinux
+
+logger = logging.getLogger(__name__)
+
+PythonVersion = Sequence[int]
+MacVersion = Tuple[int, int]
+
+INTERPRETER_SHORT_NAMES: Dict[str, str] = {
+    "python": "py",  # Generic.
+    "cpython": "cp",
+    "pypy": "pp",
+    "ironpython": "ip",
+    "jython": "jy",
+}
+
+
+_32_BIT_INTERPRETER = struct.calcsize("P") == 4
+
+
+class Tag:
+    """
+    A representation of the tag triple for a wheel.
+
+    Instances are considered immutable and thus are hashable. Equality checking
+    is also supported.
+    """
+
+    __slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
+
+    def __init__(self, interpreter: str, abi: str, platform: str) -> None:
+        self._interpreter = interpreter.lower()
+        self._abi = abi.lower()
+        self._platform = platform.lower()
+        # The __hash__ of every single element in a Set[Tag] will be evaluated each time
+        # that a set calls its `.disjoint()` method, which may be called hundreds of
+        # times when scanning a page of links for packages with tags matching that
+        # Set[Tag]. Pre-computing the value here produces significant speedups for
+        # downstream consumers.
+        self._hash = hash((self._interpreter, self._abi, self._platform))
+
+    @property
+    def interpreter(self) -> str:
+        return self._interpreter
+
+    @property
+    def abi(self) -> str:
+        return self._abi
+
+    @property
+    def platform(self) -> str:
+        return self._platform
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Tag):
+            return NotImplemented
+
+        return (
+            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.
+            and (self._platform == other._platform)
+            and (self._abi == other._abi)
+            and (self._interpreter == other._interpreter)
+        )
+
+    def __hash__(self) -> int:
+        return self._hash
+
+    def __str__(self) -> str:
+        return f"{self._interpreter}-{self._abi}-{self._platform}"
+
+    def __repr__(self) -> str:
+        return f"<{self} @ {id(self)}>"
+
+
+def parse_tag(tag: str) -> FrozenSet[Tag]:
+    """
+    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
+
+    Returning a set is required due to the possibility that the tag is a
+    compressed tag set.
+    """
+    tags = set()
+    interpreters, abis, platforms = tag.split("-")
+    for interpreter in interpreters.split("."):
+        for abi in abis.split("."):
+            for platform_ in platforms.split("."):
+                tags.add(Tag(interpreter, abi, platform_))
+    return frozenset(tags)
+
+
+def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:
+    value: Union[int, str, None] = sysconfig.get_config_var(name)
+    if value is None and warn:
+        logger.debug(
+            "Config variable '%s' is unset, Python ABI tag may be incorrect", name
+        )
+    return value
+
+
+def _normalize_string(string: str) -> str:
+    return string.replace(".", "_").replace("-", "_").replace(" ", "_")
+
+
+def _is_threaded_cpython(abis: List[str]) -> bool:
+    """
+    Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
+
+    The threaded builds are indicated by a "t" in the abiflags.
+    """
+    if len(abis) == 0:
+        return False
+    # expect e.g., cp313
+    m = re.match(r"cp\d+(.*)", abis[0])
+    if not m:
+        return False
+    abiflags = m.group(1)
+    return "t" in abiflags
+
+
+def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:
+    """
+    Determine if the Python version supports abi3.
+
+    PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)
+    builds do not support abi3.
+    """
+    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
+
+
+def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
+    py_version = tuple(py_version)  # To allow for version comparison.
+    abis = []
+    version = _version_nodot(py_version[:2])
+    threading = debug = pymalloc = ucs4 = ""
+    with_debug = _get_config_var("Py_DEBUG", warn)
+    has_refcount = hasattr(sys, "gettotalrefcount")
+    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
+    # extension modules is the best option.
+    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
+    has_ext = "_d.pyd" in EXTENSION_SUFFIXES
+    if with_debug or (with_debug is None and (has_refcount or has_ext)):
+        debug = "d"
+    if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn):
+        threading = "t"
+    if py_version < (3, 8):
+        with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
+        if with_pymalloc or with_pymalloc is None:
+            pymalloc = "m"
+        if py_version < (3, 3):
+            unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
+            if unicode_size == 4 or (
+                unicode_size is None and sys.maxunicode == 0x10FFFF
+            ):
+                ucs4 = "u"
+    elif debug:
+        # Debug builds can also load "normal" extension modules.
+        # We can also assume no UCS-4 or pymalloc requirement.
+        abis.append(f"cp{version}{threading}")
+    abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
+    return abis
+
+
+def cpython_tags(
+    python_version: Optional[PythonVersion] = None,
+    abis: Optional[Iterable[str]] = None,
+    platforms: Optional[Iterable[str]] = None,
+    *,
+    warn: bool = False,
+) -> Iterator[Tag]:
+    """
+    Yields the tags for a CPython interpreter.
+
+    The tags consist of:
+    - cp--
+    - cp-abi3-
+    - cp-none-
+    - cp-abi3-  # Older Python versions down to 3.2.
+
+    If python_version only specifies a major version then user-provided ABIs and
+    the 'none' ABItag will be used.
+
+    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
+    their normal position and not at the beginning.
+    """
+    if not python_version:
+        python_version = sys.version_info[:2]
+
+    interpreter = f"cp{_version_nodot(python_version[:2])}"
+
+    if abis is None:
+        if len(python_version) > 1:
+            abis = _cpython_abis(python_version, warn)
+        else:
+            abis = []
+    abis = list(abis)
+    # 'abi3' and 'none' are explicitly handled later.
+    for explicit_abi in ("abi3", "none"):
+        try:
+            abis.remove(explicit_abi)
+        except ValueError:
+            pass
+
+    platforms = list(platforms or platform_tags())
+    for abi in abis:
+        for platform_ in platforms:
+            yield Tag(interpreter, abi, platform_)
+
+    threading = _is_threaded_cpython(abis)
+    use_abi3 = _abi3_applies(python_version, threading)
+    if use_abi3:
+        yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
+    yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
+
+    if use_abi3:
+        for minor_version in range(python_version[1] - 1, 1, -1):
+            for platform_ in platforms:
+                interpreter = "cp{version}".format(
+                    version=_version_nodot((python_version[0], minor_version))
+                )
+                yield Tag(interpreter, "abi3", platform_)
+
+
+def _generic_abi() -> List[str]:
+    """
+    Return the ABI tag based on EXT_SUFFIX.
+    """
+    # The following are examples of `EXT_SUFFIX`.
+    # We want to keep the parts which are related to the ABI and remove the
+    # parts which are related to the platform:
+    # - linux:   '.cpython-310-x86_64-linux-gnu.so' => cp310
+    # - mac:     '.cpython-310-darwin.so'           => cp310
+    # - win:     '.cp310-win_amd64.pyd'             => cp310
+    # - win:     '.pyd'                             => cp37 (uses _cpython_abis())
+    # - pypy:    '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
+    # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
+    #                                               => graalpy_38_native
+
+    ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
+    if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
+        raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
+    parts = ext_suffix.split(".")
+    if len(parts) < 3:
+        # CPython3.7 and earlier uses ".pyd" on Windows.
+        return _cpython_abis(sys.version_info[:2])
+    soabi = parts[1]
+    if soabi.startswith("cpython"):
+        # non-windows
+        abi = "cp" + soabi.split("-")[1]
+    elif soabi.startswith("cp"):
+        # windows
+        abi = soabi.split("-")[0]
+    elif soabi.startswith("pypy"):
+        abi = "-".join(soabi.split("-")[:2])
+    elif soabi.startswith("graalpy"):
+        abi = "-".join(soabi.split("-")[:3])
+    elif soabi:
+        # pyston, ironpython, others?
+        abi = soabi
+    else:
+        return []
+    return [_normalize_string(abi)]
+
+
+def generic_tags(
+    interpreter: Optional[str] = None,
+    abis: Optional[Iterable[str]] = None,
+    platforms: Optional[Iterable[str]] = None,
+    *,
+    warn: bool = False,
+) -> Iterator[Tag]:
+    """
+    Yields the tags for a generic interpreter.
+
+    The tags consist of:
+    - --
+
+    The "none" ABI will be added if it was not explicitly provided.
+    """
+    if not interpreter:
+        interp_name = interpreter_name()
+        interp_version = interpreter_version(warn=warn)
+        interpreter = "".join([interp_name, interp_version])
+    if abis is None:
+        abis = _generic_abi()
+    else:
+        abis = list(abis)
+    platforms = list(platforms or platform_tags())
+    if "none" not in abis:
+        abis.append("none")
+    for abi in abis:
+        for platform_ in platforms:
+            yield Tag(interpreter, abi, platform_)
+
+
+def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
+    """
+    Yields Python versions in descending order.
+
+    After the latest version, the major-only version will be yielded, and then
+    all previous versions of that major version.
+    """
+    if len(py_version) > 1:
+        yield f"py{_version_nodot(py_version[:2])}"
+    yield f"py{py_version[0]}"
+    if len(py_version) > 1:
+        for minor in range(py_version[1] - 1, -1, -1):
+            yield f"py{_version_nodot((py_version[0], minor))}"
+
+
+def compatible_tags(
+    python_version: Optional[PythonVersion] = None,
+    interpreter: Optional[str] = None,
+    platforms: Optional[Iterable[str]] = None,
+) -> Iterator[Tag]:
+    """
+    Yields the sequence of tags that are compatible with a specific version of Python.
+
+    The tags consist of:
+    - py*-none-
+    - -none-any  # ... if `interpreter` is provided.
+    - py*-none-any
+    """
+    if not python_version:
+        python_version = sys.version_info[:2]
+    platforms = list(platforms or platform_tags())
+    for version in _py_interpreter_range(python_version):
+        for platform_ in platforms:
+            yield Tag(version, "none", platform_)
+    if interpreter:
+        yield Tag(interpreter, "none", "any")
+    for version in _py_interpreter_range(python_version):
+        yield Tag(version, "none", "any")
+
+
+def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
+    if not is_32bit:
+        return arch
+
+    if arch.startswith("ppc"):
+        return "ppc"
+
+    return "i386"
+
+
+def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
+    formats = [cpu_arch]
+    if cpu_arch == "x86_64":
+        if version < (10, 4):
+            return []
+        formats.extend(["intel", "fat64", "fat32"])
+
+    elif cpu_arch == "i386":
+        if version < (10, 4):
+            return []
+        formats.extend(["intel", "fat32", "fat"])
+
+    elif cpu_arch == "ppc64":
+        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
+        if version > (10, 5) or version < (10, 4):
+            return []
+        formats.append("fat64")
+
+    elif cpu_arch == "ppc":
+        if version > (10, 6):
+            return []
+        formats.extend(["fat32", "fat"])
+
+    if cpu_arch in {"arm64", "x86_64"}:
+        formats.append("universal2")
+
+    if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
+        formats.append("universal")
+
+    return formats
+
+
+def mac_platforms(
+    version: Optional[MacVersion] = None, arch: Optional[str] = None
+) -> Iterator[str]:
+    """
+    Yields the platform tags for a macOS system.
+
+    The `version` parameter is a two-item tuple specifying the macOS version to
+    generate platform tags for. The `arch` parameter is the CPU architecture to
+    generate platform tags for. Both parameters default to the appropriate value
+    for the current system.
+    """
+    version_str, _, cpu_arch = platform.mac_ver()
+    if version is None:
+        version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
+        if version == (10, 16):
+            # When built against an older macOS SDK, Python will report macOS 10.16
+            # instead of the real version.
+            version_str = subprocess.run(
+                [
+                    sys.executable,
+                    "-sS",
+                    "-c",
+                    "import platform; print(platform.mac_ver()[0])",
+                ],
+                check=True,
+                env={"SYSTEM_VERSION_COMPAT": "0"},
+                stdout=subprocess.PIPE,
+                text=True,
+            ).stdout
+            version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
+    else:
+        version = version
+    if arch is None:
+        arch = _mac_arch(cpu_arch)
+    else:
+        arch = arch
+
+    if (10, 0) <= version and version < (11, 0):
+        # Prior to Mac OS 11, each yearly release of Mac OS bumped the
+        # "minor" version number.  The major version was always 10.
+        for minor_version in range(version[1], -1, -1):
+            compat_version = 10, minor_version
+            binary_formats = _mac_binary_formats(compat_version, arch)
+            for binary_format in binary_formats:
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=10, minor=minor_version, binary_format=binary_format
+                )
+
+    if version >= (11, 0):
+        # Starting with Mac OS 11, each yearly release bumps the major version
+        # number.   The minor versions are now the midyear updates.
+        for major_version in range(version[0], 10, -1):
+            compat_version = major_version, 0
+            binary_formats = _mac_binary_formats(compat_version, arch)
+            for binary_format in binary_formats:
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=major_version, minor=0, binary_format=binary_format
+                )
+
+    if version >= (11, 0):
+        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
+        # Arm64 support was introduced in 11.0, so no Arm binaries from previous
+        # releases exist.
+        #
+        # However, the "universal2" binary format can have a
+        # macOS version earlier than 11.0 when the x86_64 part of the binary supports
+        # that version of macOS.
+        if arch == "x86_64":
+            for minor_version in range(16, 3, -1):
+                compat_version = 10, minor_version
+                binary_formats = _mac_binary_formats(compat_version, arch)
+                for binary_format in binary_formats:
+                    yield "macosx_{major}_{minor}_{binary_format}".format(
+                        major=compat_version[0],
+                        minor=compat_version[1],
+                        binary_format=binary_format,
+                    )
+        else:
+            for minor_version in range(16, 3, -1):
+                compat_version = 10, minor_version
+                binary_format = "universal2"
+                yield "macosx_{major}_{minor}_{binary_format}".format(
+                    major=compat_version[0],
+                    minor=compat_version[1],
+                    binary_format=binary_format,
+                )
+
+
+def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
+    linux = _normalize_string(sysconfig.get_platform())
+    if not linux.startswith("linux_"):
+        # we should never be here, just yield the sysconfig one and return
+        yield linux
+        return
+    if is_32bit:
+        if linux == "linux_x86_64":
+            linux = "linux_i686"
+        elif linux == "linux_aarch64":
+            linux = "linux_armv8l"
+    _, arch = linux.split("_", 1)
+    archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
+    yield from _manylinux.platform_tags(archs)
+    yield from _musllinux.platform_tags(archs)
+    for arch in archs:
+        yield f"linux_{arch}"
+
+
+def _generic_platforms() -> Iterator[str]:
+    yield _normalize_string(sysconfig.get_platform())
+
+
+def platform_tags() -> Iterator[str]:
+    """
+    Provides the platform tags for this installation.
+    """
+    if platform.system() == "Darwin":
+        return mac_platforms()
+    elif platform.system() == "Linux":
+        return _linux_platforms()
+    else:
+        return _generic_platforms()
+
+
+def interpreter_name() -> str:
+    """
+    Returns the name of the running interpreter.
+
+    Some implementations have a reserved, two-letter abbreviation which will
+    be returned when appropriate.
+    """
+    name = sys.implementation.name
+    return INTERPRETER_SHORT_NAMES.get(name) or name
+
+
+def interpreter_version(*, warn: bool = False) -> str:
+    """
+    Returns the version of the running interpreter.
+    """
+    version = _get_config_var("py_version_nodot", warn=warn)
+    if version:
+        version = str(version)
+    else:
+        version = _version_nodot(sys.version_info[:2])
+    return version
+
+
+def _version_nodot(version: PythonVersion) -> str:
+    return "".join(map(str, version))
+
+
+def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
+    """
+    Returns the sequence of tag triples for the running interpreter.
+
+    The order of the sequence corresponds to priority order for the
+    interpreter, from most to least important.
+    """
+
+    interp_name = interpreter_name()
+    if interp_name == "cp":
+        yield from cpython_tags(warn=warn)
+    else:
+        yield from generic_tags()
+
+    if interp_name == "pp":
+        interp = "pp3"
+    elif interp_name == "cp":
+        interp = "cp" + interpreter_version(warn=warn)
+    else:
+        interp = None
+    yield from compatible_tags(interpreter=interp)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2c2f75aa806282d322c76c2117c0f0fdfb09d25
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/utils.py
@@ -0,0 +1,172 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import re
+from typing import FrozenSet, NewType, Tuple, Union, cast
+
+from .tags import Tag, parse_tag
+from .version import InvalidVersion, Version
+
+BuildTag = Union[Tuple[()], Tuple[int, str]]
+NormalizedName = NewType("NormalizedName", str)
+
+
+class InvalidName(ValueError):
+    """
+    An invalid distribution name; users should refer to the packaging user guide.
+    """
+
+
+class InvalidWheelFilename(ValueError):
+    """
+    An invalid wheel filename was found, users should refer to PEP 427.
+    """
+
+
+class InvalidSdistFilename(ValueError):
+    """
+    An invalid sdist filename was found, users should refer to the packaging user guide.
+    """
+
+
+# Core metadata spec for `Name`
+_validate_regex = re.compile(
+    r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
+)
+_canonicalize_regex = re.compile(r"[-_.]+")
+_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$")
+# PEP 427: The build number must start with a digit.
+_build_tag_regex = re.compile(r"(\d+)(.*)")
+
+
+def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
+    if validate and not _validate_regex.match(name):
+        raise InvalidName(f"name is invalid: {name!r}")
+    # This is taken from PEP 503.
+    value = _canonicalize_regex.sub("-", name).lower()
+    return cast(NormalizedName, value)
+
+
+def is_normalized_name(name: str) -> bool:
+    return _normalized_regex.match(name) is not None
+
+
+def canonicalize_version(
+    version: Union[Version, str], *, strip_trailing_zero: bool = True
+) -> str:
+    """
+    This is very similar to Version.__str__, but has one subtle difference
+    with the way it handles the release segment.
+    """
+    if isinstance(version, str):
+        try:
+            parsed = Version(version)
+        except InvalidVersion:
+            # Legacy versions cannot be normalized
+            return version
+    else:
+        parsed = version
+
+    parts = []
+
+    # Epoch
+    if parsed.epoch != 0:
+        parts.append(f"{parsed.epoch}!")
+
+    # Release segment
+    release_segment = ".".join(str(x) for x in parsed.release)
+    if strip_trailing_zero:
+        # NB: This strips trailing '.0's to normalize
+        release_segment = re.sub(r"(\.0)+$", "", release_segment)
+    parts.append(release_segment)
+
+    # Pre-release
+    if parsed.pre is not None:
+        parts.append("".join(str(x) for x in parsed.pre))
+
+    # Post-release
+    if parsed.post is not None:
+        parts.append(f".post{parsed.post}")
+
+    # Development release
+    if parsed.dev is not None:
+        parts.append(f".dev{parsed.dev}")
+
+    # Local version segment
+    if parsed.local is not None:
+        parts.append(f"+{parsed.local}")
+
+    return "".join(parts)
+
+
+def parse_wheel_filename(
+    filename: str,
+) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
+    if not filename.endswith(".whl"):
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (extension must be '.whl'): {filename}"
+        )
+
+    filename = filename[:-4]
+    dashes = filename.count("-")
+    if dashes not in (4, 5):
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (wrong number of parts): {filename}"
+        )
+
+    parts = filename.split("-", dashes - 2)
+    name_part = parts[0]
+    # See PEP 427 for the rules on escaping the project name.
+    if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
+        raise InvalidWheelFilename(f"Invalid project name: {filename}")
+    name = canonicalize_name(name_part)
+
+    try:
+        version = Version(parts[1])
+    except InvalidVersion as e:
+        raise InvalidWheelFilename(
+            f"Invalid wheel filename (invalid version): {filename}"
+        ) from e
+
+    if dashes == 5:
+        build_part = parts[2]
+        build_match = _build_tag_regex.match(build_part)
+        if build_match is None:
+            raise InvalidWheelFilename(
+                f"Invalid build number: {build_part} in '{filename}'"
+            )
+        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
+    else:
+        build = ()
+    tags = parse_tag(parts[-1])
+    return (name, version, build, tags)
+
+
+def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
+    if filename.endswith(".tar.gz"):
+        file_stem = filename[: -len(".tar.gz")]
+    elif filename.endswith(".zip"):
+        file_stem = filename[: -len(".zip")]
+    else:
+        raise InvalidSdistFilename(
+            f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
+            f" {filename}"
+        )
+
+    # We are requiring a PEP 440 version, which cannot contain dashes,
+    # so we split on the last dash.
+    name_part, sep, version_part = file_stem.rpartition("-")
+    if not sep:
+        raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
+
+    name = canonicalize_name(name_part)
+
+    try:
+        version = Version(version_part)
+    except InvalidVersion as e:
+        raise InvalidSdistFilename(
+            f"Invalid sdist filename (invalid version): {filename}"
+        ) from e
+
+    return (name, version)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..cda8e99935c8d92010b84437ae83d75031245d61
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/packaging/version.py
@@ -0,0 +1,561 @@
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+"""
+.. testsetup::
+
+    from packaging.version import parse, Version
+"""
+
+import itertools
+import re
+from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union
+
+from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
+
+__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
+
+LocalType = Tuple[Union[int, str], ...]
+
+CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
+CmpLocalType = Union[
+    NegativeInfinityType,
+    Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
+]
+CmpKey = Tuple[
+    int,
+    Tuple[int, ...],
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpPrePostDevType,
+    CmpLocalType,
+]
+VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
+
+
+class _Version(NamedTuple):
+    epoch: int
+    release: Tuple[int, ...]
+    dev: Optional[Tuple[str, int]]
+    pre: Optional[Tuple[str, int]]
+    post: Optional[Tuple[str, int]]
+    local: Optional[LocalType]
+
+
+def parse(version: str) -> "Version":
+    """Parse the given version string.
+
+    >>> parse('1.0.dev1')
+    
+
+    :param version: The version string to parse.
+    :raises InvalidVersion: When the version string is not a valid version.
+    """
+    return Version(version)
+
+
+class InvalidVersion(ValueError):
+    """Raised when a version string is not a valid version.
+
+    >>> Version("invalid")
+    Traceback (most recent call last):
+        ...
+    packaging.version.InvalidVersion: Invalid version: 'invalid'
+    """
+
+
+class _BaseVersion:
+    _key: Tuple[Any, ...]
+
+    def __hash__(self) -> int:
+        return hash(self._key)
+
+    # Please keep the duplicated `isinstance` check
+    # in the six comparisons hereunder
+    # unless you find a way to avoid adding overhead function calls.
+    def __lt__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key < other._key
+
+    def __le__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key <= other._key
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key == other._key
+
+    def __ge__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key >= other._key
+
+    def __gt__(self, other: "_BaseVersion") -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key > other._key
+
+    def __ne__(self, other: object) -> bool:
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return self._key != other._key
+
+
+# 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
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?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
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # 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) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be rounded-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> Optional[int]:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1.2.3+abc.dev1").public
+        '1.2.3'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3+abc.dev1").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
+) -> Optional[Tuple[str, int]]:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a 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 if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
+    """
+    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_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[LocalType],
+) -> CmpKey:
+    # 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 not a 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: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric 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 (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt
new file mode 100644
index 0000000000000000000000000000000000000000..14666103a82ea7fced3d8cffb8a9b2a9e03fb492
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/vendored/vendor.txt
@@ -0,0 +1 @@
+packaging==24.0
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/wheelfile.py b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/wheelfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a0f4596c566420135991713ee75ca29c4cff3ed
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/wheel/wheelfile.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+import csv
+import hashlib
+import os.path
+import re
+import stat
+import time
+from io import StringIO, TextIOWrapper
+from typing import IO, TYPE_CHECKING, Literal
+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
+
+from wheel.cli import WheelError
+from wheel.util import log, urlsafe_b64decode, urlsafe_b64encode
+
+if TYPE_CHECKING:
+    from typing import Protocol, Sized, Union
+
+    from typing_extensions import Buffer
+
+    StrPath = Union[str, os.PathLike[str]]
+
+    class SizedBuffer(Sized, Buffer, Protocol): ...
+
+
+# Non-greedy matching of an optional build number may be too clever (more
+# invalid wheel filenames will match). Separate regex for .dist-info?
+WHEEL_INFO_RE = re.compile(
+    r"""^(?P(?P[^\s-]+?)-(?P[^\s-]+?))(-(?P\d[^\s-]*))?
+     -(?P[^\s-]+?)-(?P[^\s-]+?)-(?P\S+)\.whl$""",
+    re.VERBOSE,
+)
+MINIMUM_TIMESTAMP = 315532800  # 1980-01-01 00:00:00 UTC
+
+
+def get_zipinfo_datetime(timestamp: float | None = None):
+    # Some applications need reproducible .whl files, but they can't do this without
+    # forcing the timestamp of the individual ZipInfo objects. See issue #143.
+    timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time()))
+    timestamp = max(timestamp, MINIMUM_TIMESTAMP)
+    return time.gmtime(timestamp)[0:6]
+
+
+class WheelFile(ZipFile):
+    """A ZipFile derivative class that also reads SHA-256 hashes from
+    .dist-info/RECORD and checks any read files against those.
+    """
+
+    _default_algorithm = hashlib.sha256
+
+    def __init__(
+        self,
+        file: StrPath,
+        mode: Literal["r", "w", "x", "a"] = "r",
+        compression: int = ZIP_DEFLATED,
+    ):
+        basename = os.path.basename(file)
+        self.parsed_filename = WHEEL_INFO_RE.match(basename)
+        if not basename.endswith(".whl") or self.parsed_filename is None:
+            raise WheelError(f"Bad wheel filename {basename!r}")
+
+        ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True)
+
+        self.dist_info_path = "{}.dist-info".format(
+            self.parsed_filename.group("namever")
+        )
+        self.record_path = self.dist_info_path + "/RECORD"
+        self._file_hashes: dict[str, tuple[None, None] | tuple[int, bytes]] = {}
+        self._file_sizes = {}
+        if mode == "r":
+            # Ignore RECORD and any embedded wheel signatures
+            self._file_hashes[self.record_path] = None, None
+            self._file_hashes[self.record_path + ".jws"] = None, None
+            self._file_hashes[self.record_path + ".p7s"] = None, None
+
+            # Fill in the expected hashes by reading them from RECORD
+            try:
+                record = self.open(self.record_path)
+            except KeyError:
+                raise WheelError(f"Missing {self.record_path} file") from None
+
+            with record:
+                for line in csv.reader(
+                    TextIOWrapper(record, newline="", encoding="utf-8")
+                ):
+                    path, hash_sum, size = line
+                    if not hash_sum:
+                        continue
+
+                    algorithm, hash_sum = hash_sum.split("=")
+                    try:
+                        hashlib.new(algorithm)
+                    except ValueError:
+                        raise WheelError(
+                            f"Unsupported hash algorithm: {algorithm}"
+                        ) from None
+
+                    if algorithm.lower() in {"md5", "sha1"}:
+                        raise WheelError(
+                            f"Weak hash algorithm ({algorithm}) is not permitted by "
+                            f"PEP 427"
+                        )
+
+                    self._file_hashes[path] = (
+                        algorithm,
+                        urlsafe_b64decode(hash_sum.encode("ascii")),
+                    )
+
+    def open(
+        self,
+        name_or_info: str | ZipInfo,
+        mode: Literal["r", "w"] = "r",
+        pwd: bytes | None = None,
+    ) -> IO[bytes]:
+        def _update_crc(newdata: bytes) -> None:
+            eof = ef._eof
+            update_crc_orig(newdata)
+            running_hash.update(newdata)
+            if eof and running_hash.digest() != expected_hash:
+                raise WheelError(f"Hash mismatch for file '{ef_name}'")
+
+        ef_name = (
+            name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info
+        )
+        if (
+            mode == "r"
+            and not ef_name.endswith("/")
+            and ef_name not in self._file_hashes
+        ):
+            raise WheelError(f"No hash found for file '{ef_name}'")
+
+        ef = ZipFile.open(self, name_or_info, mode, pwd)
+        if mode == "r" and not ef_name.endswith("/"):
+            algorithm, expected_hash = self._file_hashes[ef_name]
+            if expected_hash is not None:
+                # Monkey patch the _update_crc method to also check for the hash from
+                # RECORD
+                running_hash = hashlib.new(algorithm)
+                update_crc_orig, ef._update_crc = ef._update_crc, _update_crc
+
+        return ef
+
+    def write_files(self, base_dir: str):
+        log.info(f"creating '{self.filename}' and adding '{base_dir}' to it")
+        deferred: list[tuple[str, str]] = []
+        for root, dirnames, filenames in os.walk(base_dir):
+            # Sort the directory names so that `os.walk` will walk them in a
+            # defined order on the next iteration.
+            dirnames.sort()
+            for name in sorted(filenames):
+                path = os.path.normpath(os.path.join(root, name))
+                if os.path.isfile(path):
+                    arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/")
+                    if arcname == self.record_path:
+                        pass
+                    elif root.endswith(".dist-info"):
+                        deferred.append((path, arcname))
+                    else:
+                        self.write(path, arcname)
+
+        deferred.sort()
+        for path, arcname in deferred:
+            self.write(path, arcname)
+
+    def write(
+        self,
+        filename: str,
+        arcname: str | None = None,
+        compress_type: int | None = None,
+    ) -> None:
+        with open(filename, "rb") as f:
+            st = os.fstat(f.fileno())
+            data = f.read()
+
+        zinfo = ZipInfo(
+            arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime)
+        )
+        zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16
+        zinfo.compress_type = compress_type or self.compression
+        self.writestr(zinfo, data, compress_type)
+
+    def writestr(
+        self,
+        zinfo_or_arcname: str | ZipInfo,
+        data: SizedBuffer | str,
+        compress_type: int | None = None,
+    ):
+        if isinstance(zinfo_or_arcname, str):
+            zinfo_or_arcname = ZipInfo(
+                zinfo_or_arcname, date_time=get_zipinfo_datetime()
+            )
+            zinfo_or_arcname.compress_type = self.compression
+            zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16
+
+        if isinstance(data, str):
+            data = data.encode("utf-8")
+
+        ZipFile.writestr(self, zinfo_or_arcname, data, compress_type)
+        fname = (
+            zinfo_or_arcname.filename
+            if isinstance(zinfo_or_arcname, ZipInfo)
+            else zinfo_or_arcname
+        )
+        log.info(f"adding '{fname}'")
+        if fname != self.record_path:
+            hash_ = self._default_algorithm(data)
+            self._file_hashes[fname] = (
+                hash_.name,
+                urlsafe_b64encode(hash_.digest()).decode("ascii"),
+            )
+            self._file_sizes[fname] = len(data)
+
+    def close(self):
+        # Write RECORD
+        if self.fp is not None and self.mode == "w" and self._file_hashes:
+            data = StringIO()
+            writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n")
+            writer.writerows(
+                (
+                    (fname, algorithm + "=" + hash_, self._file_sizes[fname])
+                    for fname, (algorithm, hash_) in self._file_hashes.items()
+                )
+            )
+            writer.writerow((format(self.record_path), "", ""))
+            self.writestr(self.record_path, data.getvalue())
+
+        ZipFile.close(self)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/LICENSE
@@ -0,0 +1,17 @@
+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.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..1399281717f23d7a37cb8c56153afedf0c73c860
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/METADATA
@@ -0,0 +1,102 @@
+Metadata-Version: 2.1
+Name: zipp
+Version: 3.19.2
+Summary: Backport of pathlib-compatible object wrapper for zip files
+Author-email: "Jason R. Coombs" 
+Project-URL: Homepage, https://github.com/jaraco/zipp
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: doc
+Requires-Dist: sphinx >=3.5 ; extra == 'doc'
+Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'
+Requires-Dist: rst.linker >=1.9 ; extra == 'doc'
+Requires-Dist: furo ; extra == 'doc'
+Requires-Dist: sphinx-lint ; extra == 'doc'
+Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'
+Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'
+Requires-Dist: pytest-cov ; extra == 'test'
+Requires-Dist: pytest-mypy ; extra == 'test'
+Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'
+Requires-Dist: pytest-ruff >=0.2.1 ; extra == 'test'
+Requires-Dist: jaraco.itertools ; extra == 'test'
+Requires-Dist: jaraco.functools ; extra == 'test'
+Requires-Dist: more-itertools ; extra == 'test'
+Requires-Dist: big-O ; extra == 'test'
+Requires-Dist: pytest-ignore-flaky ; extra == 'test'
+Requires-Dist: jaraco.test ; extra == 'test'
+Requires-Dist: importlib-resources ; (python_version < "3.9") and extra == 'test'
+
+.. image:: https://img.shields.io/pypi/v/zipp.svg
+   :target: https://pypi.org/project/zipp
+
+.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
+
+.. image:: https://github.com/jaraco/zipp/actions/workflows/main.yml/badge.svg
+   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
+   :alt: tests
+
+.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. .. image:: https://readthedocs.org/projects/PROJECT_RTD/badge/?version=latest
+..    :target: https://PROJECT_RTD.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2024-informational
+   :target: https://blog.jaraco.com/skeleton
+
+.. image:: https://tidelift.com/badges/package/pypi/zipp
+   :target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme
+
+
+A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
+`Path object `_.
+
+
+Compatibility
+=============
+
+New features are introduced in this third-party library and later merged
+into CPython. The following table indicates which versions of this library
+were contributed to different versions in the standard library:
+
+.. list-table::
+   :header-rows: 1
+
+   * - zipp
+     - stdlib
+   * - 3.18
+     - 3.13
+   * - 3.16
+     - 3.12
+   * - 3.5
+     - 3.11
+   * - 3.2
+     - 3.10
+   * - 3.3 ??
+     - 3.9
+   * - 1.0
+     - 3.8
+
+
+Usage
+=====
+
+Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python.
+
+For Enterprise
+==============
+
+Available as part of the Tidelift Subscription.
+
+This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
+
+`Learn more `_.
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..77c02835d891989ded4fbb04d1fdbdb92c208c10
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/RECORD
@@ -0,0 +1,15 @@
+zipp-3.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+zipp-3.19.2.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+zipp-3.19.2.dist-info/METADATA,sha256=UIrk_kMIHGSwsKKChYizqMw0MMZpPRZ2ZiVpQAsN_bE,3575
+zipp-3.19.2.dist-info/RECORD,,
+zipp-3.19.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp-3.19.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+zipp-3.19.2.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
+zipp/__init__.py,sha256=QuI1g00G4fRAcGt-HqbV0oWIkmSgedCGGYsHHYzNa8A,13412
+zipp/__pycache__/__init__.cpython-312.pyc,,
+zipp/__pycache__/glob.cpython-312.pyc,,
+zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp/compat/__pycache__/__init__.cpython-312.pyc,,
+zipp/compat/__pycache__/py310.cpython-312.pyc,,
+zipp/compat/py310.py,sha256=eZpkW0zRtunkhEh8jjX3gCGe22emoKCBJw72Zt4RkhA,219
+zipp/glob.py,sha256=etWpnfEoRyfUvrUsi6sTiGmErvPwe6HzY6pT8jg_lUI,3082
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e82f676f82a3381fa909d1e6578c7a22044fafca
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp-3.19.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+zipp
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d65297b8354b934f687de1ab79c1f8cdf30050ff
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/__init__.py
@@ -0,0 +1,501 @@
+import io
+import posixpath
+import zipfile
+import itertools
+import contextlib
+import pathlib
+import re
+import stat
+import sys
+
+from .compat.py310 import text_encoding
+from .glob import Translator
+
+
+__all__ = ['Path']
+
+
+def _parents(path):
+    """
+    Given a path with elements separated by
+    posixpath.sep, generate all parents of that path.
+
+    >>> list(_parents('b/d'))
+    ['b']
+    >>> list(_parents('/b/d/'))
+    ['/b']
+    >>> list(_parents('b/d/f/'))
+    ['b/d', 'b']
+    >>> list(_parents('b'))
+    []
+    >>> list(_parents(''))
+    []
+    """
+    return itertools.islice(_ancestry(path), 1, None)
+
+
+def _ancestry(path):
+    """
+    Given a path with elements separated by
+    posixpath.sep, generate all elements of that path
+
+    >>> list(_ancestry('b/d'))
+    ['b/d', 'b']
+    >>> list(_ancestry('/b/d/'))
+    ['/b/d', '/b']
+    >>> list(_ancestry('b/d/f/'))
+    ['b/d/f', 'b/d', 'b']
+    >>> list(_ancestry('b'))
+    ['b']
+    >>> list(_ancestry(''))
+    []
+    """
+    path = path.rstrip(posixpath.sep)
+    while path and path != posixpath.sep:
+        yield path
+        path, tail = posixpath.split(path)
+
+
+_dedupe = dict.fromkeys
+"""Deduplicate an iterable in original order"""
+
+
+def _difference(minuend, subtrahend):
+    """
+    Return items in minuend not in subtrahend, retaining order
+    with O(1) lookup.
+    """
+    return itertools.filterfalse(set(subtrahend).__contains__, minuend)
+
+
+class InitializedState:
+    """
+    Mix-in to save the initialization state for pickling.
+    """
+
+    def __init__(self, *args, **kwargs):
+        self.__args = args
+        self.__kwargs = kwargs
+        super().__init__(*args, **kwargs)
+
+    def __getstate__(self):
+        return self.__args, self.__kwargs
+
+    def __setstate__(self, state):
+        args, kwargs = state
+        super().__init__(*args, **kwargs)
+
+
+class SanitizedNames:
+    """
+    ZipFile mix-in to ensure names are sanitized.
+    """
+
+    def namelist(self):
+        return list(map(self._sanitize, super().namelist()))
+
+    @staticmethod
+    def _sanitize(name):
+        r"""
+        Ensure a relative path with posix separators and no dot names.
+
+        Modeled after
+        https://github.com/python/cpython/blob/bcc1be39cb1d04ad9fc0bd1b9193d3972835a57c/Lib/zipfile/__init__.py#L1799-L1813
+        but provides consistent cross-platform behavior.
+
+        >>> san = SanitizedNames._sanitize
+        >>> san('/foo/bar')
+        'foo/bar'
+        >>> san('//foo.txt')
+        'foo.txt'
+        >>> san('foo/.././bar.txt')
+        'foo/bar.txt'
+        >>> san('foo../.bar.txt')
+        'foo../.bar.txt'
+        >>> san('\\foo\\bar.txt')
+        'foo/bar.txt'
+        >>> san('D:\\foo.txt')
+        'D/foo.txt'
+        >>> san('\\\\server\\share\\file.txt')
+        'server/share/file.txt'
+        >>> san('\\\\?\\GLOBALROOT\\Volume3')
+        '?/GLOBALROOT/Volume3'
+        >>> san('\\\\.\\PhysicalDrive1\\root')
+        'PhysicalDrive1/root'
+
+        Retain any trailing slash.
+        >>> san('abc/')
+        'abc/'
+
+        Raises a ValueError if the result is empty.
+        >>> san('../..')
+        Traceback (most recent call last):
+        ...
+        ValueError: Empty filename
+        """
+
+        def allowed(part):
+            return part and part not in {'..', '.'}
+
+        # Remove the drive letter.
+        # Don't use ntpath.splitdrive, because that also strips UNC paths
+        bare = re.sub('^([A-Z]):', r'\1', name, flags=re.IGNORECASE)
+        clean = bare.replace('\\', '/')
+        parts = clean.split('/')
+        joined = '/'.join(filter(allowed, parts))
+        if not joined:
+            raise ValueError("Empty filename")
+        return joined + '/' * name.endswith('/')
+
+
+class CompleteDirs(InitializedState, SanitizedNames, zipfile.ZipFile):
+    """
+    A ZipFile subclass that ensures that implied directories
+    are always included in the namelist.
+
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt']))
+    ['foo/', 'foo/bar/']
+    >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/']))
+    ['foo/']
+    """
+
+    @staticmethod
+    def _implied_dirs(names):
+        parents = itertools.chain.from_iterable(map(_parents, names))
+        as_dirs = (p + posixpath.sep for p in parents)
+        return _dedupe(_difference(as_dirs, names))
+
+    def namelist(self):
+        names = super().namelist()
+        return names + list(self._implied_dirs(names))
+
+    def _name_set(self):
+        return set(self.namelist())
+
+    def resolve_dir(self, name):
+        """
+        If the name represents a directory, return that name
+        as a directory (with the trailing slash).
+        """
+        names = self._name_set()
+        dirname = name + '/'
+        dir_match = name not in names and dirname in names
+        return dirname if dir_match else name
+
+    def getinfo(self, name):
+        """
+        Supplement getinfo for implied dirs.
+        """
+        try:
+            return super().getinfo(name)
+        except KeyError:
+            if not name.endswith('/') or name not in self._name_set():
+                raise
+            return zipfile.ZipInfo(filename=name)
+
+    @classmethod
+    def make(cls, source):
+        """
+        Given a source (filename or zipfile), return an
+        appropriate CompleteDirs subclass.
+        """
+        if isinstance(source, CompleteDirs):
+            return source
+
+        if not isinstance(source, zipfile.ZipFile):
+            return cls(source)
+
+        # Only allow for FastLookup when supplied zipfile is read-only
+        if 'r' not in source.mode:
+            cls = CompleteDirs
+
+        source.__class__ = cls
+        return source
+
+    @classmethod
+    def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile:
+        """
+        Given a writable zip file zf, inject directory entries for
+        any directories implied by the presence of children.
+        """
+        for name in cls._implied_dirs(zf.namelist()):
+            zf.writestr(name, b"")
+        return zf
+
+
+class FastLookup(CompleteDirs):
+    """
+    ZipFile subclass to ensure implicit
+    dirs exist and are resolved rapidly.
+    """
+
+    def namelist(self):
+        with contextlib.suppress(AttributeError):
+            return self.__names
+        self.__names = super().namelist()
+        return self.__names
+
+    def _name_set(self):
+        with contextlib.suppress(AttributeError):
+            return self.__lookup
+        self.__lookup = super()._name_set()
+        return self.__lookup
+
+
+def _extract_text_encoding(encoding=None, *args, **kwargs):
+    # compute stack level so that the caller of the caller sees any warning.
+    is_pypy = sys.implementation.name == 'pypy'
+    stack_level = 3 + is_pypy
+    return text_encoding(encoding, stack_level), args, kwargs
+
+
+class Path:
+    """
+    A :class:`importlib.resources.abc.Traversable` interface for zip files.
+
+    Implements many of the features users enjoy from
+    :class:`pathlib.Path`.
+
+    Consider a zip file with this structure::
+
+        .
+        ├── a.txt
+        └── b
+            ├── c.txt
+            └── d
+                └── e.txt
+
+    >>> data = io.BytesIO()
+    >>> zf = zipfile.ZipFile(data, 'w')
+    >>> zf.writestr('a.txt', 'content of a')
+    >>> zf.writestr('b/c.txt', 'content of c')
+    >>> zf.writestr('b/d/e.txt', 'content of e')
+    >>> zf.filename = 'mem/abcde.zip'
+
+    Path accepts the zipfile object itself or a filename
+
+    >>> path = Path(zf)
+
+    From there, several path operations are available.
+
+    Directory iteration (including the zip file itself):
+
+    >>> a, b = path.iterdir()
+    >>> a
+    Path('mem/abcde.zip', 'a.txt')
+    >>> b
+    Path('mem/abcde.zip', 'b/')
+
+    name property:
+
+    >>> b.name
+    'b'
+
+    join with divide operator:
+
+    >>> c = b / 'c.txt'
+    >>> c
+    Path('mem/abcde.zip', 'b/c.txt')
+    >>> c.name
+    'c.txt'
+
+    Read text:
+
+    >>> c.read_text(encoding='utf-8')
+    'content of c'
+
+    existence:
+
+    >>> c.exists()
+    True
+    >>> (b / 'missing.txt').exists()
+    False
+
+    Coercion to string:
+
+    >>> import os
+    >>> str(c).replace(os.sep, posixpath.sep)
+    'mem/abcde.zip/b/c.txt'
+
+    At the root, ``name``, ``filename``, and ``parent``
+    resolve to the zipfile.
+
+    >>> str(path)
+    'mem/abcde.zip/'
+    >>> path.name
+    'abcde.zip'
+    >>> path.filename == pathlib.Path('mem/abcde.zip')
+    True
+    >>> str(path.parent)
+    'mem'
+
+    If the zipfile has no filename, such attributes are not
+    valid and accessing them will raise an Exception.
+
+    >>> zf.filename = None
+    >>> path.name
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.filename
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    >>> path.parent
+    Traceback (most recent call last):
+    ...
+    TypeError: ...
+
+    # workaround python/cpython#106763
+    >>> pass
+    """
+
+    __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
+
+    def __init__(self, root, at=""):
+        """
+        Construct a Path from a ZipFile or filename.
+
+        Note: When the source is an existing ZipFile object,
+        its type (__class__) will be mutated to a
+        specialized type. If the caller wishes to retain the
+        original type, the caller should either create a
+        separate ZipFile object or pass a filename.
+        """
+        self.root = FastLookup.make(root)
+        self.at = at
+
+    def __eq__(self, other):
+        """
+        >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo'
+        False
+        """
+        if self.__class__ is not other.__class__:
+            return NotImplemented
+        return (self.root, self.at) == (other.root, other.at)
+
+    def __hash__(self):
+        return hash((self.root, self.at))
+
+    def open(self, mode='r', *args, pwd=None, **kwargs):
+        """
+        Open this entry as text or binary following the semantics
+        of ``pathlib.Path.open()`` by passing arguments through
+        to io.TextIOWrapper().
+        """
+        if self.is_dir():
+            raise IsADirectoryError(self)
+        zip_mode = mode[0]
+        if not self.exists() and zip_mode == 'r':
+            raise FileNotFoundError(self)
+        stream = self.root.open(self.at, zip_mode, pwd=pwd)
+        if 'b' in mode:
+            if args or kwargs:
+                raise ValueError("encoding args invalid for binary operation")
+            return stream
+        # Text mode:
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        return io.TextIOWrapper(stream, encoding, *args, **kwargs)
+
+    def _base(self):
+        return pathlib.PurePosixPath(self.at or self.root.filename)
+
+    @property
+    def name(self):
+        return self._base().name
+
+    @property
+    def suffix(self):
+        return self._base().suffix
+
+    @property
+    def suffixes(self):
+        return self._base().suffixes
+
+    @property
+    def stem(self):
+        return self._base().stem
+
+    @property
+    def filename(self):
+        return pathlib.Path(self.root.filename).joinpath(self.at)
+
+    def read_text(self, *args, **kwargs):
+        encoding, args, kwargs = _extract_text_encoding(*args, **kwargs)
+        with self.open('r', encoding, *args, **kwargs) as strm:
+            return strm.read()
+
+    def read_bytes(self):
+        with self.open('rb') as strm:
+            return strm.read()
+
+    def _is_child(self, path):
+        return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
+
+    def _next(self, at):
+        return self.__class__(self.root, at)
+
+    def is_dir(self):
+        return not self.at or self.at.endswith("/")
+
+    def is_file(self):
+        return self.exists() and not self.is_dir()
+
+    def exists(self):
+        return self.at in self.root._name_set()
+
+    def iterdir(self):
+        if not self.is_dir():
+            raise ValueError("Can't listdir a file")
+        subs = map(self._next, self.root.namelist())
+        return filter(self._is_child, subs)
+
+    def match(self, path_pattern):
+        return pathlib.PurePosixPath(self.at).match(path_pattern)
+
+    def is_symlink(self):
+        """
+        Return whether this path is a symlink.
+        """
+        info = self.root.getinfo(self.at)
+        mode = info.external_attr >> 16
+        return stat.S_ISLNK(mode)
+
+    def glob(self, pattern):
+        if not pattern:
+            raise ValueError(f"Unacceptable pattern: {pattern!r}")
+
+        prefix = re.escape(self.at)
+        tr = Translator(seps='/')
+        matches = re.compile(prefix + tr.translate(pattern)).fullmatch
+        names = (data.filename for data in self.root.filelist)
+        return map(self._next, filter(matches, names))
+
+    def rglob(self, pattern):
+        return self.glob(f'**/{pattern}')
+
+    def relative_to(self, other, *extra):
+        return posixpath.relpath(str(self), str(other.joinpath(*extra)))
+
+    def __str__(self):
+        return posixpath.join(self.root.filename, self.at)
+
+    def __repr__(self):
+        return self.__repr.format(self=self)
+
+    def joinpath(self, *other):
+        next = posixpath.join(self.at, *other)
+        return self._next(self.root.resolve_dir(next))
+
+    __truediv__ = joinpath
+
+    @property
+    def parent(self):
+        if not self.at:
+            return self.filename.parent
+        parent_at = posixpath.dirname(self.at.rstrip('/'))
+        if parent_at:
+            parent_at += '/'
+        return self._next(parent_at)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/compat/py310.py b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/compat/py310.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5ca53e037b267ff1b196b3b208dea0acdebe4c5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/compat/py310.py
@@ -0,0 +1,11 @@
+import sys
+import io
+
+
+def _text_encoding(encoding, stacklevel=2, /):  # pragma: no cover
+    return encoding
+
+
+text_encoding = (
+    io.text_encoding if sys.version_info > (3, 10) else _text_encoding  # type: ignore
+)
diff --git a/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/glob.py b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/glob.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c41d77c3f6549bd58d778dfe978a6ed728ede5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/_vendor/zipp/glob.py
@@ -0,0 +1,106 @@
+import os
+import re
+
+
+_default_seps = os.sep + str(os.altsep) * bool(os.altsep)
+
+
+class Translator:
+    """
+    >>> Translator('xyz')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+
+    >>> Translator('')
+    Traceback (most recent call last):
+    ...
+    AssertionError: Invalid separators
+    """
+
+    seps: str
+
+    def __init__(self, seps: str = _default_seps):
+        assert seps and set(seps) <= set(_default_seps), "Invalid separators"
+        self.seps = seps
+
+    def translate(self, pattern):
+        """
+        Given a glob pattern, produce a regex that matches it.
+        """
+        return self.extend(self.translate_core(pattern))
+
+    def extend(self, pattern):
+        r"""
+        Extend regex for pattern-wide concerns.
+
+        Apply '(?s:)' to create a non-matching group that
+        matches newlines (valid on Unix).
+
+        Append '\Z' to imply fullmatch even when match is used.
+        """
+        return rf'(?s:{pattern})\Z'
+
+    def translate_core(self, pattern):
+        r"""
+        Given a glob pattern, produce a regex that matches it.
+
+        >>> t = Translator()
+        >>> t.translate_core('*.txt').replace('\\\\', '')
+        '[^/]*\\.txt'
+        >>> t.translate_core('a?txt')
+        'a[^/]txt'
+        >>> t.translate_core('**/*').replace('\\\\', '')
+        '.*/[^/][^/]*'
+        """
+        self.restrict_rglob(pattern)
+        return ''.join(map(self.replace, separate(self.star_not_empty(pattern))))
+
+    def replace(self, match):
+        """
+        Perform the replacements for a match from :func:`separate`.
+        """
+        return match.group('set') or (
+            re.escape(match.group(0))
+            .replace('\\*\\*', r'.*')
+            .replace('\\*', rf'[^{re.escape(self.seps)}]*')
+            .replace('\\?', r'[^/]')
+        )
+
+    def restrict_rglob(self, pattern):
+        """
+        Raise ValueError if ** appears in anything but a full path segment.
+
+        >>> Translator().translate('**foo')
+        Traceback (most recent call last):
+        ...
+        ValueError: ** must appear alone in a path segment
+        """
+        seps_pattern = rf'[{re.escape(self.seps)}]+'
+        segments = re.split(seps_pattern, pattern)
+        if any('**' in segment and segment != '**' for segment in segments):
+            raise ValueError("** must appear alone in a path segment")
+
+    def star_not_empty(self, pattern):
+        """
+        Ensure that * will not match an empty segment.
+        """
+
+        def handle_segment(match):
+            segment = match.group(0)
+            return '?*' if segment == '*' else segment
+
+        not_seps_pattern = rf'[^{re.escape(self.seps)}]+'
+        return re.sub(not_seps_pattern, handle_segment, pattern)
+
+
+def separate(pattern):
+    """
+    Separate out character sets to avoid translating their contents.
+
+    >>> [m.group(0) for m in separate('*.txt')]
+    ['*.txt']
+    >>> [m.group(0) for m in separate('a[?]txt')]
+    ['a', '[?]', 'txt']
+    """
+    return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern)
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/NOTICE b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..ac5464d88c6f071c18d8eceb1e81d2550573599b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/NOTICE
@@ -0,0 +1,438 @@
+The code contained in this directory was automatically generated using the
+following command:
+
+    python -m validate_pyproject.pre_compile --output-dir=setuptools/config/_validate_pyproject --enable-plugins setuptools distutils --very-verbose -t setuptools=setuptools/config/setuptools.schema.json -t distutils=setuptools/config/distutils.schema.json
+
+Please avoid changing it manually.
+
+
+You can report issues or suggest changes directly to `validate-pyproject`
+(or to the relevant plugin repository)
+
+- https://github.com/abravalheri/validate-pyproject/issues
+
+
+***
+
+The following files include code from opensource projects
+(either as direct copies or modified versions):
+
+- `fastjsonschema_exceptions.py`:
+    - project: `fastjsonschema` - licensed under BSD-3-Clause
+      (https://github.com/horejsek/python-fastjsonschema)
+- `extra_validations.py` and `format.py`, `error_reporting.py`:
+    - project: `validate-pyproject` - licensed under MPL-2.0
+      (https://github.com/abravalheri/validate-pyproject)
+
+
+Additionally the following files are automatically generated by tools provided
+by the same projects:
+
+- `__init__.py`
+- `fastjsonschema_validations.py`
+
+The relevant copyright notes and licenses are included below.
+
+
+***
+
+`fastjsonschema`
+================
+
+Copyright (c) 2018, Michal Horejsek
+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 {organization} 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.
+
+
+
+***
+
+`validate-pyproject`
+====================
+
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+     means each individual or legal entity that creates, contributes to the
+     creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+     means the combination of the Contributions of others (if any) used by a
+     Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+     means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+     means Source Code Form to which the initial Contributor has attached the
+     notice in Exhibit A, the Executable Form of such Source Code Form, and
+     Modifications of such Source Code Form, in each case including portions
+     thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+     means
+
+     a. that the initial Contributor has attached the notice described in
+        Exhibit B to the Covered Software; or
+
+     b. that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the terms of
+        a Secondary License.
+
+1.6. "Executable Form"
+
+     means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+     means a work that combines Covered Software with other material, in a
+     separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+     means this document.
+
+1.9. "Licensable"
+
+     means having the right to grant, to the maximum extent possible, whether
+     at the time of the initial grant or subsequently, any and all of the
+     rights conveyed by this License.
+
+1.10. "Modifications"
+
+     means any of the following:
+
+     a. any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered Software; or
+
+     b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+      means any patent claim(s), including without limitation, method,
+      process, and apparatus claims, in any patent Licensable by such
+      Contributor that would be infringed, but for the grant of the License,
+      by the making, using, selling, offering for sale, having made, import,
+      or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+      means either the GNU General Public License, Version 2.0, the GNU Lesser
+      General Public License, Version 2.1, the GNU Affero General Public
+      License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+      means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+      means an individual or a legal entity exercising rights under this
+      License. For legal entities, "You" includes any entity that controls, is
+      controlled by, or is under common control with You. For purposes of this
+      definition, "control" means (a) the power, direct or indirect, to cause
+      the direction or management of such entity, whether by contract or
+      otherwise, or (b) ownership of more than fifty percent (50%) of the
+      outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+     Each Contributor hereby grants You a world-wide, royalty-free,
+     non-exclusive license:
+
+     a. under intellectual property rights (other than patent or trademark)
+        Licensable by such Contributor to use, reproduce, make available,
+        modify, display, perform, distribute, and otherwise exploit its
+        Contributions, either on an unmodified basis, with Modifications, or
+        as part of a Larger Work; and
+
+     b. under Patent Claims of such Contributor to make, use, sell, offer for
+        sale, have made, import, and otherwise transfer either its
+        Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+     The licenses granted in Section 2.1 with respect to any Contribution
+     become effective for each Contribution on the date the Contributor first
+     distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+     The licenses granted in this Section 2 are the only rights granted under
+     this License. No additional rights or licenses will be implied from the
+     distribution or licensing of Covered Software under this License.
+     Notwithstanding Section 2.1(b) above, no patent license is granted by a
+     Contributor:
+
+     a. for any code that a Contributor has removed from Covered Software; or
+
+     b. for infringements caused by: (i) Your and any other third party's
+        modifications of Covered Software, or (ii) the combination of its
+        Contributions with other software (except as part of its Contributor
+        Version); or
+
+     c. under Patent Claims infringed by Covered Software in the absence of
+        its Contributions.
+
+     This License does not grant any rights in the trademarks, service marks,
+     or logos of any Contributor (except as may be necessary to comply with
+     the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+     No Contributor makes additional grants as a result of Your choice to
+     distribute the Covered Software under a subsequent version of this
+     License (see Section 10.2) or under the terms of a Secondary License (if
+     permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+     Each Contributor represents that the Contributor believes its
+     Contributions are its original creation(s) or it has sufficient rights to
+     grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+     This License is not intended to limit any rights You have under
+     applicable copyright doctrines of fair use, fair dealing, or other
+     equivalents.
+
+2.7. Conditions
+
+     Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+     Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+     All distribution of Covered Software in Source Code Form, including any
+     Modifications that You create or to which You contribute, must be under
+     the terms of this License. You must inform recipients that the Source
+     Code Form of the Covered Software is governed by the terms of this
+     License, and how they can obtain a copy of this License. You may not
+     attempt to alter or restrict the recipients' rights in the Source Code
+     Form.
+
+3.2. Distribution of Executable Form
+
+     If You distribute Covered Software in Executable Form then:
+
+     a. such Covered Software must also be made available in Source Code Form,
+        as described in Section 3.1, and You must inform recipients of the
+        Executable Form how they can obtain a copy of such Source Code Form by
+        reasonable means in a timely manner, at a charge no more than the cost
+        of distribution to the recipient; and
+
+     b. You may distribute such Executable Form under the terms of this
+        License, or sublicense it under different terms, provided that the
+        license for the Executable Form does not attempt to limit or alter the
+        recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+     You may create and distribute a Larger Work under terms of Your choice,
+     provided that You also comply with the requirements of this License for
+     the Covered Software. If the Larger Work is a combination of Covered
+     Software with a work governed by one or more Secondary Licenses, and the
+     Covered Software is not Incompatible With Secondary Licenses, this
+     License permits You to additionally distribute such Covered Software
+     under the terms of such Secondary License(s), so that the recipient of
+     the Larger Work may, at their option, further distribute the Covered
+     Software under the terms of either this License or such Secondary
+     License(s).
+
+3.4. Notices
+
+     You may not remove or alter the substance of any license notices
+     (including copyright notices, patent notices, disclaimers of warranty, or
+     limitations of liability) contained within the Source Code Form of the
+     Covered Software, except that You may alter any license notices to the
+     extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+     You may choose to offer, and to charge a fee for, warranty, support,
+     indemnity or liability obligations to one or more recipients of Covered
+     Software. However, You may do so only on Your own behalf, and not on
+     behalf of any Contributor. You must make it absolutely clear that any
+     such warranty, support, indemnity, or liability obligation is offered by
+     You alone, and You hereby agree to indemnify every Contributor for any
+     liability incurred by such Contributor as a result of warranty, support,
+     indemnity or liability terms You offer. You may include additional
+     disclaimers of warranty and limitations of liability specific to any
+     jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+   If it is impossible for You to comply with any of the terms of this License
+   with respect to some or all of the Covered Software due to statute,
+   judicial order, or regulation then You must: (a) comply with the terms of
+   this License to the maximum extent possible; and (b) describe the
+   limitations and the code they affect. Such description must be placed in a
+   text file included with all distributions of the Covered Software under
+   this License. Except to the extent prohibited by statute or regulation,
+   such description must be sufficiently detailed for a recipient of ordinary
+   skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+     fail to comply with any of its terms. However, if You become compliant,
+     then the rights granted under this License from a particular Contributor
+     are reinstated (a) provisionally, unless and until such Contributor
+     explicitly and finally terminates Your grants, and (b) on an ongoing
+     basis, if such Contributor fails to notify You of the non-compliance by
+     some reasonable means prior to 60 days after You have come back into
+     compliance. Moreover, Your grants from a particular Contributor are
+     reinstated on an ongoing basis if such Contributor notifies You of the
+     non-compliance by some reasonable means, this is the first time You have
+     received notice of non-compliance with this License from such
+     Contributor, and You become compliant prior to 30 days after Your receipt
+     of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+     infringement claim (excluding declaratory judgment actions,
+     counter-claims, and cross-claims) alleging that a Contributor Version
+     directly or indirectly infringes any patent, then the rights granted to
+     You by any and all Contributors for the Covered Software under Section
+     2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+     license agreements (excluding distributors and resellers) which have been
+     validly granted by You or Your distributors under this License prior to
+     termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+   Covered Software is provided under this License on an "as is" basis,
+   without warranty of any kind, either expressed, implied, or statutory,
+   including, without limitation, warranties that the Covered Software is free
+   of defects, merchantable, fit for a particular purpose or non-infringing.
+   The entire risk as to the quality and performance of the Covered Software
+   is with You. Should any Covered Software prove defective in any respect,
+   You (not any Contributor) assume the cost of any necessary servicing,
+   repair, or correction. This disclaimer of warranty constitutes an essential
+   part of this License. No use of  any Covered Software is authorized under
+   this License except under this disclaimer.
+
+7. Limitation of Liability
+
+   Under no circumstances and under no legal theory, whether tort (including
+   negligence), contract, or otherwise, shall any Contributor, or anyone who
+   distributes Covered Software as permitted above, be liable to You for any
+   direct, indirect, special, incidental, or consequential damages of any
+   character including, without limitation, damages for lost profits, loss of
+   goodwill, work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses, even if such party shall have been
+   informed of the possibility of such damages. This limitation of liability
+   shall not apply to liability for death or personal injury resulting from
+   such party's negligence to the extent applicable law prohibits such
+   limitation. Some jurisdictions do not allow the exclusion or limitation of
+   incidental or consequential damages, so this exclusion and limitation may
+   not apply to You.
+
+8. Litigation
+
+   Any litigation relating to this License may be brought only in the courts
+   of a jurisdiction where the defendant maintains its principal place of
+   business and such litigation shall be governed by laws of that
+   jurisdiction, without reference to its conflict-of-law provisions. Nothing
+   in this Section shall prevent a party's ability to bring cross-claims or
+   counter-claims.
+
+9. Miscellaneous
+
+   This License represents the complete agreement concerning the subject
+   matter hereof. If any provision of this License is held to be
+   unenforceable, such provision shall be reformed only to the extent
+   necessary to make it enforceable. Any law or regulation which provides that
+   the language of a contract shall be construed against the drafter shall not
+   be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+      Mozilla Foundation is the license steward. Except as provided in Section
+      10.3, no one other than the license steward has the right to modify or
+      publish new versions of this License. Each version will be given a
+      distinguishing version number.
+
+10.2. Effect of New Versions
+
+      You may distribute the Covered Software under the terms of the version
+      of the License under which You originally received the Covered Software,
+      or under the terms of any subsequent version published by the license
+      steward.
+
+10.3. Modified Versions
+
+      If you create software not governed by this License, and you want to
+      create a new license for such software, you may create and use a
+      modified version of this License if you rename the license and remove
+      any references to the name of the license steward (except to note that
+      such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+      Licenses If You choose to distribute Source Code Form that is
+      Incompatible With Secondary Licenses under the terms of this version of
+      the License, the notice described in Exhibit B of this License must be
+      attached.
+
+Exhibit A - Source Code Form License Notice
+
+      This Source Code Form is subject to the
+      terms of the Mozilla Public License, v.
+      2.0. If a copy of the MPL was not
+      distributed with this file, You can
+      obtain one at
+      https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+      This Source Code Form is "Incompatible
+      With Secondary Licenses", as defined by
+      the Mozilla Public License, v. 2.0.
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/__init__.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f612bd51c4ac1d272318ed6fb96e4aeb57e3e27
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/__init__.py
@@ -0,0 +1,34 @@
+from functools import reduce
+from typing import Any, Callable, Dict
+
+from . import formats
+from .error_reporting import detailed_errors, ValidationError
+from .extra_validations import EXTRA_VALIDATIONS
+from .fastjsonschema_exceptions import JsonSchemaException, JsonSchemaValueException
+from .fastjsonschema_validations import validate as _validate
+
+__all__ = [
+    "validate",
+    "FORMAT_FUNCTIONS",
+    "EXTRA_VALIDATIONS",
+    "ValidationError",
+    "JsonSchemaException",
+    "JsonSchemaValueException",
+]
+
+
+FORMAT_FUNCTIONS: Dict[str, Callable[[str], bool]] = {
+    fn.__name__.replace("_", "-"): fn
+    for fn in formats.__dict__.values()
+    if callable(fn) and not fn.__name__.startswith("_")
+}
+
+
+def validate(data: Any) -> bool:
+    """Validate the given ``data`` object using JSON Schema
+    This function raises ``ValidationError`` if ``data`` is invalid.
+    """
+    with detailed_errors():
+        _validate(data, custom_formats=FORMAT_FUNCTIONS)
+        reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)
+    return True
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/error_reporting.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/error_reporting.py
new file mode 100644
index 0000000000000000000000000000000000000000..3591231c09f56494eb46119f9794053439b3fe8c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/error_reporting.py
@@ -0,0 +1,336 @@
+import io
+import json
+import logging
+import os
+import re
+import typing
+from contextlib import contextmanager
+from textwrap import indent, wrap
+from typing import Any, Dict, Generator, Iterator, List, Optional, Sequence, Union
+
+from .fastjsonschema_exceptions import JsonSchemaValueException
+
+if typing.TYPE_CHECKING:
+    import sys
+
+    if sys.version_info < (3, 11):
+        from typing_extensions import Self
+    else:
+        from typing import Self
+
+_logger = logging.getLogger(__name__)
+
+_MESSAGE_REPLACEMENTS = {
+    "must be named by propertyName definition": "keys must be named by",
+    "one of contains definition": "at least one item that matches",
+    " same as const definition:": "",
+    "only specified items": "only items matching the definition",
+}
+
+_SKIP_DETAILS = (
+    "must not be empty",
+    "is always invalid",
+    "must not be there",
+)
+
+_NEED_DETAILS = {"anyOf", "oneOf", "allOf", "contains", "propertyNames", "not", "items"}
+
+_CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)")
+_IDENTIFIER = re.compile(r"^[\w_]+$", re.I)
+
+_TOML_JARGON = {
+    "object": "table",
+    "property": "key",
+    "properties": "keys",
+    "property names": "keys",
+}
+
+_FORMATS_HELP = """
+For more details about `format` see
+https://validate-pyproject.readthedocs.io/en/latest/api/validate_pyproject.formats.html
+"""
+
+
+class ValidationError(JsonSchemaValueException):
+    """Report violations of a given JSON schema.
+
+    This class extends :exc:`~fastjsonschema.JsonSchemaValueException`
+    by adding the following properties:
+
+    - ``summary``: an improved version of the ``JsonSchemaValueException`` error message
+      with only the necessary information)
+
+    - ``details``: more contextual information about the error like the failing schema
+      itself and the value that violates the schema.
+
+    Depending on the level of the verbosity of the ``logging`` configuration
+    the exception message will be only ``summary`` (default) or a combination of
+    ``summary`` and ``details`` (when the logging level is set to :obj:`logging.DEBUG`).
+    """
+
+    summary = ""
+    details = ""
+    _original_message = ""
+
+    @classmethod
+    def _from_jsonschema(cls, ex: JsonSchemaValueException) -> "Self":
+        formatter = _ErrorFormatting(ex)
+        obj = cls(str(formatter), ex.value, formatter.name, ex.definition, ex.rule)
+        debug_code = os.getenv("JSONSCHEMA_DEBUG_CODE_GENERATION", "false").lower()
+        if debug_code != "false":  # pragma: no cover
+            obj.__cause__, obj.__traceback__ = ex.__cause__, ex.__traceback__
+        obj._original_message = ex.message
+        obj.summary = formatter.summary
+        obj.details = formatter.details
+        return obj
+
+
+@contextmanager
+def detailed_errors() -> Generator[None, None, None]:
+    try:
+        yield
+    except JsonSchemaValueException as ex:
+        raise ValidationError._from_jsonschema(ex) from None
+
+
+class _ErrorFormatting:
+    def __init__(self, ex: JsonSchemaValueException):
+        self.ex = ex
+        self.name = f"`{self._simplify_name(ex.name)}`"
+        self._original_message: str = self.ex.message.replace(ex.name, self.name)
+        self._summary = ""
+        self._details = ""
+
+    def __str__(self) -> str:
+        if _logger.getEffectiveLevel() <= logging.DEBUG and self.details:
+            return f"{self.summary}\n\n{self.details}"
+
+        return self.summary
+
+    @property
+    def summary(self) -> str:
+        if not self._summary:
+            self._summary = self._expand_summary()
+
+        return self._summary
+
+    @property
+    def details(self) -> str:
+        if not self._details:
+            self._details = self._expand_details()
+
+        return self._details
+
+    @staticmethod
+    def _simplify_name(name: str) -> str:
+        x = len("data.")
+        return name[x:] if name.startswith("data.") else name
+
+    def _expand_summary(self) -> str:
+        msg = self._original_message
+
+        for bad, repl in _MESSAGE_REPLACEMENTS.items():
+            msg = msg.replace(bad, repl)
+
+        if any(substring in msg for substring in _SKIP_DETAILS):
+            return msg
+
+        schema = self.ex.rule_definition
+        if self.ex.rule in _NEED_DETAILS and schema:
+            summary = _SummaryWriter(_TOML_JARGON)
+            return f"{msg}:\n\n{indent(summary(schema), '    ')}"
+
+        return msg
+
+    def _expand_details(self) -> str:
+        optional = []
+        definition = self.ex.definition or {}
+        desc_lines = definition.pop("$$description", [])
+        desc = definition.pop("description", None) or " ".join(desc_lines)
+        if desc:
+            description = "\n".join(
+                wrap(
+                    desc,
+                    width=80,
+                    initial_indent="    ",
+                    subsequent_indent="    ",
+                    break_long_words=False,
+                )
+            )
+            optional.append(f"DESCRIPTION:\n{description}")
+        schema = json.dumps(definition, indent=4)
+        value = json.dumps(self.ex.value, indent=4)
+        defaults = [
+            f"GIVEN VALUE:\n{indent(value, '    ')}",
+            f"OFFENDING RULE: {self.ex.rule!r}",
+            f"DEFINITION:\n{indent(schema, '    ')}",
+        ]
+        msg = "\n\n".join(optional + defaults)
+        epilog = f"\n{_FORMATS_HELP}" if "format" in msg.lower() else ""
+        return msg + epilog
+
+
+class _SummaryWriter:
+    _IGNORE = frozenset(("description", "default", "title", "examples"))
+
+    def __init__(self, jargon: Optional[Dict[str, str]] = None):
+        self.jargon: Dict[str, str] = jargon or {}
+        # Clarify confusing terms
+        self._terms = {
+            "anyOf": "at least one of the following",
+            "oneOf": "exactly one of the following",
+            "allOf": "all of the following",
+            "not": "(*NOT* the following)",
+            "prefixItems": f"{self._jargon('items')} (in order)",
+            "items": "items",
+            "contains": "contains at least one of",
+            "propertyNames": (
+                f"non-predefined acceptable {self._jargon('property names')}"
+            ),
+            "patternProperties": f"{self._jargon('properties')} named via pattern",
+            "const": "predefined value",
+            "enum": "one of",
+        }
+        # Attributes that indicate that the definition is easy and can be done
+        # inline (e.g. string and number)
+        self._guess_inline_defs = [
+            "enum",
+            "const",
+            "maxLength",
+            "minLength",
+            "pattern",
+            "format",
+            "minimum",
+            "maximum",
+            "exclusiveMinimum",
+            "exclusiveMaximum",
+            "multipleOf",
+        ]
+
+    def _jargon(self, term: Union[str, List[str]]) -> Union[str, List[str]]:
+        if isinstance(term, list):
+            return [self.jargon.get(t, t) for t in term]
+        return self.jargon.get(term, term)
+
+    def __call__(
+        self,
+        schema: Union[dict, List[dict]],
+        prefix: str = "",
+        *,
+        _path: Sequence[str] = (),
+    ) -> str:
+        if isinstance(schema, list):
+            return self._handle_list(schema, prefix, _path)
+
+        filtered = self._filter_unecessary(schema, _path)
+        simple = self._handle_simple_dict(filtered, _path)
+        if simple:
+            return f"{prefix}{simple}"
+
+        child_prefix = self._child_prefix(prefix, "  ")
+        item_prefix = self._child_prefix(prefix, "- ")
+        indent = len(prefix) * " "
+        with io.StringIO() as buffer:
+            for i, (key, value) in enumerate(filtered.items()):
+                child_path = [*_path, key]
+                line_prefix = prefix if i == 0 else indent
+                buffer.write(f"{line_prefix}{self._label(child_path)}:")
+                # ^  just the first item should receive the complete prefix
+                if isinstance(value, dict):
+                    filtered = self._filter_unecessary(value, child_path)
+                    simple = self._handle_simple_dict(filtered, child_path)
+                    buffer.write(
+                        f" {simple}"
+                        if simple
+                        else f"\n{self(value, child_prefix, _path=child_path)}"
+                    )
+                elif isinstance(value, list) and (
+                    key != "type" or self._is_property(child_path)
+                ):
+                    children = self._handle_list(value, item_prefix, child_path)
+                    sep = " " if children.startswith("[") else "\n"
+                    buffer.write(f"{sep}{children}")
+                else:
+                    buffer.write(f" {self._value(value, child_path)}\n")
+            return buffer.getvalue()
+
+    def _is_unecessary(self, path: Sequence[str]) -> bool:
+        if self._is_property(path) or not path:  # empty path => instruction @ root
+            return False
+        key = path[-1]
+        return any(key.startswith(k) for k in "$_") or key in self._IGNORE
+
+    def _filter_unecessary(
+        self, schema: Dict[str, Any], path: Sequence[str]
+    ) -> Dict[str, Any]:
+        return {
+            key: value
+            for key, value in schema.items()
+            if not self._is_unecessary([*path, key])
+        }
+
+    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> Optional[str]:
+        inline = any(p in value for p in self._guess_inline_defs)
+        simple = not any(isinstance(v, (list, dict)) for v in value.values())
+        if inline or simple:
+            return f"{{{', '.join(self._inline_attrs(value, path))}}}\n"
+        return None
+
+    def _handle_list(
+        self, schemas: list, prefix: str = "", path: Sequence[str] = ()
+    ) -> str:
+        if self._is_unecessary(path):
+            return ""
+
+        repr_ = repr(schemas)
+        if all(not isinstance(e, (dict, list)) for e in schemas) and len(repr_) < 60:
+            return f"{repr_}\n"
+
+        item_prefix = self._child_prefix(prefix, "- ")
+        return "".join(
+            self(v, item_prefix, _path=[*path, f"[{i}]"]) for i, v in enumerate(schemas)
+        )
+
+    def _is_property(self, path: Sequence[str]) -> bool:
+        """Check if the given path can correspond to an arbitrarily named property"""
+        counter = 0
+        for key in path[-2::-1]:
+            if key not in {"properties", "patternProperties"}:
+                break
+            counter += 1
+
+        # If the counter if even, the path correspond to a JSON Schema keyword
+        # otherwise it can be any arbitrary string naming a property
+        return counter % 2 == 1
+
+    def _label(self, path: Sequence[str]) -> str:
+        *parents, key = path
+        if not self._is_property(path):
+            norm_key = _separate_terms(key)
+            return self._terms.get(key) or " ".join(self._jargon(norm_key))
+
+        if parents[-1] == "patternProperties":
+            return f"(regex {key!r})"
+        return repr(key)  # property name
+
+    def _value(self, value: Any, path: Sequence[str]) -> str:
+        if path[-1] == "type" and not self._is_property(path):
+            type_ = self._jargon(value)
+            return f"[{', '.join(type_)}]" if isinstance(type_, list) else type_
+        return repr(value)
+
+    def _inline_attrs(self, schema: dict, path: Sequence[str]) -> Iterator[str]:
+        for key, value in schema.items():
+            child_path = [*path, key]
+            yield f"{self._label(child_path)}: {self._value(value, child_path)}"
+
+    def _child_prefix(self, parent_prefix: str, child_prefix: str) -> str:
+        return len(parent_prefix) * " " + child_prefix
+
+
+def _separate_terms(word: str) -> List[str]:
+    """
+    >>> _separate_terms("FooBar-foo")
+    ['foo', 'bar', 'foo']
+    """
+    return [w.lower() for w in _CAMEL_CASE_SPLITTER.split(word) if w]
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/extra_validations.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/extra_validations.py
new file mode 100644
index 0000000000000000000000000000000000000000..789411d0ff397041f87a834e634bac8488024326
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/extra_validations.py
@@ -0,0 +1,82 @@
+"""The purpose of this module is implement PEP 621 validations that are
+difficult to express as a JSON Schema (or that are not supported by the current
+JSON Schema library).
+"""
+
+from inspect import cleandoc
+from typing import Mapping, TypeVar
+
+from .error_reporting import ValidationError
+
+T = TypeVar("T", bound=Mapping)
+
+
+class RedefiningStaticFieldAsDynamic(ValidationError):
+    _DESC = """According to PEP 621:
+
+    Build back-ends MUST raise an error if the metadata specifies a field
+    statically as well as being listed in dynamic.
+    """
+    __doc__ = _DESC
+    _URL = (
+        "https://packaging.python.org/en/latest/specifications/"
+        "pyproject-toml/#dynamic"
+    )
+
+
+class IncludedDependencyGroupMustExist(ValidationError):
+    _DESC = """An included dependency group must exist and must not be cyclic.
+    """
+    __doc__ = _DESC
+    _URL = "https://peps.python.org/pep-0735/"
+
+
+def validate_project_dynamic(pyproject: T) -> T:
+    project_table = pyproject.get("project", {})
+    dynamic = project_table.get("dynamic", [])
+
+    for field in dynamic:
+        if field in project_table:
+            raise RedefiningStaticFieldAsDynamic(
+                message=f"You cannot provide a value for `project.{field}` and "
+                "list it under `project.dynamic` at the same time",
+                value={
+                    field: project_table[field],
+                    "...": " # ...",
+                    "dynamic": dynamic,
+                },
+                name=f"data.project.{field}",
+                definition={
+                    "description": cleandoc(RedefiningStaticFieldAsDynamic._DESC),
+                    "see": RedefiningStaticFieldAsDynamic._URL,
+                },
+                rule="PEP 621",
+            )
+
+    return pyproject
+
+
+def validate_include_depenency(pyproject: T) -> T:
+    dependency_groups = pyproject.get("dependency-groups", {})
+    for key, value in dependency_groups.items():
+        for each in value:
+            if (
+                isinstance(each, dict)
+                and (include_group := each.get("include-group"))
+                and include_group not in dependency_groups
+            ):
+                raise IncludedDependencyGroupMustExist(
+                    message=f"The included dependency group {include_group} doesn't exist",
+                    value=each,
+                    name=f"data.dependency_groups.{key}",
+                    definition={
+                        "description": cleandoc(IncludedDependencyGroupMustExist._DESC),
+                        "see": IncludedDependencyGroupMustExist._URL,
+                    },
+                    rule="PEP 735",
+                )
+    # TODO: check for `include-group` cycles (can be conditional to graphlib)
+    return pyproject
+
+
+EXTRA_VALIDATIONS = (validate_project_dynamic, validate_include_depenency)
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2dddd6a106f021a4723c1e8f5953ccc09e55e1f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py
@@ -0,0 +1,51 @@
+import re
+
+
+SPLIT_RE = re.compile(r'[\.\[\]]+')
+
+
+class JsonSchemaException(ValueError):
+    """
+    Base exception of ``fastjsonschema`` library.
+    """
+
+
+class JsonSchemaValueException(JsonSchemaException):
+    """
+    Exception raised by validation function. Available properties:
+
+     * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``),
+     * invalid ``value`` (e.g. ``60``),
+     * ``name`` of a path in the data structure (e.g. ``data.property[index]``),
+     * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``),
+     * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``),
+     * ``rule`` which the ``value`` is breaking (e.g. ``maximum``)
+     * and ``rule_definition`` (e.g. ``42``).
+
+    .. versionchanged:: 2.14.0
+        Added all extra properties.
+    """
+
+    def __init__(self, message, value=None, name=None, definition=None, rule=None):
+        super().__init__(message)
+        self.message = message
+        self.value = value
+        self.name = name
+        self.definition = definition
+        self.rule = rule
+
+    @property
+    def path(self):
+        return [item for item in SPLIT_RE.split(self.name) if item != '']
+
+    @property
+    def rule_definition(self):
+        if not self.rule or not self.definition:
+            return None
+        return self.definition.get(self.rule)
+
+
+class JsonSchemaDefinitionException(JsonSchemaException):
+    """
+    Exception raised by generator of validation function.
+    """
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
new file mode 100644
index 0000000000000000000000000000000000000000..c69368a83ff1bdb89cf4853e00429f0125ca3dce
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
@@ -0,0 +1,1412 @@
+# noqa
+# ruff: noqa
+# flake8: noqa
+# pylint: skip-file
+# mypy: ignore-errors
+# yapf: disable
+# pylama:skip=1
+
+
+# *** PLEASE DO NOT MODIFY DIRECTLY: Automatically generated code *** 
+
+
+VERSION = "2.20.0"
+from decimal import Decimal
+import re
+from .fastjsonschema_exceptions import JsonSchemaValueException
+
+
+REGEX_PATTERNS = {
+    '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': re.compile('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])\\Z'),
+    '^.*$': re.compile('^.*$'),
+    '.+': re.compile('.+'),
+    '^.+$': re.compile('^.+$'),
+    'idn-email_re_pattern': re.compile('^[^@]+@[^@]+\\.[^@]+\\Z')
+}
+
+NoneType = type(None)
+
+def validate(data, custom_formats={}, name_prefix=None):
+    validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats, (name_prefix or "data") + "")
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "build-system" in data_keys:
+            data_keys.remove("build-system")
+            data__buildsystem = data["build-system"]
+            if not isinstance(data__buildsystem, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must be object", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='type')
+            data__buildsystem_is_dict = isinstance(data__buildsystem, dict)
+            if data__buildsystem_is_dict:
+                data__buildsystem__missing_keys = set(['requires']) - data__buildsystem.keys()
+                if data__buildsystem__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must contain " + (str(sorted(data__buildsystem__missing_keys)) + " properties"), value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='required')
+                data__buildsystem_keys = set(data__buildsystem.keys())
+                if "requires" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("requires")
+                    data__buildsystem__requires = data__buildsystem["requires"]
+                    if not isinstance(data__buildsystem__requires, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.requires must be array", value=data__buildsystem__requires, name="" + (name_prefix or "data") + ".build-system.requires", definition={'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, rule='type')
+                    data__buildsystem__requires_is_list = isinstance(data__buildsystem__requires, (list, tuple))
+                    if data__buildsystem__requires_is_list:
+                        data__buildsystem__requires_len = len(data__buildsystem__requires)
+                        for data__buildsystem__requires_x, data__buildsystem__requires_item in enumerate(data__buildsystem__requires):
+                            if not isinstance(data__buildsystem__requires_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.requires[{data__buildsystem__requires_x}]".format(**locals()) + " must be string", value=data__buildsystem__requires_item, name="" + (name_prefix or "data") + ".build-system.requires[{data__buildsystem__requires_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "build-backend" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("build-backend")
+                    data__buildsystem__buildbackend = data__buildsystem["build-backend"]
+                    if not isinstance(data__buildsystem__buildbackend, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.build-backend must be string", value=data__buildsystem__buildbackend, name="" + (name_prefix or "data") + ".build-system.build-backend", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='type')
+                    if isinstance(data__buildsystem__buildbackend, str):
+                        if not custom_formats["pep517-backend-reference"](data__buildsystem__buildbackend):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.build-backend must be pep517-backend-reference", value=data__buildsystem__buildbackend, name="" + (name_prefix or "data") + ".build-system.build-backend", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='format')
+                if "backend-path" in data__buildsystem_keys:
+                    data__buildsystem_keys.remove("backend-path")
+                    data__buildsystem__backendpath = data__buildsystem["backend-path"]
+                    if not isinstance(data__buildsystem__backendpath, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.backend-path must be array", value=data__buildsystem__backendpath, name="" + (name_prefix or "data") + ".build-system.backend-path", definition={'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}, rule='type')
+                    data__buildsystem__backendpath_is_list = isinstance(data__buildsystem__backendpath, (list, tuple))
+                    if data__buildsystem__backendpath_is_list:
+                        data__buildsystem__backendpath_len = len(data__buildsystem__backendpath)
+                        for data__buildsystem__backendpath_x, data__buildsystem__backendpath_item in enumerate(data__buildsystem__backendpath):
+                            if not isinstance(data__buildsystem__backendpath_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system.backend-path[{data__buildsystem__backendpath_x}]".format(**locals()) + " must be string", value=data__buildsystem__backendpath_item, name="" + (name_prefix or "data") + ".build-system.backend-path[{data__buildsystem__backendpath_x}]".format(**locals()) + "", definition={'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}, rule='type')
+                if data__buildsystem_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".build-system must not contain "+str(data__buildsystem_keys)+" properties", value=data__buildsystem, name="" + (name_prefix or "data") + ".build-system", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='additionalProperties')
+        if "project" in data_keys:
+            data_keys.remove("project")
+            data__project = data["project"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data__project, custom_formats, (name_prefix or "data") + ".project")
+        if "tool" in data_keys:
+            data_keys.remove("tool")
+            data__tool = data["tool"]
+            if not isinstance(data__tool, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".tool must be object", value=data__tool, name="" + (name_prefix or "data") + ".tool", definition={'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, rule='type')
+            data__tool_is_dict = isinstance(data__tool, dict)
+            if data__tool_is_dict:
+                data__tool_keys = set(data__tool.keys())
+                if "distutils" in data__tool_keys:
+                    data__tool_keys.remove("distutils")
+                    data__tool__distutils = data__tool["distutils"]
+                    validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data__tool__distutils, custom_formats, (name_prefix or "data") + ".tool.distutils")
+                if "setuptools" in data__tool_keys:
+                    data__tool_keys.remove("setuptools")
+                    data__tool__setuptools = data__tool["setuptools"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data__tool__setuptools, custom_formats, (name_prefix or "data") + ".tool.setuptools")
+        if "dependency-groups" in data_keys:
+            data_keys.remove("dependency-groups")
+            data__dependencygroups = data["dependency-groups"]
+            if not isinstance(data__dependencygroups, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must be object", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='type')
+            data__dependencygroups_is_dict = isinstance(data__dependencygroups, dict)
+            if data__dependencygroups_is_dict:
+                data__dependencygroups_keys = set(data__dependencygroups.keys())
+                for data__dependencygroups_key, data__dependencygroups_val in data__dependencygroups.items():
+                    if REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_key):
+                        if data__dependencygroups_key in data__dependencygroups_keys:
+                            data__dependencygroups_keys.remove(data__dependencygroups_key)
+                        if not isinstance(data__dependencygroups_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + " must be array", value=data__dependencygroups_val, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}, rule='type')
+                        data__dependencygroups_val_is_list = isinstance(data__dependencygroups_val, (list, tuple))
+                        if data__dependencygroups_val_is_list:
+                            data__dependencygroups_val_len = len(data__dependencygroups_val)
+                            for data__dependencygroups_val_x, data__dependencygroups_val_item in enumerate(data__dependencygroups_val):
+                                data__dependencygroups_val_item_one_of_count1 = 0
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (str)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be string", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='type')
+                                        if isinstance(data__dependencygroups_val_item, str):
+                                            if not custom_formats["pep508"](data__dependencygroups_val_item):
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be pep508", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, rule='format')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 < 2:
+                                    try:
+                                        if not isinstance(data__dependencygroups_val_item, (dict)):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be object", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='type')
+                                        data__dependencygroups_val_item_is_dict = isinstance(data__dependencygroups_val_item, dict)
+                                        if data__dependencygroups_val_item_is_dict:
+                                            data__dependencygroups_val_item_keys = set(data__dependencygroups_val_item.keys())
+                                            if "include-group" in data__dependencygroups_val_item_keys:
+                                                data__dependencygroups_val_item_keys.remove("include-group")
+                                                data__dependencygroups_val_item__includegroup = data__dependencygroups_val_item["include-group"]
+                                                if not isinstance(data__dependencygroups_val_item__includegroup, (str)):
+                                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must be string", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='type')
+                                                if isinstance(data__dependencygroups_val_item__includegroup, str):
+                                                    if not REGEX_PATTERNS['^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'].search(data__dependencygroups_val_item__includegroup):
+                                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + " must match pattern ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$", value=data__dependencygroups_val_item__includegroup, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}].include-group".format(**locals()) + "", definition={'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}, rule='pattern')
+                                            if data__dependencygroups_val_item_keys:
+                                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must not contain "+str(data__dependencygroups_val_item_keys)+" properties", value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}, rule='additionalProperties')
+                                        data__dependencygroups_val_item_one_of_count1 += 1
+                                    except JsonSchemaValueException: pass
+                                if data__dependencygroups_val_item_one_of_count1 != 1:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__dependencygroups_val_item_one_of_count1) + " matches found)"), value=data__dependencygroups_val_item, name="" + (name_prefix or "data") + ".dependency-groups.{data__dependencygroups_key}[{data__dependencygroups_val_x}]".format(**locals()) + "", definition={'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}, rule='oneOf')
+                if data__dependencygroups_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependency-groups must not contain "+str(data__dependencygroups_keys)+" properties", value=data__dependencygroups, name="" + (name_prefix or "data") + ".dependency-groups", definition={'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$ref': '#/definitions/package-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$ref': '#/definitions/package-name'}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$ref': '#/definitions/ext-module'}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive-for-dependencies'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive-for-dependencies'}}}, 'readme': {'type': 'object', 'anyOf': [{'$ref': '#/definitions/file-directive'}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'$ref': '#/definitions/file-directive/properties/file'}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, 'dependency-groups': {'type': 'object', 'description': 'Dependency groups following PEP 735', 'additionalProperties': False, 'patternProperties': {'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$': {'type': 'array', 'items': {'oneOf': [{'type': 'string', 'description': 'Python package specifiers following PEP 508', 'format': 'pep508'}, {'type': 'object', 'additionalProperties': False, 'properties': {'include-group': {'description': 'Another dependency group to include in this one', 'type': 'string', 'pattern': '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$'}}}]}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points `_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points `_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "platforms" in data_keys:
+            data_keys.remove("platforms")
+            data__platforms = data["platforms"]
+            if not isinstance(data__platforms, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".platforms must be array", value=data__platforms, name="" + (name_prefix or "data") + ".platforms", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__platforms_is_list = isinstance(data__platforms, (list, tuple))
+            if data__platforms_is_list:
+                data__platforms_len = len(data__platforms)
+                for data__platforms_x, data__platforms_item in enumerate(data__platforms):
+                    if not isinstance(data__platforms_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".platforms[{data__platforms_x}]".format(**locals()) + " must be string", value=data__platforms_item, name="" + (name_prefix or "data") + ".platforms[{data__platforms_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "provides" in data_keys:
+            data_keys.remove("provides")
+            data__provides = data["provides"]
+            if not isinstance(data__provides, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides must be array", value=data__provides, name="" + (name_prefix or "data") + ".provides", definition={'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')
+            data__provides_is_list = isinstance(data__provides, (list, tuple))
+            if data__provides_is_list:
+                data__provides_len = len(data__provides)
+                for data__provides_x, data__provides_item in enumerate(data__provides):
+                    if not isinstance(data__provides_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + " must be string", value=data__provides_item, name="" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                    if isinstance(data__provides_item, str):
+                        if not custom_formats["pep508-identifier"](data__provides_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + " must be pep508-identifier", value=data__provides_item, name="" + (name_prefix or "data") + ".provides[{data__provides_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+        if "obsoletes" in data_keys:
+            data_keys.remove("obsoletes")
+            data__obsoletes = data["obsoletes"]
+            if not isinstance(data__obsoletes, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes must be array", value=data__obsoletes, name="" + (name_prefix or "data") + ".obsoletes", definition={'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')
+            data__obsoletes_is_list = isinstance(data__obsoletes, (list, tuple))
+            if data__obsoletes_is_list:
+                data__obsoletes_len = len(data__obsoletes)
+                for data__obsoletes_x, data__obsoletes_item in enumerate(data__obsoletes):
+                    if not isinstance(data__obsoletes_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + " must be string", value=data__obsoletes_item, name="" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                    if isinstance(data__obsoletes_item, str):
+                        if not custom_formats["pep508-identifier"](data__obsoletes_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + " must be pep508-identifier", value=data__obsoletes_item, name="" + (name_prefix or "data") + ".obsoletes[{data__obsoletes_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+        if "zip-safe" in data_keys:
+            data_keys.remove("zip-safe")
+            data__zipsafe = data["zip-safe"]
+            if not isinstance(data__zipsafe, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".zip-safe must be boolean", value=data__zipsafe, name="" + (name_prefix or "data") + ".zip-safe", definition={'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, rule='type')
+        if "script-files" in data_keys:
+            data_keys.remove("script-files")
+            data__scriptfiles = data["script-files"]
+            if not isinstance(data__scriptfiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files must be array", value=data__scriptfiles, name="" + (name_prefix or "data") + ".script-files", definition={'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, rule='type')
+            data__scriptfiles_is_list = isinstance(data__scriptfiles, (list, tuple))
+            if data__scriptfiles_is_list:
+                data__scriptfiles_len = len(data__scriptfiles)
+                for data__scriptfiles_x, data__scriptfiles_item in enumerate(data__scriptfiles):
+                    if not isinstance(data__scriptfiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".script-files[{data__scriptfiles_x}]".format(**locals()) + " must be string", value=data__scriptfiles_item, name="" + (name_prefix or "data") + ".script-files[{data__scriptfiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "eager-resources" in data_keys:
+            data_keys.remove("eager-resources")
+            data__eagerresources = data["eager-resources"]
+            if not isinstance(data__eagerresources, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources must be array", value=data__eagerresources, name="" + (name_prefix or "data") + ".eager-resources", definition={'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__eagerresources_is_list = isinstance(data__eagerresources, (list, tuple))
+            if data__eagerresources_is_list:
+                data__eagerresources_len = len(data__eagerresources)
+                for data__eagerresources_x, data__eagerresources_item in enumerate(data__eagerresources):
+                    if not isinstance(data__eagerresources_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".eager-resources[{data__eagerresources_x}]".format(**locals()) + " must be string", value=data__eagerresources_item, name="" + (name_prefix or "data") + ".eager-resources[{data__eagerresources_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "packages" in data_keys:
+            data_keys.remove("packages")
+            data__packages = data["packages"]
+            data__packages_one_of_count2 = 0
+            if data__packages_one_of_count2 < 2:
+                try:
+                    if not isinstance(data__packages, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be array", value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, rule='type')
+                    data__packages_is_list = isinstance(data__packages, (list, tuple))
+                    if data__packages_is_list:
+                        data__packages_len = len(data__packages)
+                        for data__packages_x, data__packages_item in enumerate(data__packages):
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packages_item, custom_formats, (name_prefix or "data") + ".packages[{data__packages_x}]".format(**locals()))
+                    data__packages_one_of_count2 += 1
+                except JsonSchemaValueException: pass
+            if data__packages_one_of_count2 < 2:
+                try:
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data__packages, custom_formats, (name_prefix or "data") + ".packages")
+                    data__packages_one_of_count2 += 1
+                except JsonSchemaValueException: pass
+            if data__packages_one_of_count2 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".packages must be valid exactly by one definition" + (" (" + str(data__packages_one_of_count2) + " matches found)"), value=data__packages, name="" + (name_prefix or "data") + ".packages", definition={'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, rule='oneOf')
+        if "package-dir" in data_keys:
+            data_keys.remove("package-dir")
+            data__packagedir = data["package-dir"]
+            if not isinstance(data__packagedir, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be object", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='type')
+            data__packagedir_is_dict = isinstance(data__packagedir, dict)
+            if data__packagedir_is_dict:
+                data__packagedir_keys = set(data__packagedir.keys())
+                for data__packagedir_key, data__packagedir_val in data__packagedir.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__packagedir_key):
+                        if data__packagedir_key in data__packagedir_keys:
+                            data__packagedir_keys.remove(data__packagedir_key)
+                        if not isinstance(data__packagedir_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + " must be string", value=data__packagedir_val, name="" + (name_prefix or "data") + ".package-dir.{data__packagedir_key}".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__packagedir_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must not contain "+str(data__packagedir_keys)+" properties", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='additionalProperties')
+                data__packagedir_len = len(data__packagedir)
+                if data__packagedir_len != 0:
+                    data__packagedir_property_names = True
+                    for data__packagedir_key in data__packagedir:
+                        try:
+                            data__packagedir_key_any_of_count3 = 0
+                            if not data__packagedir_key_any_of_count3:
+                                try:
+                                    if data__packagedir_key != "":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be same as const definition: ", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'const': ''}, rule='const')
+                                    data__packagedir_key_any_of_count3 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedir_key_any_of_count3:
+                                try:
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data__packagedir_key, custom_formats, (name_prefix or "data") + ".package-dir")
+                                    data__packagedir_key_any_of_count3 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedir_key_any_of_count3:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir cannot be validated by any definition", value=data__packagedir_key, name="" + (name_prefix or "data") + ".package-dir", definition={'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__packagedir_property_names = False
+                    if not data__packagedir_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-dir must be named by propertyName definition", value=data__packagedir, name="" + (name_prefix or "data") + ".package-dir", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='propertyNames')
+        if "package-data" in data_keys:
+            data_keys.remove("package-data")
+            data__packagedata = data["package-data"]
+            if not isinstance(data__packagedata, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be object", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__packagedata_is_dict = isinstance(data__packagedata, dict)
+            if data__packagedata_is_dict:
+                data__packagedata_keys = set(data__packagedata.keys())
+                for data__packagedata_key, data__packagedata_val in data__packagedata.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__packagedata_key):
+                        if data__packagedata_key in data__packagedata_keys:
+                            data__packagedata_keys.remove(data__packagedata_key)
+                        if not isinstance(data__packagedata_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data.{data__packagedata_key}".format(**locals()) + " must be array", value=data__packagedata_val, name="" + (name_prefix or "data") + ".package-data.{data__packagedata_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__packagedata_val_is_list = isinstance(data__packagedata_val, (list, tuple))
+                        if data__packagedata_val_is_list:
+                            data__packagedata_val_len = len(data__packagedata_val)
+                            for data__packagedata_val_x, data__packagedata_val_item in enumerate(data__packagedata_val):
+                                if not isinstance(data__packagedata_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + " must be string", value=data__packagedata_val_item, name="" + (name_prefix or "data") + ".package-data.{data__packagedata_key}[{data__packagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__packagedata_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must not contain "+str(data__packagedata_keys)+" properties", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                data__packagedata_len = len(data__packagedata)
+                if data__packagedata_len != 0:
+                    data__packagedata_property_names = True
+                    for data__packagedata_key in data__packagedata:
+                        try:
+                            data__packagedata_key_any_of_count4 = 0
+                            if not data__packagedata_key_any_of_count4:
+                                try:
+                                    if not isinstance(data__packagedata_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be string", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                                    if isinstance(data__packagedata_key, str):
+                                        if not custom_formats["python-module-name"](data__packagedata_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be python-module-name", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                                    data__packagedata_key_any_of_count4 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedata_key_any_of_count4:
+                                try:
+                                    if data__packagedata_key != "*":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be same as const definition: *", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'const': '*'}, rule='const')
+                                    data__packagedata_key_any_of_count4 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__packagedata_key_any_of_count4:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data cannot be validated by any definition", value=data__packagedata_key, name="" + (name_prefix or "data") + ".package-data", definition={'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__packagedata_property_names = False
+                    if not data__packagedata_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".package-data must be named by propertyName definition", value=data__packagedata, name="" + (name_prefix or "data") + ".package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+        if "include-package-data" in data_keys:
+            data_keys.remove("include-package-data")
+            data__includepackagedata = data["include-package-data"]
+            if not isinstance(data__includepackagedata, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-package-data must be boolean", value=data__includepackagedata, name="" + (name_prefix or "data") + ".include-package-data", definition={'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, rule='type')
+        if "exclude-package-data" in data_keys:
+            data_keys.remove("exclude-package-data")
+            data__excludepackagedata = data["exclude-package-data"]
+            if not isinstance(data__excludepackagedata, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be object", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__excludepackagedata_is_dict = isinstance(data__excludepackagedata, dict)
+            if data__excludepackagedata_is_dict:
+                data__excludepackagedata_keys = set(data__excludepackagedata.keys())
+                for data__excludepackagedata_key, data__excludepackagedata_val in data__excludepackagedata.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__excludepackagedata_key):
+                        if data__excludepackagedata_key in data__excludepackagedata_keys:
+                            data__excludepackagedata_keys.remove(data__excludepackagedata_key)
+                        if not isinstance(data__excludepackagedata_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}".format(**locals()) + " must be array", value=data__excludepackagedata_val, name="" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__excludepackagedata_val_is_list = isinstance(data__excludepackagedata_val, (list, tuple))
+                        if data__excludepackagedata_val_is_list:
+                            data__excludepackagedata_val_len = len(data__excludepackagedata_val)
+                            for data__excludepackagedata_val_x, data__excludepackagedata_val_item in enumerate(data__excludepackagedata_val):
+                                if not isinstance(data__excludepackagedata_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + " must be string", value=data__excludepackagedata_val_item, name="" + (name_prefix or "data") + ".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if data__excludepackagedata_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must not contain "+str(data__excludepackagedata_keys)+" properties", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')
+                data__excludepackagedata_len = len(data__excludepackagedata)
+                if data__excludepackagedata_len != 0:
+                    data__excludepackagedata_property_names = True
+                    for data__excludepackagedata_key in data__excludepackagedata:
+                        try:
+                            data__excludepackagedata_key_any_of_count5 = 0
+                            if not data__excludepackagedata_key_any_of_count5:
+                                try:
+                                    if not isinstance(data__excludepackagedata_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be string", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')
+                                    if isinstance(data__excludepackagedata_key, str):
+                                        if not custom_formats["python-module-name"](data__excludepackagedata_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be python-module-name", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')
+                                    data__excludepackagedata_key_any_of_count5 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__excludepackagedata_key_any_of_count5:
+                                try:
+                                    if data__excludepackagedata_key != "*":
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be same as const definition: *", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'const': '*'}, rule='const')
+                                    data__excludepackagedata_key_any_of_count5 += 1
+                                except JsonSchemaValueException: pass
+                            if not data__excludepackagedata_key_any_of_count5:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data cannot be validated by any definition", value=data__excludepackagedata_key, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, rule='anyOf')
+                        except JsonSchemaValueException:
+                            data__excludepackagedata_property_names = False
+                    if not data__excludepackagedata_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".exclude-package-data must be named by propertyName definition", value=data__excludepackagedata, name="" + (name_prefix or "data") + ".exclude-package-data", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')
+        if "namespace-packages" in data_keys:
+            data_keys.remove("namespace-packages")
+            data__namespacepackages = data["namespace-packages"]
+            if not isinstance(data__namespacepackages, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages must be array", value=data__namespacepackages, name="" + (name_prefix or "data") + ".namespace-packages", definition={'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, rule='type')
+            data__namespacepackages_is_list = isinstance(data__namespacepackages, (list, tuple))
+            if data__namespacepackages_is_list:
+                data__namespacepackages_len = len(data__namespacepackages)
+                for data__namespacepackages_x, data__namespacepackages_item in enumerate(data__namespacepackages):
+                    if not isinstance(data__namespacepackages_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be string", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+                    if isinstance(data__namespacepackages_item, str):
+                        if not custom_formats["python-module-name-relaxed"](data__namespacepackages_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__namespacepackages_item, name="" + (name_prefix or "data") + ".namespace-packages[{data__namespacepackages_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "py-modules" in data_keys:
+            data_keys.remove("py-modules")
+            data__pymodules = data["py-modules"]
+            if not isinstance(data__pymodules, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules must be array", value=data__pymodules, name="" + (name_prefix or "data") + ".py-modules", definition={'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, rule='type')
+            data__pymodules_is_list = isinstance(data__pymodules, (list, tuple))
+            if data__pymodules_is_list:
+                data__pymodules_len = len(data__pymodules)
+                for data__pymodules_x, data__pymodules_item in enumerate(data__pymodules):
+                    if not isinstance(data__pymodules_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be string", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+                    if isinstance(data__pymodules_item, str):
+                        if not custom_formats["python-module-name-relaxed"](data__pymodules_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + " must be python-module-name-relaxed", value=data__pymodules_item, name="" + (name_prefix or "data") + ".py-modules[{data__pymodules_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "ext-modules" in data_keys:
+            data_keys.remove("ext-modules")
+            data__extmodules = data["ext-modules"]
+            if not isinstance(data__extmodules, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".ext-modules must be array", value=data__extmodules, name="" + (name_prefix or "data") + ".ext-modules", definition={'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, rule='type')
+            data__extmodules_is_list = isinstance(data__extmodules, (list, tuple))
+            if data__extmodules_is_list:
+                data__extmodules_len = len(data__extmodules)
+                for data__extmodules_x, data__extmodules_item in enumerate(data__extmodules):
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data__extmodules_item, custom_formats, (name_prefix or "data") + ".ext-modules[{data__extmodules_x}]".format(**locals()))
+        if "data-files" in data_keys:
+            data_keys.remove("data-files")
+            data__datafiles = data["data-files"]
+            if not isinstance(data__datafiles, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files must be object", value=data__datafiles, name="" + (name_prefix or "data") + ".data-files", definition={'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')
+            data__datafiles_is_dict = isinstance(data__datafiles, dict)
+            if data__datafiles_is_dict:
+                data__datafiles_keys = set(data__datafiles.keys())
+                for data__datafiles_key, data__datafiles_val in data__datafiles.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__datafiles_key):
+                        if data__datafiles_key in data__datafiles_keys:
+                            data__datafiles_keys.remove(data__datafiles_key)
+                        if not isinstance(data__datafiles_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files.{data__datafiles_key}".format(**locals()) + " must be array", value=data__datafiles_val, name="" + (name_prefix or "data") + ".data-files.{data__datafiles_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                        data__datafiles_val_is_list = isinstance(data__datafiles_val, (list, tuple))
+                        if data__datafiles_val_is_list:
+                            data__datafiles_val_len = len(data__datafiles_val)
+                            for data__datafiles_val_x, data__datafiles_val_item in enumerate(data__datafiles_val):
+                                if not isinstance(data__datafiles_val_item, (str)):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".data-files.{data__datafiles_key}[{data__datafiles_val_x}]".format(**locals()) + " must be string", value=data__datafiles_val_item, name="" + (name_prefix or "data") + ".data-files.{data__datafiles_key}[{data__datafiles_val_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "cmdclass" in data_keys:
+            data_keys.remove("cmdclass")
+            data__cmdclass = data["cmdclass"]
+            if not isinstance(data__cmdclass, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass must be object", value=data__cmdclass, name="" + (name_prefix or "data") + ".cmdclass", definition={'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, rule='type')
+            data__cmdclass_is_dict = isinstance(data__cmdclass, dict)
+            if data__cmdclass_is_dict:
+                data__cmdclass_keys = set(data__cmdclass.keys())
+                for data__cmdclass_key, data__cmdclass_val in data__cmdclass.items():
+                    if REGEX_PATTERNS['^.*$'].search(data__cmdclass_key):
+                        if data__cmdclass_key in data__cmdclass_keys:
+                            data__cmdclass_keys.remove(data__cmdclass_key)
+                        if not isinstance(data__cmdclass_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + " must be string", value=data__cmdclass_val, name="" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')
+                        if isinstance(data__cmdclass_val, str):
+                            if not custom_formats["python-qualified-identifier"](data__cmdclass_val):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + " must be python-qualified-identifier", value=data__cmdclass_val, name="" + (name_prefix or "data") + ".cmdclass.{data__cmdclass_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')
+        if "license-files" in data_keys:
+            data_keys.remove("license-files")
+            data__licensefiles = data["license-files"]
+            if not isinstance(data__licensefiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, rule='type')
+            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
+            if data__licensefiles_is_list:
+                data__licensefiles_len = len(data__licensefiles)
+                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):
+                    if not isinstance(data__licensefiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + " must be string", value=data__licensefiles_item, name="" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "dynamic" in data_keys:
+            data_keys.remove("dynamic")
+            data__dynamic = data["dynamic"]
+            if not isinstance(data__dynamic, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be object", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='type')
+            data__dynamic_is_dict = isinstance(data__dynamic, dict)
+            if data__dynamic_is_dict:
+                data__dynamic_keys = set(data__dynamic.keys())
+                if "version" in data__dynamic_keys:
+                    data__dynamic_keys.remove("version")
+                    data__dynamic__version = data__dynamic["version"]
+                    data__dynamic__version_one_of_count6 = 0
+                    if data__dynamic__version_one_of_count6 < 2:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
+                        except JsonSchemaValueException: pass
+                    if data__dynamic__version_one_of_count6 < 2:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__version, custom_formats, (name_prefix or "data") + ".dynamic.version")
+                            data__dynamic__version_one_of_count6 += 1
+                        except JsonSchemaValueException: pass
+                    if data__dynamic__version_one_of_count6 != 1:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.version must be valid exactly by one definition" + (" (" + str(data__dynamic__version_one_of_count6) + " matches found)"), value=data__dynamic__version, name="" + (name_prefix or "data") + ".dynamic.version", definition={'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, rule='oneOf')
+                if "classifiers" in data__dynamic_keys:
+                    data__dynamic_keys.remove("classifiers")
+                    data__dynamic__classifiers = data__dynamic["classifiers"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__classifiers, custom_formats, (name_prefix or "data") + ".dynamic.classifiers")
+                if "description" in data__dynamic_keys:
+                    data__dynamic_keys.remove("description")
+                    data__dynamic__description = data__dynamic["description"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__description, custom_formats, (name_prefix or "data") + ".dynamic.description")
+                if "entry-points" in data__dynamic_keys:
+                    data__dynamic_keys.remove("entry-points")
+                    data__dynamic__entrypoints = data__dynamic["entry-points"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__entrypoints, custom_formats, (name_prefix or "data") + ".dynamic.entry-points")
+                if "dependencies" in data__dynamic_keys:
+                    data__dynamic_keys.remove("dependencies")
+                    data__dynamic__dependencies = data__dynamic["dependencies"]
+                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__dependencies, custom_formats, (name_prefix or "data") + ".dynamic.dependencies")
+                if "optional-dependencies" in data__dynamic_keys:
+                    data__dynamic_keys.remove("optional-dependencies")
+                    data__dynamic__optionaldependencies = data__dynamic["optional-dependencies"]
+                    if not isinstance(data__dynamic__optionaldependencies, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be object", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='type')
+                    data__dynamic__optionaldependencies_is_dict = isinstance(data__dynamic__optionaldependencies, dict)
+                    if data__dynamic__optionaldependencies_is_dict:
+                        data__dynamic__optionaldependencies_keys = set(data__dynamic__optionaldependencies.keys())
+                        for data__dynamic__optionaldependencies_key, data__dynamic__optionaldependencies_val in data__dynamic__optionaldependencies.items():
+                            if REGEX_PATTERNS['.+'].search(data__dynamic__optionaldependencies_key):
+                                if data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies_keys:
+                                    data__dynamic__optionaldependencies_keys.remove(data__dynamic__optionaldependencies_key)
+                                validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data__dynamic__optionaldependencies_val, custom_formats, (name_prefix or "data") + ".dynamic.optional-dependencies.{data__dynamic__optionaldependencies_key}".format(**locals()))
+                        if data__dynamic__optionaldependencies_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must not contain "+str(data__dynamic__optionaldependencies_keys)+" properties", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='additionalProperties')
+                        data__dynamic__optionaldependencies_len = len(data__dynamic__optionaldependencies)
+                        if data__dynamic__optionaldependencies_len != 0:
+                            data__dynamic__optionaldependencies_property_names = True
+                            for data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies:
+                                try:
+                                    if not isinstance(data__dynamic__optionaldependencies_key, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be string", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')
+                                    if isinstance(data__dynamic__optionaldependencies_key, str):
+                                        if not custom_formats["pep508-identifier"](data__dynamic__optionaldependencies_key):
+                                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be pep508-identifier", value=data__dynamic__optionaldependencies_key, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')
+                                except JsonSchemaValueException:
+                                    data__dynamic__optionaldependencies_property_names = False
+                            if not data__dynamic__optionaldependencies_property_names:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.optional-dependencies must be named by propertyName definition", value=data__dynamic__optionaldependencies, name="" + (name_prefix or "data") + ".dynamic.optional-dependencies", definition={'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, rule='propertyNames')
+                if "readme" in data__dynamic_keys:
+                    data__dynamic_keys.remove("readme")
+                    data__dynamic__readme = data__dynamic["readme"]
+                    if not isinstance(data__dynamic__readme, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='type')
+                    data__dynamic__readme_any_of_count7 = 0
+                    if not data__dynamic__readme_any_of_count7:
+                        try:
+                            validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data__dynamic__readme, custom_formats, (name_prefix or "data") + ".dynamic.readme")
+                            data__dynamic__readme_any_of_count7 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__dynamic__readme_any_of_count7:
+                        try:
+                            if not isinstance(data__dynamic__readme, (dict)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must be object", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='type')
+                            data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
+                            if data__dynamic__readme_is_dict:
+                                data__dynamic__readme_keys = set(data__dynamic__readme.keys())
+                                if "content-type" in data__dynamic__readme_keys:
+                                    data__dynamic__readme_keys.remove("content-type")
+                                    data__dynamic__readme__contenttype = data__dynamic__readme["content-type"]
+                                    if not isinstance(data__dynamic__readme__contenttype, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme.content-type must be string", value=data__dynamic__readme__contenttype, name="" + (name_prefix or "data") + ".dynamic.readme.content-type", definition={'type': 'string'}, rule='type')
+                                if "file" in data__dynamic__readme_keys:
+                                    data__dynamic__readme_keys.remove("file")
+                                    data__dynamic__readme__file = data__dynamic__readme["file"]
+                                    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data__dynamic__readme__file, custom_formats, (name_prefix or "data") + ".dynamic.readme.file")
+                                if data__dynamic__readme_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must not contain "+str(data__dynamic__readme_keys)+" properties", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}, rule='additionalProperties')
+                            data__dynamic__readme_any_of_count7 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__dynamic__readme_any_of_count7:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme cannot be validated by any definition", value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='anyOf')
+                    data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)
+                    if data__dynamic__readme_is_dict:
+                        data__dynamic__readme__missing_keys = set(['file']) - data__dynamic__readme.keys()
+                        if data__dynamic__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic.readme must contain " + (str(sorted(data__dynamic__readme__missing_keys)) + " properties"), value=data__dynamic__readme, name="" + (name_prefix or "data") + ".dynamic.readme", definition={'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}, rule='required')
+                if data__dynamic_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must not contain "+str(data__dynamic_keys)+" properties", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html', 'title': '``tool.setuptools`` table', '$$description': ['``setuptools``-specific configurations that can be set by users that require', 'customization.', 'These configurations are completely optional and probably can be skipped when', 'creating simple packages. They are equivalent to some of the `Keywords', '`_', 'used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.', 'It considers only ``setuptools`` `parameters', '`_', 'that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``', 'and ``setup_requires`` (incompatible with modern workflows/standards).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'$$description': ['Whether the project can be safely installed and run from a zip file.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'boolean'}, 'script-files': {'$$description': ['Legacy way of defining scripts (entry-points are preferred).', 'Equivalent to the ``script`` keyword in ``setup.py``', '(it was renamed to avoid confusion with entry-point based ``project.scripts``', 'defined in :pep:`621`).', '**DISCOURAGED**: generic script wrappers are tricky and may not work properly.', 'Whenever possible, please use ``project.scripts`` instead.'], 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.', '**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and', '``setup.py install`` in the context of ``eggs`` (**DEPRECATED**).'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}}, {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'const': ''}, {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'anyOf': [{'type': 'string', 'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html', 'description': '**DEPRECATED**: use implicit namespaces instead (:pep:`420`).'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name-relaxed'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'ext-modules': {'description': 'Extension modules to be compiled by setuptools', 'type': 'array', 'items': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}}, 'data-files': {'$$description': ['``dict``-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', '**DISCOURAGED**: please notice this might not work as expected with wheels.', 'Whenever possible, consider using data files inside the package directories', '(or create a new namespace package that only contains data files).', 'See `data files support', '`_.'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., "dotted" form with module), e.g.::\n\n', '    cmdclass = {mycmd = "pkg.subpkg.module.CommandClass"}\n\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['**PROVISIONAL**: list of glob patterns for all license files being distributed.', '(likely to become standard with :pep:`639`).', "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.', 'Also ensure to set ``project.dynamic`` accordingly.'], 'oneOf': [{'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'type': 'string', 'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$ref': '#/definitions/file-directive'}]}}}, 'readme': {'type': 'object', 'anyOf': [{'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'type': 'object', 'properties': {'content-type': {'type': 'string'}, 'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'additionalProperties': False}], 'required': ['file']}}}}, 'definitions': {'package-name': {'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, 'ext-module': {'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, 'file-directive': {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'file-directive-for-dependencies': {'title': "'file:' directive for dependencies", 'allOf': [{'$$description': ['**BETA**: subset of the ``requirements.txt`` format', 'without ``pip`` flags and options', '(one :pep:`508`-compliant string per line,', 'lines that are blank or start with ``#`` are excluded).', 'See `dynamic metadata', '`_.']}, {'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'attr-directive': {'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_properties_file(data, custom_formats={}, name_prefix=None):
+    data_one_of_count8 = 0
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 < 2:
+        try:
+            if not isinstance(data, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be array", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data_is_list = isinstance(data, (list, tuple))
+            if data_is_list:
+                data_len = len(data)
+                for data_x, data_item in enumerate(data):
+                    if not isinstance(data_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + " must be string", value=data_item, name="" + (name_prefix or "data") + "[{data_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+            data_one_of_count8 += 1
+        except JsonSchemaValueException: pass
+    if data_one_of_count8 != 1:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be valid exactly by one definition" + (" (" + str(data_one_of_count8) + " matches found)"), value=data, name="" + (name_prefix or "data") + "", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive_for_dependencies(data, custom_formats={}, name_prefix=None):
+    validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats, (name_prefix or "data") + "")
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_file_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['file']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='required')
+        data_keys = set(data.keys())
+        if "file" in data_keys:
+            data_keys.remove("file")
+            data__file = data["file"]
+            data__file_one_of_count9 = 0
+            if data__file_one_of_count9 < 2:
+                try:
+                    if not isinstance(data__file, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be string", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'string'}, rule='type')
+                    data__file_one_of_count9 += 1
+                except JsonSchemaValueException: pass
+            if data__file_one_of_count9 < 2:
+                try:
+                    if not isinstance(data__file, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be array", value=data__file, name="" + (name_prefix or "data") + ".file", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                    data__file_is_list = isinstance(data__file, (list, tuple))
+                    if data__file_is_list:
+                        data__file_len = len(data__file)
+                        for data__file_x, data__file_item in enumerate(data__file):
+                            if not isinstance(data__file_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + " must be string", value=data__file_item, name="" + (name_prefix or "data") + ".file[{data__file_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                    data__file_one_of_count9 += 1
+                except JsonSchemaValueException: pass
+            if data__file_one_of_count9 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".file must be valid exactly by one definition" + (" (" + str(data__file_one_of_count9) + " matches found)"), value=data__file, name="" + (name_prefix or "data") + ".file", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/file-directive', 'title': "'file:' directive", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_attr_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['attr']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='required')
+        data_keys = set(data.keys())
+        if "attr" in data_keys:
+            data_keys.remove("attr")
+            data__attr = data["attr"]
+            if not isinstance(data__attr, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be string", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')
+            if isinstance(data__attr, str):
+                if not custom_formats["python-qualified-identifier"](data__attr):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".attr must be python-qualified-identifier", value=data__attr, name="" + (name_prefix or "data") + ".attr", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'title': "'attr:' directive", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string', 'format': 'python-qualified-identifier'}}, 'required': ['attr']}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_ext_module(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['name', 'sources']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='required')
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+            if isinstance(data__name, str):
+                if not custom_formats["python-module-name-relaxed"](data__name):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be python-module-name-relaxed", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+        if "sources" in data_keys:
+            data_keys.remove("sources")
+            data__sources = data["sources"]
+            if not isinstance(data__sources, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources must be array", value=data__sources, name="" + (name_prefix or "data") + ".sources", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__sources_is_list = isinstance(data__sources, (list, tuple))
+            if data__sources_is_list:
+                data__sources_len = len(data__sources)
+                for data__sources_x, data__sources_item in enumerate(data__sources):
+                    if not isinstance(data__sources_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + " must be string", value=data__sources_item, name="" + (name_prefix or "data") + ".sources[{data__sources_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "include-dirs" in data_keys:
+            data_keys.remove("include-dirs")
+            data__includedirs = data["include-dirs"]
+            if not isinstance(data__includedirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs must be array", value=data__includedirs, name="" + (name_prefix or "data") + ".include-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__includedirs_is_list = isinstance(data__includedirs, (list, tuple))
+            if data__includedirs_is_list:
+                data__includedirs_len = len(data__includedirs)
+                for data__includedirs_x, data__includedirs_item in enumerate(data__includedirs):
+                    if not isinstance(data__includedirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + " must be string", value=data__includedirs_item, name="" + (name_prefix or "data") + ".include-dirs[{data__includedirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "define-macros" in data_keys:
+            data_keys.remove("define-macros")
+            data__definemacros = data["define-macros"]
+            if not isinstance(data__definemacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros must be array", value=data__definemacros, name="" + (name_prefix or "data") + ".define-macros", definition={'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, rule='type')
+            data__definemacros_is_list = isinstance(data__definemacros, (list, tuple))
+            if data__definemacros_is_list:
+                data__definemacros_len = len(data__definemacros)
+                for data__definemacros_x, data__definemacros_item in enumerate(data__definemacros):
+                    if not isinstance(data__definemacros_item, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must be array", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='type')
+                    data__definemacros_item_is_list = isinstance(data__definemacros_item, (list, tuple))
+                    if data__definemacros_item_is_list:
+                        data__definemacros_item_len = len(data__definemacros_item)
+                        if data__definemacros_item_len > 0:
+                            data__definemacros_item__0 = data__definemacros_item[0]
+                            if not isinstance(data__definemacros_item__0, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + " must be string", value=data__definemacros_item__0, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][0]".format(**locals()) + "", definition={'description': 'macro name', 'type': 'string'}, rule='type')
+                        if data__definemacros_item_len > 1:
+                            data__definemacros_item__1 = data__definemacros_item[1]
+                            data__definemacros_item__1_one_of_count10 = 0
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be string", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 < 2:
+                                try:
+                                    if not isinstance(data__definemacros_item__1, (NoneType)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be null", value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'type': 'null'}, rule='type')
+                                    data__definemacros_item__1_one_of_count10 += 1
+                                except JsonSchemaValueException: pass
+                            if data__definemacros_item__1_one_of_count10 != 1:
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + " must be valid exactly by one definition" + (" (" + str(data__definemacros_item__1_one_of_count10) + " matches found)"), value=data__definemacros_item__1, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}][1]".format(**locals()) + "", definition={'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}, rule='oneOf')
+                        if data__definemacros_item_len > 2:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + " must contain only specified items", value=data__definemacros_item, name="" + (name_prefix or "data") + ".define-macros[{data__definemacros_x}]".format(**locals()) + "", definition={'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}, rule='items')
+        if "undef-macros" in data_keys:
+            data_keys.remove("undef-macros")
+            data__undefmacros = data["undef-macros"]
+            if not isinstance(data__undefmacros, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros must be array", value=data__undefmacros, name="" + (name_prefix or "data") + ".undef-macros", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__undefmacros_is_list = isinstance(data__undefmacros, (list, tuple))
+            if data__undefmacros_is_list:
+                data__undefmacros_len = len(data__undefmacros)
+                for data__undefmacros_x, data__undefmacros_item in enumerate(data__undefmacros):
+                    if not isinstance(data__undefmacros_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + " must be string", value=data__undefmacros_item, name="" + (name_prefix or "data") + ".undef-macros[{data__undefmacros_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "library-dirs" in data_keys:
+            data_keys.remove("library-dirs")
+            data__librarydirs = data["library-dirs"]
+            if not isinstance(data__librarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs must be array", value=data__librarydirs, name="" + (name_prefix or "data") + ".library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__librarydirs_is_list = isinstance(data__librarydirs, (list, tuple))
+            if data__librarydirs_is_list:
+                data__librarydirs_len = len(data__librarydirs)
+                for data__librarydirs_x, data__librarydirs_item in enumerate(data__librarydirs):
+                    if not isinstance(data__librarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + " must be string", value=data__librarydirs_item, name="" + (name_prefix or "data") + ".library-dirs[{data__librarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "libraries" in data_keys:
+            data_keys.remove("libraries")
+            data__libraries = data["libraries"]
+            if not isinstance(data__libraries, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries must be array", value=data__libraries, name="" + (name_prefix or "data") + ".libraries", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__libraries_is_list = isinstance(data__libraries, (list, tuple))
+            if data__libraries_is_list:
+                data__libraries_len = len(data__libraries)
+                for data__libraries_x, data__libraries_item in enumerate(data__libraries):
+                    if not isinstance(data__libraries_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + " must be string", value=data__libraries_item, name="" + (name_prefix or "data") + ".libraries[{data__libraries_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "runtime-library-dirs" in data_keys:
+            data_keys.remove("runtime-library-dirs")
+            data__runtimelibrarydirs = data["runtime-library-dirs"]
+            if not isinstance(data__runtimelibrarydirs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs must be array", value=data__runtimelibrarydirs, name="" + (name_prefix or "data") + ".runtime-library-dirs", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__runtimelibrarydirs_is_list = isinstance(data__runtimelibrarydirs, (list, tuple))
+            if data__runtimelibrarydirs_is_list:
+                data__runtimelibrarydirs_len = len(data__runtimelibrarydirs)
+                for data__runtimelibrarydirs_x, data__runtimelibrarydirs_item in enumerate(data__runtimelibrarydirs):
+                    if not isinstance(data__runtimelibrarydirs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + " must be string", value=data__runtimelibrarydirs_item, name="" + (name_prefix or "data") + ".runtime-library-dirs[{data__runtimelibrarydirs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-objects" in data_keys:
+            data_keys.remove("extra-objects")
+            data__extraobjects = data["extra-objects"]
+            if not isinstance(data__extraobjects, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects must be array", value=data__extraobjects, name="" + (name_prefix or "data") + ".extra-objects", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extraobjects_is_list = isinstance(data__extraobjects, (list, tuple))
+            if data__extraobjects_is_list:
+                data__extraobjects_len = len(data__extraobjects)
+                for data__extraobjects_x, data__extraobjects_item in enumerate(data__extraobjects):
+                    if not isinstance(data__extraobjects_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + " must be string", value=data__extraobjects_item, name="" + (name_prefix or "data") + ".extra-objects[{data__extraobjects_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-compile-args" in data_keys:
+            data_keys.remove("extra-compile-args")
+            data__extracompileargs = data["extra-compile-args"]
+            if not isinstance(data__extracompileargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args must be array", value=data__extracompileargs, name="" + (name_prefix or "data") + ".extra-compile-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extracompileargs_is_list = isinstance(data__extracompileargs, (list, tuple))
+            if data__extracompileargs_is_list:
+                data__extracompileargs_len = len(data__extracompileargs)
+                for data__extracompileargs_x, data__extracompileargs_item in enumerate(data__extracompileargs):
+                    if not isinstance(data__extracompileargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + " must be string", value=data__extracompileargs_item, name="" + (name_prefix or "data") + ".extra-compile-args[{data__extracompileargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "extra-link-args" in data_keys:
+            data_keys.remove("extra-link-args")
+            data__extralinkargs = data["extra-link-args"]
+            if not isinstance(data__extralinkargs, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args must be array", value=data__extralinkargs, name="" + (name_prefix or "data") + ".extra-link-args", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__extralinkargs_is_list = isinstance(data__extralinkargs, (list, tuple))
+            if data__extralinkargs_is_list:
+                data__extralinkargs_len = len(data__extralinkargs)
+                for data__extralinkargs_x, data__extralinkargs_item in enumerate(data__extralinkargs):
+                    if not isinstance(data__extralinkargs_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + " must be string", value=data__extralinkargs_item, name="" + (name_prefix or "data") + ".extra-link-args[{data__extralinkargs_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "export-symbols" in data_keys:
+            data_keys.remove("export-symbols")
+            data__exportsymbols = data["export-symbols"]
+            if not isinstance(data__exportsymbols, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols must be array", value=data__exportsymbols, name="" + (name_prefix or "data") + ".export-symbols", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__exportsymbols_is_list = isinstance(data__exportsymbols, (list, tuple))
+            if data__exportsymbols_is_list:
+                data__exportsymbols_len = len(data__exportsymbols)
+                for data__exportsymbols_x, data__exportsymbols_item in enumerate(data__exportsymbols):
+                    if not isinstance(data__exportsymbols_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + " must be string", value=data__exportsymbols_item, name="" + (name_prefix or "data") + ".export-symbols[{data__exportsymbols_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "swig-opts" in data_keys:
+            data_keys.remove("swig-opts")
+            data__swigopts = data["swig-opts"]
+            if not isinstance(data__swigopts, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts must be array", value=data__swigopts, name="" + (name_prefix or "data") + ".swig-opts", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__swigopts_is_list = isinstance(data__swigopts, (list, tuple))
+            if data__swigopts_is_list:
+                data__swigopts_len = len(data__swigopts)
+                for data__swigopts_x, data__swigopts_item in enumerate(data__swigopts):
+                    if not isinstance(data__swigopts_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + " must be string", value=data__swigopts_item, name="" + (name_prefix or "data") + ".swig-opts[{data__swigopts_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "depends" in data_keys:
+            data_keys.remove("depends")
+            data__depends = data["depends"]
+            if not isinstance(data__depends, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends must be array", value=data__depends, name="" + (name_prefix or "data") + ".depends", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__depends_is_list = isinstance(data__depends, (list, tuple))
+            if data__depends_is_list:
+                data__depends_len = len(data__depends)
+                for data__depends_x, data__depends_item in enumerate(data__depends):
+                    if not isinstance(data__depends_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + " must be string", value=data__depends_item, name="" + (name_prefix or "data") + ".depends[{data__depends_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "language" in data_keys:
+            data_keys.remove("language")
+            data__language = data["language"]
+            if not isinstance(data__language, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".language must be string", value=data__language, name="" + (name_prefix or "data") + ".language", definition={'type': 'string'}, rule='type')
+        if "optional" in data_keys:
+            data_keys.remove("optional")
+            data__optional = data["optional"]
+            if not isinstance(data__optional, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional must be boolean", value=data__optional, name="" + (name_prefix or "data") + ".optional", definition={'type': 'boolean'}, rule='type')
+        if "py-limited-api" in data_keys:
+            data_keys.remove("py-limited-api")
+            data__pylimitedapi = data["py-limited-api"]
+            if not isinstance(data__pylimitedapi, (bool)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".py-limited-api must be boolean", value=data__pylimitedapi, name="" + (name_prefix or "data") + ".py-limited-api", definition={'type': 'boolean'}, rule='type')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/ext-module', 'title': 'Extension module', 'description': 'Parameters to construct a :class:`setuptools.Extension` object', 'type': 'object', 'required': ['name', 'sources'], 'additionalProperties': False, 'properties': {'name': {'type': 'string', 'format': 'python-module-name-relaxed'}, 'sources': {'type': 'array', 'items': {'type': 'string'}}, 'include-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'define-macros': {'type': 'array', 'items': {'type': 'array', 'items': [{'description': 'macro name', 'type': 'string'}, {'description': 'macro value', 'oneOf': [{'type': 'string'}, {'type': 'null'}]}], 'additionalItems': False}}, 'undef-macros': {'type': 'array', 'items': {'type': 'string'}}, 'library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'libraries': {'type': 'array', 'items': {'type': 'string'}}, 'runtime-library-dirs': {'type': 'array', 'items': {'type': 'string'}}, 'extra-objects': {'type': 'array', 'items': {'type': 'string'}}, 'extra-compile-args': {'type': 'array', 'items': {'type': 'string'}}, 'extra-link-args': {'type': 'array', 'items': {'type': 'string'}}, 'export-symbols': {'type': 'array', 'items': {'type': 'string'}}, 'swig-opts': {'type': 'array', 'items': {'type': 'string'}}, 'depends': {'type': 'array', 'items': {'type': 'string'}}, 'language': {'type': 'string'}, 'optional': {'type': 'boolean'}, 'py-limited-api': {'type': 'boolean'}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_find_directive(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "find" in data_keys:
+            data_keys.remove("find")
+            data__find = data["find"]
+            if not isinstance(data__find, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find must be object", value=data__find, name="" + (name_prefix or "data") + ".find", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='type')
+            data__find_is_dict = isinstance(data__find, dict)
+            if data__find_is_dict:
+                data__find_keys = set(data__find.keys())
+                if "where" in data__find_keys:
+                    data__find_keys.remove("where")
+                    data__find__where = data__find["where"]
+                    if not isinstance(data__find__where, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.where must be array", value=data__find__where, name="" + (name_prefix or "data") + ".find.where", definition={'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+                    data__find__where_is_list = isinstance(data__find__where, (list, tuple))
+                    if data__find__where_is_list:
+                        data__find__where_len = len(data__find__where)
+                        for data__find__where_x, data__find__where_item in enumerate(data__find__where):
+                            if not isinstance(data__find__where_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.where[{data__find__where_x}]".format(**locals()) + " must be string", value=data__find__where_item, name="" + (name_prefix or "data") + ".find.where[{data__find__where_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "exclude" in data__find_keys:
+                    data__find_keys.remove("exclude")
+                    data__find__exclude = data__find["exclude"]
+                    if not isinstance(data__find__exclude, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.exclude must be array", value=data__find__exclude, name="" + (name_prefix or "data") + ".find.exclude", definition={'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, rule='type')
+                    data__find__exclude_is_list = isinstance(data__find__exclude, (list, tuple))
+                    if data__find__exclude_is_list:
+                        data__find__exclude_len = len(data__find__exclude)
+                        for data__find__exclude_x, data__find__exclude_item in enumerate(data__find__exclude):
+                            if not isinstance(data__find__exclude_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.exclude[{data__find__exclude_x}]".format(**locals()) + " must be string", value=data__find__exclude_item, name="" + (name_prefix or "data") + ".find.exclude[{data__find__exclude_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "include" in data__find_keys:
+                    data__find_keys.remove("include")
+                    data__find__include = data__find["include"]
+                    if not isinstance(data__find__include, (list, tuple)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.include must be array", value=data__find__include, name="" + (name_prefix or "data") + ".find.include", definition={'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, rule='type')
+                    data__find__include_is_list = isinstance(data__find__include, (list, tuple))
+                    if data__find__include_is_list:
+                        data__find__include_len = len(data__find__include)
+                        for data__find__include_x, data__find__include_item in enumerate(data__find__include):
+                            if not isinstance(data__find__include_item, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.include[{data__find__include_x}]".format(**locals()) + " must be string", value=data__find__include_item, name="" + (name_prefix or "data") + ".find.include[{data__find__include_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+                if "namespaces" in data__find_keys:
+                    data__find_keys.remove("namespaces")
+                    data__find__namespaces = data__find["namespaces"]
+                    if not isinstance(data__find__namespaces, (bool)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".find.namespaces must be boolean", value=data__find__namespaces, name="" + (name_prefix or "data") + ".find.namespaces", definition={'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}, rule='type')
+                if data__find_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".find must not contain "+str(data__find_keys)+" properties", value=data__find, name="" + (name_prefix or "data") + ".find", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='additionalProperties')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/find-directive', 'title': "'find:' directive", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', "Can container shell-style wildcards (e.g. ``'pkg.*'``)"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='additionalProperties')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_userguide_pyproject_config_html__definitions_package_name(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (str)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='type')
+    data_any_of_count11 = 0
+    if not data_any_of_count11:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='type')
+            if isinstance(data, str):
+                if not custom_formats["python-module-name-relaxed"](data):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-module-name-relaxed", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'python-module-name-relaxed'}, rule='format')
+            data_any_of_count11 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count11:
+        try:
+            if not isinstance(data, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='type')
+            if isinstance(data, str):
+                if not custom_formats["pep561-stub-name"](data):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep561-stub-name", value=data, name="" + (name_prefix or "data") + "", definition={'type': 'string', 'format': 'pep561-stub-name'}, rule='format')
+            data_any_of_count11 += 1
+        except JsonSchemaValueException: pass
+    if not data_any_of_count11:
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " cannot be validated by any definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/package-name', 'title': 'Valid package name', 'description': 'Valid package name (importable or :pep:`561`).', 'type': 'string', 'anyOf': [{'type': 'string', 'format': 'python-module-name-relaxed'}, {'type': 'string', 'format': 'pep561-stub-name'}]}, rule='anyOf')
+    return data
+
+def validate_https___setuptools_pypa_io_en_latest_deprecated_distutils_configfile_html(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html', 'title': '``tool.distutils`` table', '$$description': ['**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``', 'subtables to configure arguments for ``distutils`` commands.', 'Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` commands via `distutils configuration files', '`_.', 'See also `the old Python docs _`.'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "global" in data_keys:
+            data_keys.remove("global")
+            data__global = data["global"]
+            if not isinstance(data__global, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".global must be object", value=data__global, name="" + (name_prefix or "data") + ".global", definition={'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}, rule='type')
+        for data_key, data_val in data.items():
+            if REGEX_PATTERNS['.+'].search(data_key):
+                if data_key in data_keys:
+                    data_keys.remove(data_key)
+                if not isinstance(data_val, (dict)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be object", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'object'}, rule='type')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='type')
+    try:
+        try:
+            data_is_dict = isinstance(data, dict)
+            if data_is_dict:
+                data__missing_keys = set(['dynamic']) - data.keys()
+                if data__missing_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, rule='required')
+                data_keys = set(data.keys())
+                if "dynamic" in data_keys:
+                    data_keys.remove("dynamic")
+                    data__dynamic = data["dynamic"]
+                    data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
+                    if data__dynamic_is_list:
+                        data__dynamic_contains = False
+                        for data__dynamic_key in data__dynamic:
+                            try:
+                                if data__dynamic_key != "version":
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be same as const definition: version", value=data__dynamic_key, name="" + (name_prefix or "data") + ".dynamic", definition={'const': 'version'}, rule='const')
+                                data__dynamic_contains = True
+                                break
+                            except JsonSchemaValueException: pass
+                        if not data__dynamic_contains:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must contain one of contains definition", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}, rule='contains')
+        except JsonSchemaValueException: pass
+        else:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must NOT match a disallowed definition", value=data, name="" + (name_prefix or "data") + "", definition={'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, rule='not')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['version']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, rule='required')
+    try:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data__missing_keys = set(['license-files']) - data.keys()
+            if data__missing_keys:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'required': ['license-files']}, rule='required')
+    except JsonSchemaValueException:
+        pass
+    else:
+        data_is_dict = isinstance(data, dict)
+        if data_is_dict:
+            data_keys = set(data.keys())
+            if "license" in data_keys:
+                data_keys.remove("license")
+                data__license = data["license"]
+                if not isinstance(data__license, (str)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string'}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data__missing_keys = set(['name']) - data.keys()
+        if data__missing_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must contain " + (str(sorted(data__missing_keys)) + " properties"), value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='required')
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='type')
+            if isinstance(data__name, str):
+                if not custom_formats["pep508-identifier"](data__name):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be pep508-identifier", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='format')
+        if "version" in data_keys:
+            data_keys.remove("version")
+            data__version = data["version"]
+            if not isinstance(data__version, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".version must be string", value=data__version, name="" + (name_prefix or "data") + ".version", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='type')
+            if isinstance(data__version, str):
+                if not custom_formats["pep440"](data__version):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".version must be pep440", value=data__version, name="" + (name_prefix or "data") + ".version", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='format')
+        if "description" in data_keys:
+            data_keys.remove("description")
+            data__description = data["description"]
+            if not isinstance(data__description, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".description must be string", value=data__description, name="" + (name_prefix or "data") + ".description", definition={'type': 'string', '$$description': ['The `summary description of the project', '`_']}, rule='type')
+        if "readme" in data_keys:
+            data_keys.remove("readme")
+            data__readme = data["readme"]
+            data__readme_one_of_count12 = 0
+            if data__readme_one_of_count12 < 2:
+                try:
+                    if not isinstance(data__readme, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be string", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, rule='type')
+                    data__readme_one_of_count12 += 1
+                except JsonSchemaValueException: pass
+            if data__readme_one_of_count12 < 2:
+                try:
+                    if not isinstance(data__readme, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be object", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}, rule='type')
+                    data__readme_any_of_count13 = 0
+                    if not data__readme_any_of_count13:
+                        try:
+                            data__readme_is_dict = isinstance(data__readme, dict)
+                            if data__readme_is_dict:
+                                data__readme__missing_keys = set(['file']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, rule='required')
+                                data__readme_keys = set(data__readme.keys())
+                                if "file" in data__readme_keys:
+                                    data__readme_keys.remove("file")
+                                    data__readme__file = data__readme["file"]
+                                    if not isinstance(data__readme__file, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.file must be string", value=data__readme__file, name="" + (name_prefix or "data") + ".readme.file", definition={'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}, rule='type')
+                            data__readme_any_of_count13 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__readme_any_of_count13:
+                        try:
+                            data__readme_is_dict = isinstance(data__readme, dict)
+                            if data__readme_is_dict:
+                                data__readme__missing_keys = set(['text']) - data__readme.keys()
+                                if data__readme__missing_keys:
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}, rule='required')
+                                data__readme_keys = set(data__readme.keys())
+                                if "text" in data__readme_keys:
+                                    data__readme_keys.remove("text")
+                                    data__readme__text = data__readme["text"]
+                                    if not isinstance(data__readme__text, (str)):
+                                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.text must be string", value=data__readme__text, name="" + (name_prefix or "data") + ".readme.text", definition={'type': 'string', 'description': 'Full text describing the project.'}, rule='type')
+                            data__readme_any_of_count13 += 1
+                        except JsonSchemaValueException: pass
+                    if not data__readme_any_of_count13:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme cannot be validated by any definition", value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, rule='anyOf')
+                    data__readme_is_dict = isinstance(data__readme, dict)
+                    if data__readme_is_dict:
+                        data__readme__missing_keys = set(['content-type']) - data__readme.keys()
+                        if data__readme__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must contain " + (str(sorted(data__readme__missing_keys)) + " properties"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}, rule='required')
+                        data__readme_keys = set(data__readme.keys())
+                        if "content-type" in data__readme_keys:
+                            data__readme_keys.remove("content-type")
+                            data__readme__contenttype = data__readme["content-type"]
+                            if not isinstance(data__readme__contenttype, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme.content-type must be string", value=data__readme__contenttype, name="" + (name_prefix or "data") + ".readme.content-type", definition={'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}, rule='type')
+                    data__readme_one_of_count12 += 1
+                except JsonSchemaValueException: pass
+            if data__readme_one_of_count12 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".readme must be valid exactly by one definition" + (" (" + str(data__readme_one_of_count12) + " matches found)"), value=data__readme, name="" + (name_prefix or "data") + ".readme", definition={'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, rule='oneOf')
+        if "requires-python" in data_keys:
+            data_keys.remove("requires-python")
+            data__requirespython = data["requires-python"]
+            if not isinstance(data__requirespython, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".requires-python must be string", value=data__requirespython, name="" + (name_prefix or "data") + ".requires-python", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, rule='type')
+            if isinstance(data__requirespython, str):
+                if not custom_formats["pep508-versionspec"](data__requirespython):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".requires-python must be pep508-versionspec", value=data__requirespython, name="" + (name_prefix or "data") + ".requires-python", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, rule='format')
+        if "license" in data_keys:
+            data_keys.remove("license")
+            data__license = data["license"]
+            data__license_one_of_count14 = 0
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be string", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='type')
+                    if isinstance(data__license, str):
+                        if not custom_formats["SPDX"](data__license):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be SPDX", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, rule='format')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='type')
+                    data__license_is_dict = isinstance(data__license, dict)
+                    if data__license_is_dict:
+                        data__license__missing_keys = set(['file']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='required')
+                        data__license_keys = set(data__license.keys())
+                        if "file" in data__license_keys:
+                            data__license_keys.remove("file")
+                            data__license__file = data__license["file"]
+                            if not isinstance(data__license__file, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.file must be string", value=data__license__file, name="" + (name_prefix or "data") + ".license.file", definition={'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}, rule='type')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 < 2:
+                try:
+                    if not isinstance(data__license, (dict)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be object", value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='type')
+                    data__license_is_dict = isinstance(data__license, dict)
+                    if data__license_is_dict:
+                        data__license__missing_keys = set(['text']) - data__license.keys()
+                        if data__license__missing_keys:
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must contain " + (str(sorted(data__license__missing_keys)) + " properties"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}, rule='required')
+                        data__license_keys = set(data__license.keys())
+                        if "text" in data__license_keys:
+                            data__license_keys.remove("text")
+                            data__license__text = data__license["text"]
+                            if not isinstance(data__license__text, (str)):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license.text must be string", value=data__license__text, name="" + (name_prefix or "data") + ".license.text", definition={'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}, rule='type')
+                    data__license_one_of_count14 += 1
+                except JsonSchemaValueException: pass
+            if data__license_one_of_count14 != 1:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license must be valid exactly by one definition" + (" (" + str(data__license_one_of_count14) + " matches found)"), value=data__license, name="" + (name_prefix or "data") + ".license", definition={'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, rule='oneOf')
+        if "license-files" in data_keys:
+            data_keys.remove("license-files")
+            data__licensefiles = data["license-files"]
+            if not isinstance(data__licensefiles, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files must be array", value=data__licensefiles, name="" + (name_prefix or "data") + ".license-files", definition={'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, rule='type')
+            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))
+            if data__licensefiles_is_list:
+                data__licensefiles_len = len(data__licensefiles)
+                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):
+                    if not isinstance(data__licensefiles_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + " must be string", value=data__licensefiles_item, name="" + (name_prefix or "data") + ".license-files[{data__licensefiles_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "authors" in data_keys:
+            data_keys.remove("authors")
+            data__authors = data["authors"]
+            if not isinstance(data__authors, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".authors must be array", value=data__authors, name="" + (name_prefix or "data") + ".authors", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, rule='type')
+            data__authors_is_list = isinstance(data__authors, (list, tuple))
+            if data__authors_is_list:
+                data__authors_len = len(data__authors)
+                for data__authors_x, data__authors_item in enumerate(data__authors):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__authors_item, custom_formats, (name_prefix or "data") + ".authors[{data__authors_x}]".format(**locals()))
+        if "maintainers" in data_keys:
+            data_keys.remove("maintainers")
+            data__maintainers = data["maintainers"]
+            if not isinstance(data__maintainers, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".maintainers must be array", value=data__maintainers, name="" + (name_prefix or "data") + ".maintainers", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, rule='type')
+            data__maintainers_is_list = isinstance(data__maintainers, (list, tuple))
+            if data__maintainers_is_list:
+                data__maintainers_len = len(data__maintainers)
+                for data__maintainers_x, data__maintainers_item in enumerate(data__maintainers):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data__maintainers_item, custom_formats, (name_prefix or "data") + ".maintainers[{data__maintainers_x}]".format(**locals()))
+        if "keywords" in data_keys:
+            data_keys.remove("keywords")
+            data__keywords = data["keywords"]
+            if not isinstance(data__keywords, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".keywords must be array", value=data__keywords, name="" + (name_prefix or "data") + ".keywords", definition={'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, rule='type')
+            data__keywords_is_list = isinstance(data__keywords, (list, tuple))
+            if data__keywords_is_list:
+                data__keywords_len = len(data__keywords)
+                for data__keywords_x, data__keywords_item in enumerate(data__keywords):
+                    if not isinstance(data__keywords_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".keywords[{data__keywords_x}]".format(**locals()) + " must be string", value=data__keywords_item, name="" + (name_prefix or "data") + ".keywords[{data__keywords_x}]".format(**locals()) + "", definition={'type': 'string'}, rule='type')
+        if "classifiers" in data_keys:
+            data_keys.remove("classifiers")
+            data__classifiers = data["classifiers"]
+            if not isinstance(data__classifiers, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers must be array", value=data__classifiers, name="" + (name_prefix or "data") + ".classifiers", definition={'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, rule='type')
+            data__classifiers_is_list = isinstance(data__classifiers, (list, tuple))
+            if data__classifiers_is_list:
+                data__classifiers_len = len(data__classifiers)
+                for data__classifiers_x, data__classifiers_item in enumerate(data__classifiers):
+                    if not isinstance(data__classifiers_item, (str)):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + " must be string", value=data__classifiers_item, name="" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, rule='type')
+                    if isinstance(data__classifiers_item, str):
+                        if not custom_formats["trove-classifier"](data__classifiers_item):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + " must be trove-classifier", value=data__classifiers_item, name="" + (name_prefix or "data") + ".classifiers[{data__classifiers_x}]".format(**locals()) + "", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, rule='format')
+        if "urls" in data_keys:
+            data_keys.remove("urls")
+            data__urls = data["urls"]
+            if not isinstance(data__urls, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls must be object", value=data__urls, name="" + (name_prefix or "data") + ".urls", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='type')
+            data__urls_is_dict = isinstance(data__urls, dict)
+            if data__urls_is_dict:
+                data__urls_keys = set(data__urls.keys())
+                for data__urls_key, data__urls_val in data__urls.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__urls_key):
+                        if data__urls_key in data__urls_keys:
+                            data__urls_keys.remove(data__urls_key)
+                        if not isinstance(data__urls_val, (str)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + " must be string", value=data__urls_val, name="" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'url'}, rule='type')
+                        if isinstance(data__urls_val, str):
+                            if not custom_formats["url"](data__urls_val):
+                                raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + " must be url", value=data__urls_val, name="" + (name_prefix or "data") + ".urls.{data__urls_key}".format(**locals()) + "", definition={'type': 'string', 'format': 'url'}, rule='format')
+                if data__urls_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".urls must not contain "+str(data__urls_keys)+" properties", value=data__urls, name="" + (name_prefix or "data") + ".urls", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='additionalProperties')
+        if "scripts" in data_keys:
+            data_keys.remove("scripts")
+            data__scripts = data["scripts"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__scripts, custom_formats, (name_prefix or "data") + ".scripts")
+        if "gui-scripts" in data_keys:
+            data_keys.remove("gui-scripts")
+            data__guiscripts = data["gui-scripts"]
+            validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__guiscripts, custom_formats, (name_prefix or "data") + ".gui-scripts")
+        if "entry-points" in data_keys:
+            data_keys.remove("entry-points")
+            data__entrypoints = data["entry-points"]
+            data__entrypoints_is_dict = isinstance(data__entrypoints, dict)
+            if data__entrypoints_is_dict:
+                data__entrypoints_keys = set(data__entrypoints.keys())
+                for data__entrypoints_key, data__entrypoints_val in data__entrypoints.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__entrypoints_key):
+                        if data__entrypoints_key in data__entrypoints_keys:
+                            data__entrypoints_keys.remove(data__entrypoints_key)
+                        validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data__entrypoints_val, custom_formats, (name_prefix or "data") + ".entry-points.{data__entrypoints_key}".format(**locals()))
+                if data__entrypoints_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must not contain "+str(data__entrypoints_keys)+" properties", value=data__entrypoints, name="" + (name_prefix or "data") + ".entry-points", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='additionalProperties')
+                data__entrypoints_len = len(data__entrypoints)
+                if data__entrypoints_len != 0:
+                    data__entrypoints_property_names = True
+                    for data__entrypoints_key in data__entrypoints:
+                        try:
+                            if isinstance(data__entrypoints_key, str):
+                                if not custom_formats["python-entrypoint-group"](data__entrypoints_key):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must be python-entrypoint-group", value=data__entrypoints_key, name="" + (name_prefix or "data") + ".entry-points", definition={'format': 'python-entrypoint-group'}, rule='format')
+                        except JsonSchemaValueException:
+                            data__entrypoints_property_names = False
+                    if not data__entrypoints_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".entry-points must be named by propertyName definition", value=data__entrypoints, name="" + (name_prefix or "data") + ".entry-points", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='propertyNames')
+        if "dependencies" in data_keys:
+            data_keys.remove("dependencies")
+            data__dependencies = data["dependencies"]
+            if not isinstance(data__dependencies, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dependencies must be array", value=data__dependencies, name="" + (name_prefix or "data") + ".dependencies", definition={'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')
+            data__dependencies_is_list = isinstance(data__dependencies, (list, tuple))
+            if data__dependencies_is_list:
+                data__dependencies_len = len(data__dependencies)
+                for data__dependencies_x, data__dependencies_item in enumerate(data__dependencies):
+                    validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__dependencies_item, custom_formats, (name_prefix or "data") + ".dependencies[{data__dependencies_x}]".format(**locals()))
+        if "optional-dependencies" in data_keys:
+            data_keys.remove("optional-dependencies")
+            data__optionaldependencies = data["optional-dependencies"]
+            if not isinstance(data__optionaldependencies, (dict)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be object", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')
+            data__optionaldependencies_is_dict = isinstance(data__optionaldependencies, dict)
+            if data__optionaldependencies_is_dict:
+                data__optionaldependencies_keys = set(data__optionaldependencies.keys())
+                for data__optionaldependencies_key, data__optionaldependencies_val in data__optionaldependencies.items():
+                    if REGEX_PATTERNS['^.+$'].search(data__optionaldependencies_key):
+                        if data__optionaldependencies_key in data__optionaldependencies_keys:
+                            data__optionaldependencies_keys.remove(data__optionaldependencies_key)
+                        if not isinstance(data__optionaldependencies_val, (list, tuple)):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}".format(**locals()) + " must be array", value=data__optionaldependencies_val, name="" + (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}".format(**locals()) + "", definition={'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')
+                        data__optionaldependencies_val_is_list = isinstance(data__optionaldependencies_val, (list, tuple))
+                        if data__optionaldependencies_val_is_list:
+                            data__optionaldependencies_val_len = len(data__optionaldependencies_val)
+                            for data__optionaldependencies_val_x, data__optionaldependencies_val_item in enumerate(data__optionaldependencies_val):
+                                validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data__optionaldependencies_val_item, custom_formats, (name_prefix or "data") + ".optional-dependencies.{data__optionaldependencies_key}[{data__optionaldependencies_val_x}]".format(**locals()))
+                if data__optionaldependencies_keys:
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must not contain "+str(data__optionaldependencies_keys)+" properties", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')
+                data__optionaldependencies_len = len(data__optionaldependencies)
+                if data__optionaldependencies_len != 0:
+                    data__optionaldependencies_property_names = True
+                    for data__optionaldependencies_key in data__optionaldependencies:
+                        try:
+                            if isinstance(data__optionaldependencies_key, str):
+                                if not custom_formats["pep508-identifier"](data__optionaldependencies_key):
+                                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be pep508-identifier", value=data__optionaldependencies_key, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'format': 'pep508-identifier'}, rule='format')
+                        except JsonSchemaValueException:
+                            data__optionaldependencies_property_names = False
+                    if not data__optionaldependencies_property_names:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".optional-dependencies must be named by propertyName definition", value=data__optionaldependencies, name="" + (name_prefix or "data") + ".optional-dependencies", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='propertyNames')
+        if "dynamic" in data_keys:
+            data_keys.remove("dynamic")
+            data__dynamic = data["dynamic"]
+            if not isinstance(data__dynamic, (list, tuple)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic must be array", value=data__dynamic, name="" + (name_prefix or "data") + ".dynamic", definition={'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}, rule='type')
+            data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))
+            if data__dynamic_is_list:
+                data__dynamic_len = len(data__dynamic)
+                for data__dynamic_x, data__dynamic_item in enumerate(data__dynamic):
+                    if data__dynamic_item not in ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']:
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + " must be one of ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']", value=data__dynamic_item, name="" + (name_prefix or "data") + ".dynamic[{data__dynamic_x}]".format(**locals()) + "", definition={'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}, rule='enum')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$schema': 'http://json-schema.org/draft-07/schema#', '$id': 'https://packaging.python.org/en/latest/specifications/pyproject-toml/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '`_', "with meaning similar to the one defined in `core metadata's Description", '`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '`_.']}, 'license': {'description': '`Project license `_.', 'oneOf': [{'type': 'string', 'description': 'An SPDX license identifier', 'format': 'SPDX'}, {'type': 'object', 'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'type': 'object', 'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '`_.']}}, 'required': ['text']}]}, 'license-files': {'description': 'Paths or globs to paths of license files', 'type': 'array', 'items': {'type': 'string'}}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'authors' of the project.", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': ["The people or organizations considered to be the 'maintainers' of the project.", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier `_.'}, '$$description': ['`Trove classifiers `_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'license-files', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'allOf': [{'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as "Required", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}}, {'if': {'required': ['license-files']}, 'then': {'properties': {'license': {'type': 'string'}}}}], 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='additionalProperties')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_dependency(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (str)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be string", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='type')
+    if isinstance(data, str):
+        if not custom_formats["pep508"](data):
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must be pep508", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='format')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_entry_point_group(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        for data_key, data_val in data.items():
+            if REGEX_PATTERNS['^.+$'].search(data_key):
+                if data_key in data_keys:
+                    data_keys.remove(data_key)
+                if not isinstance(data_val, (str)):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be string", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='type')
+                if isinstance(data_val, str):
+                    if not custom_formats["python-entrypoint-reference"](data_val):
+                        raise JsonSchemaValueException("" + (name_prefix or "data") + ".{data_key}".format(**locals()) + " must be python-entrypoint-reference", value=data_val, name="" + (name_prefix or "data") + ".{data_key}".format(**locals()) + "", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='additionalProperties')
+        data_len = len(data)
+        if data_len != 0:
+            data_property_names = True
+            for data_key in data:
+                try:
+                    if isinstance(data_key, str):
+                        if not custom_formats["python-entrypoint-name"](data_key):
+                            raise JsonSchemaValueException("" + (name_prefix or "data") + " must be python-entrypoint-name", value=data_key, name="" + (name_prefix or "data") + "", definition={'format': 'python-entrypoint-name'}, rule='format')
+                except JsonSchemaValueException:
+                    data_property_names = False
+            if not data_property_names:
+                raise JsonSchemaValueException("" + (name_prefix or "data") + " must be named by propertyName definition", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '`_', 'and `setuptools docs', '`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='propertyNames')
+    return data
+
+def validate_https___packaging_python_org_en_latest_specifications_pyproject_toml___definitions_author(data, custom_formats={}, name_prefix=None):
+    if not isinstance(data, (dict)):
+        raise JsonSchemaValueException("" + (name_prefix or "data") + " must be object", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='type')
+    data_is_dict = isinstance(data, dict)
+    if data_is_dict:
+        data_keys = set(data.keys())
+        if "name" in data_keys:
+            data_keys.remove("name")
+            data__name = data["name"]
+            if not isinstance(data__name, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".name must be string", value=data__name, name="" + (name_prefix or "data") + ".name", definition={'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, rule='type')
+        if "email" in data_keys:
+            data_keys.remove("email")
+            data__email = data["email"]
+            if not isinstance(data__email, (str)):
+                raise JsonSchemaValueException("" + (name_prefix or "data") + ".email must be string", value=data__email, name="" + (name_prefix or "data") + ".email", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='type')
+            if isinstance(data__email, str):
+                if not REGEX_PATTERNS["idn-email_re_pattern"].match(data__email):
+                    raise JsonSchemaValueException("" + (name_prefix or "data") + ".email must be idn-email", value=data__email, name="" + (name_prefix or "data") + ".email", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='format')
+        if data_keys:
+            raise JsonSchemaValueException("" + (name_prefix or "data") + " must not contain "+str(data_keys)+" properties", value=data, name="" + (name_prefix or "data") + "", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://peps.python.org/pep-0621/#authors-maintainers', 'type': 'object', 'additionalProperties': False, 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='additionalProperties')
+    return data
diff --git a/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/formats.py b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/formats.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cf4a465ef0156deef5bd4d1fc02350e40ff2fe5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/config/_validate_pyproject/formats.py
@@ -0,0 +1,402 @@
+"""
+The functions in this module are used to validate schemas with the
+`format JSON Schema keyword
+`_.
+
+The correspondence is given by replacing the ``_`` character in the name of the
+function with a ``-`` to obtain the format name and vice versa.
+"""
+
+import builtins
+import logging
+import os
+import re
+import string
+import typing
+from itertools import chain as _chain
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+_logger = logging.getLogger(__name__)
+
+# -------------------------------------------------------------------------------------
+# PEP 440
+
+VERSION_PATTERN = r"""
+    v?
+    (?:
+        (?:(?P[0-9]+)!)?                           # epoch
+        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
+        (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?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
+"""
+
+VERSION_REGEX = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.X | re.I)
+
+
+def pep440(version: str) -> bool:
+    """See :ref:`PyPA's version specification `
+    (initially introduced in :pep:`440`).
+    """
+    return VERSION_REGEX.match(version) is not None
+
+
+# -------------------------------------------------------------------------------------
+# PEP 508
+
+PEP508_IDENTIFIER_PATTERN = r"([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])"
+PEP508_IDENTIFIER_REGEX = re.compile(f"^{PEP508_IDENTIFIER_PATTERN}$", re.I)
+
+
+def pep508_identifier(name: str) -> bool:
+    """See :ref:`PyPA's name specification `
+    (initially introduced in :pep:`508#names`).
+    """
+    return PEP508_IDENTIFIER_REGEX.match(name) is not None
+
+
+try:
+    try:
+        from packaging import requirements as _req
+    except ImportError:  # pragma: no cover
+        # let's try setuptools vendored version
+        from setuptools._vendor.packaging import (  # type: ignore[no-redef]
+            requirements as _req,
+        )
+
+    def pep508(value: str) -> bool:
+        """See :ref:`PyPA's dependency specifiers `
+        (initially introduced in :pep:`508`).
+        """
+        try:
+            _req.Requirement(value)
+            return True
+        except _req.InvalidRequirement:
+            return False
+
+except ImportError:  # pragma: no cover
+    _logger.warning(
+        "Could not find an installation of `packaging`. Requirements, dependencies and "
+        "versions might not be validated. "
+        "To enforce validation, please install `packaging`."
+    )
+
+    def pep508(value: str) -> bool:
+        return True
+
+
+def pep508_versionspec(value: str) -> bool:
+    """Expression that can be used to specify/lock versions (including ranges)
+    See ``versionspec`` in :ref:`PyPA's dependency specifiers
+    ` (initially introduced in :pep:`508`).
+    """
+    if any(c in value for c in (";", "]", "@")):
+        # In PEP 508:
+        # conditional markers, extras and URL specs are not included in the
+        # versionspec
+        return False
+    # Let's pretend we have a dependency called `requirement` with the given
+    # version spec, then we can reuse the pep508 function for validation:
+    return pep508(f"requirement{value}")
+
+
+# -------------------------------------------------------------------------------------
+# PEP 517
+
+
+def pep517_backend_reference(value: str) -> bool:
+    """See PyPA's specification for defining build-backend references
+    introduced in :pep:`517#source-trees`.
+
+    This is similar to an entry-point reference (e.g., ``package.module:object``).
+    """
+    module, _, obj = value.partition(":")
+    identifiers = (i.strip() for i in _chain(module.split("."), obj.split(".")))
+    return all(python_identifier(i) for i in identifiers if i)
+
+
+# -------------------------------------------------------------------------------------
+# Classifiers - PEP 301
+
+
+def _download_classifiers() -> str:
+    import ssl
+    from email.message import Message
+    from urllib.request import urlopen
+
+    url = "https://pypi.org/pypi?:action=list_classifiers"
+    context = ssl.create_default_context()
+    with urlopen(url, context=context) as response:  # noqa: S310 (audit URLs)
+        headers = Message()
+        headers["content_type"] = response.getheader("content-type", "text/plain")
+        return response.read().decode(headers.get_param("charset", "utf-8"))  # type: ignore[no-any-return]
+
+
+class _TroveClassifier:
+    """The ``trove_classifiers`` package is the official way of validating classifiers,
+    however this package might not be always available.
+    As a workaround we can still download a list from PyPI.
+    We also don't want to be over strict about it, so simply skipping silently is an
+    option (classifiers will be validated anyway during the upload to PyPI).
+    """
+
+    downloaded: typing.Union[None, "Literal[False]", typing.Set[str]]
+    """
+    None => not cached yet
+    False => unavailable
+    set => cached values
+    """
+
+    def __init__(self) -> None:
+        self.downloaded = None
+        self._skip_download = False
+        self.__name__ = "trove_classifier"  # Emulate a public function
+
+    def _disable_download(self) -> None:
+        # This is a private API. Only setuptools has the consent of using it.
+        self._skip_download = True
+
+    def __call__(self, value: str) -> bool:
+        if self.downloaded is False or self._skip_download is True:
+            return True
+
+        if os.getenv("NO_NETWORK") or os.getenv("VALIDATE_PYPROJECT_NO_NETWORK"):
+            self.downloaded = False
+            msg = (
+                "Install ``trove-classifiers`` to ensure proper validation. "
+                "Skipping download of classifiers list from PyPI (NO_NETWORK)."
+            )
+            _logger.debug(msg)
+            return True
+
+        if self.downloaded is None:
+            msg = (
+                "Install ``trove-classifiers`` to ensure proper validation. "
+                "Meanwhile a list of classifiers will be downloaded from PyPI."
+            )
+            _logger.debug(msg)
+            try:
+                self.downloaded = set(_download_classifiers().splitlines())
+            except Exception:
+                self.downloaded = False
+                _logger.debug("Problem with download, skipping validation")
+                return True
+
+        return value in self.downloaded or value.lower().startswith("private ::")
+
+
+try:
+    from trove_classifiers import classifiers as _trove_classifiers
+
+    def trove_classifier(value: str) -> bool:
+        """See https://pypi.org/classifiers/"""
+        return value in _trove_classifiers or value.lower().startswith("private ::")
+
+except ImportError:  # pragma: no cover
+    trove_classifier = _TroveClassifier()
+
+
+# -------------------------------------------------------------------------------------
+# Stub packages - PEP 561
+
+
+def pep561_stub_name(value: str) -> bool:
+    """Name of a directory containing type stubs.
+    It must follow the name scheme ``-stubs`` as defined in
+    :pep:`561#stub-only-packages`.
+    """
+    top, *children = value.split(".")
+    if not top.endswith("-stubs"):
+        return False
+    return python_module_name(".".join([top[: -len("-stubs")], *children]))
+
+
+# -------------------------------------------------------------------------------------
+# Non-PEP related
+
+
+def url(value: str) -> bool:
+    """Valid URL (validation uses :obj:`urllib.parse`).
+    For maximum compatibility please make sure to include a ``scheme`` prefix
+    in your URL (e.g. ``http://``).
+    """
+    from urllib.parse import urlparse
+
+    try:
+        parts = urlparse(value)
+        if not parts.scheme:
+            _logger.warning(
+                "For maximum compatibility please make sure to include a "
+                "`scheme` prefix in your URL (e.g. 'http://'). "
+                f"Given value: {value}"
+            )
+            if not (value.startswith("/") or value.startswith("\\") or "@" in value):
+                parts = urlparse(f"http://{value}")
+
+        return bool(parts.scheme and parts.netloc)
+    except Exception:
+        return False
+
+
+# https://packaging.python.org/specifications/entry-points/
+ENTRYPOINT_PATTERN = r"[^\[\s=]([^=]*[^\s=])?"
+ENTRYPOINT_REGEX = re.compile(f"^{ENTRYPOINT_PATTERN}$", re.I)
+RECOMMEDED_ENTRYPOINT_PATTERN = r"[\w.-]+"
+RECOMMEDED_ENTRYPOINT_REGEX = re.compile(f"^{RECOMMEDED_ENTRYPOINT_PATTERN}$", re.I)
+ENTRYPOINT_GROUP_PATTERN = r"\w+(\.\w+)*"
+ENTRYPOINT_GROUP_REGEX = re.compile(f"^{ENTRYPOINT_GROUP_PATTERN}$", re.I)
+
+
+def python_identifier(value: str) -> bool:
+    """Can be used as identifier in Python.
+    (Validation uses :obj:`str.isidentifier`).
+    """
+    return value.isidentifier()
+
+
+def python_qualified_identifier(value: str) -> bool:
+    """
+    Python "dotted identifier", i.e. a sequence of :obj:`python_identifier`
+    concatenated with ``"."`` (e.g.: ``package.module.submodule``).
+    """
+    if value.startswith(".") or value.endswith("."):
+        return False
+    return all(python_identifier(m) for m in value.split("."))
+
+
+def python_module_name(value: str) -> bool:
+    """Module name that can be used in an ``import``-statement in Python.
+    See :obj:`python_qualified_identifier`.
+    """
+    return python_qualified_identifier(value)
+
+
+def python_module_name_relaxed(value: str) -> bool:
+    """Similar to :obj:`python_module_name`, but relaxed to also accept
+    dash characters (``-``) and cover special cases like ``pip-run``.
+
+    It is recommended, however, that beginners avoid dash characters,
+    as they require advanced knowledge about Python internals.
+
+    The following are disallowed:
+
+    * names starting/ending in dashes,
+    * names ending in ``-stubs`` (potentially collide with :obj:`pep561_stub_name`).
+    """
+    if value.startswith("-") or value.endswith("-"):
+        return False
+    if value.endswith("-stubs"):
+        return False  # Avoid collision with PEP 561
+    return python_module_name(value.replace("-", "_"))
+
+
+def python_entrypoint_group(value: str) -> bool:
+    """See ``Data model > group`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    return ENTRYPOINT_GROUP_REGEX.match(value) is not None
+
+
+def python_entrypoint_name(value: str) -> bool:
+    """See ``Data model > name`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    if not ENTRYPOINT_REGEX.match(value):
+        return False
+    if not RECOMMEDED_ENTRYPOINT_REGEX.match(value):
+        msg = f"Entry point `{value}` does not follow recommended pattern: "
+        msg += RECOMMEDED_ENTRYPOINT_PATTERN
+        _logger.warning(msg)
+    return True
+
+
+def python_entrypoint_reference(value: str) -> bool:
+    """Reference to a Python object using in the format::
+
+        importable.module:object.attr
+
+    See ``Data model >object reference`` in the :ref:`PyPA's entry-points specification
+    `.
+    """
+    module, _, rest = value.partition(":")
+    if "[" in rest:
+        obj, _, extras_ = rest.partition("[")
+        if extras_.strip()[-1] != "]":
+            return False
+        extras = (x.strip() for x in extras_.strip(string.whitespace + "[]").split(","))
+        if not all(pep508_identifier(e) for e in extras):
+            return False
+        _logger.warning(f"`{value}` - using extras for entry points is not recommended")
+    else:
+        obj = rest
+
+    module_parts = module.split(".")
+    identifiers = _chain(module_parts, obj.split(".")) if rest else iter(module_parts)
+    return all(python_identifier(i.strip()) for i in identifiers)
+
+
+def uint8(value: builtins.int) -> bool:
+    r"""Unsigned 8-bit integer (:math:`0 \leq x < 2^8`)"""
+    return 0 <= value < 2**8
+
+
+def uint16(value: builtins.int) -> bool:
+    r"""Unsigned 16-bit integer (:math:`0 \leq x < 2^{16}`)"""
+    return 0 <= value < 2**16
+
+
+def uint(value: builtins.int) -> bool:
+    r"""Unsigned 64-bit integer (:math:`0 \leq x < 2^{64}`)"""
+    return 0 <= value < 2**64
+
+
+def int(value: builtins.int) -> bool:
+    r"""Signed 64-bit integer (:math:`-2^{63} \leq x < 2^{63}`)"""
+    return -(2**63) <= value < 2**63
+
+
+try:
+    from packaging import licenses as _licenses
+
+    def SPDX(value: str) -> bool:
+        """See :ref:`PyPA's License-Expression specification
+        ` (added in :pep:`639`).
+        """
+        try:
+            _licenses.canonicalize_license_expression(value)
+            return True
+        except _licenses.InvalidLicenseExpression:
+            return False
+
+except ImportError:  # pragma: no cover
+    _logger.warning(
+        "Could not find an up-to-date installation of `packaging`. "
+        "License expressions might not be validated. "
+        "To enforce validation, please install `packaging>=24.2`."
+    )
+
+    def SPDX(value: str) -> bool:
+        return True
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/__init__.py b/python_embeded/Lib/site-packages/setuptools/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb70bfb7115a2a94a8b942b31cafc3a550f0c005
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/__init__.py
@@ -0,0 +1,13 @@
+import locale
+import sys
+
+import pytest
+
+__all__ = ['fail_on_ascii']
+
+if sys.version_info >= (3, 11):
+    locale_encoding = locale.getencoding()
+else:
+    locale_encoding = locale.getpreferredencoding(False)
+is_ascii = locale_encoding == 'ANSI_X3.4-1968'
+fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale")
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/compat/__init__.py b/python_embeded/Lib/site-packages/setuptools/tests/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/compat/py39.py b/python_embeded/Lib/site-packages/setuptools/tests/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdb9dac1fa3f121a634082515d1a305fc09793c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/compat/py39.py
@@ -0,0 +1,3 @@
+from jaraco.test.cpython import from_test_support, try_import
+
+os_helper = try_import('os_helper') or from_test_support('can_symlink')
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/__init__.py b/python_embeded/Lib/site-packages/setuptools/tests/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/__init__.py b/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a16423f448e7773f5e6dc9b365efe80f40a778
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/__init__.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+import re
+import time
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.request import urlopen
+
+__all__ = ["DOWNLOAD_DIR", "retrieve_file", "output_file", "urls_from_file"]
+
+
+NAME_REMOVE = ("http://", "https://", "github.com/", "/raw/")
+DOWNLOAD_DIR = Path(__file__).parent
+
+
+# ----------------------------------------------------------------------
+# Please update ./preload.py accordingly when modifying this file
+# ----------------------------------------------------------------------
+
+
+def output_file(url: str, download_dir: Path = DOWNLOAD_DIR) -> Path:
+    file_name = url.strip()
+    for part in NAME_REMOVE:
+        file_name = file_name.replace(part, '').strip().strip('/:').strip()
+    return Path(download_dir, re.sub(r"[^\-_\.\w\d]+", "_", file_name))
+
+
+def retrieve_file(url: str, download_dir: Path = DOWNLOAD_DIR, wait: float = 5) -> Path:
+    path = output_file(url, download_dir)
+    if path.exists():
+        print(f"Skipping {url} (already exists: {path})")
+    else:
+        download_dir.mkdir(exist_ok=True, parents=True)
+        print(f"Downloading {url} to {path}")
+        try:
+            download(url, path)
+        except HTTPError:
+            time.sleep(wait)  # wait a few seconds and try again.
+            download(url, path)
+    return path
+
+
+def urls_from_file(list_file: Path) -> list[str]:
+    """``list_file`` should be a text file where each line corresponds to a URL to
+    download.
+    """
+    print(f"file: {list_file}")
+    content = list_file.read_text(encoding="utf-8")
+    return [url for url in content.splitlines() if not url.startswith("#")]
+
+
+def download(url: str, dest: Path):
+    with urlopen(url) as f:
+        data = f.read()
+
+    with open(dest, "wb") as f:
+        f.write(data)
+
+    assert Path(dest).exists()
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/preload.py b/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/preload.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eeb5dd75d3dcb375cee5acaf11ad385084bff5a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/downloads/preload.py
@@ -0,0 +1,18 @@
+"""This file can be used to preload files needed for testing.
+
+For example you can use::
+
+    cd setuptools/tests/config
+    python -m downloads.preload setupcfg_examples.txt
+
+to make sure the `setup.cfg` examples are downloaded before starting the tests.
+"""
+
+import sys
+from pathlib import Path
+
+from . import retrieve_file, urls_from_file
+
+if __name__ == "__main__":
+    urls = urls_from_file(Path(sys.argv[1]))
+    list(map(retrieve_file, urls))
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/setupcfg_examples.txt b/python_embeded/Lib/site-packages/setuptools/tests/config/setupcfg_examples.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6aab887ff1fe631d97f1abea90a8448040746a12
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/setupcfg_examples.txt
@@ -0,0 +1,22 @@
+# ====================================================================
+# Some popular packages that use setup.cfg (and others not so popular)
+# Reference: https://hugovk.github.io/top-pypi-packages/
+# ====================================================================
+https://github.com/pypa/setuptools/raw/52c990172fec37766b3566679724aa8bf70ae06d/setup.cfg
+https://github.com/pypa/wheel/raw/0acd203cd896afec7f715aa2ff5980a403459a3b/setup.cfg
+https://github.com/python/importlib_metadata/raw/2f05392ca980952a6960d82b2f2d2ea10aa53239/setup.cfg
+https://github.com/jaraco/skeleton/raw/d9008b5c510cd6969127a6a2ab6f832edddef296/setup.cfg
+https://github.com/jaraco/zipp/raw/700d3a96390e970b6b962823bfea78b4f7e1c537/setup.cfg
+https://github.com/pallets/jinja/raw/7d72eb7fefb7dce065193967f31f805180508448/setup.cfg
+https://github.com/tkem/cachetools/raw/2fd87a94b8d3861d80e9e4236cd480bfdd21c90d/setup.cfg
+https://github.com/aio-libs/aiohttp/raw/5e0e6b7080f2408d5f1dd544c0e1cf88378b7b10/setup.cfg
+https://github.com/pallets/flask/raw/9486b6cf57bd6a8a261f67091aca8ca78eeec1e3/setup.cfg
+https://github.com/pallets/click/raw/6411f425fae545f42795665af4162006b36c5e4a/setup.cfg
+https://github.com/sqlalchemy/sqlalchemy/raw/533f5718904b620be8d63f2474229945d6f8ba5d/setup.cfg
+https://github.com/pytest-dev/pluggy/raw/461ef63291d13589c4e21aa182cd1529257e9a0a/setup.cfg
+https://github.com/pytest-dev/pytest/raw/c7be96dae487edbd2f55b561b31b68afac1dabe6/setup.cfg
+https://github.com/platformdirs/platformdirs/raw/7b7852128dd6f07511b618d6edea35046bd0c6ff/setup.cfg
+https://github.com/pandas-dev/pandas/raw/bc17343f934a33dc231c8c74be95d8365537c376/setup.cfg
+https://github.com/django/django/raw/4e249d11a6e56ca8feb4b055b681cec457ef3a3d/setup.cfg
+https://github.com/pyscaffold/pyscaffold/raw/de7aa5dc059fbd04307419c667cc4961bc9df4b8/setup.cfg
+https://github.com/pypa/virtualenv/raw/f92eda6e3da26a4d28c2663ffb85c4960bdb990c/setup.cfg
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py b/python_embeded/Lib/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..489fd98e26710e74d66204b6f51c2523586aaa04
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
@@ -0,0 +1,772 @@
+"""Make sure that applying the configuration from pyproject.toml is equivalent to
+applying a similar configuration from setup.cfg
+
+To run these tests offline, please have a look on ``./downloads/preload.py``
+"""
+
+from __future__ import annotations
+
+import io
+import re
+import tarfile
+from inspect import cleandoc
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+from ini2toml.api import LiteTranslator
+from packaging.metadata import Metadata
+
+import setuptools  # noqa: F401 # ensure monkey patch to metadata
+from setuptools._static import is_static
+from setuptools.command.egg_info import write_requirements
+from setuptools.config import expand, pyprojecttoml, setupcfg
+from setuptools.config._apply_pyprojecttoml import _MissingDynamic, _some_attrgetter
+from setuptools.dist import Distribution
+from setuptools.errors import InvalidConfigError, RemovedConfigError
+from setuptools.warnings import InformationOnly, SetuptoolsDeprecationWarning
+
+from .downloads import retrieve_file, urls_from_file
+
+HERE = Path(__file__).parent
+EXAMPLES_FILE = "setupcfg_examples.txt"
+
+
+def makedist(path, **attrs):
+    return Distribution({"src_root": path, **attrs})
+
+
+def _mock_expand_patterns(patterns, *_, **__):
+    """
+    Allow comparing the given patterns for 2 dist objects.
+    We need to strip special chars to avoid errors when validating.
+    """
+    return [re.sub("[^a-z0-9]+", "", p, flags=re.I) or "empty" for p in patterns]
+
+
+@pytest.mark.parametrize("url", urls_from_file(HERE / EXAMPLES_FILE))
+@pytest.mark.filterwarnings("ignore")
+@pytest.mark.uses_network
+def test_apply_pyproject_equivalent_to_setupcfg(url, monkeypatch, tmp_path):
+    monkeypatch.setattr(expand, "read_attr", Mock(return_value="0.0.1"))
+    monkeypatch.setattr(
+        Distribution, "_expand_patterns", Mock(side_effect=_mock_expand_patterns)
+    )
+    setupcfg_example = retrieve_file(url)
+    pyproject_example = Path(tmp_path, "pyproject.toml")
+    setupcfg_text = setupcfg_example.read_text(encoding="utf-8")
+    toml_config = LiteTranslator().translate(setupcfg_text, "setup.cfg")
+    pyproject_example.write_text(toml_config, encoding="utf-8")
+
+    dist_toml = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject_example)
+    dist_cfg = setupcfg.apply_configuration(makedist(tmp_path), setupcfg_example)
+
+    pkg_info_toml = core_metadata(dist_toml)
+    pkg_info_cfg = core_metadata(dist_cfg)
+    assert pkg_info_toml == pkg_info_cfg
+
+    if any(getattr(d, "license_files", None) for d in (dist_toml, dist_cfg)):
+        assert set(dist_toml.license_files) == set(dist_cfg.license_files)
+
+    if any(getattr(d, "entry_points", None) for d in (dist_toml, dist_cfg)):
+        print(dist_cfg.entry_points)
+        ep_toml = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_toml.entry_points.items()
+        }
+        ep_cfg = {
+            (k, *sorted(i.replace(" ", "") for i in v))
+            for k, v in dist_cfg.entry_points.items()
+        }
+        assert ep_toml == ep_cfg
+
+    if any(getattr(d, "package_data", None) for d in (dist_toml, dist_cfg)):
+        pkg_data_toml = {(k, *sorted(v)) for k, v in dist_toml.package_data.items()}
+        pkg_data_cfg = {(k, *sorted(v)) for k, v in dist_cfg.package_data.items()}
+        assert pkg_data_toml == pkg_data_cfg
+
+    if any(getattr(d, "data_files", None) for d in (dist_toml, dist_cfg)):
+        data_files_toml = {(k, *sorted(v)) for k, v in dist_toml.data_files}
+        data_files_cfg = {(k, *sorted(v)) for k, v in dist_cfg.data_files}
+        assert data_files_toml == data_files_cfg
+
+    assert set(dist_toml.install_requires) == set(dist_cfg.install_requires)
+    if any(getattr(d, "extras_require", None) for d in (dist_toml, dist_cfg)):
+        extra_req_toml = {(k, *sorted(v)) for k, v in dist_toml.extras_require.items()}
+        extra_req_cfg = {(k, *sorted(v)) for k, v in dist_cfg.extras_require.items()}
+        assert extra_req_toml == extra_req_cfg
+
+
+PEP621_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+description = "Lovely Spam! Wonderful Spam!"
+readme = "README.rst"
+requires-python = ">=3.8"
+license-files = ["LICENSE.txt"]  # Updated to be PEP 639 compliant
+keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"]
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Brett Cannon", email = "brett@python.org"},
+  {name = "John X. Ãørçeč", email = "john@utf8.org"},
+  {name = "Γαμα קּ 東", email = "gama@utf8.org"},
+]
+classifiers = [
+  "Development Status :: 4 - Beta",
+  "Programming Language :: Python"
+]
+
+dependencies = [
+  "httpx",
+  "gidgethub[httpx]>4.0.0",
+  "django>2.1; os_name != 'nt'",
+  "django>2.0; os_name == 'nt'"
+]
+
+[project.optional-dependencies]
+test = [
+  "pytest < 5.0.0",
+  "pytest-cov[all]"
+]
+
+[project.urls]
+homepage = "http://example.com"
+documentation = "http://readthedocs.org"
+repository = "http://github.com"
+changelog = "http://github.com/me/spam/blob/master/CHANGELOG.md"
+
+[project.scripts]
+spam-cli = "spam:main_cli"
+
+[project.gui-scripts]
+spam-gui = "spam:main_gui"
+
+[project.entry-points."spam.magical"]
+tomatoes = "spam:main_tomatoes"
+"""
+
+PEP621_INTERNATIONAL_EMAIL_EXAMPLE = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+maintainers = [
+  {name = "Степан Бандера", email = "криївка@оун-упа.укр"},
+]
+"""
+
+PEP621_EXAMPLE_SCRIPT = """
+def main_cli(): pass
+def main_gui(): pass
+def main_tomatoes(): pass
+"""
+
+PEP639_LICENSE_TEXT = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = {text = "MIT"}
+"""
+
+PEP639_LICENSE_EXPRESSION = """\
+[project]
+name = "spam"
+version = "2020.0.0"
+authors = [
+  {email = "hi@pradyunsg.me"},
+  {name = "Tzu-Ping Chung"}
+]
+license = "mit or apache-2.0"  # should be normalized in metadata
+classifiers = [
+    "Development Status :: 5 - Production/Stable",
+    "Programming Language :: Python",
+]
+"""
+
+
+def _pep621_example_project(
+    tmp_path,
+    readme="README.rst",
+    pyproject_text=PEP621_EXAMPLE,
+):
+    pyproject = tmp_path / "pyproject.toml"
+    text = pyproject_text
+    replacements = {'readme = "README.rst"': f'readme = "{readme}"'}
+    for orig, subst in replacements.items():
+        text = text.replace(orig, subst)
+    pyproject.write_text(text, encoding="utf-8")
+
+    (tmp_path / readme).write_text("hello world", encoding="utf-8")
+    (tmp_path / "LICENSE.txt").write_text("--- LICENSE stub ---", encoding="utf-8")
+    (tmp_path / "spam.py").write_text(PEP621_EXAMPLE_SCRIPT, encoding="utf-8")
+    return pyproject
+
+
+def test_pep621_example(tmp_path):
+    """Make sure the example in PEP 621 works"""
+    pyproject = _pep621_example_project(tmp_path)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert set(dist.metadata.license_files) == {"LICENSE.txt"}
+
+
+@pytest.mark.parametrize(
+    ("readme", "ctype"),
+    [
+        ("Readme.txt", "text/plain"),
+        ("readme.md", "text/markdown"),
+        ("text.rst", "text/x-rst"),
+    ],
+)
+def test_readme_content_type(tmp_path, readme, ctype):
+    pyproject = _pep621_example_project(tmp_path, readme)
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type == ctype
+
+
+def test_undefined_content_type(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README.tex")
+    with pytest.raises(ValueError, match="Undefined content type for README.tex"):
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+def test_no_explicit_content_type_for_missing_extension(tmp_path):
+    pyproject = _pep621_example_project(tmp_path, "README")
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.long_description_content_type is None
+
+
+@pytest.mark.parametrize(
+    ("pyproject_text", "expected_maintainers_meta_value"),
+    (
+        pytest.param(
+            PEP621_EXAMPLE,
+            (
+                'Brett Cannon , "John X. Ãørçeč" , '
+                'Γαμα קּ 東 '
+            ),
+            id='non-international-emails',
+        ),
+        pytest.param(
+            PEP621_INTERNATIONAL_EMAIL_EXAMPLE,
+            'Степан Бандера <криївка@оун-упа.укр>',
+            marks=pytest.mark.xfail(
+                reason="CPython's `email.headerregistry.Address` only supports "
+                'RFC 5322, as of Nov 10, 2022 and latest Python 3.11.0',
+                strict=True,
+            ),
+            id='international-email',
+        ),
+    ),
+)
+def test_utf8_maintainer_in_metadata(  # issue-3663
+    expected_maintainers_meta_value,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.maintainer_email == expected_maintainers_meta_value
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert f"Maintainer-email: {expected_maintainers_meta_value}" in content
+
+
+@pytest.mark.parametrize(
+    (
+        'pyproject_text',
+        'license',
+        'license_expression',
+        'content_str',
+        'not_content_str',
+    ),
+    (
+        pytest.param(
+            PEP639_LICENSE_TEXT,
+            'MIT',
+            None,
+            'License: MIT',
+            'License-Expression: ',
+            id='license-text',
+            marks=[
+                pytest.mark.filterwarnings(
+                    "ignore:.project.license. as a TOML table is deprecated",
+                )
+            ],
+        ),
+        pytest.param(
+            PEP639_LICENSE_EXPRESSION,
+            None,
+            'MIT OR Apache-2.0',
+            'License-Expression: MIT OR Apache-2.0',
+            'License: ',
+            id='license-expression',
+        ),
+    ),
+)
+def test_license_in_metadata(
+    license,
+    license_expression,
+    content_str,
+    not_content_str,
+    pyproject_text,
+    tmp_path,
+):
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        pyproject_text=pyproject_text,
+    )
+    dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+    assert dist.metadata.license == license
+    assert dist.metadata.license_expression == license_expression
+    pkg_file = tmp_path / "PKG-FILE"
+    with open(pkg_file, "w", encoding="utf-8") as fh:
+        dist.metadata.write_pkg_file(fh)
+    content = pkg_file.read_text(encoding="utf-8")
+    assert "Metadata-Version: 2.4" in content
+    assert content_str in content
+    assert not_content_str not in content
+
+
+def test_license_classifier_with_license_expression(tmp_path):
+    text = PEP639_LICENSE_EXPRESSION.rsplit("\n", 2)[0]
+    pyproject = _pep621_example_project(
+        tmp_path,
+        "README",
+        f"{text}\n    \"License :: OSI Approved :: MIT License\"\n]",
+    )
+    msg = "License classifiers have been superseded by license expressions"
+    with pytest.raises(InvalidConfigError, match=msg) as exc:
+        pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    assert "License :: OSI Approved :: MIT License" in str(exc.value)
+
+
+def test_license_classifier_without_license_expression(tmp_path):
+    text = """\
+    [project]
+    name = "spam"
+    version = "2020.0.0"
+    license = {text = "mit or apache-2.0"}
+    classifiers = ["License :: OSI Approved :: MIT License"]
+    """
+    pyproject = _pep621_example_project(tmp_path, "README", text)
+
+    msg1 = "License classifiers are deprecated(?:.|\n)*MIT License"
+    msg2 = ".project.license. as a TOML table is deprecated"
+    with (
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+        pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+    ):
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    # Check license classifier is still included
+    assert dist.metadata.get_classifiers() == ["License :: OSI Approved :: MIT License"]
+
+
+class TestLicenseFiles:
+    def base_pyproject(
+        self,
+        tmp_path,
+        additional_text="",
+        license_toml='license = {file = "LICENSE.txt"}\n',
+    ):
+        text = PEP639_LICENSE_EXPRESSION
+
+        # Sanity-check
+        assert 'license = "mit or apache-2.0"' in text
+        assert 'license-files' not in text
+        assert "[tool.setuptools]" not in text
+
+        text = re.sub(
+            r"(license = .*)\n",
+            license_toml,
+            text,
+            count=1,
+        )
+        assert license_toml in text  # sanity check
+        text = f"{text}\n{additional_text}\n"
+        pyproject = _pep621_example_project(tmp_path, "README", pyproject_text=text)
+        return pyproject
+
+    def base_pyproject_license_pep639(self, tmp_path, additional_text=""):
+        return self.base_pyproject(
+            tmp_path,
+            additional_text=additional_text,
+            license_toml='license = "licenseref-Proprietary"'
+            '\nlicense-files = ["_FILE*"]\n',
+        )
+
+    def test_both_license_and_license_files_defined(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject(tmp_path, setuptools_config)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        # Would normally match the `license_files` patterns, but we want to exclude it
+        # by being explicit. On the other hand, contents should be added to `license`
+        license = tmp_path / "LICENSE.txt"
+        license.write_text("LicenseRef-Proprietary\n", encoding="utf-8")
+
+        msg1 = "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'"
+        msg2 = ".project.license. as a TOML table is deprecated"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg2),
+        ):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license == "LicenseRef-Proprietary\n"
+
+    def test_both_license_and_license_files_defined_pep639(self, tmp_path):
+        # Set license and license-files
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+
+        (tmp_path / "_FILE.txt").touch()
+        (tmp_path / "_FILE.rst").touch()
+
+        msg = "Normalizing.*LicenseRef"
+        with pytest.warns(InformationOnly, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert set(dist.metadata.license_files) == {"_FILE.rst", "_FILE.txt"}
+        assert dist.metadata.license is None
+        assert dist.metadata.license_expression == "LicenseRef-Proprietary"
+
+    def test_license_files_defined_twice(self, tmp_path):
+        # Set project.license-files and tools.setuptools.license-files
+        setuptools_config = '[tool.setuptools]\nlicense-files = ["_FILE*"]'
+        pyproject = self.base_pyproject_license_pep639(tmp_path, setuptools_config)
+
+        msg = "'project.license-files' is defined already. Remove 'tool.setuptools.license-files'"
+        with pytest.raises(InvalidConfigError, match=msg):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    def test_default_patterns(self, tmp_path):
+        setuptools_config = '[tool.setuptools]\nzip-safe = false'
+        # ^ used just to trigger section validation
+        pyproject = self.base_pyproject(tmp_path, setuptools_config, license_toml="")
+
+        license_files = "LICENCE-a.html COPYING-abc.txt AUTHORS-xyz NOTICE,def".split()
+
+        for fname in license_files:
+            (tmp_path / fname).write_text(f"{fname}\n", encoding="utf-8")
+
+        dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert (tmp_path / "LICENSE.txt").exists()  # from base example
+        assert set(dist.metadata.license_files) == {*license_files, "LICENSE.txt"}
+
+    def test_missing_patterns(self, tmp_path):
+        pyproject = self.base_pyproject_license_pep639(tmp_path)
+        assert list(tmp_path.glob("_FILE*")) == []  # sanity check
+
+        msg1 = "Cannot find any files for the given pattern.*"
+        msg2 = "Normalizing 'licenseref-Proprietary' to 'LicenseRef-Proprietary'"
+        with (
+            pytest.warns(SetuptoolsDeprecationWarning, match=msg1),
+            pytest.warns(InformationOnly, match=msg2),
+        ):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+    def test_deprecated_file_expands_to_text(self, tmp_path):
+        """Make sure the old example with ``license = {text = ...}`` works"""
+
+        assert 'license-files = ["LICENSE.txt"]' in PEP621_EXAMPLE  # sanity check
+        text = PEP621_EXAMPLE.replace(
+            'license-files = ["LICENSE.txt"]',
+            'license = {file = "LICENSE.txt"}',
+        )
+        pyproject = _pep621_example_project(tmp_path, pyproject_text=text)
+
+        msg = ".project.license. as a TOML table is deprecated"
+        with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
+            dist = pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+        assert dist.metadata.license == "--- LICENSE stub ---"
+        assert set(dist.metadata.license_files) == {"LICENSE.txt"}  # auto-filled
+
+
+class TestPyModules:
+    # https://github.com/pypa/setuptools/issues/4316
+
+    def dist(self, name):
+        toml_config = f"""
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        py-modules = [{name!r}]
+        """
+        pyproject = Path("pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        return pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+
+    @pytest.mark.parametrize("module", ["pip-run", "abc-d.λ-xyz-e"])
+    def test_valid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        assert module in self.dist(module).py_modules
+
+    @pytest.mark.parametrize("module", ["pip run", "-pip-run", "pip-run-stubs"])
+    def test_invalid_module_name(self, tmp_path, monkeypatch, module):
+        monkeypatch.chdir(tmp_path)
+        with pytest.raises(ValueError, match="py-modules"):
+            self.dist(module).py_modules
+
+
+class TestExtModules:
+    def test_pyproject_sets_attribute(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        pyproject = Path("pyproject.toml")
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        [tool.setuptools]
+        ext-modules = [
+          {name = "my.ext", sources = ["hello.c", "world.c"]}
+        ]
+        """
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        with pytest.warns(pyprojecttoml._ExperimentalConfiguration):
+            dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert len(dist.ext_modules) == 1
+        assert dist.ext_modules[0].name == "my.ext"
+        assert set(dist.ext_modules[0].sources) == {"hello.c", "world.c"}
+
+
+class TestDeprecatedFields:
+    def test_namespace_packages(self, tmp_path):
+        pyproject = tmp_path / "pyproject.toml"
+        config = """
+        [project]
+        name = "myproj"
+        version = "42"
+        [tool.setuptools]
+        namespace-packages = ["myproj.pkg"]
+        """
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.raises(RemovedConfigError, match="namespace-packages"):
+            pyprojecttoml.apply_configuration(makedist(tmp_path), pyproject)
+
+
+class TestPresetField:
+    def pyproject(self, tmp_path, dynamic, extra_content=""):
+        content = f"[project]\nname = 'proj'\ndynamic = {dynamic!r}\n"
+        if "version" not in dynamic:
+            content += "version = '42'\n"
+        file = tmp_path / "pyproject.toml"
+        file.write_text(content + extra_content, encoding="utf-8")
+        return file
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("license_expression", "license", "MIT"),
+            pytest.param(
+                *("license", "license", "Not SPDX"),
+                marks=[pytest.mark.filterwarnings("ignore:.*license. overwritten")],
+            ),
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+            ("entry_points", "scripts", {"console_scripts": ["foobar=foobar:main"]}),
+            ("entry_points", "gui-scripts", {"gui_scripts": ["bazquux=bazquux:main"]}),
+            pytest.param(
+                *("install_requires", "dependencies", ["six"]),
+                marks=[
+                    pytest.mark.filterwarnings("ignore:.*install_requires. overwritten")
+                ],
+            ),
+        ],
+    )
+    def test_not_listed_in_dynamic(self, tmp_path, attr, field, value):
+        """Setuptools cannot set a field if not listed in ``dynamic``"""
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, **{attr: value})
+        msg = re.compile(f"defined outside of `pyproject.toml`:.*{field}", re.S)
+        with pytest.warns(_MissingDynamic, match=msg):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert not dist_value
+
+    @pytest.mark.parametrize(
+        ("attr", "field", "value"),
+        [
+            ("license_expression", "license", "MIT"),
+            ("install_requires", "dependencies", []),
+            ("extras_require", "optional-dependencies", {}),
+            ("install_requires", "dependencies", ["six"]),
+            ("classifiers", "classifiers", ["Private :: Classifier"]),
+        ],
+    )
+    def test_listed_in_dynamic(self, tmp_path, attr, field, value):
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, **{attr: value})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        dist_value = _some_attrgetter(f"metadata.{attr}", attr)(dist)
+        assert dist_value == value
+
+    def test_license_files_exempt_from_dynamic(self, monkeypatch, tmp_path):
+        """
+        license-file is currently not considered in the context of dynamic.
+        As per 2025-02-19, https://packaging.python.org/en/latest/specifications/pyproject-toml/#license-files
+        allows setuptools to fill-in `license-files` the way it sees fit:
+
+        > If the license-files key is not defined, tools can decide how to handle license files.
+        > For example they can choose not to include any files or use their own
+        > logic to discover the appropriate files in the distribution.
+
+        Using license_files from setup.py to fill-in the value is in accordance
+        with this rule.
+        """
+        monkeypatch.chdir(tmp_path)
+        pyproject = self.pyproject(tmp_path, [])
+        dist = makedist(tmp_path, license_files=["LIC*"])
+        (tmp_path / "LIC1").write_text("42", encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert dist.metadata.license_files == ["LIC1"]
+
+    def test_warning_overwritten_dependencies(self, tmp_path):
+        src = "[project]\nname='pkg'\nversion='0.1'\ndependencies=['click']\n"
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(src, encoding="utf-8")
+        dist = makedist(tmp_path, install_requires=["wheel"])
+        with pytest.warns(match="`install_requires` overwritten"):
+            dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "wheel" not in dist.install_requires
+
+    def test_optional_dependencies_dont_remove_env_markers(self, tmp_path):
+        """
+        Internally setuptools converts dependencies with markers to "extras".
+        If ``install_requires`` is given by ``setup.py``, we have to ensure that
+        applying ``optional-dependencies`` does not overwrite the mandatory
+        dependencies with markers (see #3204).
+        """
+        # If setuptools replace its internal mechanism that uses `requires.txt`
+        # this test has to be rewritten to adapt accordingly
+        extra = "\n[project.optional-dependencies]\nfoo = ['bar>1']\n"
+        pyproject = self.pyproject(tmp_path, ["dependencies"], extra)
+        install_req = ['importlib-resources (>=3.0.0) ; python_version < "3.7"']
+        dist = makedist(tmp_path, install_requires=install_req)
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert "foo" in dist.extras_require
+        egg_info = dist.get_command_obj("egg_info")
+        write_requirements(egg_info, tmp_path, tmp_path / "requires.txt")
+        reqs = (tmp_path / "requires.txt").read_text(encoding="utf-8")
+        assert "importlib-resources" in reqs
+        assert "bar" in reqs
+        assert ':python_version < "3.7"' in reqs
+
+    @pytest.mark.parametrize(
+        ("field", "group"),
+        [("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")],
+    )
+    @pytest.mark.filterwarnings("error")
+    def test_scripts_dont_require_dynamic_entry_points(self, tmp_path, field, group):
+        # Issue 3862
+        pyproject = self.pyproject(tmp_path, [field])
+        dist = makedist(tmp_path, entry_points={group: ["foobar=foobar:main"]})
+        dist = pyprojecttoml.apply_configuration(dist, pyproject)
+        assert group in dist.entry_points
+
+
+class TestMeta:
+    def test_example_file_in_sdist(self, setuptools_sdist):
+        """Meta test to ensure tests can run from sdist"""
+        with tarfile.open(setuptools_sdist) as tar:
+            assert any(name.endswith(EXAMPLES_FILE) for name in tar.getnames())
+
+
+class TestInteropCommandLineParsing:
+    def test_version(self, tmp_path, monkeypatch, capsys):
+        # See pypa/setuptools#4047
+        # This test can be removed once the CLI interface of setup.py is removed
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        opts = {"script_args": ["--version"]}
+        dist = pyprojecttoml.apply_configuration(Distribution(opts), pyproject)
+        dist.parse_command_line()  # <-- there should be no exception here.
+        captured = capsys.readouterr()
+        assert "42.0" in captured.out
+
+
+class TestStaticConfig:
+    def test_mark_static_fields(self, tmp_path, monkeypatch):
+        monkeypatch.chdir(tmp_path)
+        toml_config = """
+        [project]
+        name = "test"
+        version = "42.0"
+        dependencies = ["hello"]
+        keywords = ["world"]
+        classifiers = ["private :: hello world"]
+        [tool.setuptools]
+        obsoletes = ["abcd"]
+        provides = ["abcd"]
+        platforms = ["abcd"]
+        """
+        pyproject = Path(tmp_path, "pyproject.toml")
+        pyproject.write_text(cleandoc(toml_config), encoding="utf-8")
+        dist = pyprojecttoml.apply_configuration(Distribution({}), pyproject)
+        assert is_static(dist.install_requires)
+        assert is_static(dist.metadata.keywords)
+        assert is_static(dist.metadata.classifiers)
+        assert is_static(dist.metadata.obsoletes)
+        assert is_static(dist.metadata.provides)
+        assert is_static(dist.metadata.platforms)
+
+
+# --- Auxiliary Functions ---
+
+
+def core_metadata(dist) -> str:
+    with io.StringIO() as buffer:
+        dist.metadata.write_pkg_file(buffer)
+        pkg_file_txt = buffer.getvalue()
+
+    # Make sure core metadata is valid
+    Metadata.from_email(pkg_file_txt, validate=True)  # can raise exceptions
+
+    skip_prefixes: tuple[str, ...] = ()
+    skip_lines = set()
+    # ---- DIFF NORMALISATION ----
+    # PEP 621 is very particular about author/maintainer metadata conversion, so skip
+    skip_prefixes += ("Author:", "Author-email:", "Maintainer:", "Maintainer-email:")
+    # May be redundant with Home-page
+    skip_prefixes += ("Project-URL: Homepage,", "Home-page:")
+    # May be missing in original (relying on default) but backfilled in the TOML
+    skip_prefixes += ("Description-Content-Type:",)
+    # Remove empty lines
+    skip_lines.add("")
+
+    result = []
+    for line in pkg_file_txt.splitlines():
+        if line.startswith(skip_prefixes) or line in skip_lines:
+            continue
+        result.append(line + "\n")
+
+    return "".join(result)
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/test_expand.py b/python_embeded/Lib/site-packages/setuptools/tests/config/test_expand.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5710ec63d7d9d4ed7b709203bb2fc4b512f2093
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/test_expand.py
@@ -0,0 +1,247 @@
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from setuptools._static import is_static
+from setuptools.config import expand
+from setuptools.discovery import find_package_path
+
+from distutils.errors import DistutilsOptionError
+
+
+def write_files(files, root_dir):
+    for file, content in files.items():
+        path = root_dir / file
+        path.parent.mkdir(exist_ok=True, parents=True)
+        path.write_text(content, encoding="utf-8")
+
+
+def test_glob_relative(tmp_path, monkeypatch):
+    files = {
+        "dir1/dir2/dir3/file1.txt",
+        "dir1/dir2/file2.txt",
+        "dir1/file3.txt",
+        "a.ini",
+        "b.ini",
+        "dir1/c.ini",
+        "dir1/dir2/a.ini",
+    }
+
+    write_files({k: "" for k in files}, tmp_path)
+    patterns = ["**/*.txt", "[ab].*", "**/[ac].ini"]
+    monkeypatch.chdir(tmp_path)
+    assert set(expand.glob_relative(patterns)) == files
+    # Make sure the same APIs work outside cwd
+    assert set(expand.glob_relative(patterns, tmp_path)) == files
+
+
+def test_read_files(tmp_path, monkeypatch):
+    dir_ = tmp_path / "dir_"
+    (tmp_path / "_dir").mkdir(exist_ok=True)
+    (tmp_path / "a.txt").touch()
+    files = {"a.txt": "a", "dir1/b.txt": "b", "dir1/dir2/c.txt": "c"}
+    write_files(files, dir_)
+
+    secrets = Path(str(dir_) + "secrets")
+    secrets.mkdir(exist_ok=True)
+    write_files({"secrets.txt": "secret keys"}, secrets)
+
+    with monkeypatch.context() as m:
+        m.chdir(dir_)
+        assert expand.read_files(list(files)) == "a\nb\nc"
+
+        cannot_access_msg = r"Cannot access '.*\.\..a\.txt'"
+        with pytest.raises(DistutilsOptionError, match=cannot_access_msg):
+            expand.read_files(["../a.txt"])
+
+        cannot_access_secrets_msg = r"Cannot access '.*secrets\.txt'"
+        with pytest.raises(DistutilsOptionError, match=cannot_access_secrets_msg):
+            expand.read_files(["../dir_secrets/secrets.txt"])
+
+    # Make sure the same APIs work outside cwd
+    assert expand.read_files(list(files), dir_) == "a\nb\nc"
+    with pytest.raises(DistutilsOptionError, match=cannot_access_msg):
+        expand.read_files(["../a.txt"], dir_)
+
+
+class TestReadAttr:
+    @pytest.mark.parametrize(
+        "example",
+        [
+            # No cookie means UTF-8:
+            b"__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
+            # If a cookie is present, honor it:
+            b"# -*- coding: utf-8 -*-\n__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
+            b"# -*- coding: latin1 -*-\n__version__ = '\xe9'\nraise SystemExit(1)\n",
+        ],
+    )
+    def test_read_attr_encoding_cookie(self, example, tmp_path):
+        (tmp_path / "mod.py").write_bytes(example)
+        assert expand.read_attr('mod.__version__', root_dir=tmp_path) == 'é'
+
+    def test_read_attr(self, tmp_path, monkeypatch):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": "VERSION = '0.1.1'",
+            "pkg/sub/mod.py": (
+                "VALUES = {'a': 0, 'b': {42}, 'c': (0, 1, 1)}\nraise SystemExit(1)"
+            ),
+        }
+        write_files(files, tmp_path)
+
+        with monkeypatch.context() as m:
+            m.chdir(tmp_path)
+            # Make sure it can read the attr statically without evaluating the module
+            version = expand.read_attr('pkg.sub.VERSION')
+            values = expand.read_attr('lib.mod.VALUES', {'lib': 'pkg/sub'})
+
+        assert version == '0.1.1'
+        assert is_static(values)
+
+        assert values['a'] == 0
+        assert values['b'] == {42}
+        assert is_static(values)
+
+        # Make sure the same APIs work outside cwd
+        assert expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path) == '0.1.1'
+        values = expand.read_attr('lib.mod.VALUES', {'lib': 'pkg/sub'}, tmp_path)
+        assert values['c'] == (0, 1, 1)
+
+    @pytest.mark.parametrize(
+        "example",
+        [
+            "VERSION: str\nVERSION = '0.1.1'\nraise SystemExit(1)\n",
+            "VERSION: str = '0.1.1'\nraise SystemExit(1)\n",
+        ],
+    )
+    def test_read_annotated_attr(self, tmp_path, example):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": example,
+        }
+        write_files(files, tmp_path)
+        # Make sure this attribute can be read statically
+        version = expand.read_attr('pkg.sub.VERSION', root_dir=tmp_path)
+        assert version == '0.1.1'
+        assert is_static(version)
+
+    @pytest.mark.parametrize(
+        "example",
+        [
+            "VERSION = (lambda: '0.1.1')()\n",
+            "def fn(): return '0.1.1'\nVERSION = fn()\n",
+            "VERSION: str = (lambda: '0.1.1')()\n",
+        ],
+    )
+    def test_read_dynamic_attr(self, tmp_path, monkeypatch, example):
+        files = {
+            "pkg/__init__.py": "",
+            "pkg/sub/__init__.py": example,
+        }
+        write_files(files, tmp_path)
+        monkeypatch.chdir(tmp_path)
+        version = expand.read_attr('pkg.sub.VERSION')
+        assert version == '0.1.1'
+        assert not is_static(version)
+
+    def test_import_order(self, tmp_path):
+        """
+        Sometimes the import machinery will import the parent package of a nested
+        module, which triggers side-effects and might create problems (see issue #3176)
+
+        ``read_attr`` should bypass these limitations by resolving modules statically
+        (via ast.literal_eval).
+        """
+        files = {
+            "src/pkg/__init__.py": "from .main import func\nfrom .about import version",
+            "src/pkg/main.py": "import super_complicated_dep\ndef func(): return 42",
+            "src/pkg/about.py": "version = '42'",
+        }
+        write_files(files, tmp_path)
+        attr_desc = "pkg.about.version"
+        package_dir = {"": "src"}
+        # `import super_complicated_dep` should not run, otherwise the build fails
+        assert expand.read_attr(attr_desc, package_dir, tmp_path) == "42"
+
+
+@pytest.mark.parametrize(
+    ("package_dir", "file", "module", "return_value"),
+    [
+        ({"": "src"}, "src/pkg/main.py", "pkg.main", 42),
+        ({"pkg": "lib"}, "lib/main.py", "pkg.main", 13),
+        ({}, "single_module.py", "single_module", 70),
+        ({}, "flat_layout/pkg.py", "flat_layout.pkg", 836),
+    ],
+)
+def test_resolve_class(monkeypatch, tmp_path, package_dir, file, module, return_value):
+    monkeypatch.setattr(sys, "modules", {})  # reproducibility
+    files = {file: f"class Custom:\n    def testing(self): return {return_value}"}
+    write_files(files, tmp_path)
+    cls = expand.resolve_class(f"{module}.Custom", package_dir, tmp_path)
+    assert cls().testing() == return_value
+
+
+@pytest.mark.parametrize(
+    ("args", "pkgs"),
+    [
+        ({"where": ["."], "namespaces": False}, {"pkg", "other"}),
+        ({"where": [".", "dir1"], "namespaces": False}, {"pkg", "other", "dir2"}),
+        ({"namespaces": True}, {"pkg", "other", "dir1", "dir1.dir2"}),
+        ({}, {"pkg", "other", "dir1", "dir1.dir2"}),  # default value for `namespaces`
+    ],
+)
+def test_find_packages(tmp_path, args, pkgs):
+    files = {
+        "pkg/__init__.py",
+        "other/__init__.py",
+        "dir1/dir2/__init__.py",
+    }
+    write_files({k: "" for k in files}, tmp_path)
+
+    package_dir = {}
+    kwargs = {"root_dir": tmp_path, "fill_package_dir": package_dir, **args}
+    where = kwargs.get("where", ["."])
+    assert set(expand.find_packages(**kwargs)) == pkgs
+    for pkg in pkgs:
+        pkg_path = find_package_path(pkg, package_dir, tmp_path)
+        assert os.path.exists(pkg_path)
+
+    # Make sure the same APIs work outside cwd
+    where = [
+        str((tmp_path / p).resolve()).replace(os.sep, "/")  # ensure posix-style paths
+        for p in args.pop("where", ["."])
+    ]
+
+    assert set(expand.find_packages(where=where, **args)) == pkgs
+
+
+@pytest.mark.parametrize(
+    ("files", "where", "expected_package_dir"),
+    [
+        (["pkg1/__init__.py", "pkg1/other.py"], ["."], {}),
+        (["pkg1/__init__.py", "pkg2/__init__.py"], ["."], {}),
+        (["src/pkg1/__init__.py", "src/pkg1/other.py"], ["src"], {"": "src"}),
+        (["src/pkg1/__init__.py", "src/pkg2/__init__.py"], ["src"], {"": "src"}),
+        (
+            ["src1/pkg1/__init__.py", "src2/pkg2/__init__.py"],
+            ["src1", "src2"],
+            {"pkg1": "src1/pkg1", "pkg2": "src2/pkg2"},
+        ),
+        (
+            ["src/pkg1/__init__.py", "pkg2/__init__.py"],
+            ["src", "."],
+            {"pkg1": "src/pkg1"},
+        ),
+    ],
+)
+def test_fill_package_dir(tmp_path, files, where, expected_package_dir):
+    write_files({k: "" for k in files}, tmp_path)
+    pkg_dir = {}
+    kwargs = {"root_dir": tmp_path, "fill_package_dir": pkg_dir, "namespaces": False}
+    pkgs = expand.find_packages(where=where, **kwargs)
+    assert set(pkg_dir.items()) == set(expected_package_dir.items())
+    for pkg in pkgs:
+        pkg_path = find_package_path(pkg, pkg_dir, tmp_path)
+        assert os.path.exists(pkg_path)
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml.py b/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..db40fcd23da137dfb2f4ddde7ffb722193ee83e2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml.py
@@ -0,0 +1,396 @@
+import re
+from configparser import ConfigParser
+from inspect import cleandoc
+
+import jaraco.path
+import pytest
+import tomli_w
+from path import Path
+
+import setuptools  # noqa: F401 # force distutils.core to be patched
+from setuptools.config.pyprojecttoml import (
+    _ToolsTypoInMetadata,
+    apply_configuration,
+    expand_configuration,
+    read_configuration,
+    validate,
+)
+from setuptools.dist import Distribution
+from setuptools.errors import OptionError
+
+import distutils.core
+
+EXAMPLE = """
+[project]
+name = "myproj"
+keywords = ["some", "key", "words"]
+dynamic = ["version", "readme"]
+requires-python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
+dependencies = [
+    'importlib-metadata>=0.12;python_version<"3.8"',
+    'importlib-resources>=1.0;python_version<"3.7"',
+    'pathlib2>=2.3.3,<3;python_version < "3.4" and sys.platform != "win32"',
+]
+
+[project.optional-dependencies]
+docs = [
+    "sphinx>=3",
+    "sphinx-argparse>=0.2.5",
+    "sphinx-rtd-theme>=0.4.3",
+]
+testing = [
+    "pytest>=1",
+    "coverage>=3,<5",
+]
+
+[project.scripts]
+exec = "pkg.__main__:exec"
+
+[build-system]
+requires = ["setuptools", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools]
+package-dir = {"" = "src"}
+zip-safe = true
+platforms = ["any"]
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.setuptools.cmdclass]
+sdist = "pkg.mod.CustomSdist"
+
+[tool.setuptools.dynamic.version]
+attr = "pkg.__version__.VERSION"
+
+[tool.setuptools.dynamic.readme]
+file = ["README.md"]
+content-type = "text/markdown"
+
+[tool.setuptools.package-data]
+"*" = ["*.txt"]
+
+[tool.setuptools.data-files]
+"data" = ["_files/*.txt"]
+
+[tool.distutils.sdist]
+formats = "gztar"
+
+[tool.distutils.bdist_wheel]
+universal = true
+"""
+
+
+def create_example(path, pkg_root):
+    files = {
+        "pyproject.toml": EXAMPLE,
+        "README.md": "hello world",
+        "_files": {
+            "file.txt": "",
+        },
+    }
+    packages = {
+        "pkg": {
+            "__init__.py": "",
+            "mod.py": "class CustomSdist: pass",
+            "__version__.py": "VERSION = (3, 10)",
+            "__main__.py": "def exec(): print('hello')",
+        },
+    }
+
+    assert pkg_root  # Meta-test: cannot be empty string.
+
+    if pkg_root == ".":
+        files = {**files, **packages}
+        # skip other files: flat-layout will raise error for multi-package dist
+    else:
+        # Use this opportunity to ensure namespaces are discovered
+        files[pkg_root] = {**packages, "other": {"nested": {"__init__.py": ""}}}
+
+    jaraco.path.build(files, prefix=path)
+
+
+def verify_example(config, path, pkg_root):
+    pyproject = path / "pyproject.toml"
+    pyproject.write_text(tomli_w.dumps(config), encoding="utf-8")
+    expanded = expand_configuration(config, path)
+    expanded_project = expanded["project"]
+    assert read_configuration(pyproject, expand=True) == expanded
+    assert expanded_project["version"] == "3.10"
+    assert expanded_project["readme"]["text"] == "hello world"
+    assert "packages" in expanded["tool"]["setuptools"]
+    if pkg_root == ".":
+        # Auto-discovery will raise error for multi-package dist
+        assert set(expanded["tool"]["setuptools"]["packages"]) == {"pkg"}
+    else:
+        assert set(expanded["tool"]["setuptools"]["packages"]) == {
+            "pkg",
+            "other",
+            "other.nested",
+        }
+    assert expanded["tool"]["setuptools"]["include-package-data"] is True
+    assert "" in expanded["tool"]["setuptools"]["package-data"]
+    assert "*" not in expanded["tool"]["setuptools"]["package-data"]
+    assert expanded["tool"]["setuptools"]["data-files"] == [
+        ("data", ["_files/file.txt"])
+    ]
+
+
+def test_read_configuration(tmp_path):
+    create_example(tmp_path, "src")
+    pyproject = tmp_path / "pyproject.toml"
+
+    config = read_configuration(pyproject, expand=False)
+    assert config["project"].get("version") is None
+    assert config["project"].get("readme") is None
+
+    verify_example(config, tmp_path, "src")
+
+
+@pytest.mark.parametrize(
+    ("pkg_root", "opts"),
+    [
+        (".", {}),
+        ("src", {}),
+        ("lib", {"packages": {"find": {"where": ["lib"]}}}),
+    ],
+)
+def test_discovered_package_dir_with_attr_directive_in_config(tmp_path, pkg_root, opts):
+    create_example(tmp_path, pkg_root)
+
+    pyproject = tmp_path / "pyproject.toml"
+
+    config = read_configuration(pyproject, expand=False)
+    assert config["project"].get("version") is None
+    assert config["project"].get("readme") is None
+    config["tool"]["setuptools"].pop("packages", None)
+    config["tool"]["setuptools"].pop("package-dir", None)
+
+    config["tool"]["setuptools"].update(opts)
+    verify_example(config, tmp_path, pkg_root)
+
+
+ENTRY_POINTS = {
+    "console_scripts": {"a": "mod.a:func"},
+    "gui_scripts": {"b": "mod.b:func"},
+    "other": {"c": "mod.c:func [extra]"},
+}
+
+
+class TestEntryPoints:
+    def write_entry_points(self, tmp_path):
+        entry_points = ConfigParser()
+        entry_points.read_dict(ENTRY_POINTS)
+        with open(tmp_path / "entry-points.txt", "w", encoding="utf-8") as f:
+            entry_points.write(f)
+
+    def pyproject(self, dynamic=None):
+        project = {"dynamic": dynamic or ["scripts", "gui-scripts", "entry-points"]}
+        tool = {"dynamic": {"entry-points": {"file": "entry-points.txt"}}}
+        return {"project": project, "tool": {"setuptools": tool}}
+
+    def test_all_listed_in_dynamic(self, tmp_path):
+        self.write_entry_points(tmp_path)
+        expanded = expand_configuration(self.pyproject(), tmp_path)
+        expanded_project = expanded["project"]
+        assert len(expanded_project["scripts"]) == 1
+        assert expanded_project["scripts"]["a"] == "mod.a:func"
+        assert len(expanded_project["gui-scripts"]) == 1
+        assert expanded_project["gui-scripts"]["b"] == "mod.b:func"
+        assert len(expanded_project["entry-points"]) == 1
+        assert expanded_project["entry-points"]["other"]["c"] == "mod.c:func [extra]"
+
+    @pytest.mark.parametrize("missing_dynamic", ("scripts", "gui-scripts"))
+    def test_scripts_not_listed_in_dynamic(self, tmp_path, missing_dynamic):
+        self.write_entry_points(tmp_path)
+        dynamic = {"scripts", "gui-scripts", "entry-points"} - {missing_dynamic}
+
+        msg = f"defined outside of `pyproject.toml`:.*{missing_dynamic}"
+        with pytest.raises(OptionError, match=re.compile(msg, re.S)):
+            expand_configuration(self.pyproject(dynamic), tmp_path)
+
+
+class TestClassifiers:
+    def test_dynamic(self, tmp_path):
+        # Let's create a project example that has dynamic classifiers
+        # coming from a txt file.
+        create_example(tmp_path, "src")
+        classifiers = cleandoc(
+            """
+            Framework :: Flask
+            Programming Language :: Haskell
+            """
+        )
+        (tmp_path / "classifiers.txt").write_text(classifiers, encoding="utf-8")
+
+        pyproject = tmp_path / "pyproject.toml"
+        config = read_configuration(pyproject, expand=False)
+        dynamic = config["project"]["dynamic"]
+        config["project"]["dynamic"] = list({*dynamic, "classifiers"})
+        dynamic_config = config["tool"]["setuptools"]["dynamic"]
+        dynamic_config["classifiers"] = {"file": "classifiers.txt"}
+
+        # When the configuration is expanded,
+        # each line of the file should be an different classifier.
+        validate(config, pyproject)
+        expanded = expand_configuration(config, tmp_path)
+
+        assert set(expanded["project"]["classifiers"]) == {
+            "Framework :: Flask",
+            "Programming Language :: Haskell",
+        }
+
+    def test_dynamic_without_config(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["classifiers"]
+        """
+
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.raises(OptionError, match="No configuration .* .classifiers."):
+            read_configuration(pyproject)
+
+    def test_dynamic_readme_from_setup_script_args(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["readme"]
+        """
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        dist = Distribution(attrs={"long_description": "42"})
+        # No error should occur because of missing `readme`
+        dist = apply_configuration(dist, pyproject)
+        assert dist.metadata.long_description == "42"
+
+    def test_dynamic_without_file(self, tmp_path):
+        config = """
+        [project]
+        name = "myproj"
+        version = '42'
+        dynamic = ["classifiers"]
+
+        [tool.setuptools.dynamic]
+        classifiers = {file = ["classifiers.txt"]}
+        """
+
+        pyproject = tmp_path / "pyproject.toml"
+        pyproject.write_text(cleandoc(config), encoding="utf-8")
+        with pytest.warns(UserWarning, match="File .*classifiers.txt. cannot be found"):
+            expanded = read_configuration(pyproject)
+        assert "classifiers" not in expanded["project"]
+
+
+@pytest.mark.parametrize(
+    "example",
+    (
+        """
+        [project]
+        name = "myproj"
+        version = "1.2"
+
+        [my-tool.that-disrespect.pep518]
+        value = 42
+        """,
+    ),
+)
+def test_ignore_unrelated_config(tmp_path, example):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
+
+    # Make sure no error is raised due to 3rd party configs in pyproject.toml
+    assert read_configuration(pyproject) is not None
+
+
+@pytest.mark.parametrize(
+    ("example", "error_msg"),
+    [
+        (
+            """
+            [project]
+            name = "myproj"
+            version = "1.2"
+            requires = ['pywin32; platform_system=="Windows"' ]
+            """,
+            "configuration error: .project. must not contain ..requires.. properties",
+        ),
+    ],
+)
+def test_invalid_example(tmp_path, example, error_msg):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(example), encoding="utf-8")
+
+    pattern = re.compile(f"invalid pyproject.toml.*{error_msg}.*", re.M | re.S)
+    with pytest.raises(ValueError, match=pattern):
+        read_configuration(pyproject)
+
+
+@pytest.mark.parametrize("config", ("", "[tool.something]\nvalue = 42"))
+def test_empty(tmp_path, config):
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(config, encoding="utf-8")
+
+    # Make sure no error is raised
+    assert read_configuration(pyproject) == {}
+
+
+@pytest.mark.parametrize("config", ("[project]\nname = 'myproj'\nversion='42'\n",))
+def test_include_package_data_by_default(tmp_path, config):
+    """Builds with ``pyproject.toml`` should consider ``include-package-data=True`` as
+    default.
+    """
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(config, encoding="utf-8")
+
+    config = read_configuration(pyproject)
+    assert config["tool"]["setuptools"]["include-package-data"] is True
+
+
+def test_include_package_data_in_setuppy(tmp_path):
+    """Builds with ``pyproject.toml`` should consider ``include_package_data`` set in
+    ``setup.py``.
+
+    See https://github.com/pypa/setuptools/issues/3197#issuecomment-1079023889
+    """
+    files = {
+        "pyproject.toml": "[project]\nname = 'myproj'\nversion='42'\n",
+        "setup.py": "__import__('setuptools').setup(include_package_data=False)",
+    }
+    jaraco.path.build(files, prefix=tmp_path)
+
+    with Path(tmp_path):
+        dist = distutils.core.run_setup("setup.py", {}, stop_after="config")
+
+    assert dist.get_name() == "myproj"
+    assert dist.get_version() == "42"
+    assert dist.include_package_data is False
+
+
+def test_warn_tools_typo(tmp_path):
+    """Test that the common ``tools.setuptools`` typo in ``pyproject.toml`` issues a warning
+
+    See https://github.com/pypa/setuptools/issues/4150
+    """
+    config = """
+    [build-system]
+    requires = ["setuptools"]
+    build-backend = "setuptools.build_meta"
+
+    [project]
+    name = "myproj"
+    version = '42'
+
+    [tools.setuptools]
+    packages = ["package"]
+    """
+
+    pyproject = tmp_path / "pyproject.toml"
+    pyproject.write_text(cleandoc(config), encoding="utf-8")
+
+    with pytest.warns(_ToolsTypoInMetadata):
+        read_configuration(pyproject)
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py b/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
new file mode 100644
index 0000000000000000000000000000000000000000..e42f28ffaaf5270a74fe9f03885b75bb91858030
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
@@ -0,0 +1,109 @@
+from inspect import cleandoc
+
+import pytest
+from jaraco import path
+
+from setuptools.config.pyprojecttoml import apply_configuration
+from setuptools.dist import Distribution
+from setuptools.warnings import SetuptoolsWarning
+
+
+def test_dynamic_dependencies(tmp_path):
+    files = {
+        "requirements.txt": "six\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["dependencies"]
+
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
+
+            [tool.setuptools.dynamic.dependencies]
+            file = ["requirements.txt"]
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
+    dist = Distribution()
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
+    assert dist.install_requires == ["six"]
+
+
+def test_dynamic_optional_dependencies(tmp_path):
+    files = {
+        "requirements-docs.txt": "sphinx\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
+
+            [tool.setuptools.dynamic.optional-dependencies.docs]
+            file = ["requirements-docs.txt"]
+
+            [build-system]
+            requires = ["setuptools", "wheel"]
+            build-backend = "setuptools.build_meta"
+            """
+        ),
+    }
+    path.build(files, prefix=tmp_path)
+    dist = Distribution()
+    dist = apply_configuration(dist, tmp_path / "pyproject.toml")
+    assert dist.extras_require == {"docs": ["sphinx"]}
+
+
+def test_mixed_dynamic_optional_dependencies(tmp_path):
+    """
+    Test that if PEP 621 was loosened to allow mixing of dynamic and static
+    configurations in the case of fields containing sub-fields (groups),
+    things would work out.
+    """
+    files = {
+        "requirements-images.txt": "pillow~=42.0\n  # comment\n",
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            dynamic = ["optional-dependencies"]
+
+            [project.optional-dependencies]
+            docs = ["sphinx"]
+
+            [tool.setuptools.dynamic.optional-dependencies.images]
+            file = ["requirements-images.txt"]
+            """
+        ),
+    }
+
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
+    with pytest.raises(ValueError, match="project.optional-dependencies"):
+        apply_configuration(Distribution(), pyproject)
+
+
+def test_mixed_extras_require_optional_dependencies(tmp_path):
+    files = {
+        "pyproject.toml": cleandoc(
+            """
+            [project]
+            name = "myproj"
+            version = "1.0"
+            optional-dependencies.docs = ["sphinx"]
+            """
+        ),
+    }
+
+    path.build(files, prefix=tmp_path)
+    pyproject = tmp_path / "pyproject.toml"
+
+    with pytest.warns(SetuptoolsWarning, match=".extras_require. overwritten"):
+        dist = Distribution({"extras_require": {"hello": ["world"]}})
+        dist = apply_configuration(dist, pyproject)
+        assert dist.extras_require == {"docs": ["sphinx"]}
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/config/test_setupcfg.py b/python_embeded/Lib/site-packages/setuptools/tests/config/test_setupcfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..61af99044742b46ec99ad1d38f34f576908f3e68
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/config/test_setupcfg.py
@@ -0,0 +1,980 @@
+import configparser
+import contextlib
+import inspect
+import re
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+import pytest
+from packaging.requirements import InvalidRequirement
+
+from setuptools.config.setupcfg import ConfigHandler, Target, read_configuration
+from setuptools.dist import Distribution, _Distribution
+from setuptools.warnings import SetuptoolsDeprecationWarning
+
+from ..textwrap import DALS
+
+from distutils.errors import DistutilsFileError, DistutilsOptionError
+
+
+class ErrConfigHandler(ConfigHandler[Target]):
+    """Erroneous handler. Fails to implement required methods."""
+
+    section_prefix = "**err**"
+
+
+def make_package_dir(name, base_dir, ns=False):
+    dir_package = base_dir
+    for dir_name in name.split('/'):
+        dir_package = dir_package.mkdir(dir_name)
+    init_file = None
+    if not ns:
+        init_file = dir_package.join('__init__.py')
+        init_file.write('')
+    return dir_package, init_file
+
+
+def fake_env(
+    tmpdir, setup_cfg, setup_py=None, encoding='ascii', package_path='fake_package'
+):
+    if setup_py is None:
+        setup_py = 'from setuptools import setup\nsetup()\n'
+
+    tmpdir.join('setup.py').write(setup_py)
+    config = tmpdir.join('setup.cfg')
+    config.write(setup_cfg.encode(encoding), mode='wb')
+
+    package_dir, init_file = make_package_dir(package_path, tmpdir)
+
+    init_file.write(
+        'VERSION = (1, 2, 3)\n'
+        '\n'
+        'VERSION_MAJOR = 1'
+        '\n'
+        'def get_version():\n'
+        '    return [3, 4, 5, "dev"]\n'
+        '\n'
+    )
+
+    return package_dir, config
+
+
+@contextlib.contextmanager
+def get_dist(tmpdir, kwargs_initial=None, parse=True):
+    kwargs_initial = kwargs_initial or {}
+
+    with tmpdir.as_cwd():
+        dist = Distribution(kwargs_initial)
+        dist.script_name = 'setup.py'
+        parse and dist.parse_config_files()
+
+        yield dist
+
+
+def test_parsers_implemented():
+    with pytest.raises(NotImplementedError):
+        handler = ErrConfigHandler(None, {}, False, Mock())
+        handler.parsers
+
+
+class TestConfigurationReader:
+    def test_basic(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = 10.1.1\n'
+            'keywords = one, two\n'
+            '\n'
+            '[options]\n'
+            'scripts = bin/a.py, bin/b.py\n',
+        )
+        config_dict = read_configuration(str(config))
+        assert config_dict['metadata']['version'] == '10.1.1'
+        assert config_dict['metadata']['keywords'] == ['one', 'two']
+        assert config_dict['options']['scripts'] == ['bin/a.py', 'bin/b.py']
+
+    def test_no_config(self, tmpdir):
+        with pytest.raises(DistutilsFileError):
+            read_configuration(str(tmpdir.join('setup.cfg')))
+
+    def test_ignore_errors(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[metadata]\nversion = attr: none.VERSION\nkeywords = one, two\n',
+        )
+        with pytest.raises(ImportError):
+            read_configuration(str(config))
+
+        config_dict = read_configuration(str(config), ignore_option_errors=True)
+
+        assert config_dict['metadata']['keywords'] == ['one', 'two']
+        assert 'version' not in config_dict['metadata']
+
+        config.remove()
+
+
+class TestMetadata:
+    def test_basic(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = 10.1.1\n'
+            'description = Some description\n'
+            'long_description_content_type = text/something\n'
+            'long_description = file: README\n'
+            'name = fake_name\n'
+            'keywords = one, two\n'
+            'provides = package, package.sub\n'
+            'license = otherlic\n'
+            'download_url = http://test.test.com/test/\n'
+            'maintainer_email = test@test.com\n',
+        )
+
+        tmpdir.join('README').write('readme contents\nline2')
+
+        meta_initial = {
+            # This will be used so `otherlic` won't replace it.
+            'license': 'BSD 3-Clause License',
+        }
+
+        with get_dist(tmpdir, meta_initial) as dist:
+            metadata = dist.metadata
+
+            assert metadata.version == '10.1.1'
+            assert metadata.description == 'Some description'
+            assert metadata.long_description_content_type == 'text/something'
+            assert metadata.long_description == 'readme contents\nline2'
+            assert metadata.provides == ['package', 'package.sub']
+            assert metadata.license == 'BSD 3-Clause License'
+            assert metadata.name == 'fake_name'
+            assert metadata.keywords == ['one', 'two']
+            assert metadata.download_url == 'http://test.test.com/test/'
+            assert metadata.maintainer_email == 'test@test.com'
+
+    def test_license_cfg(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [metadata]
+            name=foo
+            version=0.0.1
+            license=Apache 2.0
+            """
+            ),
+        )
+
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+
+            assert metadata.name == "foo"
+            assert metadata.version == "0.0.1"
+            assert metadata.license == "Apache 2.0"
+
+    def test_file_mixed(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\nlong_description = file: README.rst, CHANGES.rst\n\n',
+        )
+
+        tmpdir.join('README.rst').write('readme contents\nline2')
+        tmpdir.join('CHANGES.rst').write('changelog contents\nand stuff')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.long_description == (
+                'readme contents\nline2\nchangelog contents\nand stuff'
+            )
+
+    def test_file_sandboxed(self, tmpdir):
+        tmpdir.ensure("README")
+        project = tmpdir.join('depth1', 'depth2')
+        project.ensure(dir=True)
+        fake_env(project, '[metadata]\nlong_description = file: ../../README\n')
+
+        with get_dist(project, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()  # file: out of sandbox
+
+    def test_aliases(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'author_email = test@test.com\n'
+            'home_page = http://test.test.com/test/\n'
+            'summary = Short summary\n'
+            'platform = a, b\n'
+            'classifier =\n'
+            '  Framework :: Django\n'
+            '  Programming Language :: Python :: 3.5\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.author_email == 'test@test.com'
+            assert metadata.url == 'http://test.test.com/test/'
+            assert metadata.description == 'Short summary'
+            assert metadata.platforms == ['a', 'b']
+            assert metadata.classifiers == [
+                'Framework :: Django',
+                'Programming Language :: Python :: 3.5',
+            ]
+
+    def test_multiline(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'name = fake_name\n'
+            'keywords =\n'
+            '  one\n'
+            '  two\n'
+            'classifiers =\n'
+            '  Framework :: Django\n'
+            '  Programming Language :: Python :: 3.5\n',
+        )
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.keywords == ['one', 'two']
+            assert metadata.classifiers == [
+                'Framework :: Django',
+                'Programming Language :: Python :: 3.5',
+            ]
+
+    def test_dict(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'project_urls =\n'
+            '  Link One = https://example.com/one/\n'
+            '  Link Two = https://example.com/two/\n',
+        )
+        with get_dist(tmpdir) as dist:
+            metadata = dist.metadata
+            assert metadata.project_urls == {
+                'Link One': 'https://example.com/one/',
+                'Link Two': 'https://example.com/two/',
+            }
+
+    def test_version(self, tmpdir):
+        package_dir, config = fake_env(
+            tmpdir, '[metadata]\nversion = attr: fake_package.VERSION\n'
+        )
+
+        sub_a = package_dir.mkdir('subpkg_a')
+        sub_a.join('__init__.py').write('')
+        sub_a.join('mod.py').write('VERSION = (2016, 11, 26)')
+
+        sub_b = package_dir.mkdir('subpkg_b')
+        sub_b.join('__init__.py').write('')
+        sub_b.join('mod.py').write(
+            'import third_party_module\nVERSION = (2016, 11, 26)'
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+        config.write('[metadata]\nversion = attr: fake_package.get_version\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '3.4.5.dev'
+
+        config.write('[metadata]\nversion = attr: fake_package.VERSION_MAJOR\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1'
+
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_a.mod.VERSION\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '2016.11.26'
+
+        config.write('[metadata]\nversion = attr: fake_package.subpkg_b.mod.VERSION\n')
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '2016.11.26'
+
+    def test_version_file(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\nversion = file: fake_package/version.txt\n')
+        tmpdir.join('fake_package', 'version.txt').write('1.2.3\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+        tmpdir.join('fake_package', 'version.txt').write('1.2.3\n4.5.6\n')
+        with pytest.raises(DistutilsOptionError):
+            with get_dist(tmpdir) as dist:
+                dist.metadata.version
+
+    def test_version_with_package_dir_simple(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_simple.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    = src\n',
+            package_path='src/fake_package_simple',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_version_with_package_dir_rename(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_rename.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    fake_package_rename = fake_dir\n',
+            package_path='fake_dir',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_version_with_package_dir_complex(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[metadata]\n'
+            'version = attr: fake_package_complex.VERSION\n'
+            '[options]\n'
+            'package_dir =\n'
+            '    fake_package_complex = src/fake_dir\n',
+            package_path='src/fake_dir',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.version == '1.2.3'
+
+    def test_unknown_meta_item(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\nname = fake_name\nunknown = some\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            dist.parse_config_files()  # Skip unknown.
+
+    def test_usupported_section(self, tmpdir):
+        fake_env(tmpdir, '[metadata.some]\nkey = val\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()
+
+    def test_classifiers(self, tmpdir):
+        expected = set([
+            'Framework :: Django',
+            'Programming Language :: Python :: 3',
+            'Programming Language :: Python :: 3.5',
+        ])
+
+        # From file.
+        _, config = fake_env(tmpdir, '[metadata]\nclassifiers = file: classifiers\n')
+
+        tmpdir.join('classifiers').write(
+            'Framework :: Django\n'
+            'Programming Language :: Python :: 3\n'
+            'Programming Language :: Python :: 3.5\n'
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.metadata.classifiers) == expected
+
+        # From list notation
+        config.write(
+            '[metadata]\n'
+            'classifiers =\n'
+            '    Framework :: Django\n'
+            '    Programming Language :: Python :: 3\n'
+            '    Programming Language :: Python :: 3.5\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.metadata.classifiers) == expected
+
+    def test_interpolation(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\ndescription = %(message)s\n')
+        with pytest.raises(configparser.InterpolationMissingOptionError):
+            with get_dist(tmpdir):
+                pass
+
+    def test_non_ascii_1(self, tmpdir):
+        fake_env(tmpdir, '[metadata]\ndescription = éàïôñ\n', encoding='utf-8')
+        with get_dist(tmpdir):
+            pass
+
+    def test_non_ascii_3(self, tmpdir):
+        fake_env(tmpdir, '\n# -*- coding: invalid\n')
+        with get_dist(tmpdir):
+            pass
+
+    def test_non_ascii_4(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '# -*- coding: utf-8\n[metadata]\ndescription = éàïôñ\n',
+            encoding='utf-8',
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.metadata.description == 'éàïôñ'
+
+    def test_not_utf8(self, tmpdir):
+        """
+        Config files encoded not in UTF-8 will fail
+        """
+        fake_env(
+            tmpdir,
+            '# vim: set fileencoding=iso-8859-15 :\n[metadata]\ndescription = éàïôñ\n',
+            encoding='iso-8859-15',
+        )
+        with pytest.raises(UnicodeDecodeError):
+            with get_dist(tmpdir):
+                pass
+
+    @pytest.mark.parametrize(
+        ("error_msg", "config", "invalid"),
+        [
+            (
+                "Invalid dash-separated key 'author-email' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    author-email = test@test.com
+                    maintainer_email = foo@foo.com
+                    """
+                ),
+                {"author-email": "test@test.com"},
+            ),
+            (
+                "Invalid uppercase key 'Name' in 'metadata' (setup.cfg)",
+                DALS(
+                    """
+                    [metadata]
+                    Name = foo
+                    description = Some description
+                    """
+                ),
+                {"Name": "foo"},
+            ),
+        ],
+    )
+    def test_invalid_options_previously_deprecated(
+        self, tmpdir, error_msg, config, invalid
+    ):
+        # This test and related methods can be removed when no longer needed.
+        # Deprecation postponed due to push-back from the community in
+        # https://github.com/pypa/setuptools/issues/4910
+        fake_env(tmpdir, config)
+        with pytest.warns(SetuptoolsDeprecationWarning, match=re.escape(error_msg)):
+            dist = get_dist(tmpdir).__enter__()
+
+        tmpdir.join('setup.cfg').remove()
+
+        for field, value in invalid.items():
+            attr = field.replace("-", "_").lower()
+            assert getattr(dist.metadata, attr) == value
+
+
+class TestOptions:
+    def test_basic(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options]\n'
+            'zip_safe = True\n'
+            'include_package_data = yes\n'
+            'package_dir = b=c, =src\n'
+            'packages = pack_a, pack_b.subpack\n'
+            'namespace_packages = pack1, pack2\n'
+            'scripts = bin/one.py, bin/two.py\n'
+            'eager_resources = bin/one.py, bin/two.py\n'
+            'install_requires = docutils>=0.3; pack ==1.1, ==1.3; hey\n'
+            'setup_requires = docutils>=0.3; spack ==1.1, ==1.3; there\n'
+            'dependency_links = http://some.com/here/1, '
+            'http://some.com/there/2\n'
+            'python_requires = >=1.0, !=2.8\n'
+            'py_modules = module1, module2\n',
+        )
+        deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+        with deprec, get_dist(tmpdir) as dist:
+            assert dist.zip_safe
+            assert dist.include_package_data
+            assert dist.package_dir == {'': 'src', 'b': 'c'}
+            assert dist.packages == ['pack_a', 'pack_b.subpack']
+            assert dist.namespace_packages == ['pack1', 'pack2']
+            assert dist.scripts == ['bin/one.py', 'bin/two.py']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
+            assert dist.python_requires == '>=1.0, !=2.8'
+            assert dist.py_modules == ['module1', 'module2']
+
+    def test_multiline(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options]\n'
+            'package_dir = \n'
+            '  b=c\n'
+            '  =src\n'
+            'packages = \n'
+            '  pack_a\n'
+            '  pack_b.subpack\n'
+            'namespace_packages = \n'
+            '  pack1\n'
+            '  pack2\n'
+            'scripts = \n'
+            '  bin/one.py\n'
+            '  bin/two.py\n'
+            'eager_resources = \n'
+            '  bin/one.py\n'
+            '  bin/two.py\n'
+            'install_requires = \n'
+            '  docutils>=0.3\n'
+            '  pack ==1.1, ==1.3\n'
+            '  hey\n'
+            'setup_requires = \n'
+            '  docutils>=0.3\n'
+            '  spack ==1.1, ==1.3\n'
+            '  there\n'
+            'dependency_links = \n'
+            '  http://some.com/here/1\n'
+            '  http://some.com/there/2\n',
+        )
+        deprec = pytest.warns(SetuptoolsDeprecationWarning, match="namespace_packages")
+        with deprec, get_dist(tmpdir) as dist:
+            assert dist.package_dir == {'': 'src', 'b': 'c'}
+            assert dist.packages == ['pack_a', 'pack_b.subpack']
+            assert dist.namespace_packages == ['pack1', 'pack2']
+            assert dist.scripts == ['bin/one.py', 'bin/two.py']
+            assert dist.dependency_links == ([
+                'http://some.com/here/1',
+                'http://some.com/there/2',
+            ])
+            assert dist.install_requires == ([
+                'docutils>=0.3',
+                'pack==1.1,==1.3',
+                'hey',
+            ])
+            assert dist.setup_requires == ([
+                'docutils>=0.3',
+                'spack ==1.1, ==1.3',
+                'there',
+            ])
+
+    def test_package_dir_fail(self, tmpdir):
+        fake_env(tmpdir, '[options]\npackage_dir = a b\n')
+        with get_dist(tmpdir, parse=False) as dist:
+            with pytest.raises(DistutilsOptionError):
+                dist.parse_config_files()
+
+    def test_package_data(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.package_data]\n'
+            '* = *.txt, *.rst\n'
+            'hello = *.msg\n'
+            '\n'
+            '[options.exclude_package_data]\n'
+            '* = fake1.txt, fake2.txt\n'
+            'hello = *.dat\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.package_data == {
+                '': ['*.txt', '*.rst'],
+                'hello': ['*.msg'],
+            }
+            assert dist.exclude_package_data == {
+                '': ['fake1.txt', 'fake2.txt'],
+                'hello': ['*.dat'],
+            }
+
+    def test_packages(self, tmpdir):
+        fake_env(tmpdir, '[options]\npackages = find:\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package']
+
+    def test_find_directive(self, tmpdir):
+        dir_package, config = fake_env(tmpdir, '[options]\npackages = find:\n')
+
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package)
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == set([
+                'fake_package',
+                'fake_package.sub_two',
+                'fake_package.sub_one',
+            ])
+
+        config.write(
+            '[options]\n'
+            'packages = find:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'where = .\n'
+            'include =\n'
+            '    fake_package.sub_one\n'
+            '    two\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package.sub_one']
+
+        config.write(
+            '[options]\n'
+            'packages = find:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'exclude =\n'
+            '    fake_package.sub_one\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == set(['fake_package', 'fake_package.sub_two'])
+
+    def test_find_namespace_directive(self, tmpdir):
+        dir_package, config = fake_env(
+            tmpdir, '[options]\npackages = find_namespace:\n'
+        )
+
+        make_package_dir('sub_one', dir_package)
+        make_package_dir('sub_two', dir_package, ns=True)
+
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == {
+                'fake_package',
+                'fake_package.sub_two',
+                'fake_package.sub_one',
+            }
+
+        config.write(
+            '[options]\n'
+            'packages = find_namespace:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'where = .\n'
+            'include =\n'
+            '    fake_package.sub_one\n'
+            '    two\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert dist.packages == ['fake_package.sub_one']
+
+        config.write(
+            '[options]\n'
+            'packages = find_namespace:\n'
+            '\n'
+            '[options.packages.find]\n'
+            'exclude =\n'
+            '    fake_package.sub_one\n'
+        )
+        with get_dist(tmpdir) as dist:
+            assert set(dist.packages) == {'fake_package', 'fake_package.sub_two'}
+
+    def test_extras_require(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.extras_require]\n'
+            'pdf = ReportLab>=1.2; RXP\n'
+            'rest = \n'
+            '  docutils>=0.3\n'
+            '  pack ==1.1, ==1.3\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.extras_require == {
+                'pdf': ['ReportLab>=1.2', 'RXP'],
+                'rest': ['docutils>=0.3', 'pack==1.1,==1.3'],
+            }
+            assert set(dist.metadata.provides_extras) == {'pdf', 'rest'}
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo = bar;python_version<'3'",
+            "[options.extras_require]\nfoo = bar;os_name=='linux'",
+            "[options.extras_require]\nfoo = bar;python_version<'3'\n",
+            "[options.extras_require]\nfoo = bar;os_name=='linux'\n",
+            "[options]\ninstall_requires = bar;python_version<'3'",
+            "[options]\ninstall_requires = bar;os_name=='linux'",
+            "[options]\ninstall_requires = bar;python_version<'3'\n",
+            "[options]\ninstall_requires = bar;os_name=='linux'\n",
+        ],
+    )
+    def test_raises_accidental_env_marker_misconfig(self, config, tmpdir):
+        fake_env(tmpdir, config)
+        match = (
+            r"One of the parsed requirements in `(install_requires|extras_require.+)` "
+            "looks like a valid environment marker.*"
+        )
+        with pytest.raises(InvalidRequirement, match=match):
+            with get_dist(tmpdir) as _:
+                pass
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo = bar;python_version<3",
+            "[options.extras_require]\nfoo = bar;python_version<3\n",
+            "[options]\ninstall_requires = bar;python_version<3",
+            "[options]\ninstall_requires = bar;python_version<3\n",
+        ],
+    )
+    def test_warn_accidental_env_marker_misconfig(self, config, tmpdir):
+        fake_env(tmpdir, config)
+        match = (
+            r"One of the parsed requirements in `(install_requires|extras_require.+)` "
+            "looks like a valid environment marker.*"
+        )
+        with pytest.warns(SetuptoolsDeprecationWarning, match=match):
+            with get_dist(tmpdir) as _:
+                pass
+
+    @pytest.mark.parametrize(
+        "config",
+        [
+            "[options.extras_require]\nfoo =\n    bar;python_version<'3'",
+            "[options.extras_require]\nfoo = bar;baz\nboo = xxx;yyy",
+            "[options.extras_require]\nfoo =\n    bar;python_version<'3'\n",
+            "[options.extras_require]\nfoo = bar;baz\nboo = xxx;yyy\n",
+            "[options.extras_require]\nfoo =\n    bar\n    python_version<3\n",
+            "[options]\ninstall_requires =\n    bar;python_version<'3'",
+            "[options]\ninstall_requires = bar;baz\nboo = xxx;yyy",
+            "[options]\ninstall_requires =\n    bar;python_version<'3'\n",
+            "[options]\ninstall_requires = bar;baz\nboo = xxx;yyy\n",
+            "[options]\ninstall_requires =\n    bar\n    python_version<3\n",
+        ],
+    )
+    @pytest.mark.filterwarnings("error::setuptools.SetuptoolsDeprecationWarning")
+    def test_nowarn_accidental_env_marker_misconfig(self, config, tmpdir, recwarn):
+        fake_env(tmpdir, config)
+        num_warnings = len(recwarn)
+        with get_dist(tmpdir) as _:
+            pass
+        # The examples are valid, no warnings shown
+        assert len(recwarn) == num_warnings
+
+    def test_dash_preserved_extras_require(self, tmpdir):
+        fake_env(tmpdir, '[options.extras_require]\nfoo-a = foo\nfoo_b = test\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.extras_require == {'foo-a': ['foo'], 'foo_b': ['test']}
+
+    def test_entry_points(self, tmpdir):
+        _, config = fake_env(
+            tmpdir,
+            '[options.entry_points]\n'
+            'group1 = point1 = pack.module:func, '
+            '.point2 = pack.module2:func_rest [rest]\n'
+            'group2 = point3 = pack.module:func2\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == {
+                'group1': [
+                    'point1 = pack.module:func',
+                    '.point2 = pack.module2:func_rest [rest]',
+                ],
+                'group2': ['point3 = pack.module:func2'],
+            }
+
+        expected = (
+            '[blogtool.parsers]\n'
+            '.rst = some.nested.module:SomeClass.some_classmethod[reST]\n'
+        )
+
+        tmpdir.join('entry_points').write(expected)
+
+        # From file.
+        config.write('[options]\nentry_points = file: entry_points\n')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == expected
+
+    def test_case_sensitive_entry_points(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.entry_points]\n'
+            'GROUP1 = point1 = pack.module:func, '
+            '.point2 = pack.module2:func_rest [rest]\n'
+            'group2 = point3 = pack.module:func2\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            assert dist.entry_points == {
+                'GROUP1': [
+                    'point1 = pack.module:func',
+                    '.point2 = pack.module2:func_rest [rest]',
+                ],
+                'group2': ['point3 = pack.module:func2'],
+            }
+
+    def test_data_files(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.data_files]\n'
+            'cfg =\n'
+            '      a/b.conf\n'
+            '      c/d.conf\n'
+            'data = e/f.dat, g/h.dat\n',
+        )
+
+        with get_dist(tmpdir) as dist:
+            expected = [
+                ('cfg', ['a/b.conf', 'c/d.conf']),
+                ('data', ['e/f.dat', 'g/h.dat']),
+            ]
+            assert sorted(dist.data_files) == sorted(expected)
+
+    def test_data_files_globby(self, tmpdir):
+        fake_env(
+            tmpdir,
+            '[options.data_files]\n'
+            'cfg =\n'
+            '      a/b.conf\n'
+            '      c/d.conf\n'
+            'data = *.dat\n'
+            'icons = \n'
+            '      *.ico\n'
+            'audio = \n'
+            '      *.wav\n'
+            '      sounds.db\n',
+        )
+
+        # Create dummy files for glob()'s sake:
+        tmpdir.join('a.dat').write('')
+        tmpdir.join('b.dat').write('')
+        tmpdir.join('c.dat').write('')
+        tmpdir.join('a.ico').write('')
+        tmpdir.join('b.ico').write('')
+        tmpdir.join('c.ico').write('')
+        tmpdir.join('beep.wav').write('')
+        tmpdir.join('boop.wav').write('')
+        tmpdir.join('sounds.db').write('')
+
+        with get_dist(tmpdir) as dist:
+            expected = [
+                ('cfg', ['a/b.conf', 'c/d.conf']),
+                ('data', ['a.dat', 'b.dat', 'c.dat']),
+                ('icons', ['a.ico', 'b.ico', 'c.ico']),
+                ('audio', ['beep.wav', 'boop.wav', 'sounds.db']),
+            ]
+            assert sorted(dist.data_files) == sorted(expected)
+
+    def test_python_requires_simple(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=>=2.7
+            """
+            ),
+        )
+        with get_dist(tmpdir) as dist:
+            dist.parse_config_files()
+
+    def test_python_requires_compound(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=>=2.7,!=3.0.*
+            """
+            ),
+        )
+        with get_dist(tmpdir) as dist:
+            dist.parse_config_files()
+
+    def test_python_requires_invalid(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            python_requires=invalid
+            """
+            ),
+        )
+        with pytest.raises(Exception):
+            with get_dist(tmpdir) as dist:
+                dist.parse_config_files()
+
+    def test_cmdclass(self, tmpdir):
+        module_path = Path(tmpdir, "src/custom_build.py")  # auto discovery for src
+        module_path.parent.mkdir(parents=True, exist_ok=True)
+        module_path.write_text(
+            "from distutils.core import Command\nclass CustomCmd(Command): pass\n",
+            encoding="utf-8",
+        )
+
+        setup_cfg = """
+            [options]
+            cmdclass =
+                customcmd = custom_build.CustomCmd
+        """
+        fake_env(tmpdir, inspect.cleandoc(setup_cfg))
+
+        with get_dist(tmpdir) as dist:
+            cmdclass = dist.cmdclass['customcmd']
+            assert cmdclass.__name__ == "CustomCmd"
+            assert cmdclass.__module__ == "custom_build"
+            assert module_path.samefile(inspect.getfile(cmdclass))
+
+    def test_requirements_file(self, tmpdir):
+        fake_env(
+            tmpdir,
+            DALS(
+                """
+            [options]
+            install_requires = file:requirements.txt
+            [options.extras_require]
+            colors = file:requirements-extra.txt
+            """
+            ),
+        )
+
+        tmpdir.join('requirements.txt').write('\ndocutils>=0.3\n\n')
+        tmpdir.join('requirements-extra.txt').write('colorama')
+
+        with get_dist(tmpdir) as dist:
+            assert dist.install_requires == ['docutils>=0.3']
+            assert dist.extras_require == {'colors': ['colorama']}
+
+
+saved_dist_init = _Distribution.__init__
+
+
+class TestExternalSetters:
+    # During creation of the setuptools Distribution() object, we call
+    # the init of the parent distutils Distribution object via
+    # _Distribution.__init__ ().
+    #
+    # It's possible distutils calls out to various keyword
+    # implementations (i.e. distutils.setup_keywords entry points)
+    # that may set a range of variables.
+    #
+    # This wraps distutil's Distribution.__init__ and simulates
+    # pbr or something else setting these values.
+    def _fake_distribution_init(self, dist, attrs):
+        saved_dist_init(dist, attrs)
+        # see self._DISTUTILS_UNSUPPORTED_METADATA
+        dist.metadata.long_description_content_type = 'text/something'
+        # Test overwrite setup() args
+        dist.metadata.project_urls = {
+            'Link One': 'https://example.com/one/',
+            'Link Two': 'https://example.com/two/',
+        }
+
+    @patch.object(_Distribution, '__init__', autospec=True)
+    def test_external_setters(self, mock_parent_init, tmpdir):
+        mock_parent_init.side_effect = self._fake_distribution_init
+
+        dist = Distribution(attrs={'project_urls': {'will_be': 'ignored'}})
+
+        assert dist.metadata.long_description_content_type == 'text/something'
+        assert dist.metadata.project_urls == {
+            'Link One': 'https://example.com/one/',
+            'Link Two': 'https://example.com/two/',
+        }
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/external.html b/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/external.html
new file mode 100644
index 0000000000000000000000000000000000000000..92e4702f634dfb37a404bec3103b76f6afcaa917
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/external.html
@@ -0,0 +1,3 @@
+
+bad old link
+
diff --git a/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html b/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..fefb028bd3ee7d45a414d6e96a7b2a21ffd7eda7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html
@@ -0,0 +1,4 @@
+
+foobar-0.1.tar.gz
+external homepage
+ diff --git a/python_embeded/Lib/site-packages/setuptools/tests/integration/__init__.py b/python_embeded/Lib/site-packages/setuptools/tests/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/setuptools/tests/integration/helpers.py b/python_embeded/Lib/site-packages/setuptools/tests/integration/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..77b196e029b6d2eeb25f0b84a4f7630f65201189 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/integration/helpers.py @@ -0,0 +1,77 @@ +"""Reusable functions and classes for different types of integration tests. + +For example ``Archive`` can be used to check the contents of distribution built +with setuptools, and ``run`` will always try to be as verbose as possible to +facilitate debugging. +""" + +import os +import subprocess +import tarfile +from pathlib import Path +from zipfile import ZipFile + + +def run(cmd, env=None): + r = subprocess.run( + cmd, + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, **(env or {})}, + # ^-- allow overwriting instead of discarding the current env + ) + + out = r.stdout + "\n" + r.stderr + # pytest omits stdout/err by default, if the test fails they help debugging + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print(f"Command: {cmd}\nreturn code: {r.returncode}\n\n{out}") + + if r.returncode == 0: + return out + raise subprocess.CalledProcessError(r.returncode, cmd, r.stdout, r.stderr) + + +class Archive: + """Compatibility layer for ZipFile/Info and TarFile/Info""" + + def __init__(self, filename): + self._filename = filename + if filename.endswith("tar.gz"): + self._obj = tarfile.open(filename, "r:gz") + elif filename.endswith("zip"): + self._obj = ZipFile(filename) + else: + raise ValueError(f"{filename} doesn't seem to be a zip or tar.gz") + + def __iter__(self): + if hasattr(self._obj, "infolist"): + return iter(self._obj.infolist()) + return iter(self._obj) + + def get_name(self, zip_or_tar_info): + if hasattr(zip_or_tar_info, "filename"): + return zip_or_tar_info.filename + return zip_or_tar_info.name + + def get_content(self, zip_or_tar_info): + if hasattr(self._obj, "extractfile"): + content = self._obj.extractfile(zip_or_tar_info) + if content is None: + msg = f"Invalid {zip_or_tar_info.name} in {self._filename}" + raise ValueError(msg) + return str(content.read(), "utf-8") + return str(self._obj.read(zip_or_tar_info), "utf-8") + + +def get_sdist_members(sdist_path): + with tarfile.open(sdist_path, "r:gz") as tar: + files = [Path(f) for f in tar.getnames()] + # remove root folder + relative_files = ("/".join(f.parts[1:]) for f in files) + return {f for f in relative_files if f} + + +def get_wheel_members(wheel_path): + with ZipFile(wheel_path) as zipfile: + return set(zipfile.namelist()) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pbr.py b/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..f89e5b8b2151430d0994836dd609f1b75490a336 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pbr.py @@ -0,0 +1,20 @@ +import subprocess + +import pytest + + +@pytest.mark.uses_network +def test_pbr_integration(pbr_package, venv): + """Ensure pbr packages install.""" + cmd = [ + 'python', + '-m', + 'pip', + '-v', + 'install', + '--no-build-isolation', + pbr_package, + ] + venv.run(cmd, stderr=subprocess.STDOUT) + out = venv.run(["python", "-c", "import mypkg.hello"]) + assert "Hello world!" in out diff --git a/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pip_install_sdist.py b/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pip_install_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..4e84f218323e6ad67adfbce07cea5a16e91a311c --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/integration/test_pip_install_sdist.py @@ -0,0 +1,223 @@ +# https://github.com/python/mypy/issues/16936 +# mypy: disable-error-code="has-type" +"""Integration tests for setuptools that focus on building packages via pip. + +The idea behind these tests is not to exhaustively check all the possible +combinations of packages, operating systems, supporting libraries, etc, but +rather check a limited number of popular packages and how they interact with +the exposed public API. This way if any change in API is introduced, we hope to +identify backward compatibility problems before publishing a release. + +The number of tested packages is purposefully kept small, to minimise duration +and the associated maintenance cost (changes in the way these packages define +their build process may require changes in the tests). +""" + +import json +import os +import shutil +import sys +from enum import Enum +from glob import glob +from hashlib import md5 +from urllib.request import urlopen + +import pytest +from packaging.requirements import Requirement + +from .helpers import Archive, run + +pytestmark = pytest.mark.integration + + +(LATEST,) = Enum("v", "LATEST") # type: ignore[misc] # https://github.com/python/mypy/issues/16936 +"""Default version to be checked""" +# There are positive and negative aspects of checking the latest version of the +# packages. +# The main positive aspect is that the latest version might have already +# removed the use of APIs deprecated in previous releases of setuptools. + + +# Packages to be tested: +# (Please notice the test environment cannot support EVERY library required for +# compiling binary extensions. In Ubuntu/Debian nomenclature, we only assume +# that `build-essential`, `gfortran` and `libopenblas-dev` are installed, +# due to their relevance to the numerical/scientific programming ecosystem) +EXAMPLES = [ + ("pip", LATEST), # just in case... + ("pytest", LATEST), # uses setuptools_scm + ("mypy", LATEST), # custom build_py + ext_modules + # --- Popular packages: https://hugovk.github.io/top-pypi-packages/ --- + ("botocore", LATEST), + ("kiwisolver", LATEST), # build_ext + ("brotli", LATEST), # not in the list but used by urllib3 + ("pyyaml", LATEST), # cython + custom build_ext + custom distclass + ("charset-normalizer", LATEST), # uses mypyc, used by aiohttp + ("protobuf", LATEST), + # ("requests", LATEST), # XXX: https://github.com/psf/requests/pull/6920 + ("celery", LATEST), + # When adding packages to this list, make sure they expose a `__version__` + # attribute, or modify the tests below +] + + +# Some packages have "optional" dependencies that modify their build behaviour +# and are not listed in pyproject.toml, others still use `setup_requires` +EXTRA_BUILD_DEPS = { + "pyyaml": ("Cython<3.0",), # constraint to avoid errors + "charset-normalizer": ("mypy>=1.4.1",), # no pyproject.toml available +} + +EXTRA_ENV_VARS = { + "pyyaml": {"PYYAML_FORCE_CYTHON": "1"}, + "charset-normalizer": {"CHARSET_NORMALIZER_USE_MYPYC": "1"}, +} + +IMPORT_NAME = { + "pyyaml": "yaml", + "protobuf": "google.protobuf", +} + + +VIRTUALENV = (sys.executable, "-m", "virtualenv") + + +# By default, pip will try to build packages in isolation (PEP 517), which +# means it will download the previous stable version of setuptools. +# `pip` flags can avoid that (the version of setuptools under test +# should be the one to be used) +INSTALL_OPTIONS = ( + "--ignore-installed", + "--no-build-isolation", + # Omit "--no-binary :all:" the sdist is supplied directly. + # Allows dependencies as wheels. +) +# The downside of `--no-build-isolation` is that pip will not download build +# dependencies. The test script will have to also handle that. + + +@pytest.fixture +def venv_python(tmp_path): + run([*VIRTUALENV, str(tmp_path / ".venv")]) + possible_path = (str(p.parent) for p in tmp_path.glob(".venv/*/python*")) + return shutil.which("python", path=os.pathsep.join(possible_path)) + + +@pytest.fixture(autouse=True) +def _prepare(tmp_path, venv_python, monkeypatch): + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + os.makedirs(download_path, exist_ok=True) + + # Environment vars used for building some of the packages + monkeypatch.setenv("USE_MYPYC", "1") + + yield + + # Let's provide the maximum amount of information possible in the case + # it is necessary to debug the tests directly from the CI logs. + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Temporary directory:") + map(print, tmp_path.glob("*")) + print("Virtual environment:") + run([venv_python, "-m", "pip", "freeze"]) + + +@pytest.mark.parametrize(("package", "version"), EXAMPLES) +@pytest.mark.uses_network +def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel): + venv_pip = (venv_python, "-m", "pip") + sdist = retrieve_sdist(package, version, tmp_path) + deps = build_deps(package, sdist) + if deps: + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Dependencies:", deps) + run([*venv_pip, "install", *deps]) + + # Use a virtualenv to simulate PEP 517 isolation + # but install fresh setuptools wheel to ensure the version under development + env = EXTRA_ENV_VARS.get(package, {}) + run([*venv_pip, "install", "--force-reinstall", setuptools_wheel]) + run([*venv_pip, "install", *INSTALL_OPTIONS, sdist], env) + + # Execute a simple script to make sure the package was installed correctly + pkg = IMPORT_NAME.get(package, package).replace("-", "_") + script = f"import {pkg}; print(getattr({pkg}, '__version__', 0))" + run([venv_python, "-c", script]) + + +# ---- Helper Functions ---- + + +def retrieve_sdist(package, version, tmp_path): + """Either use cached sdist file or download it from PyPI""" + # `pip download` cannot be used due to + # https://github.com/pypa/pip/issues/1884 + # https://discuss.python.org/t/pep-625-file-name-of-a-source-distribution/4686 + # We have to find the correct distribution file and download it + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + dist = retrieve_pypi_sdist_metadata(package, version) + + # Remove old files to prevent cache to grow indefinitely + for file in glob(os.path.join(download_path, f"{package}*")): + if dist["filename"] != file: + os.unlink(file) + + dist_file = os.path.join(download_path, dist["filename"]) + if not os.path.exists(dist_file): + download(dist["url"], dist_file, dist["md5_digest"]) + return dist_file + + +def retrieve_pypi_sdist_metadata(package, version): + # https://warehouse.pypa.io/api-reference/json.html + id_ = package if version is LATEST else f"{package}/{version}" + with urlopen(f"https://pypi.org/pypi/{id_}/json") as f: + metadata = json.load(f) + + if metadata["info"]["yanked"]: + raise ValueError(f"Release for {package} {version} was yanked") + + version = metadata["info"]["version"] + release = metadata["releases"][version] if version is LATEST else metadata["urls"] + (sdist,) = filter(lambda d: d["packagetype"] == "sdist", release) + return sdist + + +def download(url, dest, md5_digest): + with urlopen(url) as f: + data = f.read() + + assert md5(data).hexdigest() == md5_digest + + with open(dest, "wb") as f: + f.write(data) + + assert os.path.exists(dest) + + +def build_deps(package, sdist_file): + """Find out what are the build dependencies for a package. + + "Manually" install them, since pip will not install build + deps with `--no-build-isolation`. + """ + # delay importing, since pytest discovery phase may hit this file from a + # testenv without tomli + from setuptools.compat.py310 import tomllib + + archive = Archive(sdist_file) + info = tomllib.loads(_read_pyproject(archive)) + deps = info.get("build-system", {}).get("requires", []) + deps += EXTRA_BUILD_DEPS.get(package, []) + # Remove setuptools from requirements (and deduplicate) + requirements = {Requirement(d).name: d for d in deps} + return [v for k, v in requirements.items() if k != "setuptools"] + + +def _read_pyproject(archive): + contents = ( + archive.get_content(member) + for member in archive + if os.path.basename(archive.get_name(member)) == "pyproject.toml" + ) + return next(contents, "") diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_dist.py b/python_embeded/Lib/site-packages/setuptools/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..552ee2d2ea756cb5d486c6ee1d3395c11a78021f --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_dist.py @@ -0,0 +1,278 @@ +import os +import re +import urllib.parse +import urllib.request + +import pytest + +from setuptools import Distribution +from setuptools.dist import check_package_data, check_specifier + +from .fixtures import make_trivial_sdist +from .test_find_packages import ensure_files +from .textwrap import DALS + +from distutils.errors import DistutilsSetupError + + +def test_dist_fetch_build_egg(tmpdir): + """ + Check multiple calls to `Distribution.fetch_build_egg` work as expected. + """ + index = tmpdir.mkdir('index') + index_url = urllib.parse.urljoin('file://', urllib.request.pathname2url(str(index))) + + def sdist_with_index(distname, version): + dist_dir = index.mkdir(distname) + dist_sdist = f'{distname}-{version}.tar.gz' + make_trivial_sdist(str(dist_dir.join(dist_sdist)), distname, version) + with dist_dir.join('index.html').open('w') as fp: + fp.write( + DALS( + """ + + {dist_sdist}
+ + """ + ).format(dist_sdist=dist_sdist) + ) + + sdist_with_index('barbazquux', '3.2.0') + sdist_with_index('barbazquux-runner', '2.11.1') + with tmpdir.join('setup.cfg').open('w') as fp: + fp.write( + DALS( + """ + [easy_install] + index_url = {index_url} + """ + ).format(index_url=index_url) + ) + reqs = """ + barbazquux-runner + barbazquux + """.split() + with tmpdir.as_cwd(): + dist = Distribution() + dist.parse_config_files() + resolved_dists = [dist.fetch_build_egg(r) for r in reqs] + assert [dist.name for dist in resolved_dists if dist] == reqs + + +EXAMPLE_BASE_INFO = dict( + name="package", + version="0.0.1", + author="Foo Bar", + author_email="foo@bar.net", + long_description="Long\ndescription", + description="Short description", + keywords=["one", "two"], +) + + +def test_provides_extras_deterministic_order(): + attrs = dict(extras_require=dict(a=['foo'], b=['bar'])) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['a', 'b'] + attrs['extras_require'] = dict(reversed(attrs['extras_require'].items())) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['b', 'a'] + + +CHECK_PACKAGE_DATA_TESTS = ( + # Valid. + ( + { + '': ['*.txt', '*.rst'], + 'hello': ['*.msg'], + }, + None, + ), + # Not a dictionary. + ( + ( + ('', ['*.txt', '*.rst']), + ('hello', ['*.msg']), + ), + ( + "'package_data' must be a dictionary mapping package" + " names to lists of string wildcard patterns" + ), + ), + # Invalid key type. + ( + { + 400: ['*.txt', '*.rst'], + }, + ("keys of 'package_data' dict must be strings (got 400)"), + ), + # Invalid value type. + ( + { + 'hello': '*.msg', + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got '*.msg')" + ), + ), + # Invalid value type (generators are single use) + ( + { + 'hello': (x for x in "generator"), + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got =3.0, !=3.1'} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + attrs = {'name': 'foo', 'python_requires': ['>=3.0', '!=3.1']} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + # invalid specifier value + attrs = {'name': 'foo', 'python_requires': '>=invalid-version'} + with pytest.raises(DistutilsSetupError): + dist = Distribution(attrs) + + +def test_metadata_name(): + with pytest.raises(DistutilsSetupError, match='missing.*name'): + Distribution()._validate_metadata() + + +@pytest.mark.parametrize( + ('dist_name', 'py_module'), + [ + ("my.pkg", "my_pkg"), + ("my-pkg", "my_pkg"), + ("my_pkg", "my_pkg"), + ("pkg", "pkg"), + ], +) +def test_dist_default_py_modules(tmp_path, dist_name, py_module): + (tmp_path / f"{py_module}.py").touch() + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- make sure common tool files are ignored + + attrs = {**EXAMPLE_BASE_INFO, "name": dist_name, "src_root": str(tmp_path)} + # Find `py_modules` corresponding to dist_name if not given + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules == [py_module] + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicity_py_module"]}) + dist.set_defaults() + assert dist.py_modules == ["explicity_py_module"] + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicity_package"]}) + dist.set_defaults() + assert not dist.py_modules + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files', 'packages'), + [ + ("my.pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my-pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my.pkg", None, ["my/pkg/__init__.py"], ["my", "my.pkg"]), + ( + "my_pkg", + None, + ["src/my_pkg/__init__.py", "src/my_pkg2/__init__.py"], + ["my_pkg", "my_pkg2"], + ), + ( + "my_pkg", + {"pkg": "lib", "pkg2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ["pkg", "pkg.nested", "pkg2"], + ), + ], +) +def test_dist_default_packages( + tmp_path, dist_name, package_dir, package_files, packages +): + ensure_files(tmp_path, package_files) + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- should not be included by default + + attrs = { + **EXAMPLE_BASE_INFO, + "name": dist_name, + "src_root": str(tmp_path), + "package_dir": package_dir, + } + # Find `packages` either corresponding to dist_name or inside src + dist = Distribution(attrs) + dist.set_defaults() + assert not dist.py_modules + assert not dist.py_modules + assert set(dist.packages) == set(packages) + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicit_py_module"]}) + dist.set_defaults() + assert not dist.packages + assert set(dist.py_modules) == {"explicit_py_module"} + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicit_package"]}) + dist.set_defaults() + assert not dist.py_modules + assert set(dist.packages) == {"explicit_package"} + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files'), + [ + ("my.pkg.nested", None, ["my/pkg/nested/__init__.py"]), + ("my.pkg", None, ["my/pkg/__init__.py", "my/pkg/file.py"]), + ("my_pkg", None, ["my_pkg.py"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/nested/__init__.py"]), + ("my_pkg", None, ["src/my_pkg/__init__.py", "src/my_pkg/nested/__init__.py"]), + ( + "my_pkg", + {"my_pkg": "lib", "my_pkg.lib2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ), + # Should not try to guess a name from multiple py_modules/packages + ("UNKNOWN", None, ["src/mod1.py", "src/mod2.py"]), + ("UNKNOWN", None, ["src/pkg1/__ini__.py", "src/pkg2/__init__.py"]), + ], +) +def test_dist_default_name(tmp_path, dist_name, package_dir, package_files): + """Make sure dist.name is discovered from packages/py_modules""" + ensure_files(tmp_path, package_files) + attrs = { + **EXAMPLE_BASE_INFO, + "src_root": "/".join(os.path.split(tmp_path)), # POSIX-style + "package_dir": package_dir, + } + del attrs["name"] + + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules or dist.packages + assert dist.get_name() == dist_name diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_dist_info.py b/python_embeded/Lib/site-packages/setuptools/tests/test_dist_info.py new file mode 100644 index 0000000000000000000000000000000000000000..010018d1e6de7c0e0d1321bfafdac4251977ffca --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_dist_info.py @@ -0,0 +1,147 @@ +"""Test .dist-info style distributions.""" + +import pathlib +import re +import shutil +import subprocess +import sys +from functools import partial + +import pytest + +from setuptools.archive_util import unpack_archive + +from .textwrap import DALS + +read = partial(pathlib.Path.read_text, encoding="utf-8") + + +class TestDistInfo: + def test_invalid_version(self, tmp_path): + """ + Supplying an invalid version crashes dist_info. + """ + config = "[metadata]\nname=proj\nversion=42\n[egg_info]\ntag_build=invalid!!!\n" + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + msg = re.compile("invalid version", re.M | re.I) + proc = run_command_inner("dist_info", cwd=tmp_path, check=False) + assert proc.returncode + assert msg.search(proc.stdout) + assert not list(tmp_path.glob("*.dist-info")) + + def test_tag_arguments(self, tmp_path): + config = """ + [metadata] + name=proj + version=42 + [egg_info] + tag_date=1 + tag_build=.post + """ + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + + print(run_command("dist_info", "--no-date", cwd=tmp_path)) + dist_info = next(tmp_path.glob("*.dist-info")) + assert dist_info.name.startswith("proj-42") + shutil.rmtree(dist_info) + + print(run_command("dist_info", "--tag-build", ".a", cwd=tmp_path)) + dist_info = next(tmp_path.glob("*.dist-info")) + assert dist_info.name.startswith("proj-42a") + + @pytest.mark.parametrize("keep_egg_info", (False, True)) + def test_output_dir(self, tmp_path, keep_egg_info): + config = "[metadata]\nname=proj\nversion=42\n" + (tmp_path / "setup.cfg").write_text(config, encoding="utf-8") + out = tmp_path / "__out" + out.mkdir() + opts = ["--keep-egg-info"] if keep_egg_info else [] + run_command("dist_info", "--output-dir", out, *opts, cwd=tmp_path) + assert len(list(out.glob("*.dist-info"))) == 1 + assert len(list(tmp_path.glob("*.dist-info"))) == 0 + expected_egg_info = int(keep_egg_info) + assert len(list(out.glob("*.egg-info"))) == expected_egg_info + assert len(list(tmp_path.glob("*.egg-info"))) == 0 + assert len(list(out.glob("*.__bkp__"))) == 0 + assert len(list(tmp_path.glob("*.__bkp__"))) == 0 + + +class TestWheelCompatibility: + """Make sure the .dist-info directory produced with the ``dist_info`` command + is the same as the one produced by ``bdist_wheel``. + """ + + SETUPCFG = DALS( + """ + [metadata] + name = {name} + version = {version} + + [options] + install_requires = + foo>=12; sys_platform != "linux" + + [options.extras_require] + test = pytest + + [options.entry_points] + console_scripts = + executable-name = my_package.module:function + discover = + myproj = my_package.other_module:function + """ + ) + + EGG_INFO_OPTS = [ + # Related: #3088 #2872 + ("", ""), + (".post", "[egg_info]\ntag_build = post\n"), + (".post", "[egg_info]\ntag_build = .post\n"), + (".post", "[egg_info]\ntag_build = post\ntag_date = 1\n"), + (".dev", "[egg_info]\ntag_build = .dev\n"), + (".dev", "[egg_info]\ntag_build = .dev\ntag_date = 1\n"), + ("a1", "[egg_info]\ntag_build = .a1\n"), + ("+local", "[egg_info]\ntag_build = +local\n"), + ] + + @pytest.mark.parametrize("name", "my-proj my_proj my.proj My.Proj".split()) + @pytest.mark.parametrize("version", ["0.42.13"]) + @pytest.mark.parametrize(("suffix", "cfg"), EGG_INFO_OPTS) + def test_dist_info_is_the_same_as_in_wheel( + self, name, version, tmp_path, suffix, cfg + ): + config = self.SETUPCFG.format(name=name, version=version) + cfg + + for i in "dir_wheel", "dir_dist": + (tmp_path / i).mkdir() + (tmp_path / i / "setup.cfg").write_text(config, encoding="utf-8") + + run_command("bdist_wheel", cwd=tmp_path / "dir_wheel") + wheel = next(tmp_path.glob("dir_wheel/dist/*.whl")) + unpack_archive(wheel, tmp_path / "unpack") + wheel_dist_info = next(tmp_path.glob("unpack/*.dist-info")) + + run_command("dist_info", cwd=tmp_path / "dir_dist") + dist_info = next(tmp_path.glob("dir_dist/*.dist-info")) + + assert dist_info.name == wheel_dist_info.name + assert dist_info.name.startswith(f"my_proj-{version}{suffix}") + for file in "METADATA", "entry_points.txt": + assert read(dist_info / file) == read(wheel_dist_info / file) + + +def run_command_inner(*cmd, **kwargs): + opts = { + "stderr": subprocess.STDOUT, + "stdout": subprocess.PIPE, + "text": True, + "encoding": "utf-8", + "check": True, + **kwargs, + } + cmd = [sys.executable, "-c", "__import__('setuptools').setup()", *map(str, cmd)] + return subprocess.run(cmd, **opts) + + +def run_command(*args, **kwargs): + return run_command_inner(*args, **kwargs).stdout diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_distutils_adoption.py b/python_embeded/Lib/site-packages/setuptools/tests/test_distutils_adoption.py new file mode 100644 index 0000000000000000000000000000000000000000..f99a58849950029f53322c19cde1c171fe26622c --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_distutils_adoption.py @@ -0,0 +1,198 @@ +import os +import platform +import sys +import textwrap + +import pytest + +IS_PYPY = '__pypy__' in sys.builtin_module_names + +_TEXT_KWARGS = {"text": True, "encoding": "utf-8"} # For subprocess.run + + +def win_sr(env): + """ + On Windows, SYSTEMROOT must be present to avoid + + > Fatal Python error: _Py_HashRandomization_Init: failed to + > get random numbers to initialize Python + """ + if env and platform.system() == 'Windows': + env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] + return env + + +def find_distutils(venv, imports='distutils', env=None, **kwargs): + py_cmd = 'import {imports}; print(distutils.__file__)'.format(**locals()) + cmd = ['python', '-c', py_cmd] + return venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS, **kwargs) + + +def count_meta_path(venv, env=None): + py_cmd = textwrap.dedent( + """ + import sys + is_distutils = lambda finder: finder.__class__.__name__ == "DistutilsMetaFinder" + print(len(list(filter(is_distutils, sys.meta_path)))) + """ + ) + cmd = ['python', '-c', py_cmd] + return int(venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS)) + + +skip_without_stdlib_distutils = pytest.mark.skipif( + sys.version_info >= (3, 12), + reason='stdlib distutils is removed from Python 3.12+', +) + + +@skip_without_stdlib_distutils +def test_distutils_stdlib(venv): + """ + Ensure stdlib distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='stdlib') + assert venv.name not in find_distutils(venv, env=env).split(os.sep) + assert count_meta_path(venv, env=env) == 0 + + +def test_distutils_local_with_setuptools(venv): + """ + Ensure local distutils is used when appropriate. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + loc = find_distutils(venv, imports='setuptools, distutils', env=env) + assert venv.name in loc.split(os.sep) + assert count_meta_path(venv, env=env) <= 1 + + +@pytest.mark.xfail('IS_PYPY', reason='pypy imports distutils on startup') +def test_distutils_local(venv): + """ + Even without importing, the setuptools-local copy of distutils is + preferred. + """ + env = dict(SETUPTOOLS_USE_DISTUTILS='local') + assert venv.name in find_distutils(venv, env=env).split(os.sep) + assert count_meta_path(venv, env=env) <= 1 + + +def test_pip_import(venv): + """ + Ensure pip can be imported. + Regression test for #3002. + """ + cmd = ['python', '-c', 'import pip'] + venv.run(cmd, **_TEXT_KWARGS) + + +def test_distutils_has_origin(): + """ + Distutils module spec should have an origin. #2990. + """ + assert __import__('distutils').__spec__.origin + + +ENSURE_IMPORTS_ARE_NOT_DUPLICATED = r""" +# Depending on the importlib machinery and _distutils_hack, some imports are +# duplicated resulting in different module objects being loaded, which prevents +# patches as shown in #3042. +# This script provides a way of verifying if this duplication is happening. + +from distutils import cmd +import distutils.command.sdist as sdist + +# import last to prevent caching +from distutils import {imported_module} + +for mod in (cmd, sdist): + assert mod.{imported_module} == {imported_module}, ( + f"\n{{mod.dir_util}}\n!=\n{{{imported_module}}}" + ) + +print("success") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + ('distutils_version', 'imported_module'), + [ + pytest.param("stdlib", "dir_util", marks=skip_without_stdlib_distutils), + pytest.param("stdlib", "file_util", marks=skip_without_stdlib_distutils), + pytest.param("stdlib", "archive_util", marks=skip_without_stdlib_distutils), + ("local", "dir_util"), + ("local", "file_util"), + ("local", "archive_util"), + ], +) +def test_modules_are_not_duplicated_on_import(distutils_version, imported_module, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + script = ENSURE_IMPORTS_ARE_NOT_DUPLICATED.format(imported_module=imported_module) + cmd = ['python', '-c', script] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" + + +ENSURE_LOG_IMPORT_IS_NOT_DUPLICATED = r""" +import types +import distutils.dist as dist +from distutils import log +if isinstance(dist.log, types.ModuleType): + assert dist.log == log, f"\n{dist.log}\n!=\n{log}" +print("success") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + "distutils_version", + [ + "local", + pytest.param("stdlib", marks=skip_without_stdlib_distutils), + ], +) +def test_log_module_is_not_duplicated_on_import(distutils_version, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + cmd = ['python', '-c', ENSURE_LOG_IMPORT_IS_NOT_DUPLICATED] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" + + +ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY = r""" +from setuptools.modified import newer +from {imported_module}.errors import DistutilsError + +# Can't use pytest.raises in this context +try: + newer("", "") +except DistutilsError: + print("success") +else: + raise AssertionError("Expected to raise") +""" + + +@pytest.mark.usefixtures("tmpdir_cwd") +@pytest.mark.parametrize( + ('distutils_version', 'imported_module'), + [ + ("local", "distutils"), + # Unfortunately we still get ._distutils.errors.DistutilsError with SETUPTOOLS_USE_DISTUTILS=stdlib + # But that's a deprecated use-case we don't mind not fully supporting in newer code + pytest.param( + "stdlib", "setuptools._distutils", marks=skip_without_stdlib_distutils + ), + ], +) +def test_consistent_error_from_modified_py(distutils_version, imported_module, venv): + env = dict(SETUPTOOLS_USE_DISTUTILS=distutils_version) + cmd = [ + 'python', + '-c', + ENSURE_CONSISTENT_ERROR_FROM_MODIFIED_PY.format( + imported_module=imported_module + ), + ] + output = venv.run(cmd, env=win_sr(env), **_TEXT_KWARGS).strip() + assert output == "success" diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_editable_install.py b/python_embeded/Lib/site-packages/setuptools/tests/test_editable_install.py new file mode 100644 index 0000000000000000000000000000000000000000..225fc6a2f501e46e6b8f0c0010bf332dd1e59c54 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_editable_install.py @@ -0,0 +1,1263 @@ +from __future__ import annotations + +import os +import platform +import stat +import subprocess +import sys +from copy import deepcopy +from importlib import import_module +from importlib.machinery import EXTENSION_SUFFIXES +from pathlib import Path +from textwrap import dedent +from typing import Any +from unittest.mock import Mock +from uuid import uuid4 + +import jaraco.envs +import jaraco.path +import pytest +from path import Path as _Path + +from setuptools._importlib import resources as importlib_resources +from setuptools.command.editable_wheel import ( + _encode_pth, + _find_namespaces, + _find_package_roots, + _find_virtual_namespaces, + _finder_template, + _LinkTree, + _TopLevelFinder, + editable_wheel, +) +from setuptools.dist import Distribution +from setuptools.extension import Extension +from setuptools.warnings import SetuptoolsDeprecationWarning + +from . import contexts, namespaces + +from distutils.core import run_setup + + +@pytest.fixture(params=["strict", "lenient"]) +def editable_opts(request): + if request.param == "strict": + return ["--config-settings", "editable-mode=strict"] + return [] + + +EXAMPLE = { + 'pyproject.toml': dedent( + """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + license = {text = "MIT"} + description = "This is a Python package" + dynamic = ["readme"] + classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers" + ] + urls = {Homepage = "https://github.com"} + + [tool.setuptools] + package-dir = {"" = "src"} + packages = {find = {where = ["src"]}} + license-files = ["LICENSE*"] + + [tool.setuptools.dynamic] + readme = {file = "README.rst"} + + [tool.distutils.egg_info] + tag-build = ".post0" + """ + ), + "MANIFEST.in": dedent( + """\ + global-include *.py *.txt + global-exclude *.py[cod] + prune dist + prune build + """ + ).strip(), + "README.rst": "This is a ``README``", + "LICENSE.txt": "---- placeholder MIT license ----", + "src": { + "mypkg": { + "__init__.py": dedent( + """\ + import sys + from importlib.metadata import PackageNotFoundError, version + + try: + __version__ = version(__name__) + except PackageNotFoundError: + __version__ = "unknown" + """ + ), + "__main__.py": dedent( + """\ + from importlib.resources import read_text + from . import __version__, __name__ as parent + from .mod import x + + data = read_text(parent, "data.txt") + print(__version__, data, x) + """ + ), + "mod.py": "x = ''", + "data.txt": "Hello World", + } + }, +} + + +SETUP_SCRIPT_STUB = "__import__('setuptools').setup()" + + +@pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") +@pytest.mark.parametrize( + "files", + [ + {**EXAMPLE, "setup.py": SETUP_SCRIPT_STUB}, + EXAMPLE, # No setup.py script + ], +) +def test_editable_with_pyproject(tmp_path, venv, files, editable_opts): + project = tmp_path / "mypkg" + project.mkdir() + jaraco.path.build(files, prefix=project) + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + + cmd = ["python", "-m", "mypkg"] + assert venv.run(cmd).strip() == "3.14159.post0 Hello World" + + (project / "src/mypkg/data.txt").write_text("foobar", encoding="utf-8") + (project / "src/mypkg/mod.py").write_text("x = 42", encoding="utf-8") + assert venv.run(cmd).strip() == "3.14159.post0 foobar 42" + + +def test_editable_with_flat_layout(tmp_path, venv, editable_opts): + files = { + "mypkg": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + + [tool.setuptools] + packages = ["pkg"] + py-modules = ["mod"] + """ + ), + "pkg": {"__init__.py": "a = 4"}, + "mod.py": "b = 2", + }, + } + jaraco.path.build(files, prefix=tmp_path) + project = tmp_path / "mypkg" + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + cmd = ["python", "-c", "import pkg, mod; print(pkg.a, mod.b)"] + assert venv.run(cmd).strip() == "4 2" + + +def test_editable_with_single_module(tmp_path, venv, editable_opts): + files = { + "mypkg": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "mod" + version = "3.14159" + + [tool.setuptools] + py-modules = ["mod"] + """ + ), + "mod.py": "b = 2", + }, + } + jaraco.path.build(files, prefix=tmp_path) + project = tmp_path / "mypkg" + + cmd = [ + "python", + "-m", + "pip", + "install", + "--no-build-isolation", # required to force current version of setuptools + "-e", + str(project), + *editable_opts, + ] + print(venv.run(cmd)) + cmd = ["python", "-c", "import mod; print(mod.b)"] + assert venv.run(cmd).strip() == "2" + + +class TestLegacyNamespaces: + # legacy => pkg_resources.declare_namespace(...) + setup(namespace_packages=...) + + def test_nspkg_file_is_unique(self, tmp_path, monkeypatch): + deprecation = pytest.warns( + SetuptoolsDeprecationWarning, match=".*namespace_packages parameter.*" + ) + installation_dir = tmp_path / ".installation_dir" + installation_dir.mkdir() + examples = ( + "myns.pkgA", + "myns.pkgB", + "myns.n.pkgA", + "myns.n.pkgB", + ) + + for name in examples: + pkg = namespaces.build_namespace_package(tmp_path, name, version="42") + with deprecation, monkeypatch.context() as ctx: + ctx.chdir(pkg) + dist = run_setup("setup.py", stop_after="config") + cmd = editable_wheel(dist) + cmd.finalize_options() + editable_name = cmd.get_finalized_command("dist_info").name + cmd._install_namespaces(installation_dir, editable_name) + + files = list(installation_dir.glob("*-nspkg.pth")) + assert len(files) == len(examples) + + @pytest.mark.parametrize( + "impl", + ( + "pkg_resources", + # "pkgutil", => does not work + ), + ) + @pytest.mark.parametrize("ns", ("myns.n",)) + def test_namespace_package_importable( + self, venv, tmp_path, ns, impl, editable_opts + ): + """ + Installing two packages sharing the same namespace, one installed + naturally using pip or `--single-version-externally-managed` + and the other installed in editable mode should leave the namespace + intact and both packages reachable by import. + (Ported from test_develop). + """ + build_system = """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + """ + pkg_A = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgA", impl=impl) + pkg_B = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgB", impl=impl) + (pkg_A / "pyproject.toml").write_text(build_system, encoding="utf-8") + (pkg_B / "pyproject.toml").write_text(build_system, encoding="utf-8") + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-c", f"import {ns}.pkgA; import {ns}.pkgB"]) + # additionally ensure that pkg_resources import works + venv.run(["python", "-c", "import pkg_resources"]) + + +class TestPep420Namespaces: + def test_namespace_package_importable(self, venv, tmp_path, editable_opts): + """ + Installing two packages sharing the same namespace, one installed + normally using pip and the other installed in editable mode + should allow importing both packages. + """ + pkg_A = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgA') + pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB') + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-c", "import myns.n.pkgA; import myns.n.pkgB"]) + + def test_namespace_created_via_package_dir(self, venv, tmp_path, editable_opts): + """Currently users can create a namespace by tweaking `package_dir`""" + files = { + "pkgA": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "pkgA" + version = "3.14159" + + [tool.setuptools] + package-dir = {"myns.n.pkgA" = "src"} + """ + ), + "src": {"__init__.py": "a = 1"}, + }, + } + jaraco.path.build(files, prefix=tmp_path) + pkg_A = tmp_path / "pkgA" + pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB') + pkg_C = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgC') + + # use pip to install to the target directory + opts = editable_opts[:] + opts.append("--no-build-isolation") # force current version of setuptools + venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts]) + venv.run(["python", "-m", "pip", "install", "-e", str(pkg_C), *opts]) + venv.run(["python", "-c", "from myns.n import pkgA, pkgB, pkgC"]) + + def test_namespace_accidental_config_in_lenient_mode(self, venv, tmp_path): + """Sometimes users might specify an ``include`` pattern that ignores parent + packages. In a normal installation this would ignore all modules inside the + parent packages, and make them namespaces (reported in issue #3504), + so the editable mode should preserve this behaviour. + """ + files = { + "pkgA": { + "pyproject.toml": dedent( + """\ + [build-system] + requires = ["setuptools", "wheel"] + build-backend = "setuptools.build_meta" + + [project] + name = "pkgA" + version = "3.14159" + + [tool.setuptools] + packages.find.include = ["mypkg.*"] + """ + ), + "mypkg": { + "__init__.py": "", + "other.py": "b = 1", + "n": { + "__init__.py": "", + "pkgA.py": "a = 1", + }, + }, + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + }, + } + jaraco.path.build(files, prefix=tmp_path) + pkg_A = tmp_path / "pkgA" + + # use pip to install to the target directory + opts = ["--no-build-isolation"] # force current version of setuptools + venv.run(["python", "-m", "pip", "-v", "install", "-e", str(pkg_A), *opts]) + out = venv.run(["python", "-c", "from mypkg.n import pkgA; print(pkgA.a)"]) + assert out.strip() == "1" + cmd = """\ + try: + import mypkg.other + except ImportError: + print("mypkg.other not defined") + """ + out = venv.run(["python", "-c", dedent(cmd)]) + assert "mypkg.other not defined" in out + + +def test_editable_with_prefix(tmp_path, sample_project, editable_opts): + """ + Editable install to a prefix should be discoverable. + """ + prefix = tmp_path / 'prefix' + + # figure out where pip will likely install the package + site_packages_all = [ + prefix / Path(path).relative_to(sys.prefix) + for path in sys.path + if 'site-packages' in path and path.startswith(sys.prefix) + ] + + for sp in site_packages_all: + sp.mkdir(parents=True) + + # install workaround + _addsitedirs(site_packages_all) + + env = dict(os.environ, PYTHONPATH=os.pathsep.join(map(str, site_packages_all))) + cmd = [ + sys.executable, + '-m', + 'pip', + 'install', + '--editable', + str(sample_project), + '--prefix', + str(prefix), + '--no-build-isolation', + *editable_opts, + ] + subprocess.check_call(cmd, env=env) + + # now run 'sample' with the prefix on the PYTHONPATH + bin = 'Scripts' if platform.system() == 'Windows' else 'bin' + exe = prefix / bin / 'sample' + subprocess.check_call([exe], env=env) + + +class TestFinderTemplate: + """This test focus in getting a particular implementation detail right. + If at some point in time the implementation is changed for something different, + this test can be modified or even excluded. + """ + + def install_finder(self, finder): + loc = {} + exec(finder, loc, loc) + loc["install"]() + + def test_packages(self, tmp_path): + files = { + "src1": { + "pkg1": { + "__init__.py": "", + "subpkg": {"mod1.py": "a = 42"}, + }, + }, + "src2": {"mod2.py": "a = 43"}, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "pkg1": str(tmp_path / "src1/pkg1"), + "mod2": str(tmp_path / "src2/mod2"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("pkg1", "pkg1.subpkg", "pkg1.subpkg.mod1", "mod2"): + sys.modules.pop(mod, None) + + self.install_finder(template) + mod1 = import_module("pkg1.subpkg.mod1") + mod2 = import_module("mod2") + subpkg = import_module("pkg1.subpkg") + + assert mod1.a == 42 + assert mod2.a == 43 + expected = str((tmp_path / "src1/pkg1/subpkg").resolve()) + assert_path(subpkg, expected) + + def test_namespace(self, tmp_path): + files = {"pkg": {"__init__.py": "a = 13", "text.txt": "abc"}} + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"ns.othername": str(tmp_path / "pkg")} + namespaces = {"ns": []} + + template = _finder_template(str(uuid4()), mapping, namespaces) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.othername"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkg = import_module("ns.othername") + text = importlib_resources.files(pkg) / "text.txt" + + expected = str((tmp_path / "pkg").resolve()) + assert_path(pkg, expected) + assert pkg.a == 13 + + # Make sure resources can also be found + assert text.read_text(encoding="utf-8") == "abc" + + def test_combine_namespaces(self, tmp_path): + files = { + "src1": {"ns": {"pkg1": {"__init__.py": "a = 13"}}}, + "src2": {"ns": {"mod2.py": "b = 37"}}, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "ns.pkgA": str(tmp_path / "src1/ns/pkg1"), + "ns": str(tmp_path / "src2/ns"), + } + namespaces_ = {"ns": [str(tmp_path / "src1"), str(tmp_path / "src2")]} + template = _finder_template(str(uuid4()), mapping, namespaces_) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.pkgA", "ns.mod2"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkgA = import_module("ns.pkgA") + mod2 = import_module("ns.mod2") + + expected = str((tmp_path / "src1/ns/pkg1").resolve()) + assert_path(pkgA, expected) + assert pkgA.a == 13 + assert mod2.b == 37 + + def test_combine_namespaces_nested(self, tmp_path): + """ + Users may attempt to combine namespace packages in a nested way via + ``package_dir`` as shown in pypa/setuptools#4248. + """ + + files = { + "src": {"my_package": {"my_module.py": "a = 13"}}, + "src2": {"my_package2": {"my_module2.py": "b = 37"}}, + } + + stack = jaraco.path.DirectoryStack() + with stack.context(tmp_path): + jaraco.path.build(files) + attrs = { + "script_name": "%PEP 517%", + "package_dir": { + "different_name": "src/my_package", + "different_name.subpkg": "src2/my_package2", + }, + "packages": ["different_name", "different_name.subpkg"], + } + dist = Distribution(attrs) + finder = _TopLevelFinder(dist, str(uuid4())) + code = next(v for k, v in finder.get_implementation() if k.endswith(".py")) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in attrs["packages"]: + sys.modules.pop(mod, None) + + self.install_finder(code) + mod1 = import_module("different_name.my_module") + mod2 = import_module("different_name.subpkg.my_module2") + + expected = str((tmp_path / "src/my_package/my_module.py").resolve()) + assert str(Path(mod1.__file__).resolve()) == expected + + expected = str((tmp_path / "src2/my_package2/my_module2.py").resolve()) + assert str(Path(mod2.__file__).resolve()) == expected + + assert mod1.a == 13 + assert mod2.b == 37 + + def test_dynamic_path_computation(self, tmp_path): + # Follows the example in PEP 420 + files = { + "project1": {"parent": {"child": {"one.py": "x = 1"}}}, + "project2": {"parent": {"child": {"two.py": "x = 2"}}}, + "project3": {"parent": {"child": {"three.py": "x = 3"}}}, + } + jaraco.path.build(files, prefix=tmp_path) + mapping = {} + namespaces_ = {"parent": [str(tmp_path / "project1/parent")]} + template = _finder_template(str(uuid4()), mapping, namespaces_) + + mods = (f"parent.child.{name}" for name in ("one", "two", "three")) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("parent", "parent.child", "parent.child", *mods): + sys.modules.pop(mod, None) + + self.install_finder(template) + + one = import_module("parent.child.one") + assert one.x == 1 + + with pytest.raises(ImportError): + import_module("parent.child.two") + + sys.path.append(str(tmp_path / "project2")) + two = import_module("parent.child.two") + assert two.x == 2 + + with pytest.raises(ImportError): + import_module("parent.child.three") + + sys.path.append(str(tmp_path / "project3")) + three = import_module("parent.child.three") + assert three.x == 3 + + def test_no_recursion(self, tmp_path): + # See issue #3550 + files = { + "pkg": { + "__init__.py": "from . import pkg", + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "pkg": str(tmp_path / "pkg"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("pkg", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="pkg"): + import_module("pkg") + + def test_similar_name(self, tmp_path): + files = { + "foo": { + "__init__.py": "", + "bar": { + "__init__.py": "", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = { + "foo": str(tmp_path / "foo"), + } + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("foo", None) + sys.modules.pop("foo.bar", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="foobar"): + import_module("foobar") + + def test_case_sensitivity(self, tmp_path): + files = { + "foo": { + "__init__.py": "", + "lowercase.py": "x = 1", + "bar": { + "__init__.py": "", + "lowercase.py": "x = 2", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + mapping = { + "foo": str(tmp_path / "foo"), + } + template = _finder_template(str(uuid4()), mapping, {}) + with contexts.save_paths(), contexts.save_sys_modules(): + sys.modules.pop("foo", None) + + self.install_finder(template) + with pytest.raises(ImportError, match="'FOO'"): + import_module("FOO") + + with pytest.raises(ImportError, match="'foo\\.LOWERCASE'"): + import_module("foo.LOWERCASE") + + with pytest.raises(ImportError, match="'foo\\.bar\\.Lowercase'"): + import_module("foo.bar.Lowercase") + + with pytest.raises(ImportError, match="'foo\\.BAR'"): + import_module("foo.BAR.lowercase") + + with pytest.raises(ImportError, match="'FOO'"): + import_module("FOO.bar.lowercase") + + mod = import_module("foo.lowercase") + assert mod.x == 1 + + mod = import_module("foo.bar.lowercase") + assert mod.x == 2 + + def test_namespace_case_sensitivity(self, tmp_path): + files = { + "pkg": { + "__init__.py": "a = 13", + "foo": { + "__init__.py": "b = 37", + "bar.py": "c = 42", + }, + }, + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"ns.othername": str(tmp_path / "pkg")} + namespaces = {"ns": []} + + template = _finder_template(str(uuid4()), mapping, namespaces) + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ("ns", "ns.othername"): + sys.modules.pop(mod, None) + + self.install_finder(template) + pkg = import_module("ns.othername") + expected = str((tmp_path / "pkg").resolve()) + assert_path(pkg, expected) + assert pkg.a == 13 + + foo = import_module("ns.othername.foo") + assert foo.b == 37 + + bar = import_module("ns.othername.foo.bar") + assert bar.c == 42 + + with pytest.raises(ImportError, match="'NS'"): + import_module("NS.othername.foo") + + with pytest.raises(ImportError, match="'ns\\.othername\\.FOO\\'"): + import_module("ns.othername.FOO") + + with pytest.raises(ImportError, match="'ns\\.othername\\.foo\\.BAR\\'"): + import_module("ns.othername.foo.BAR") + + def test_intermediate_packages(self, tmp_path): + """ + The finder should not import ``fullname`` if the intermediate segments + don't exist (see pypa/setuptools#4019). + """ + files = { + "src": { + "mypkg": { + "__init__.py": "", + "config.py": "a = 13", + "helloworld.py": "b = 13", + "components": { + "config.py": "a = 37", + }, + }, + } + } + jaraco.path.build(files, prefix=tmp_path) + + mapping = {"mypkg": str(tmp_path / "src/mypkg")} + template = _finder_template(str(uuid4()), mapping, {}) + + with contexts.save_paths(), contexts.save_sys_modules(): + for mod in ( + "mypkg", + "mypkg.config", + "mypkg.helloworld", + "mypkg.components", + "mypkg.components.config", + "mypkg.components.helloworld", + ): + sys.modules.pop(mod, None) + + self.install_finder(template) + + config = import_module("mypkg.components.config") + assert config.a == 37 + + helloworld = import_module("mypkg.helloworld") + assert helloworld.b == 13 + + with pytest.raises(ImportError): + import_module("mypkg.components.helloworld") + + +def test_pkg_roots(tmp_path): + """This test focus in getting a particular implementation detail right. + If at some point in time the implementation is changed for something different, + this test can be modified or even excluded. + """ + files = { + "a": {"b": {"__init__.py": "ab = 1"}, "__init__.py": "a = 1"}, + "d": {"__init__.py": "d = 1", "e": {"__init__.py": "de = 1"}}, + "f": {"g": {"h": {"__init__.py": "fgh = 1"}}}, + "other": {"__init__.py": "abc = 1"}, + "another": {"__init__.py": "abcxyz = 1"}, + "yet_another": {"__init__.py": "mnopq = 1"}, + } + jaraco.path.build(files, prefix=tmp_path) + package_dir = { + "a.b.c": "other", + "a.b.c.x.y.z": "another", + "m.n.o.p.q": "yet_another", + } + packages = [ + "a", + "a.b", + "a.b.c", + "a.b.c.x.y", + "a.b.c.x.y.z", + "d", + "d.e", + "f", + "f.g", + "f.g.h", + "m.n.o.p.q", + ] + roots = _find_package_roots(packages, package_dir, tmp_path) + assert roots == { + "a": str(tmp_path / "a"), + "a.b.c": str(tmp_path / "other"), + "a.b.c.x.y.z": str(tmp_path / "another"), + "d": str(tmp_path / "d"), + "f": str(tmp_path / "f"), + "m.n.o.p.q": str(tmp_path / "yet_another"), + } + + ns = set(dict(_find_namespaces(packages, roots))) + assert ns == {"f", "f.g"} + + ns = set(_find_virtual_namespaces(roots)) + assert ns == {"a.b", "a.b.c.x", "a.b.c.x.y", "m", "m.n", "m.n.o", "m.n.o.p"} + + +class TestOverallBehaviour: + PYPROJECT = """\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "mypkg" + version = "3.14159" + """ + + # Any: Would need a TypedDict. Keep it simple for tests + FLAT_LAYOUT: dict[str, Any] = { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "mypkg": { + "__init__.py": "", + "mod1.py": "var = 42", + "subpackage": { + "__init__.py": "", + "mod2.py": "var = 13", + "resource_file.txt": "resource 39", + }, + }, + } + + EXAMPLES = { + "flat-layout": FLAT_LAYOUT, + "src-layout": { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "src": {"mypkg": FLAT_LAYOUT["mypkg"]}, + }, + "custom-layout": { + "pyproject.toml": dedent(PYPROJECT) + + dedent( + """\ + [tool.setuptools] + packages = ["mypkg", "mypkg.subpackage"] + + [tool.setuptools.package-dir] + "mypkg.subpackage" = "other" + """ + ), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "mypkg": { + "__init__.py": "", + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], + }, + "other": FLAT_LAYOUT["mypkg"]["subpackage"], + }, + "namespace": { + "pyproject.toml": dedent(PYPROJECT), + "MANIFEST.in": EXAMPLE["MANIFEST.in"], + "otherfile.py": "", + "src": { + "mypkg": { + "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"], + "subpackage": FLAT_LAYOUT["mypkg"]["subpackage"], + }, + }, + }, + } + + @pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328") + @pytest.mark.parametrize("layout", EXAMPLES.keys()) + def test_editable_install(self, tmp_path, venv, layout, editable_opts): + project, _ = install_project( + "mypkg", venv, tmp_path, self.EXAMPLES[layout], *editable_opts + ) + + # Ensure stray files are not importable + cmd_import_error = """\ + try: + import otherfile + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_import_error)]) + assert "No module named 'otherfile'" in out + + # Ensure the modules are importable + cmd_get_vars = """\ + import mypkg, mypkg.mod1, mypkg.subpackage.mod2 + print(mypkg.mod1.var, mypkg.subpackage.mod2.var) + """ + out = venv.run(["python", "-c", dedent(cmd_get_vars)]) + assert "42 13" in out + + # Ensure resources are reachable + cmd_get_resource = """\ + import mypkg.subpackage + from setuptools._importlib import resources as importlib_resources + text = importlib_resources.files(mypkg.subpackage) / "resource_file.txt" + print(text.read_text(encoding="utf-8")) + """ + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "resource 39" in out + + # Ensure files are editable + mod1 = next(project.glob("**/mod1.py")) + mod2 = next(project.glob("**/mod2.py")) + resource_file = next(project.glob("**/resource_file.txt")) + + mod1.write_text("var = 17", encoding="utf-8") + mod2.write_text("var = 781", encoding="utf-8") + resource_file.write_text("resource 374", encoding="utf-8") + + out = venv.run(["python", "-c", dedent(cmd_get_vars)]) + assert "42 13" not in out + assert "17 781" in out + + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "resource 39" not in out + assert "resource 374" in out + + +class TestLinkTree: + FILES = deepcopy(TestOverallBehaviour.EXAMPLES["src-layout"]) + FILES["pyproject.toml"] += dedent( + """\ + [tool.setuptools] + # Temporary workaround: both `include-package-data` and `package-data` configs + # can be removed after #3260 is fixed. + include-package-data = false + package-data = {"*" = ["*.txt"]} + + [tool.setuptools.packages.find] + where = ["src"] + exclude = ["*.subpackage*"] + """ + ) + FILES["src"]["mypkg"]["resource.not_in_manifest"] = "abc" + + def test_generated_tree(self, tmp_path): + jaraco.path.build(self.FILES, prefix=tmp_path) + + with _Path(tmp_path): + name = "mypkg-3.14159" + dist = Distribution({"script_name": "%PEP 517%"}) + dist.parse_config_files() + + wheel = Mock() + aux = tmp_path / ".aux" + build = tmp_path / ".build" + aux.mkdir() + build.mkdir() + + build_py = dist.get_command_obj("build_py") + build_py.editable_mode = True + build_py.build_lib = str(build) + build_py.ensure_finalized() + outputs = build_py.get_outputs() + output_mapping = build_py.get_output_mapping() + + make_tree = _LinkTree(dist, name, aux, build) + make_tree(wheel, outputs, output_mapping) + + mod1 = next(aux.glob("**/mod1.py")) + expected = tmp_path / "src/mypkg/mod1.py" + assert_link_to(mod1, expected) + + assert next(aux.glob("**/subpackage"), None) is None + assert next(aux.glob("**/mod2.py"), None) is None + assert next(aux.glob("**/resource_file.txt"), None) is None + + assert next(aux.glob("**/resource.not_in_manifest"), None) is None + + def test_strict_install(self, tmp_path, venv): + opts = ["--config-settings", "editable-mode=strict"] + install_project("mypkg", venv, tmp_path, self.FILES, *opts) + + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + # Ensure packages excluded from distribution are not importable + cmd_import_error = """\ + try: + from mypkg import subpackage + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_import_error)]) + assert "cannot import name 'subpackage'" in out + + # Ensure resource files excluded from distribution are not reachable + cmd_get_resource = """\ + import mypkg + from setuptools._importlib import resources as importlib_resources + try: + text = importlib_resources.files(mypkg) / "resource.not_in_manifest" + print(text.read_text(encoding="utf-8")) + except FileNotFoundError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd_get_resource)]) + assert "No such file or directory" in out + assert "resource.not_in_manifest" in out + + +@pytest.mark.filterwarnings("ignore:.*compat.*:setuptools.SetuptoolsDeprecationWarning") +def test_compat_install(tmp_path, venv): + # TODO: Remove `compat` after Dec/2022. + opts = ["--config-settings", "editable-mode=compat"] + files = TestOverallBehaviour.EXAMPLES["custom-layout"] + install_project("mypkg", venv, tmp_path, files, *opts) + + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + expected_path = comparable_path(str(tmp_path)) + + # Compatible behaviour will make spurious modules and excluded + # files importable directly from the original path + for cmd in ( + "import otherfile; print(otherfile)", + "import other; print(other)", + "import mypkg; print(mypkg)", + ): + out = comparable_path(venv.run(["python", "-c", cmd])) + assert expected_path in out + + # Compatible behaviour will not consider custom mappings + cmd = """\ + try: + from mypkg import subpackage; + except ImportError as ex: + print(ex) + """ + out = venv.run(["python", "-c", dedent(cmd)]) + assert "cannot import name 'subpackage'" in out + + +@pytest.mark.uses_network +def test_pbr_integration(pbr_package, venv, editable_opts): + """Ensure editable installs work with pbr, issue #3500""" + cmd = [ + 'python', + '-m', + 'pip', + '-v', + 'install', + '--editable', + pbr_package, + *editable_opts, + ] + venv.run(cmd, stderr=subprocess.STDOUT) + out = venv.run(["python", "-c", "import mypkg.hello"]) + assert "Hello world!" in out + + +class TestCustomBuildPy: + """ + Issue #3501 indicates that some plugins/customizations might rely on: + + 1. ``build_py`` not running + 2. ``build_py`` always copying files to ``build_lib`` + + During the transition period setuptools should prevent potential errors from + happening due to those assumptions. + """ + + # TODO: Remove tests after _run_build_steps is removed. + + FILES = { + **TestOverallBehaviour.EXAMPLES["flat-layout"], + "setup.py": dedent( + """\ + import pathlib + from setuptools import setup + from setuptools.command.build_py import build_py as orig + + class my_build_py(orig): + def run(self): + super().run() + raise ValueError("TEST_RAISE") + + setup(cmdclass={"build_py": my_build_py}) + """ + ), + } + + def test_safeguarded_from_errors(self, tmp_path, venv): + """Ensure that errors in custom build_py are reported as warnings""" + # Warnings should show up + _, out = install_project("mypkg", venv, tmp_path, self.FILES) + assert "SetuptoolsDeprecationWarning" in out + assert "ValueError: TEST_RAISE" in out + # but installation should be successful + out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"]) + assert "42" in out + + +class TestCustomBuildWheel: + def install_custom_build_wheel(self, dist): + bdist_wheel_cls = dist.get_command_class("bdist_wheel") + + class MyBdistWheel(bdist_wheel_cls): + def get_tag(self): + # In issue #3513, we can see that some extensions may try to access + # the `plat_name` property in bdist_wheel + if self.plat_name.startswith("macosx-"): + _ = "macOS platform" + return super().get_tag() + + dist.cmdclass["bdist_wheel"] = MyBdistWheel + + def test_access_plat_name(self, tmpdir_cwd): + # Even when a custom bdist_wheel tries to access plat_name the build should + # be successful + jaraco.path.build({"module.py": "x = 42"}) + dist = Distribution() + dist.script_name = "setup.py" + dist.set_defaults() + self.install_custom_build_wheel(dist) + cmd = editable_wheel(dist) + cmd.ensure_finalized() + cmd.run() + wheel_file = str(next(Path().glob('dist/*.whl'))) + assert "editable" in wheel_file + + +class TestCustomBuildExt: + def install_custom_build_ext_distutils(self, dist): + from distutils.command.build_ext import build_ext as build_ext_cls + + class MyBuildExt(build_ext_cls): + pass + + dist.cmdclass["build_ext"] = MyBuildExt + + @pytest.mark.skipif( + sys.platform != "linux", reason="compilers may fail without correct setup" + ) + def test_distutils_leave_inplace_files(self, tmpdir_cwd): + jaraco.path.build({"module.c": ""}) + attrs = { + "ext_modules": [Extension("module", ["module.c"])], + } + dist = Distribution(attrs) + dist.script_name = "setup.py" + dist.set_defaults() + self.install_custom_build_ext_distutils(dist) + cmd = editable_wheel(dist) + cmd.ensure_finalized() + cmd.run() + wheel_file = str(next(Path().glob('dist/*.whl'))) + assert "editable" in wheel_file + files = [p for p in Path().glob("module.*") if p.suffix != ".c"] + assert len(files) == 1 + name = files[0].name + assert any(name.endswith(ext) for ext in EXTENSION_SUFFIXES) + + +def test_debugging_tips(tmpdir_cwd, monkeypatch): + """Make sure to display useful debugging tips to the user.""" + jaraco.path.build({"module.py": "x = 42"}) + dist = Distribution() + dist.script_name = "setup.py" + dist.set_defaults() + cmd = editable_wheel(dist) + cmd.ensure_finalized() + + SimulatedErr = type("SimulatedErr", (Exception,), {}) + simulated_failure = Mock(side_effect=SimulatedErr()) + monkeypatch.setattr(cmd, "get_finalized_command", simulated_failure) + + with pytest.raises(SimulatedErr) as ctx: + cmd.run() + assert any('debugging-tips' in note for note in ctx.value.__notes__) + + +@pytest.mark.filterwarnings("error") +def test_encode_pth(): + """Ensure _encode_pth function does not produce encoding warnings""" + content = _encode_pth("tkmilan_ç_utf8") # no warnings (would be turned into errors) + assert isinstance(content, bytes) + + +def install_project(name, venv, tmp_path, files, *opts): + project = tmp_path / name + project.mkdir() + jaraco.path.build(files, prefix=project) + opts = [*opts, "--no-build-isolation"] # force current version of setuptools + out = venv.run( + ["python", "-m", "pip", "-v", "install", "-e", str(project), *opts], + stderr=subprocess.STDOUT, + ) + return project, out + + +def _addsitedirs(new_dirs): + """To use this function, it is necessary to insert new_dir in front of sys.path. + The Python process will try to import a ``sitecustomize`` module on startup. + If we manipulate sys.path/PYTHONPATH, we can force it to run our code, + which invokes ``addsitedir`` and ensure ``.pth`` files are loaded. + """ + content = '\n'.join( + ("import site",) + + tuple(f"site.addsitedir({os.fspath(new_dir)!r})" for new_dir in new_dirs) + ) + (new_dirs[0] / "sitecustomize.py").write_text(content, encoding="utf-8") + + +# ---- Assertion Helpers ---- + + +def assert_path(pkg, expected): + # __path__ is not guaranteed to exist, so we have to account for that + if pkg.__path__: + path = next(iter(pkg.__path__), None) + if path: + assert str(Path(path).resolve()) == expected + + +def assert_link_to(file: Path, other: Path) -> None: + if file.is_symlink(): + assert str(file.resolve()) == str(other.resolve()) + else: + file_stat = file.stat() + other_stat = other.stat() + assert file_stat[stat.ST_INO] == other_stat[stat.ST_INO] + assert file_stat[stat.ST_DEV] == other_stat[stat.ST_DEV] + + +def comparable_path(str_with_path: str) -> str: + return str_with_path.lower().replace(os.sep, "/").replace("//", "/") diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_egg_info.py b/python_embeded/Lib/site-packages/setuptools/tests/test_egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..3653be096f11b77c71f58679d6e4a108903668a5 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_egg_info.py @@ -0,0 +1,1306 @@ +from __future__ import annotations + +import ast +import glob +import os +import re +import stat +import sys +import time +from pathlib import Path +from unittest import mock + +import pytest +from jaraco import path + +from setuptools import errors +from setuptools.command.egg_info import egg_info, manifest_maker, write_entries +from setuptools.dist import Distribution + +from . import contexts, environment +from .textwrap import DALS + + +class Environment(str): + pass + + +@pytest.fixture +def env(): + with contexts.tempdir(prefix='setuptools-test.') as env_dir: + env = Environment(env_dir) + os.chmod(env_dir, stat.S_IRWXU) + subs = 'home', 'lib', 'scripts', 'data', 'egg-base' + env.paths = dict((dirname, os.path.join(env_dir, dirname)) for dirname in subs) + list(map(os.mkdir, env.paths.values())) + path.build({ + env.paths['home']: { + '.pydistutils.cfg': DALS( + """ + [egg_info] + egg-base = {egg-base} + """.format(**env.paths) + ) + } + }) + yield env + + +class TestEggInfo: + setup_script = DALS( + """ + from setuptools import setup + + setup( + name='foo', + py_modules=['hello'], + entry_points={'console_scripts': ['hi = hello.run']}, + zip_safe=False, + ) + """ + ) + + def _create_project(self): + path.build({ + 'setup.py': self.setup_script, + 'hello.py': DALS( + """ + def run(): + print('hello') + """ + ), + }) + + @staticmethod + def _extract_mv_version(pkg_info_lines: list[str]) -> tuple[int, int]: + version_str = pkg_info_lines[0].split(' ')[1] + major, minor = map(int, version_str.split('.')[:2]) + return major, minor + + def test_egg_info_save_version_info_setup_empty(self, tmpdir_cwd, env): + """ + When the egg_info section is empty or not present, running + save_version_info should add the settings to the setup.cfg + in a deterministic order. + """ + setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') + dist = Distribution() + ei = egg_info(dist) + ei.initialize_options() + ei.save_version_info(setup_cfg) + + with open(setup_cfg, 'r', encoding="utf-8") as f: + content = f.read() + + assert '[egg_info]' in content + assert 'tag_build =' in content + assert 'tag_date = 0' in content + + expected_order = ( + 'tag_build', + 'tag_date', + ) + + self._validate_content_order(content, expected_order) + + @staticmethod + def _validate_content_order(content, expected): + """ + Assert that the strings in expected appear in content + in order. + """ + pattern = '.*'.join(expected) + flags = re.MULTILINE | re.DOTALL + assert re.search(pattern, content, flags) + + def test_egg_info_save_version_info_setup_defaults(self, tmpdir_cwd, env): + """ + When running save_version_info on an existing setup.cfg + with the 'default' values present from a previous run, + the file should remain unchanged. + """ + setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') + path.build({ + setup_cfg: DALS( + """ + [egg_info] + tag_build = + tag_date = 0 + """ + ), + }) + dist = Distribution() + ei = egg_info(dist) + ei.initialize_options() + ei.save_version_info(setup_cfg) + + with open(setup_cfg, 'r', encoding="utf-8") as f: + content = f.read() + + assert '[egg_info]' in content + assert 'tag_build =' in content + assert 'tag_date = 0' in content + + expected_order = ( + 'tag_build', + 'tag_date', + ) + + self._validate_content_order(content, expected_order) + + def test_expected_files_produced(self, tmpdir_cwd, env): + self._create_project() + + self._run_egg_info_command(tmpdir_cwd, env) + actual = os.listdir('foo.egg-info') + + expected = [ + 'PKG-INFO', + 'SOURCES.txt', + 'dependency_links.txt', + 'entry_points.txt', + 'not-zip-safe', + 'top_level.txt', + ] + assert sorted(actual) == expected + + def test_handling_utime_error(self, tmpdir_cwd, env): + dist = Distribution() + ei = egg_info(dist) + utime_patch = mock.patch('os.utime', side_effect=OSError("TEST")) + mkpath_patch = mock.patch( + 'setuptools.command.egg_info.egg_info.mkpath', return_val=None + ) + + with utime_patch, mkpath_patch: + import distutils.errors + + msg = r"Cannot update time stamp of directory 'None'" + with pytest.raises(distutils.errors.DistutilsFileError, match=msg): + ei.run() + + def test_license_is_a_string(self, tmpdir_cwd, env): + setup_config = DALS( + """ + [metadata] + name=foo + version=0.0.1 + license=file:MIT + """ + ) + + setup_script = DALS( + """ + from setuptools import setup + + setup() + """ + ) + + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) + + # This command should fail with a ValueError, but because it's + # currently configured to use a subprocess, the actual traceback + # object is lost and we need to parse it from stderr + with pytest.raises(AssertionError) as exc: + self._run_egg_info_command(tmpdir_cwd, env) + + # The only argument to the assertion error should be a traceback + # containing a ValueError + assert 'ValueError' in exc.value.args[0] + + def test_rebuilt(self, tmpdir_cwd, env): + """Ensure timestamps are updated when the command is re-run.""" + self._create_project() + + self._run_egg_info_command(tmpdir_cwd, env) + timestamp_a = os.path.getmtime('foo.egg-info') + + # arbitrary sleep just to handle *really* fast systems + time.sleep(0.001) + + self._run_egg_info_command(tmpdir_cwd, env) + timestamp_b = os.path.getmtime('foo.egg-info') + + assert timestamp_a != timestamp_b + + def test_manifest_template_is_read(self, tmpdir_cwd, env): + self._create_project() + path.build({ + 'MANIFEST.in': DALS( + """ + recursive-include docs *.rst + """ + ), + 'docs': { + 'usage.rst': "Run 'hi'", + }, + }) + self._run_egg_info_command(tmpdir_cwd, env) + egg_info_dir = os.path.join('.', 'foo.egg-info') + sources_txt = os.path.join(egg_info_dir, 'SOURCES.txt') + with open(sources_txt, encoding="utf-8") as f: + assert 'docs/usage.rst' in f.read().split('\n') + + def _setup_script_with_requires(self, requires, use_setup_cfg=False): + setup_script = DALS( + """ + from setuptools import setup + + setup(name='foo', zip_safe=False, %s) + """ + ) % ('' if use_setup_cfg else requires) + setup_config = requires if use_setup_cfg else '' + path.build({ + 'setup.py': setup_script, + 'setup.cfg': setup_config, + }) + + mismatch_marker = f"python_version<'{sys.version_info[0]}'" + # Alternate equivalent syntax. + mismatch_marker_alternate = f'python_version < "{sys.version_info[0]}"' + invalid_marker = "<=>++" + + class RequiresTestHelper: + @staticmethod + def parametrize(*test_list, **format_dict): + idlist = [] + argvalues = [] + for test in test_list: + test_params = test.lstrip().split('\n\n', 3) + name_kwargs = test_params.pop(0).split('\n') + if len(name_kwargs) > 1: + val = name_kwargs[1].strip() + install_cmd_kwargs = ast.literal_eval(val) + else: + install_cmd_kwargs = {} + name = name_kwargs[0].strip() + setup_py_requires, setup_cfg_requires, expected_requires = [ + DALS(a).format(**format_dict) for a in test_params + ] + for id_, requires, use_cfg in ( + (name, setup_py_requires, False), + (name + '_in_setup_cfg', setup_cfg_requires, True), + ): + idlist.append(id_) + marks = () + if requires.startswith('@xfail\n'): + requires = requires[7:] + marks = pytest.mark.xfail + argvalues.append( + pytest.param( + requires, + use_cfg, + expected_requires, + install_cmd_kwargs, + marks=marks, + ) + ) + return pytest.mark.parametrize( + ( + "requires", + "use_setup_cfg", + "expected_requires", + "install_cmd_kwargs", + ), + argvalues, + ids=idlist, + ) + + @RequiresTestHelper.parametrize( + # Format of a test: + # + # id + # install_cmd_kwargs [optional] + # + # requires block (when used in setup.py) + # + # requires block (when used in setup.cfg) + # + # expected contents of requires.txt + """ + install_requires_deterministic + + install_requires=["wheel>=0.5", "pytest"] + + [options] + install_requires = + wheel>=0.5 + pytest + + wheel>=0.5 + pytest + """, + """ + install_requires_ordered + + install_requires=["pytest>=3.0.2,!=10.9999"] + + [options] + install_requires = + pytest>=3.0.2,!=10.9999 + + pytest!=10.9999,>=3.0.2 + """, + """ + install_requires_with_marker + + install_requires=["barbazquux;{mismatch_marker}"], + + [options] + install_requires = + barbazquux; {mismatch_marker} + + [:{mismatch_marker_alternate}] + barbazquux + """, + """ + install_requires_with_extra + {'cmd': ['egg_info']} + + install_requires=["barbazquux [test]"], + + [options] + install_requires = + barbazquux [test] + + barbazquux[test] + """, + """ + install_requires_with_extra_and_marker + + install_requires=["barbazquux [test]; {mismatch_marker}"], + + [options] + install_requires = + barbazquux [test]; {mismatch_marker} + + [:{mismatch_marker_alternate}] + barbazquux[test] + """, + """ + setup_requires_with_markers + + setup_requires=["barbazquux;{mismatch_marker}"], + + [options] + setup_requires = + barbazquux; {mismatch_marker} + + """, + """ + extras_require_with_extra + {'cmd': ['egg_info']} + + extras_require={{"extra": ["barbazquux [test]"]}}, + + [options.extras_require] + extra = barbazquux [test] + + [extra] + barbazquux[test] + """, + """ + extras_require_with_extra_and_marker_in_req + + extras_require={{"extra": ["barbazquux [test]; {mismatch_marker}"]}}, + + [options.extras_require] + extra = + barbazquux [test]; {mismatch_marker} + + [extra] + + [extra:{mismatch_marker_alternate}] + barbazquux[test] + """, + # FIXME: ConfigParser does not allow : in key names! + """ + extras_require_with_marker + + extras_require={{":{mismatch_marker}": ["barbazquux"]}}, + + @xfail + [options.extras_require] + :{mismatch_marker} = barbazquux + + [:{mismatch_marker}] + barbazquux + """, + """ + extras_require_with_marker_in_req + + extras_require={{"extra": ["barbazquux; {mismatch_marker}"]}}, + + [options.extras_require] + extra = + barbazquux; {mismatch_marker} + + [extra] + + [extra:{mismatch_marker_alternate}] + barbazquux + """, + """ + extras_require_with_empty_section + + extras_require={{"empty": []}}, + + [options.extras_require] + empty = + + [empty] + """, + # Format arguments. + invalid_marker=invalid_marker, + mismatch_marker=mismatch_marker, + mismatch_marker_alternate=mismatch_marker_alternate, + ) + def test_requires( + self, + tmpdir_cwd, + env, + requires, + use_setup_cfg, + expected_requires, + install_cmd_kwargs, + ): + self._setup_script_with_requires(requires, use_setup_cfg) + self._run_egg_info_command(tmpdir_cwd, env, **install_cmd_kwargs) + egg_info_dir = os.path.join('.', 'foo.egg-info') + requires_txt = os.path.join(egg_info_dir, 'requires.txt') + if os.path.exists(requires_txt): + with open(requires_txt, encoding="utf-8") as fp: + install_requires = fp.read() + else: + install_requires = '' + assert install_requires.lstrip() == expected_requires + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_install_requires_unordered_disallowed(self, tmpdir_cwd, env): + """ + Packages that pass unordered install_requires sequences + should be rejected as they produce non-deterministic + builds. See #458. + """ + req = 'install_requires={"fake-factory==0.5.2", "pytz"}' + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + + def test_extras_require_with_invalid_marker(self, tmpdir_cwd, env): + tmpl = 'extras_require={{":{marker}": ["barbazquux"]}},' + req = tmpl.format(marker=self.invalid_marker) + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_extras_require_with_invalid_marker_in_req(self, tmpdir_cwd, env): + tmpl = 'extras_require={{"extra": ["barbazquux; {marker}"]}},' + req = tmpl.format(marker=self.invalid_marker) + self._setup_script_with_requires(req) + with pytest.raises(AssertionError): + self._run_egg_info_command(tmpdir_cwd, env) + assert glob.glob(os.path.join(env.paths['lib'], 'barbazquux*')) == [] + + def test_provides_extra(self, tmpdir_cwd, env): + self._setup_script_with_requires('extras_require={"foobar": ["barbazquux"]},') + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Provides-Extra: foobar' in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines + + def test_doesnt_provides_extra(self, tmpdir_cwd, env): + self._setup_script_with_requires( + """install_requires=["spam ; python_version<'3.6'"]""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_text = fp.read() + assert 'Provides-Extra:' not in pkg_info_text + + @pytest.mark.parametrize( + ('files', 'license_in_sources'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE + """ + ), + 'LICENSE': "Test license", + }, + True, + ), # with license + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = INVALID_LICENSE + """ + ), + 'LICENSE': "Test license", + }, + False, + ), # with an invalid license + ( + { + 'setup.cfg': DALS( + """ + """ + ), + 'LICENSE': "Test license", + }, + True, + ), # no license_file attribute, LICENSE auto-included + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE + """ + ), + 'MANIFEST.in': "exclude LICENSE", + 'LICENSE': "Test license", + }, + True, + ), # manifest is overwritten by license_file + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICEN[CS]E* + """ + ), + 'LICENSE': "Test license", + }, + True, + id="glob_pattern", + ), + ], + ) + def test_setup_cfg_license_file(self, tmpdir_cwd, env, files, license_in_sources): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + + if license_in_sources: + assert 'LICENSE' in sources_text + else: + assert 'LICENSE' not in sources_text + # for invalid license test + assert 'INVALID_LICENSE' not in sources_text + + @pytest.mark.parametrize( + ('files', 'incl_licenses', 'excl_licenses'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), # with licenses + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE-ABC, LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), # with commas + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC'], + ['LICENSE-XYZ'], + ), # with one license + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), # empty + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-XYZ'], + ['LICENSE-ABC'], + ), # on same line + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + INVALID_LICENSE + """ + ), + 'LICENSE-ABC': "Test license", + }, + ['LICENSE-ABC'], + ['INVALID_LICENSE'], + ), # with an invalid license + ( + { + 'setup.cfg': DALS( + """ + """ + ), + 'LICENSE': "Test license", + }, + ['LICENSE'], + [], + ), # no license_files attribute, LICENSE auto-included + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = LICENSE + """ + ), + 'MANIFEST.in': "exclude LICENSE", + 'LICENSE': "Test license", + }, + ['LICENSE'], + [], + ), # manifest is overwritten by license_files + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'MANIFEST.in': "exclude LICENSE-XYZ", + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + # manifest is overwritten by license_files + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + [], + ), + pytest.param( + { + 'setup.cfg': "", + 'LICENSE-ABC': "ABC license", + 'COPYING-ABC': "ABC copying", + 'NOTICE-ABC': "ABC notice", + 'AUTHORS-ABC': "ABC authors", + 'LICENCE-XYZ': "XYZ license", + 'LICENSE': "License", + 'INVALID-LICENSE': "Invalid license", + }, + [ + 'LICENSE-ABC', + 'COPYING-ABC', + 'NOTICE-ABC', + 'AUTHORS-ABC', + 'LICENCE-XYZ', + 'LICENSE', + ], + ['INVALID-LICENSE'], + # ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*') + id="default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-XYZ': "XYZ notice", + }, + ['LICENSE-ABC'], + ['NOTICE-XYZ'], + id="no_default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = + LICENSE-ABC + LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + }, + ['LICENSE-ABC'], + [], + id="files_only_added_once", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_files = **/LICENSE + """ + ), + 'LICENSE': "ABC license", + 'LICENSE-OTHER': "Don't include", + 'vendor': {'LICENSE': "Vendor license"}, + }, + ['LICENSE', 'vendor/LICENSE'], + ['LICENSE-OTHER'], + id="recursive_glob", + ), + ], + ) + def test_setup_cfg_license_files( + self, tmpdir_cwd, env, files, incl_licenses, excl_licenses + ): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] + + for lf in incl_licenses: + assert sources_lines.count(lf) == 1 + + for lf in excl_licenses: + assert sources_lines.count(lf) == 0 + + @pytest.mark.parametrize( + ('files', 'incl_licenses', 'excl_licenses'), + [ + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = + license_files = + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), # both empty + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = + LICENSE-ABC + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-XYZ': "XYZ license", + # license_file is still singular + }, + [], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), # combined + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-ABC + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # duplicate license + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + """ + ), + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # combined subset + }, + ['LICENSE-ABC', 'LICENSE-XYZ'], + ['LICENSE-PQR'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-XYZ + LICENSE-PQR + """ + ), + 'LICENSE-PQR': "Test license", + # with invalid licenses + }, + ['LICENSE-PQR'], + ['LICENSE-ABC', 'LICENSE-XYZ'], + ), + ( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE-ABC + license_files = + LICENSE-PQR + LICENSE-XYZ + """ + ), + 'MANIFEST.in': "exclude LICENSE-ABC\nexclude LICENSE-PQR", + 'LICENSE-ABC': "ABC license", + 'LICENSE-PQR': "PQR license", + 'LICENSE-XYZ': "XYZ license", + # manifest is overwritten + }, + ['LICENSE-ABC', 'LICENSE-PQR', 'LICENSE-XYZ'], + [], + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-XYZ': "XYZ notice", + }, + ['LICENSE-ABC'], + ['NOTICE-XYZ'], + id="no_default_glob_patterns", + ), + pytest.param( + { + 'setup.cfg': DALS( + """ + [metadata] + license_file = LICENSE* + license_files = + NOTICE* + """ + ), + 'LICENSE-ABC': "ABC license", + 'NOTICE-ABC': "ABC notice", + 'AUTHORS-ABC': "ABC authors", + }, + ['LICENSE-ABC', 'NOTICE-ABC'], + ['AUTHORS-ABC'], + id="combined_glob_patterrns", + ), + ], + ) + def test_setup_cfg_license_file_license_files( + self, tmpdir_cwd, env, files, incl_licenses, excl_licenses + ): + self._create_project() + path.build(files) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + + sources_text = Path(egg_info_dir, "SOURCES.txt").read_text(encoding="utf-8") + sources_lines = [line.strip() for line in sources_text.splitlines()] + + for lf in incl_licenses: + assert sources_lines.count(lf) == 1 + + for lf in excl_licenses: + assert sources_lines.count(lf) == 0 + + def test_license_file_attr_pkg_info(self, tmpdir_cwd, env): + """All matched license files should have a corresponding License-File.""" + self._create_project() + path.build({ + "setup.cfg": DALS( + """ + [metadata] + license_files = + NOTICE* + LICENSE* + **/LICENSE + """ + ), + "LICENSE-ABC": "ABC license", + "LICENSE-XYZ": "XYZ license", + "NOTICE": "included", + "IGNORE": "not include", + "vendor": {'LICENSE': "Vendor license"}, + }) + + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + license_file_lines = [ + line for line in pkg_info_lines if line.startswith('License-File:') + ] + + # Only 'NOTICE', LICENSE-ABC', and 'LICENSE-XYZ' should have been matched + # Also assert that order from license_files is keeped + assert len(license_file_lines) == 4 + assert "License-File: NOTICE" == license_file_lines[0] + assert "License-File: LICENSE-ABC" in license_file_lines[1:] + assert "License-File: LICENSE-XYZ" in license_file_lines[1:] + assert "License-File: vendor/LICENSE" in license_file_lines[3] + + def test_metadata_version(self, tmpdir_cwd, env): + """Make sure latest metadata version is used by default.""" + self._setup_script_with_requires("") + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + # Update metadata version if changed + assert self._extract_mv_version(pkg_info_lines) == (2, 4) + + def test_long_description_content_type(self, tmpdir_cwd, env): + # Test that specifying a `long_description_content_type` keyword arg to + # the `setup` function results in writing a `Description-Content-Type` + # line to the `PKG-INFO` file in the `.egg-info` + # directory. + # `Description-Content-Type` is described at + # https://github.com/pypa/python-packaging-user-guide/pull/258 + + self._setup_script_with_requires( + """long_description_content_type='text/markdown',""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + expected_line = 'Description-Content-Type: text/markdown' + assert expected_line in pkg_info_lines + assert 'Metadata-Version: 2.4' in pkg_info_lines + + def test_long_description(self, tmpdir_cwd, env): + # Test that specifying `long_description` and `long_description_content_type` + # keyword args to the `setup` function results in writing + # the description in the message payload of the `PKG-INFO` file + # in the `.egg-info` directory. + self._setup_script_with_requires( + "long_description='This is a long description\\nover multiple lines'," + "long_description_content_type='text/markdown'," + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Metadata-Version: 2.4' in pkg_info_lines + assert '' == pkg_info_lines[-1] # last line should be empty + long_desc_lines = pkg_info_lines[pkg_info_lines.index('') :] + assert 'This is a long description' in long_desc_lines + assert 'over multiple lines' in long_desc_lines + + def test_project_urls(self, tmpdir_cwd, env): + # Test that specifying a `project_urls` dict to the `setup` + # function results in writing multiple `Project-URL` lines to + # the `PKG-INFO` file in the `.egg-info` + # directory. + # `Project-URL` is described at https://packaging.python.org + # /specifications/core-metadata/#project-url-multiple-use + + self._setup_script_with_requires( + """project_urls={ + 'Link One': 'https://example.com/one/', + 'Link Two': 'https://example.com/two/', + },""" + ) + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + expected_line = 'Project-URL: Link One, https://example.com/one/' + assert expected_line in pkg_info_lines + expected_line = 'Project-URL: Link Two, https://example.com/two/' + assert expected_line in pkg_info_lines + assert self._extract_mv_version(pkg_info_lines) >= (1, 2) + + def test_license(self, tmpdir_cwd, env): + """Test single line license.""" + self._setup_script_with_requires("license='MIT',") + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'License: MIT' in pkg_info_lines + + def test_license_escape(self, tmpdir_cwd, env): + """Test license is escaped correctly if longer than one line.""" + self._setup_script_with_requires( + "license='This is a long license text \\nover multiple lines'," + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + + assert 'License: This is a long license text ' in pkg_info_lines + assert ' over multiple lines' in pkg_info_lines + assert 'text \n over multiple' in '\n'.join(pkg_info_lines) + + def test_python_requires_egg_info(self, tmpdir_cwd, env): + self._setup_script_with_requires("""python_requires='>=2.7.12',""") + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + environment.run_setup_py( + cmd=['egg_info'], + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Requires-Python: >=2.7.12' in pkg_info_lines + assert self._extract_mv_version(pkg_info_lines) >= (1, 2) + + def test_manifest_maker_warning_suppression(self): + fixtures = [ + "standard file not found: should have one of foo.py, bar.py", + "standard file 'setup.py' not found", + ] + + for msg in fixtures: + assert manifest_maker._should_suppress_warning(msg) + + def test_egg_info_includes_setup_py(self, tmpdir_cwd): + self._create_project() + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.script_name = "non_setup.py" + egg_info_instance = egg_info(dist) + egg_info_instance.finalize_options() + egg_info_instance.run() + + assert 'setup.py' in egg_info_instance.filelist.files + + with open(egg_info_instance.egg_info + "/SOURCES.txt", encoding="utf-8") as f: + sources = f.read().split('\n') + assert 'setup.py' in sources + + def _run_egg_info_command(self, tmpdir_cwd, env, cmd=None, output=None): + environ = os.environ.copy().update( + HOME=env.paths['home'], + ) + if cmd is None: + cmd = [ + 'egg_info', + ] + code, data = environment.run_setup_py( + cmd=cmd, + pypath=os.pathsep.join([env.paths['lib'], str(tmpdir_cwd)]), + data_stream=1, + env=environ, + ) + assert not code, data + + if output: + assert output in data + + def test_egg_info_tag_only_once(self, tmpdir_cwd, env): + self._create_project() + path.build({ + 'setup.cfg': DALS( + """ + [egg_info] + tag_build = dev + tag_date = 0 + tag_svn_revision = 0 + """ + ), + }) + self._run_egg_info_command(tmpdir_cwd, env) + egg_info_dir = os.path.join('.', 'foo.egg-info') + with open(os.path.join(egg_info_dir, 'PKG-INFO'), encoding="utf-8") as fp: + pkg_info_lines = fp.read().split('\n') + assert 'Version: 0.0.0.dev0' in pkg_info_lines + + +class TestWriteEntries: + def test_invalid_entry_point(self, tmpdir_cwd, env): + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.entry_points = {"foo": "foo = invalid-identifier:foo"} + cmd = dist.get_command_obj("egg_info") + expected_msg = r"(Invalid object reference|Problems to parse)" + with pytest.raises((errors.OptionError, ValueError), match=expected_msg) as ex: + write_entries(cmd, "entry_points", "entry_points.txt") + assert "ensure entry-point follows the spec" in ex.value.args[0] + assert "invalid-identifier" in str(ex.value) + + def test_valid_entry_point(self, tmpdir_cwd, env): + dist = Distribution({"name": "foo", "version": "0.0.1"}) + dist.entry_points = { + "abc": "foo = bar:baz", + "def": ["faa = bor:boz"], + } + cmd = dist.get_command_obj("egg_info") + write_entries(cmd, "entry_points", "entry_points.txt") + content = Path("entry_points.txt").read_text(encoding="utf-8") + assert "[abc]\nfoo = bar:baz\n" in content + assert "[def]\nfaa = bor:boz\n" in content diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_extern.py b/python_embeded/Lib/site-packages/setuptools/tests/test_extern.py new file mode 100644 index 0000000000000000000000000000000000000000..d7eb3c62c190dacdd4a054d2934962be2f4ee860 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_extern.py @@ -0,0 +1,15 @@ +import importlib +import pickle + +import packaging + +from setuptools import Distribution + + +def test_reimport_extern(): + packaging2 = importlib.import_module(packaging.__name__) + assert packaging is packaging2 + + +def test_distribution_picklable(): + pickle.loads(pickle.dumps(Distribution())) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_find_packages.py b/python_embeded/Lib/site-packages/setuptools/tests/test_find_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd9f8f6637d13cb898fcd446a6b090323d02014 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_find_packages.py @@ -0,0 +1,218 @@ +"""Tests for automatic package discovery""" + +import os +import shutil +import tempfile + +import pytest + +from setuptools import find_namespace_packages, find_packages +from setuptools.discovery import FlatLayoutPackageFinder + +from .compat.py39 import os_helper + + +class TestFindPackages: + def setup_method(self, method): + self.dist_dir = tempfile.mkdtemp() + self._make_pkg_structure() + + def teardown_method(self, method): + shutil.rmtree(self.dist_dir) + + def _make_pkg_structure(self): + """Make basic package structure. + + dist/ + docs/ + conf.py + pkg/ + __pycache__/ + nspkg/ + mod.py + subpkg/ + assets/ + asset + __init__.py + setup.py + + """ + self.docs_dir = self._mkdir('docs', self.dist_dir) + self._touch('conf.py', self.docs_dir) + self.pkg_dir = self._mkdir('pkg', self.dist_dir) + self._mkdir('__pycache__', self.pkg_dir) + self.ns_pkg_dir = self._mkdir('nspkg', self.pkg_dir) + self._touch('mod.py', self.ns_pkg_dir) + self.sub_pkg_dir = self._mkdir('subpkg', self.pkg_dir) + self.asset_dir = self._mkdir('assets', self.sub_pkg_dir) + self._touch('asset', self.asset_dir) + self._touch('__init__.py', self.sub_pkg_dir) + self._touch('setup.py', self.dist_dir) + + def _mkdir(self, path, parent_dir=None): + if parent_dir: + path = os.path.join(parent_dir, path) + os.mkdir(path) + return path + + def _touch(self, path, dir_=None): + if dir_: + path = os.path.join(dir_, path) + open(path, 'wb').close() + return path + + def test_regular_package(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_packages(self.dist_dir) + assert packages == ['pkg', 'pkg.subpkg'] + + def test_exclude(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_packages(self.dist_dir, exclude=('pkg.*',)) + assert packages == ['pkg'] + + def test_exclude_recursive(self): + """ + Excluding a parent package should not exclude child packages as well. + """ + self._touch('__init__.py', self.pkg_dir) + self._touch('__init__.py', self.sub_pkg_dir) + packages = find_packages(self.dist_dir, exclude=('pkg',)) + assert packages == ['pkg.subpkg'] + + def test_include_excludes_other(self): + """ + If include is specified, other packages should be excluded. + """ + self._touch('__init__.py', self.pkg_dir) + alt_dir = self._mkdir('other_pkg', self.dist_dir) + self._touch('__init__.py', alt_dir) + packages = find_packages(self.dist_dir, include=['other_pkg']) + assert packages == ['other_pkg'] + + def test_dir_with_dot_is_skipped(self): + shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) + data_dir = self._mkdir('some.data', self.pkg_dir) + self._touch('__init__.py', data_dir) + self._touch('file.dat', data_dir) + packages = find_packages(self.dist_dir) + assert 'pkg.some.data' not in packages + + def test_dir_with_packages_in_subdir_is_excluded(self): + """ + Ensure that a package in a non-package such as build/pkg/__init__.py + is excluded. + """ + build_dir = self._mkdir('build', self.dist_dir) + build_pkg_dir = self._mkdir('pkg', build_dir) + self._touch('__init__.py', build_pkg_dir) + packages = find_packages(self.dist_dir) + assert 'build.pkg' not in packages + + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') + def test_symlinked_packages_are_included(self): + """ + A symbolically-linked directory should be treated like any other + directory when matched as a package. + + Create a link from lpkg -> pkg. + """ + self._touch('__init__.py', self.pkg_dir) + linked_pkg = os.path.join(self.dist_dir, 'lpkg') + os.symlink('pkg', linked_pkg) + assert os.path.isdir(linked_pkg) + packages = find_packages(self.dist_dir) + assert 'lpkg' in packages + + def _assert_packages(self, actual, expected): + assert set(actual) == set(expected) + + def test_pep420_ns_package(self): + packages = find_namespace_packages( + self.dist_dir, include=['pkg*'], exclude=['pkg.subpkg.assets'] + ) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_includes(self): + packages = find_namespace_packages(self.dist_dir, exclude=['pkg.subpkg.assets']) + self._assert_packages(packages, ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_includes_or_excludes(self): + packages = find_namespace_packages(self.dist_dir) + expected = ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg', 'pkg.subpkg.assets'] + self._assert_packages(packages, expected) + + def test_regular_package_with_nested_pep420_ns_packages(self): + self._touch('__init__.py', self.pkg_dir) + packages = find_namespace_packages( + self.dist_dir, exclude=['docs', 'pkg.subpkg.assets'] + ) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + def test_pep420_ns_package_no_non_package_dirs(self): + shutil.rmtree(self.docs_dir) + shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) + packages = find_namespace_packages(self.dist_dir) + self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) + + +class TestFlatLayoutPackageFinder: + EXAMPLES = { + "hidden-folders": ( + [".pkg/__init__.py", "pkg/__init__.py", "pkg/nested/file.txt"], + ["pkg", "pkg.nested"], + ), + "private-packages": ( + ["_pkg/__init__.py", "pkg/_private/__init__.py"], + ["pkg", "pkg._private"], + ), + "invalid-name": ( + ["invalid-pkg/__init__.py", "other.pkg/__init__.py", "yet,another/file.py"], + [], + ), + "docs": (["pkg/__init__.py", "docs/conf.py", "docs/readme.rst"], ["pkg"]), + "tests": ( + ["pkg/__init__.py", "tests/test_pkg.py", "tests/__init__.py"], + ["pkg"], + ), + "examples": ( + [ + "pkg/__init__.py", + "examples/__init__.py", + "examples/file.py", + "example/other_file.py", + # Sub-packages should always be fine + "pkg/example/__init__.py", + "pkg/examples/__init__.py", + ], + ["pkg", "pkg.examples", "pkg.example"], + ), + "tool-specific": ( + [ + "htmlcov/index.html", + "pkg/__init__.py", + "tasks/__init__.py", + "tasks/subpackage/__init__.py", + "fabfile/__init__.py", + "fabfile/subpackage/__init__.py", + # Sub-packages should always be fine + "pkg/tasks/__init__.py", + "pkg/fabfile/__init__.py", + ], + ["pkg", "pkg.tasks", "pkg.fabfile"], + ), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_unwanted_directories_not_included(self, tmp_path, example): + files, expected_packages = self.EXAMPLES[example] + ensure_files(tmp_path, files) + found_packages = FlatLayoutPackageFinder.find(str(tmp_path)) + assert set(found_packages) == set(expected_packages) + + +def ensure_files(root_path, files): + for file in files: + path = root_path / file + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_find_py_modules.py b/python_embeded/Lib/site-packages/setuptools/tests/test_find_py_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..8034b544294e5d30274bac82f24f93613120a0d4 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_find_py_modules.py @@ -0,0 +1,73 @@ +"""Tests for automatic discovery of modules""" + +import os + +import pytest + +from setuptools.discovery import FlatLayoutModuleFinder, ModuleFinder + +from .compat.py39 import os_helper +from .test_find_packages import ensure_files + + +class TestModuleFinder: + def find(self, path, *args, **kwargs): + return set(ModuleFinder.find(str(path), *args, **kwargs)) + + EXAMPLES = { + # circumstance: (files, kwargs, expected_modules) + "simple_folder": ( + ["file.py", "other.py"], + {}, # kwargs + ["file", "other"], + ), + "exclude": ( + ["file.py", "other.py"], + {"exclude": ["f*"]}, + ["other"], + ), + "include": ( + ["file.py", "fole.py", "other.py"], + {"include": ["f*"], "exclude": ["fo*"]}, + ["file"], + ), + "invalid-name": (["my-file.py", "other.file.py"], {}, []), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_finder(self, tmp_path, example): + files, kwargs, expected_modules = self.EXAMPLES[example] + ensure_files(tmp_path, files) + assert self.find(tmp_path, **kwargs) == set(expected_modules) + + @pytest.mark.skipif(not os_helper.can_symlink(), reason='Symlink support required') + def test_symlinked_packages_are_included(self, tmp_path): + src = "_myfiles/file.py" + ensure_files(tmp_path, [src]) + os.symlink(tmp_path / src, tmp_path / "link.py") + assert self.find(tmp_path) == {"link"} + + +class TestFlatLayoutModuleFinder: + def find(self, path, *args, **kwargs): + return set(FlatLayoutModuleFinder.find(str(path))) + + EXAMPLES = { + # circumstance: (files, expected_modules) + "hidden-files": ([".module.py"], []), + "private-modules": (["_module.py"], []), + "common-names": ( + ["setup.py", "conftest.py", "test.py", "tests.py", "example.py", "mod.py"], + ["mod"], + ), + "tool-specific": ( + ["tasks.py", "fabfile.py", "noxfile.py", "dodo.py", "manage.py", "mod.py"], + ["mod"], + ), + } + + @pytest.mark.parametrize("example", EXAMPLES.keys()) + def test_unwanted_files_not_included(self, tmp_path, example): + files, expected_modules = self.EXAMPLES[example] + ensure_files(tmp_path, files) + assert self.find(tmp_path) == set(expected_modules) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_glob.py b/python_embeded/Lib/site-packages/setuptools/tests/test_glob.py new file mode 100644 index 0000000000000000000000000000000000000000..8d225a44610163c7d56d65b07c06f0f598ccfe84 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_glob.py @@ -0,0 +1,45 @@ +import pytest +from jaraco import path + +from setuptools.glob import glob + + +@pytest.mark.parametrize( + ('tree', 'pattern', 'matches'), + ( + ('', b'', []), + ('', '', []), + ( + """ + appveyor.yml + CHANGES.rst + LICENSE + MANIFEST.in + pyproject.toml + README.rst + setup.cfg + setup.py + """, + '*.rst', + ('CHANGES.rst', 'README.rst'), + ), + ( + """ + appveyor.yml + CHANGES.rst + LICENSE + MANIFEST.in + pyproject.toml + README.rst + setup.cfg + setup.py + """, + b'*.rst', + (b'CHANGES.rst', b'README.rst'), + ), + ), +) +def test_glob(monkeypatch, tmpdir, tree, pattern, matches): + monkeypatch.chdir(tmpdir) + path.build({name: '' for name in tree.split()}) + assert list(sorted(glob(pattern))) == list(sorted(matches)) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_install_scripts.py b/python_embeded/Lib/site-packages/setuptools/tests/test_install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..e62a6b7f318df2da0cf29e53c41f74e5525e78ac --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_install_scripts.py @@ -0,0 +1,89 @@ +"""install_scripts tests""" + +import sys + +import pytest + +from setuptools.command.install_scripts import install_scripts +from setuptools.dist import Distribution + +from . import contexts + + +class TestInstallScripts: + settings = dict( + name='foo', + entry_points={'console_scripts': ['foo=foo:foo']}, + version='0.0', + ) + unix_exe = '/usr/dummy-test-path/local/bin/python' + unix_spaces_exe = '/usr/bin/env dummy-test-python' + win32_exe = 'C:\\Dummy Test Path\\Program Files\\Python 3.6\\python.exe' + + def _run_install_scripts(self, install_dir, executable=None): + dist = Distribution(self.settings) + dist.script_name = 'setup.py' + cmd = install_scripts(dist) + cmd.install_dir = install_dir + if executable is not None: + bs = cmd.get_finalized_command('build_scripts') + bs.executable = executable + cmd.ensure_finalized() + with contexts.quiet(): + cmd.run() + + @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') + def test_sys_executable_escaping_unix(self, tmpdir, monkeypatch): + """ + Ensure that shebang is not quoted on Unix when getting the Python exe + from sys.executable. + """ + expected = f'#!{self.unix_exe}\n' + monkeypatch.setattr('sys.executable', self.unix_exe) + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir)) + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only') + def test_sys_executable_escaping_win32(self, tmpdir, monkeypatch): + """ + Ensure that shebang is quoted on Windows when getting the Python exe + from sys.executable and it contains a space. + """ + expected = f'#!"{self.win32_exe}"\n' + monkeypatch.setattr('sys.executable', self.win32_exe) + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir)) + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only') + def test_executable_with_spaces_escaping_unix(self, tmpdir): + """ + Ensure that shebang on Unix is not quoted, even when + a value with spaces + is specified using --executable. + """ + expected = f'#!{self.unix_spaces_exe}\n' + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir), self.unix_spaces_exe) + with open(str(tmpdir.join('foo')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected + + @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only') + def test_executable_arg_escaping_win32(self, tmpdir): + """ + Ensure that shebang on Windows is quoted when + getting a path with spaces + from --executable, that is itself properly quoted. + """ + expected = f'#!"{self.win32_exe}"\n' + with tmpdir.as_cwd(): + self._run_install_scripts(str(tmpdir), '"' + self.win32_exe + '"') + with open(str(tmpdir.join('foo-script.py')), 'r', encoding="utf-8") as f: + actual = f.readline() + assert actual == expected diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_logging.py b/python_embeded/Lib/site-packages/setuptools/tests/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..ea58001e93d8e4bcbd50bfd49303324d71858d16 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_logging.py @@ -0,0 +1,76 @@ +import functools +import inspect +import logging +import sys + +import pytest + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +setup_py = """\ +from setuptools import setup + +setup( + name="test_logging", + version="0.0" +) +""" + + +@pytest.mark.parametrize( + ('flag', 'expected_level'), [("--dry-run", "INFO"), ("--verbose", "DEBUG")] +) +def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level): + """Make sure the correct verbosity level is set (issue #3038)""" + import setuptools # noqa: F401 # import setuptools to monkeypatch distutils + + import distutils # <- load distutils after all the patches take place + + logger = logging.Logger(__name__) + monkeypatch.setattr(logging, "root", logger) + unset_log_level = logger.getEffectiveLevel() + assert logging.getLevelName(unset_log_level) == "NOTSET" + + setup_script = tmp_path / "setup.py" + setup_script.write_text(setup_py, encoding="utf-8") + dist = distutils.core.run_setup(setup_script, stop_after="init") + dist.script_args = [flag, "sdist"] + dist.parse_command_line() # <- where the log level is set + log_level = logger.getEffectiveLevel() + log_level_name = logging.getLevelName(log_level) + assert log_level_name == expected_level + + +def flaky_on_pypy(func): + @functools.wraps(func) + def _func(): + try: + func() + except AssertionError: # pragma: no cover + if IS_PYPY: + msg = "Flaky monkeypatch on PyPy (#4124)" + pytest.xfail(f"{msg}. Original discussion in #3707, #3709.") + raise + + return _func + + +@flaky_on_pypy +def test_patching_does_not_cause_problems(): + # Ensure `dist.log` is only patched if necessary + + import _distutils_hack + + import setuptools.logging + + from distutils import dist + + setuptools.logging.configure() + + if _distutils_hack.enabled(): + # Modern logging infra, no problematic patching. + assert dist.__file__ is None or "setuptools" in dist.__file__ + assert isinstance(dist.log, logging.Logger) + else: + assert inspect.ismodule(dist.log) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_manifest.py b/python_embeded/Lib/site-packages/setuptools/tests/test_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..903a528db0cc2bba27bbcef24aa1c59dc4156528 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_manifest.py @@ -0,0 +1,622 @@ +"""sdist tests""" + +from __future__ import annotations + +import contextlib +import io +import itertools +import logging +import os +import shutil +import sys +import tempfile + +import pytest + +from setuptools.command.egg_info import FileList, egg_info, translate_pattern +from setuptools.dist import Distribution +from setuptools.tests.textwrap import DALS + +from distutils import log +from distutils.errors import DistutilsTemplateError + +IS_PYPY = '__pypy__' in sys.builtin_module_names + + +def make_local_path(s): + """Converts '/' in a string to os.sep""" + return s.replace('/', os.sep) + + +SETUP_ATTRS = { + 'name': 'app', + 'version': '0.0', + 'packages': ['app'], +} + +SETUP_PY = f"""\ +from setuptools import setup + +setup(**{SETUP_ATTRS!r}) +""" + + +@contextlib.contextmanager +def quiet(): + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() + try: + yield + finally: + sys.stdout, sys.stderr = old_stdout, old_stderr + + +def touch(filename): + open(filename, 'wb').close() + + +# The set of files always in the manifest, including all files in the +# .egg-info directory +default_files = frozenset( + map( + make_local_path, + [ + 'README.rst', + 'MANIFEST.in', + 'setup.py', + 'app.egg-info/PKG-INFO', + 'app.egg-info/SOURCES.txt', + 'app.egg-info/dependency_links.txt', + 'app.egg-info/top_level.txt', + 'app/__init__.py', + ], + ) +) + + +translate_specs: list[tuple[str, list[str], list[str]]] = [ + ('foo', ['foo'], ['bar', 'foobar']), + ('foo/bar', ['foo/bar'], ['foo/bar/baz', './foo/bar', 'foo']), + # Glob matching + ('*.txt', ['foo.txt', 'bar.txt'], ['foo/foo.txt']), + ('dir/*.txt', ['dir/foo.txt', 'dir/bar.txt', 'dir/.txt'], ['notdir/foo.txt']), + ('*/*.py', ['bin/start.py'], []), + ('docs/page-?.txt', ['docs/page-9.txt'], ['docs/page-10.txt']), + # Globstars change what they mean depending upon where they are + ( + 'foo/**/bar', + ['foo/bing/bar', 'foo/bing/bang/bar', 'foo/bar'], + ['foo/abar'], + ), + ( + 'foo/**', + ['foo/bar/bing.py', 'foo/x'], + ['/foo/x'], + ), + ( + '**', + ['x', 'abc/xyz', '@nything'], + [], + ), + # Character classes + ( + 'pre[one]post', + ['preopost', 'prenpost', 'preepost'], + ['prepost', 'preonepost'], + ), + ( + 'hello[!one]world', + ['helloxworld', 'helloyworld'], + ['hellooworld', 'helloworld', 'hellooneworld'], + ), + ( + '[]one].txt', + ['o.txt', '].txt', 'e.txt'], + ['one].txt'], + ), + ( + 'foo[!]one]bar', + ['fooybar'], + ['foo]bar', 'fooobar', 'fooebar'], + ), +] +""" +A spec of inputs for 'translate_pattern' and matches and mismatches +for that input. +""" + +match_params = itertools.chain.from_iterable( + zip(itertools.repeat(pattern), matches) + for pattern, matches, mismatches in translate_specs +) + + +@pytest.fixture(params=match_params) +def pattern_match(request): + return map(make_local_path, request.param) + + +mismatch_params = itertools.chain.from_iterable( + zip(itertools.repeat(pattern), mismatches) + for pattern, matches, mismatches in translate_specs +) + + +@pytest.fixture(params=mismatch_params) +def pattern_mismatch(request): + return map(make_local_path, request.param) + + +def test_translated_pattern_match(pattern_match): + pattern, target = pattern_match + assert translate_pattern(pattern).match(target) + + +def test_translated_pattern_mismatch(pattern_mismatch): + pattern, target = pattern_mismatch + assert not translate_pattern(pattern).match(target) + + +class TempDirTestCase: + def setup_method(self, method): + self.temp_dir = tempfile.mkdtemp() + self.old_cwd = os.getcwd() + os.chdir(self.temp_dir) + + def teardown_method(self, method): + os.chdir(self.old_cwd) + shutil.rmtree(self.temp_dir) + + +class TestManifestTest(TempDirTestCase): + def setup_method(self, method): + super().setup_method(method) + + f = open(os.path.join(self.temp_dir, 'setup.py'), 'w', encoding="utf-8") + f.write(SETUP_PY) + f.close() + """ + Create a file tree like: + - LICENSE + - README.rst + - testing.rst + - .hidden.rst + - app/ + - __init__.py + - a.txt + - b.txt + - c.rst + - static/ + - app.js + - app.js.map + - app.css + - app.css.map + """ + + for fname in ['README.rst', '.hidden.rst', 'testing.rst', 'LICENSE']: + touch(os.path.join(self.temp_dir, fname)) + + # Set up the rest of the test package + test_pkg = os.path.join(self.temp_dir, 'app') + os.mkdir(test_pkg) + for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: + touch(os.path.join(test_pkg, fname)) + + # Some compiled front-end assets to include + static = os.path.join(test_pkg, 'static') + os.mkdir(static) + for fname in ['app.js', 'app.js.map', 'app.css', 'app.css.map']: + touch(os.path.join(static, fname)) + + def make_manifest(self, contents): + """Write a MANIFEST.in.""" + manifest = os.path.join(self.temp_dir, 'MANIFEST.in') + with open(manifest, 'w', encoding="utf-8") as f: + f.write(DALS(contents)) + + def get_files(self): + """Run egg_info and get all the files to include, as a set""" + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = egg_info(dist) + cmd.ensure_finalized() + + cmd.run() + + return set(cmd.filelist.files) + + def test_no_manifest(self): + """Check a missing MANIFEST.in includes only the standard files.""" + assert (default_files - set(['MANIFEST.in'])) == self.get_files() + + def test_empty_files(self): + """Check an empty MANIFEST.in includes only the standard files.""" + self.make_manifest("") + assert default_files == self.get_files() + + def test_include(self): + """Include extra rst files in the project root.""" + self.make_manifest("include *.rst") + files = default_files | set(['testing.rst', '.hidden.rst']) + assert files == self.get_files() + + def test_exclude(self): + """Include everything in app/ except the text files""" + ml = make_local_path + self.make_manifest( + """ + include app/* + exclude app/*.txt + """ + ) + files = default_files | set([ml('app/c.rst')]) + assert files == self.get_files() + + def test_include_multiple(self): + """Include with multiple patterns.""" + ml = make_local_path + self.make_manifest("include app/*.txt app/static/*") + files = default_files | set([ + ml('app/a.txt'), + ml('app/b.txt'), + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft(self): + """Include the whole app/static/ directory.""" + ml = make_local_path + self.make_manifest("graft app/static") + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft_glob_syntax(self): + """Include the whole app/static/ directory.""" + ml = make_local_path + self.make_manifest("graft */static") + files = default_files | set([ + ml('app/static/app.js'), + ml('app/static/app.js.map'), + ml('app/static/app.css'), + ml('app/static/app.css.map'), + ]) + assert files == self.get_files() + + def test_graft_global_exclude(self): + """Exclude all *.map files in the project.""" + ml = make_local_path + self.make_manifest( + """ + graft app/static + global-exclude *.map + """ + ) + files = default_files | set([ml('app/static/app.js'), ml('app/static/app.css')]) + assert files == self.get_files() + + def test_global_include(self): + """Include all *.rst, *.js, and *.css files in the whole tree.""" + ml = make_local_path + self.make_manifest( + """ + global-include *.rst *.js *.css + """ + ) + files = default_files | set([ + '.hidden.rst', + 'testing.rst', + ml('app/c.rst'), + ml('app/static/app.js'), + ml('app/static/app.css'), + ]) + assert files == self.get_files() + + def test_graft_prune(self): + """Include all files in app/, except for the whole app/static/ dir.""" + ml = make_local_path + self.make_manifest( + """ + graft app + prune app/static + """ + ) + files = default_files | set([ml('app/a.txt'), ml('app/b.txt'), ml('app/c.rst')]) + assert files == self.get_files() + + +class TestFileListTest(TempDirTestCase): + """ + A copy of the relevant bits of distutils/tests/test_filelist.py, + to ensure setuptools' version of FileList keeps parity with distutils. + """ + + @pytest.fixture(autouse=os.getenv("SETUPTOOLS_USE_DISTUTILS") == "stdlib") + def _compat_record_logs(self, monkeypatch, caplog): + """Account for stdlib compatibility""" + + def _log(_logger, level, msg, args): + exc = sys.exc_info() + rec = logging.LogRecord("distutils", level, "", 0, msg, args, exc) + caplog.records.append(rec) + + monkeypatch.setattr(log.Log, "_log", _log) + + def get_records(self, caplog, *levels): + return [r for r in caplog.records if r.levelno in levels] + + def assertNoWarnings(self, caplog): + assert self.get_records(caplog, log.WARN) == [] + caplog.clear() + + def assertWarnings(self, caplog): + if IS_PYPY and not caplog.records: + pytest.xfail("caplog checks may not work well in PyPy") + else: + assert len(self.get_records(caplog, log.WARN)) > 0 + caplog.clear() + + def make_files(self, files): + for file in files: + file = os.path.join(self.temp_dir, file) + dirname, _basename = os.path.split(file) + os.makedirs(dirname, exist_ok=True) + touch(file) + + def test_process_template_line(self): + # testing all MANIFEST.in template patterns + file_list = FileList() + ml = make_local_path + + # simulated file list + self.make_files([ + 'foo.tmp', + 'ok', + 'xo', + 'four.txt', + 'buildout.cfg', + # filelist does not filter out VCS directories, + # it's sdist that does + ml('.hg/last-message.txt'), + ml('global/one.txt'), + ml('global/two.txt'), + ml('global/files.x'), + ml('global/here.tmp'), + ml('f/o/f.oo'), + ml('dir/graft-one'), + ml('dir/dir2/graft2'), + ml('dir3/ok'), + ml('dir3/sub/ok.txt'), + ]) + + MANIFEST_IN = DALS( + """\ + include ok + include xo + exclude xo + include foo.tmp + include buildout.cfg + global-include *.x + global-include *.txt + global-exclude *.tmp + recursive-include f *.oo + recursive-exclude global *.x + graft dir + prune dir3 + """ + ) + + for line in MANIFEST_IN.split('\n'): + if not line: + continue + file_list.process_template_line(line) + + wanted = [ + 'buildout.cfg', + 'four.txt', + 'ok', + ml('.hg/last-message.txt'), + ml('dir/graft-one'), + ml('dir/dir2/graft2'), + ml('f/o/f.oo'), + ml('global/one.txt'), + ml('global/two.txt'), + ] + + file_list.sort() + assert file_list.files == wanted + + def test_exclude_pattern(self): + # return False if no match + file_list = FileList() + assert not file_list.exclude_pattern('*.py') + + # return True if files match + file_list = FileList() + file_list.files = ['a.py', 'b.py'] + assert file_list.exclude_pattern('*.py') + + # test excludes + file_list = FileList() + file_list.files = ['a.py', 'a.txt'] + file_list.exclude_pattern('*.py') + file_list.sort() + assert file_list.files == ['a.txt'] + + def test_include_pattern(self): + # return False if no match + file_list = FileList() + self.make_files([]) + assert not file_list.include_pattern('*.py') + + # return True if files match + file_list = FileList() + self.make_files(['a.py', 'b.txt']) + assert file_list.include_pattern('*.py') + + # test * matches all files + file_list = FileList() + self.make_files(['a.py', 'b.txt']) + file_list.include_pattern('*') + file_list.sort() + assert file_list.files == ['a.py', 'b.txt'] + + def test_process_template_line_invalid(self): + # invalid lines + file_list = FileList() + for action in ( + 'include', + 'exclude', + 'global-include', + 'global-exclude', + 'recursive-include', + 'recursive-exclude', + 'graft', + 'prune', + 'blarg', + ): + with pytest.raises(DistutilsTemplateError): + file_list.process_template_line(action) + + def test_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # include + file_list = FileList() + self.make_files(['a.py', 'b.txt', ml('d/c.py')]) + + file_list.process_template_line('include *.py') + file_list.sort() + assert file_list.files == ['a.py'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('include *.rb') + file_list.sort() + assert file_list.files == ['a.py'] + self.assertWarnings(caplog) + + def test_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', ml('d/c.py')] + + file_list.process_template_line('exclude *.py') + file_list.sort() + assert file_list.files == ['b.txt', ml('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('exclude *.rb') + file_list.sort() + assert file_list.files == ['b.txt', ml('d/c.py')] + self.assertWarnings(caplog) + + def test_global_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # global-include + file_list = FileList() + self.make_files(['a.py', 'b.txt', ml('d/c.py')]) + + file_list.process_template_line('global-include *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-include *.rb') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.py')] + self.assertWarnings(caplog) + + def test_global_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # global-exclude + file_list = FileList() + file_list.files = ['a.py', 'b.txt', ml('d/c.py')] + + file_list.process_template_line('global-exclude *.py') + file_list.sort() + assert file_list.files == ['b.txt'] + self.assertNoWarnings(caplog) + + file_list.process_template_line('global-exclude *.rb') + file_list.sort() + assert file_list.files == ['b.txt'] + self.assertWarnings(caplog) + + def test_recursive_include(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # recursive-include + file_list = FileList() + self.make_files(['a.py', ml('d/b.py'), ml('d/c.txt'), ml('d/d/e.py')]) + + file_list.process_template_line('recursive-include d *.py') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-include e *.py') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertWarnings(caplog) + + def test_recursive_exclude(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # recursive-exclude + file_list = FileList() + file_list.files = ['a.py', ml('d/b.py'), ml('d/c.txt'), ml('d/d/e.py')] + + file_list.process_template_line('recursive-exclude d *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.txt')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('recursive-exclude e *.py') + file_list.sort() + assert file_list.files == ['a.py', ml('d/c.txt')] + self.assertWarnings(caplog) + + def test_graft(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # graft + file_list = FileList() + self.make_files(['a.py', ml('d/b.py'), ml('d/d/e.py'), ml('f/f.py')]) + + file_list.process_template_line('graft d') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('graft e') + file_list.sort() + assert file_list.files == [ml('d/b.py'), ml('d/d/e.py')] + self.assertWarnings(caplog) + + def test_prune(self, caplog): + caplog.set_level(logging.DEBUG) + ml = make_local_path + # prune + file_list = FileList() + file_list.files = ['a.py', ml('d/b.py'), ml('d/d/e.py'), ml('f/f.py')] + + file_list.process_template_line('prune d') + file_list.sort() + assert file_list.files == ['a.py', ml('f/f.py')] + self.assertNoWarnings(caplog) + + file_list.process_template_line('prune e') + file_list.sort() + assert file_list.files == ['a.py', ml('f/f.py')] + self.assertWarnings(caplog) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_namespaces.py b/python_embeded/Lib/site-packages/setuptools/tests/test_namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f4120bf7900b2118cc066034e036ab7af1798b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_namespaces.py @@ -0,0 +1,138 @@ +import subprocess +import sys + +from setuptools._path import paths_on_pythonpath + +from . import namespaces + + +class TestNamespaces: + def test_mixed_site_and_non_site(self, tmpdir): + """ + Installing two packages sharing the same namespace, one installed + to a site dir and the other installed just to a path on PYTHONPATH + should leave the namespace in tact and both packages reachable by + import. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') + site_packages = tmpdir / 'site-packages' + path_packages = tmpdir / 'path-packages' + targets = site_packages, path_packages + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(site_packages), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(site_packages) + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_B), + '-t', + str(path_packages), + ] + subprocess.check_call(install_cmd) + try_import = [ + sys.executable, + '-c', + 'import myns.pkgA; import myns.pkgB', + ] + with paths_on_pythonpath(map(str, targets)): + subprocess.check_call(try_import) + + def test_pkg_resources_import(self, tmpdir): + """ + Ensure that a namespace package doesn't break on import + of pkg_resources. + """ + pkg = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + target = tmpdir / 'packages' + target.mkdir() + install_cmd = [ + sys.executable, + '-m', + 'pip', + 'install', + '-t', + str(target), + str(pkg), + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + try_import = [ + sys.executable, + '-c', + 'import pkg_resources', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(try_import) + + def test_namespace_package_installed_and_cwd(self, tmpdir): + """ + Installing a namespace packages but also having it in the current + working directory, only one version should take precedence. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + target = tmpdir / 'packages' + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(target), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + + # ensure that package imports and pkg_resources imports + pkg_resources_imp = [ + sys.executable, + '-c', + 'import pkg_resources; import myns.pkgA', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp, cwd=str(pkg_A)) + + def test_packages_in_the_same_namespace_installed_and_cwd(self, tmpdir): + """ + Installing one namespace package and also have another in the same + namespace in the current working directory, both of them must be + importable. + """ + pkg_A = namespaces.build_namespace_package(tmpdir, 'myns.pkgA') + pkg_B = namespaces.build_namespace_package(tmpdir, 'myns.pkgB') + target = tmpdir / 'packages' + # use pip to install to the target directory + install_cmd = [ + sys.executable, + '-m', + 'pip.__main__', + 'install', + str(pkg_A), + '-t', + str(target), + ] + subprocess.check_call(install_cmd) + namespaces.make_site_dir(target) + + # ensure that all packages import and pkg_resources imports + pkg_resources_imp = [ + sys.executable, + '-c', + 'import pkg_resources; import myns.pkgA; import myns.pkgB', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp, cwd=str(pkg_B)) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_scripts.py b/python_embeded/Lib/site-packages/setuptools/tests/test_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..8641f7b639161525e2fff3100744d7fa55d9d718 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_scripts.py @@ -0,0 +1,12 @@ +from setuptools import _scripts + + +class TestWindowsScriptWriter: + def test_header(self): + hdr = _scripts.WindowsScriptWriter.get_header('') + assert hdr.startswith('#!') + assert hdr.endswith('\n') + hdr = hdr.lstrip('#!') + hdr = hdr.rstrip('\n') + # header should not start with an escaped quote + assert not hdr.startswith('\\"') diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_sdist.py b/python_embeded/Lib/site-packages/setuptools/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..19d8ddf6dafb0cacc044a6021f283d3e9faaf800 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_sdist.py @@ -0,0 +1,984 @@ +"""sdist tests""" + +import contextlib +import io +import logging +import os +import pathlib +import sys +import tarfile +import tempfile +import unicodedata +from inspect import cleandoc +from pathlib import Path +from unittest import mock + +import jaraco.path +import pytest + +from setuptools import Command, SetuptoolsDeprecationWarning +from setuptools._importlib import metadata +from setuptools.command.egg_info import manifest_maker +from setuptools.command.sdist import sdist +from setuptools.dist import Distribution +from setuptools.extension import Extension +from setuptools.tests import fail_on_ascii + +from .text import Filenames + +import distutils +from distutils.core import run_setup + +SETUP_ATTRS = { + 'name': 'sdist_test', + 'version': '0.0', + 'packages': ['sdist_test'], + 'package_data': {'sdist_test': ['*.txt']}, + 'data_files': [("data", [os.path.join("d", "e.dat")])], +} + +SETUP_PY = f"""\ +from setuptools import setup + +setup(**{SETUP_ATTRS!r}) +""" + +EXTENSION = Extension( + name="sdist_test.f", + sources=[os.path.join("sdist_test", "f.c")], + depends=[os.path.join("sdist_test", "f.h")], +) +EXTENSION_SOURCES = EXTENSION.sources + EXTENSION.depends + + +@contextlib.contextmanager +def quiet(): + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() + try: + yield + finally: + sys.stdout, sys.stderr = old_stdout, old_stderr + + +# Convert to POSIX path +def posix(path): + if not isinstance(path, str): + return path.replace(os.sep.encode('ascii'), b'/') + else: + return path.replace(os.sep, '/') + + +# HFS Plus uses decomposed UTF-8 +def decompose(path): + if isinstance(path, str): + return unicodedata.normalize('NFD', path) + try: + path = path.decode('utf-8') + path = unicodedata.normalize('NFD', path) + path = path.encode('utf-8') + except UnicodeError: + pass # Not UTF-8 + return path + + +def read_all_bytes(filename): + with open(filename, 'rb') as fp: + return fp.read() + + +def latin1_fail(): + try: + desc, filename = tempfile.mkstemp(suffix=Filenames.latin_1) + os.close(desc) + os.remove(filename) + except Exception: + return True + + +fail_on_latin1_encoded_filenames = pytest.mark.xfail( + latin1_fail(), + reason="System does not support latin-1 filenames", +) + + +skip_under_xdist = pytest.mark.skipif( + "os.environ.get('PYTEST_XDIST_WORKER')", + reason="pytest-dev/pytest-xdist#843", +) +skip_under_stdlib_distutils = pytest.mark.skipif( + not distutils.__package__.startswith('setuptools'), + reason="the test is not supported with stdlib distutils", +) + + +def touch(path): + open(path, 'wb').close() + return path + + +def symlink_or_skip_test(src, dst): + try: + os.symlink(src, dst) + except (OSError, NotImplementedError): + pytest.skip("symlink not supported in OS") + return None + return dst + + +class TestSdistTest: + @pytest.fixture(autouse=True) + def source_dir(self, tmpdir): + tmpdir = tmpdir / "project_root" + tmpdir.mkdir() + + (tmpdir / 'setup.py').write_text(SETUP_PY, encoding='utf-8') + + # Set up the rest of the test package + test_pkg = tmpdir / 'sdist_test' + test_pkg.mkdir() + data_folder = tmpdir / 'd' + data_folder.mkdir() + # *.rst was not included in package_data, so c.rst should not be + # automatically added to the manifest when not under version control + for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: + touch(test_pkg / fname) + touch(data_folder / 'e.dat') + # C sources are not included by default, but they will be, + # if an extension module uses them as sources or depends + for fname in EXTENSION_SOURCES: + touch(tmpdir / fname) + + with tmpdir.as_cwd(): + yield tmpdir + + def assert_package_data_in_manifest(self, cmd): + manifest = cmd.filelist.files + assert os.path.join('sdist_test', 'a.txt') in manifest + assert os.path.join('sdist_test', 'b.txt') in manifest + assert os.path.join('sdist_test', 'c.rst') not in manifest + assert os.path.join('d', 'e.dat') in manifest + + def setup_with_extension(self): + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [EXTENSION]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + return cmd + + def test_package_data_in_sdist(self): + """Regression test for pull request #4: ensures that files listed in + package_data are included in the manifest even if they're not added to + version control. + """ + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_package_data_and_include_package_data_in_sdist(self): + """ + Ensure package_data and include_package_data work + together. + """ + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_extension_sources_in_sdist(self): + """ + Ensure that the files listed in Extension.sources and Extension.depends + are automatically included in the manifest. + """ + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + + def test_missing_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files don't exist. + Missing files should not be included in distribution (with no error raised). + """ + for path in EXTENSION_SOURCES: + os.remove(path) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path not in manifest + + def test_symlinked_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files are + instead symbolic links to project-local files. Referenced file paths + should be included. Symlink targets themselves should NOT be included. + """ + symlinked = [] + for path in EXTENSION_SOURCES: + base, ext = os.path.splitext(path) + target = base + "_target." + ext + + os.rename(path, target) + symlink_or_skip_test(os.path.basename(target), path) + symlinked.append(target) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + for path in symlinked: + assert path not in manifest + + _INVALID_PATHS = { + "must be relative": lambda: ( + os.path.abspath(os.path.join("sdist_test", "f.h")) + ), + "can't have `..` segments": lambda: ( + os.path.join("sdist_test", "..", "sdist_test", "f.h") + ), + "doesn't exist": lambda: ( + os.path.join("sdist_test", "this_file_does_not_exist.h") + ), + "must be inside the project root": lambda: ( + symlink_or_skip_test( + touch(os.path.join("..", "outside_of_project_root.h")), + "symlink.h", + ) + ), + } + + @skip_under_stdlib_distutils + @pytest.mark.parametrize("reason", _INVALID_PATHS.keys()) + def test_invalid_extension_depends(self, reason, caplog): + """ + Due to backwards compatibility reasons, `Extension.depends` should accept + invalid/weird paths, but then ignore them when building a sdist. + + This test verifies that the source distribution is still built + successfully with such paths, but that instead of adding these paths to + the manifest, we emit an informational message, notifying the user that + the invalid path won't be automatically included. + """ + invalid_path = self._INVALID_PATHS[reason]() + extension = Extension( + name="sdist_test.f", + sources=[], + depends=[invalid_path], + ) + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [extension]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(), caplog.at_level(logging.INFO): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + assert invalid_path not in manifest + + expected_message = [ + message + for (logger, level, message) in caplog.record_tuples + if ( + logger == "root" # + and level == logging.INFO # + and invalid_path in message # + ) + ] + assert len(expected_message) == 1 + (expected_message,) = expected_message + assert reason in expected_message + + def test_custom_build_py(self): + """ + Ensure projects defining custom build_py don't break + when creating sdists (issue #2849) + """ + from distutils.command.build_py import build_py as OrigBuildPy + + using_custom_command_guard = mock.Mock() + + class CustomBuildPy(OrigBuildPy): + """ + Some projects have custom commands inheriting from `distutils` + """ + + def get_data_files(self): + using_custom_command_guard() + return super().get_data_files() + + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Make sure we use the custom command + cmd.cmdclass = {'build_py': CustomBuildPy} + cmd.distribution.cmdclass = {'build_py': CustomBuildPy} + assert cmd.distribution.get_command_class('build_py') == CustomBuildPy + + msg = "setuptools instead of distutils" + with quiet(), pytest.warns(SetuptoolsDeprecationWarning, match=msg): + cmd.run() + + using_custom_command_guard.assert_called() + self.assert_package_data_in_manifest(cmd) + + def test_setup_py_exists(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' in manifest + + def test_setup_py_missing(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + if os.path.exists("setup.py"): + os.remove("setup.py") + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_setup_py_excluded(self): + with open("MANIFEST.in", "w", encoding="utf-8") as manifest_file: + manifest_file.write("exclude setup.py") + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_defaults_case_sensitivity(self, source_dir): + """ + Make sure default files (README.*, etc.) are added in a case-sensitive + way to avoid problems with packages built on Windows. + """ + + touch(source_dir / 'readme.rst') + touch(source_dir / 'SETUP.cfg') + + dist = Distribution(SETUP_ATTRS) + # the extension deliberately capitalized for this test + # to make sure the actual filename (not capitalized) gets added + # to the manifest + dist.script_name = 'setup.PY' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + # lowercase all names so we can test in a + # case-insensitive way to make sure the files + # are not included. + manifest = map(lambda x: x.lower(), cmd.filelist.files) + assert 'readme.rst' not in manifest, manifest + assert 'setup.py' not in manifest, manifest + assert 'setup.cfg' not in manifest, manifest + + def test_exclude_dev_only_cache_folders(self, source_dir): + included = { + # Emulate problem in https://github.com/pypa/setuptools/issues/4601 + "MANIFEST.in": ( + "global-include LICEN[CS]E* COPYING* NOTICE* AUTHORS*\n" + "global-include *.txt\n" + ), + # For the sake of being conservative and limiting unforeseen side-effects + # we just exclude dev-only cache folders at the root of the repository: + "test/.venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + "src/.nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + "doc/.tox/default/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + # Let's test against false positives with similarly named files: + ".venv-requirements.txt": "", + ".tox-coveragerc.txt": "", + ".noxy/coveragerc.txt": "", + } + + excluded = { + # .tox/.nox/.venv are well-know folders present at the root of Python repos + # and therefore should be excluded + ".tox/release/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + ".nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + ".venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + } + + for file, content in {**excluded, **included}.items(): + Path(source_dir, file).parent.mkdir(parents=True, exist_ok=True) + Path(source_dir, file).write_text(content, encoding="utf-8") + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = {f.replace(os.sep, '/') for f in cmd.filelist.files} + for path in excluded: + assert os.path.exists(path) + assert path not in manifest, (path, manifest) + for path in included: + assert os.path.exists(path) + assert path in manifest, (path, manifest) + + @fail_on_ascii + def test_manifest_is_written_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # UTF-8 filename + filename = os.path.join('sdist_test', 'smörbröd.py') + + # Must create the file or it will get stripped. + touch(filename) + + # Add UTF-8 filename and write manifest + with quiet(): + mm.run() + mm.filelist.append(filename) + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + u_contents = contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in u_contents + + @fail_on_ascii + def test_write_manifest_allows_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + + # Must touch the file or risk removal + touch(filename) + + # Add filename and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8') + mm.filelist.files.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in contents + + # The filelist should have been updated as well + assert u_filename in mm.filelist.files + + @skip_under_xdist + def test_write_manifest_skips_non_utf8_filenames(self): + """ + Files that cannot be encoded to UTF-8 (specifically, those that + weren't originally successfully decoded and have surrogate + escapes) should be omitted from the manifest. + See https://bitbucket.org/tarek/distribute/issue/303 for history. + """ + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + + # Add filename with surrogates and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8', 'surrogateescape') + mm.filelist.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The Latin-1 filename should have been skipped + assert posix(filename) not in contents + + # The filelist should have been updated as well + assert u_filename not in mm.filelist.files + + @fail_on_ascii + def test_manifest_is_read_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add UTF-8 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.utf_8) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The filelist should contain the UTF-8 filename + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @fail_on_latin1_encoded_filenames + def test_read_manifest_skips_non_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add Latin-1 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.latin_1) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + @fail_on_ascii + @fail_on_latin1_encoded_filenames + def test_sdist_with_utf8_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + touch(filename) + + with quiet(): + cmd.run() + + if sys.platform == 'darwin': + filename = decompose(filename) + + fs_enc = sys.getfilesystemencoding() + + if sys.platform == 'win32': + if fs_enc == 'cp1252': + # Python mangles the UTF-8 filename + filename = filename.decode('cp1252') + assert filename in cmd.filelist.files + else: + filename = filename.decode('mbcs') + assert filename in cmd.filelist.files + else: + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @classmethod + def make_strings(cls, item): + if isinstance(item, dict): + return {key: cls.make_strings(value) for key, value in item.items()} + if isinstance(item, list): + return list(map(cls.make_strings, item)) + return str(item) + + @fail_on_latin1_encoded_filenames + @skip_under_xdist + def test_sdist_with_latin1_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + touch(filename) + assert os.path.isfile(filename) + + with quiet(): + cmd.run() + + # not all windows systems have a default FS encoding of cp1252 + if sys.platform == 'win32': + # Latin-1 is similar to Windows-1252 however + # on mbcs filesys it is not in latin-1 encoding + fs_enc = sys.getfilesystemencoding() + if fs_enc != 'mbcs': + fs_enc = 'latin-1' + filename = filename.decode(fs_enc) + + assert filename in cmd.filelist.files + else: + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + _EXAMPLE_DIRECTIVES = { + "setup.cfg - long_description and version": """ + [metadata] + name = testing + version = file: src/VERSION.txt + license_files = DOWHATYOUWANT + long_description = file: README.rst, USAGE.rst + """, + "pyproject.toml - static readme/license files and dynamic version": """ + [project] + name = "testing" + readme = "USAGE.rst" + license-files = ["DOWHATYOUWANT"] + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = ["src/VERSION.txt"]} + """, + "pyproject.toml - directive with str instead of list": """ + [project] + name = "testing" + readme = "USAGE.rst" + license-files = ["DOWHATYOUWANT"] + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + "pyproject.toml - deprecated license table with file entry": """ + [project] + name = "testing" + readme = "USAGE.rst" + license = {file = "DOWHATYOUWANT"} + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + } + + @pytest.mark.parametrize("config", _EXAMPLE_DIRECTIVES.keys()) + @pytest.mark.filterwarnings( + "ignore:.project.license. as a TOML table is deprecated" + ) + def test_add_files_referenced_by_config_directives(self, source_dir, config): + config_file, _, _ = config.partition(" - ") + config_text = self._EXAMPLE_DIRECTIVES[config] + (source_dir / 'src').mkdir() + (source_dir / 'src/VERSION.txt').write_text("0.42", encoding="utf-8") + (source_dir / 'README.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'USAGE.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'DOWHATYOUWANT').write_text("hello world!", encoding="utf-8") + (source_dir / config_file).write_text(config_text, encoding="utf-8") + + dist = Distribution({"packages": []}) + dist.script_name = 'setup.py' + dist.parse_config_files() + + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + assert ( + 'src/VERSION.txt' in cmd.filelist.files + or 'src\\VERSION.txt' in cmd.filelist.files + ) + assert 'USAGE.rst' in cmd.filelist.files + assert 'DOWHATYOUWANT' in cmd.filelist.files + assert '/' not in cmd.filelist.files + assert '\\' not in cmd.filelist.files + + def test_pyproject_toml_in_sdist(self, source_dir): + """ + Check if pyproject.toml is included in source distribution if present + """ + touch(source_dir / 'pyproject.toml') + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' in manifest + + def test_pyproject_toml_excluded(self, source_dir): + """ + Check that pyproject.toml can excluded even if present + """ + touch(source_dir / 'pyproject.toml') + with open('MANIFEST.in', 'w', encoding="utf-8") as mts: + print('exclude pyproject.toml', file=mts) + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' not in manifest + + def test_build_subcommand_source_files(self, source_dir): + touch(source_dir / '.myfile~') + + # Sanity check: without custom commands file list should not be affected + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' not in manifest + + # Test: custom command should be able to augment file list + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + build = dist.get_command_obj("build") + build.sub_commands = [*build.sub_commands, ("build_custom", None)] + + class build_custom(Command): + def initialize_options(self): ... + + def finalize_options(self): ... + + def run(self): ... + + def get_source_files(self): + return ['.myfile~'] + + dist.cmdclass.update(build_custom=build_custom) + + cmd = sdist(dist) + cmd.use_defaults = True + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' in manifest + + @pytest.mark.skipif("os.environ.get('SETUPTOOLS_USE_DISTUTILS') == 'stdlib'") + def test_build_base_pathlib(self, source_dir): + """ + Ensure if build_base is a pathlib.Path, the build still succeeds. + """ + dist = Distribution({ + **SETUP_ATTRS, + "script_name": "setup.py", + "options": {"build": {"build_base": pathlib.Path('build')}}, + }) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + +def test_default_revctrl(): + """ + When _default_revctrl was removed from the `setuptools.command.sdist` + module in 10.0, it broke some systems which keep an old install of + setuptools (Distribute) around. Those old versions require that the + setuptools package continue to implement that interface, so this + function provides that interface, stubbed. See #320 for details. + + This interface must be maintained until Ubuntu 12.04 is no longer + supported (by Setuptools). + """ + (ep,) = metadata.EntryPoints._from_text( + """ + [setuptools.file_finders] + svn_cvs = setuptools.command.sdist:_default_revctrl + """ + ) + res = ep.load() + assert hasattr(res, '__iter__') + + +class TestRegressions: + """ + Can be removed/changed if the project decides to change how it handles symlinks + or external files. + """ + + @staticmethod + def files_for_symlink_in_extension_depends(tmp_path, dep_path): + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{dep_path!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("myheaders/dir/file.h", "myheaders/dir/../dir/file.h") + ) + def test_symlink_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a symlinked dir and a "depends" targeting that dir + files = self.files_for_symlink_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + symlink_or_skip_test(tmp_path / "external", tmp_path / "project/myheaders") + + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should contain the symlinked files + for expected in ( + "myproj-42/hello.pyx", + "myproj-42/myheaders/dir/file.h", + ): + assert expected in members + + @staticmethod + def files_for_external_path_in_extension_depends(tmp_path, dep_path): + head, _, tail = dep_path.partition("$tmp_path$/") + dep_path = tmp_path / tail if tail else head + + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{str(dep_path)!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("$tmp_path$/external/dir/file.h", "../external/dir/file.h") + ) + def test_external_path_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a "depends" targeting an external dir + files = self.files_for_external_path_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should not contain the external file + for name in members: + assert "file.h" not in name + + +def run_sdist(monkeypatch, project): + """Given a project directory, run the sdist and return its contents""" + monkeypatch.chdir(project) + with quiet(): + run_setup("setup.py", ["sdist"]) + + archive = next((project / "dist").glob("*.tar.gz")) + with tarfile.open(str(archive)) as tar: + return set(tar.getnames()) + + +def test_sanity_check_setuptools_own_sdist(setuptools_sdist): + with tarfile.open(setuptools_sdist) as tar: + files = tar.getnames() + + # setuptools sdist should not include the .tox folder + tox_files = [name for name in files if ".tox" in name] + assert len(tox_files) == 0, f"not empty {tox_files}" diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_setopt.py b/python_embeded/Lib/site-packages/setuptools/tests/test_setopt.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf25618a5d6e255ad0be0fbed51fc29c179dcfe --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_setopt.py @@ -0,0 +1,40 @@ +import configparser + +from setuptools.command import setopt + + +class TestEdit: + @staticmethod + def parse_config(filename): + parser = configparser.ConfigParser() + with open(filename, encoding='utf-8') as reader: + parser.read_file(reader) + return parser + + @staticmethod + def write_text(file, content): + with open(file, 'wb') as strm: + strm.write(content.encode('utf-8')) + + def test_utf8_encoding_retained(self, tmpdir): + """ + When editing a file, non-ASCII characters encoded in + UTF-8 should be retained. + """ + config = tmpdir.join('setup.cfg') + self.write_text(str(config), '[names]\njaraco=джарако') + setopt.edit_config(str(config), dict(names=dict(other='yes'))) + parser = self.parse_config(str(config)) + assert parser.get('names', 'jaraco') == 'джарако' + assert parser.get('names', 'other') == 'yes' + + def test_case_retained(self, tmpdir): + """ + When editing a file, case of keys should be retained. + """ + config = tmpdir.join('setup.cfg') + self.write_text(str(config), '[names]\nFoO=bAr') + setopt.edit_config(str(config), dict(names=dict(oTher='yes'))) + actual = config.read_text(encoding='ascii') + assert 'FoO' in actual + assert 'oTher' in actual diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_setuptools.py b/python_embeded/Lib/site-packages/setuptools/tests/test_setuptools.py new file mode 100644 index 0000000000000000000000000000000000000000..1d56e1a8a4ebc5c7aaeb9902ef9972f7de97ecbf --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_setuptools.py @@ -0,0 +1,290 @@ +"""Tests for the 'setuptools' package""" + +import os +import re +import sys +from zipfile import ZipFile + +import pytest +from packaging.version import Version + +import setuptools +import setuptools.depends as dep +import setuptools.dist +from setuptools.depends import Require + +import distutils.cmd +import distutils.core +from distutils.core import Extension +from distutils.errors import DistutilsSetupError + + +@pytest.fixture(autouse=True) +def isolated_dir(tmpdir_cwd): + return + + +def makeSetup(**args): + """Return distribution from 'setup(**args)', without executing commands""" + + distutils.core._setup_stop_after = "commandline" + + # Don't let system command line leak into tests! + args.setdefault('script_args', ['install']) + + try: + return setuptools.setup(**args) + finally: + distutils.core._setup_stop_after = None + + +needs_bytecode = pytest.mark.skipif( + not hasattr(dep, 'get_module_constant'), + reason="bytecode support not available", +) + + +class TestDepends: + def testExtractConst(self): + if not hasattr(dep, 'extract_constant'): + # skip on non-bytecode platforms + return + + def f1(): + global x, y, z + x = "test" + y = z # pyright: ignore[reportUnboundVariable] # Explicitly testing for this runtime issue + + fc = f1.__code__ + + # unrecognized name + assert dep.extract_constant(fc, 'q', -1) is None + + # constant assigned + assert dep.extract_constant(fc, 'x', -1) == "test" + + # expression assigned + assert dep.extract_constant(fc, 'y', -1) == -1 + + # recognized name, not assigned + assert dep.extract_constant(fc, 'z', -1) is None + + def testFindModule(self): + with pytest.raises(ImportError): + dep.find_module('no-such.-thing') + with pytest.raises(ImportError): + dep.find_module('setuptools.non-existent') + f, _p, _i = dep.find_module('setuptools.tests') + f.close() + + @needs_bytecode + def testModuleExtract(self): + from json import __version__ + + assert dep.get_module_constant('json', '__version__') == __version__ + assert dep.get_module_constant('sys', 'version') == sys.version + assert ( + dep.get_module_constant('setuptools.tests.test_setuptools', '__doc__') + == __doc__ + ) + + @needs_bytecode + def testRequire(self): + req = Require('Json', '1.0.3', 'json') + + assert req.name == 'Json' + assert req.module == 'json' + assert req.requested_version == Version('1.0.3') + assert req.attribute == '__version__' + assert req.full_name() == 'Json-1.0.3' + + from json import __version__ + + assert str(req.get_version()) == __version__ + assert req.version_ok('1.0.9') + assert not req.version_ok('0.9.1') + assert not req.version_ok('unknown') + + assert req.is_present() + assert req.is_current() + + req = Require('Do-what-I-mean', '1.0', 'd-w-i-m') + assert not req.is_present() + assert not req.is_current() + + @needs_bytecode + def test_require_present(self): + # In #1896, this test was failing for months with the only + # complaint coming from test runners (not end users). + # TODO: Evaluate if this code is needed at all. + req = Require('Tests', None, 'tests', homepage="http://example.com") + assert req.format is None + assert req.attribute is None + assert req.requested_version is None + assert req.full_name() == 'Tests' + assert req.homepage == 'http://example.com' + + from setuptools.tests import __path__ + + paths = [os.path.dirname(p) for p in __path__] + assert req.is_present(paths) + assert req.is_current(paths) + + +class TestDistro: + def setup_method(self, method): + self.e1 = Extension('bar.ext', ['bar.c']) + self.e2 = Extension('c.y', ['y.c']) + + self.dist = makeSetup( + packages=['a', 'a.b', 'a.b.c', 'b', 'c'], + py_modules=['b.d', 'x'], + ext_modules=(self.e1, self.e2), + package_dir={}, + ) + + def testDistroType(self): + assert isinstance(self.dist, setuptools.dist.Distribution) + + def testExcludePackage(self): + self.dist.exclude_package('a') + assert self.dist.packages == ['b', 'c'] + + self.dist.exclude_package('b') + assert self.dist.packages == ['c'] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1, self.e2] + + self.dist.exclude_package('c') + assert self.dist.packages == [] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1] + + # test removals from unspecified options + makeSetup().exclude_package('x') + + def testIncludeExclude(self): + # remove an extension + self.dist.exclude(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2] + + # add it back in + self.dist.include(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2, self.e1] + + # should not add duplicate + self.dist.include(ext_modules=[self.e1]) + assert self.dist.ext_modules == [self.e2, self.e1] + + def testExcludePackages(self): + self.dist.exclude(packages=['c', 'b', 'a']) + assert self.dist.packages == [] + assert self.dist.py_modules == ['x'] + assert self.dist.ext_modules == [self.e1] + + def testEmpty(self): + dist = makeSetup() + dist.include(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) + dist = makeSetup() + dist.exclude(packages=['a'], py_modules=['b'], ext_modules=[self.e2]) + + def testContents(self): + assert self.dist.has_contents_for('a') + self.dist.exclude_package('a') + assert not self.dist.has_contents_for('a') + + assert self.dist.has_contents_for('b') + self.dist.exclude_package('b') + assert not self.dist.has_contents_for('b') + + assert self.dist.has_contents_for('c') + self.dist.exclude_package('c') + assert not self.dist.has_contents_for('c') + + def testInvalidIncludeExclude(self): + with pytest.raises(DistutilsSetupError): + self.dist.include(nonexistent_option='x') + with pytest.raises(DistutilsSetupError): + self.dist.exclude(nonexistent_option='x') + with pytest.raises(DistutilsSetupError): + self.dist.include(packages={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(packages={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.include(ext_modules={'x': 'y'}) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(ext_modules={'x': 'y'}) + + with pytest.raises(DistutilsSetupError): + self.dist.include(package_dir=['q']) + with pytest.raises(DistutilsSetupError): + self.dist.exclude(package_dir=['q']) + + +@pytest.fixture +def example_source(tmpdir): + tmpdir.mkdir('foo') + (tmpdir / 'foo/bar.py').write('') + (tmpdir / 'readme.txt').write('') + return tmpdir + + +def test_findall(example_source): + found = list(setuptools.findall(str(example_source))) + expected = ['readme.txt', 'foo/bar.py'] + expected = [example_source.join(fn) for fn in expected] + assert found == expected + + +def test_findall_curdir(example_source): + with example_source.as_cwd(): + found = list(setuptools.findall()) + expected = ['readme.txt', os.path.join('foo', 'bar.py')] + assert found == expected + + +@pytest.fixture +def can_symlink(tmpdir): + """ + Skip if cannot create a symbolic link + """ + link_fn = 'link' + target_fn = 'target' + try: + os.symlink(target_fn, link_fn) + except (OSError, NotImplementedError, AttributeError): + pytest.skip("Cannot create symbolic links") + os.remove(link_fn) + + +@pytest.mark.usefixtures("can_symlink") +def test_findall_missing_symlink(tmpdir): + with tmpdir.as_cwd(): + os.symlink('foo', 'bar') + found = list(setuptools.findall()) + assert found == [] + + +@pytest.mark.xfail(reason="unable to exclude tests; #4475 #3260") +def test_its_own_wheel_does_not_contain_tests(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + for member in contents: + assert '/tests/' not in member + + +def test_wheel_includes_cli_scripts(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any('cli-64.exe' in member for member in contents) + + +def test_wheel_includes_vendored_metadata(setuptools_wheel): + with ZipFile(setuptools_wheel) as zipfile: + contents = [f.replace(os.sep, '/') for f in zipfile.namelist()] + + assert any( + re.search(r'_vendor/.*\.dist-info/METADATA', member) for member in contents + ) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_shutil_wrapper.py b/python_embeded/Lib/site-packages/setuptools/tests/test_shutil_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..74ff7e9a896328a3d57ca3639658e3b9d538585f --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_shutil_wrapper.py @@ -0,0 +1,23 @@ +import stat +import sys +from unittest.mock import Mock + +from setuptools import _shutil + + +def test_rmtree_readonly(monkeypatch, tmp_path): + """Verify onerr works as expected""" + + tmp_dir = tmp_path / "with_readonly" + tmp_dir.mkdir() + some_file = tmp_dir.joinpath("file.txt") + some_file.touch() + some_file.chmod(stat.S_IREAD) + + expected_count = 1 if sys.platform.startswith("win") else 0 + chmod_fn = Mock(wraps=_shutil.attempt_chmod_verbose) + monkeypatch.setattr(_shutil, "attempt_chmod_verbose", chmod_fn) + + _shutil.rmtree(tmp_dir) + assert chmod_fn.call_count == expected_count + assert not tmp_dir.is_dir() diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_unicode_utils.py b/python_embeded/Lib/site-packages/setuptools/tests/test_unicode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a24a9bd5305d1de7c1c925466bb7d222c85864a7 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_unicode_utils.py @@ -0,0 +1,10 @@ +from setuptools import unicode_utils + + +def test_filesys_decode_fs_encoding_is_None(monkeypatch): + """ + Test filesys_decode does not raise TypeError when + getfilesystemencoding returns None. + """ + monkeypatch.setattr('sys.getfilesystemencoding', lambda: None) + unicode_utils.filesys_decode(b'test') diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_virtualenv.py b/python_embeded/Lib/site-packages/setuptools/tests/test_virtualenv.py new file mode 100644 index 0000000000000000000000000000000000000000..b02949baf9cef8eb4df9c697add28f79a93b64d4 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_virtualenv.py @@ -0,0 +1,113 @@ +import os +import subprocess +import sys +from urllib.error import URLError +from urllib.request import urlopen + +import pytest + + +@pytest.fixture(autouse=True) +def pytest_virtualenv_works(venv): + """ + pytest_virtualenv may not work. if it doesn't, skip these + tests. See #1284. + """ + venv_prefix = venv.run(["python", "-c", "import sys; print(sys.prefix)"]).strip() + if venv_prefix == sys.prefix: + pytest.skip("virtualenv is broken (see pypa/setuptools#1284)") + + +def test_clean_env_install(venv_without_setuptools, setuptools_wheel): + """ + Check setuptools can be installed in a clean environment. + """ + cmd = ["python", "-m", "pip", "install", str(setuptools_wheel)] + venv_without_setuptools.run(cmd) + + +def access_pypi(): + # Detect if tests are being run without connectivity + if not os.environ.get('NETWORK_REQUIRED', False): # pragma: nocover + try: + urlopen('https://pypi.org', timeout=1) + except URLError: + # No network, disable most of these tests + return False + + return True + + +@pytest.mark.skipif( + 'platform.python_implementation() == "PyPy"', + reason="https://github.com/pypa/setuptools/pull/2865#issuecomment-965834995", +) +@pytest.mark.skipif(not access_pypi(), reason="no network") +# ^-- Even when it is not necessary to install a different version of `pip` +# the build process will still try to download `wheel`, see #3147 and #2986. +@pytest.mark.parametrize( + 'pip_version', + [ + None, + pytest.param( + 'pip<20.1', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<21', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<22', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'pip<23', + marks=pytest.mark.xfail( + 'sys.version_info >= (3, 12)', + reason="pip 23.1.2 required for Python 3.12 and later", + ), + ), + pytest.param( + 'https://github.com/pypa/pip/archive/main.zip', + marks=pytest.mark.xfail(reason='#2975'), + ), + ], +) +def test_pip_upgrade_from_source( + pip_version, venv_without_setuptools, setuptools_wheel, setuptools_sdist +): + """ + Check pip can upgrade setuptools from source. + """ + # Install pip/wheel, in a venv without setuptools (as it + # should not be needed for bootstrapping from source) + venv = venv_without_setuptools + venv.run(["pip", "install", "-U", "wheel"]) + if pip_version is not None: + venv.run(["python", "-m", "pip", "install", "-U", pip_version, "--retries=1"]) + with pytest.raises(subprocess.CalledProcessError): + # Meta-test to make sure setuptools is not installed + venv.run(["python", "-c", "import setuptools"]) + + # Then install from wheel. + venv.run(["pip", "install", str(setuptools_wheel)]) + # And finally try to upgrade from source. + venv.run(["pip", "install", "--no-cache-dir", "--upgrade", str(setuptools_sdist)]) + + +def test_no_missing_dependencies(bare_venv, request): + """ + Quick and dirty test to ensure all external dependencies are vendored. + """ + setuptools_dir = request.config.rootdir + bare_venv.run(['python', 'setup.py', '--help'], cwd=setuptools_dir) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_warnings.py b/python_embeded/Lib/site-packages/setuptools/tests/test_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..41193d4f717344546f8c70ad18b268a04740129b --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_warnings.py @@ -0,0 +1,106 @@ +from inspect import cleandoc + +import pytest + +from setuptools.warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning + +_EXAMPLES = { + "default": dict( + args=("Hello {x}", "\n\t{target} {v:.1f}"), + kwargs={"x": 5, "v": 3, "target": "World"}, + expected=""" + Hello 5 + !! + + ******************************************************************************** + World 3.0 + ******************************************************************************** + + !! + """, + ), + "futue_due_date": dict( + args=("Summary", "Lorem ipsum"), + kwargs={"due_date": (9999, 11, 22)}, + expected=""" + Summary + !! + + ******************************************************************************** + Lorem ipsum + + By 9999-Nov-22, you need to update your project and remove deprecated calls + or your builds will no longer be supported. + ******************************************************************************** + + !! + """, + ), + "past_due_date_with_docs": dict( + args=("Summary", "Lorem ipsum"), + kwargs={"due_date": (2000, 11, 22), "see_docs": "some_page.html"}, + expected=""" + Summary + !! + + ******************************************************************************** + Lorem ipsum + + This deprecation is overdue, please update your project and remove deprecated + calls to avoid build errors in the future. + + See https://setuptools.pypa.io/en/latest/some_page.html for details. + ******************************************************************************** + + !! + """, + ), +} + + +@pytest.mark.parametrize("example_name", _EXAMPLES.keys()) +def test_formatting(monkeypatch, example_name): + """ + It should automatically handle indentation, interpolation and things like due date. + """ + args = _EXAMPLES[example_name]["args"] + kwargs = _EXAMPLES[example_name]["kwargs"] + expected = _EXAMPLES[example_name]["expected"] + + monkeypatch.setenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false") + with pytest.warns(SetuptoolsWarning) as warn_info: + SetuptoolsWarning.emit(*args, **kwargs) + assert _get_message(warn_info) == cleandoc(expected) + + +def test_due_date_enforcement(monkeypatch): + class _MyDeprecation(SetuptoolsDeprecationWarning): + _SUMMARY = "Summary" + _DETAILS = "Lorem ipsum" + _DUE_DATE = (2000, 11, 22) + _SEE_DOCS = "some_page.html" + + monkeypatch.setenv("SETUPTOOLS_ENFORCE_DEPRECATION", "true") + with pytest.raises(SetuptoolsDeprecationWarning) as exc_info: + _MyDeprecation.emit() + + expected = """ + Summary + !! + + ******************************************************************************** + Lorem ipsum + + This deprecation is overdue, please update your project and remove deprecated + calls to avoid build errors in the future. + + See https://setuptools.pypa.io/en/latest/some_page.html for details. + ******************************************************************************** + + !! + """ + assert str(exc_info.value) == cleandoc(expected) + + +def _get_message(warn_info): + return next(warn.message.args[0] for warn in warn_info) diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_wheel.py b/python_embeded/Lib/site-packages/setuptools/tests/test_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..f91465084ad8dd700c339221c45c0b4b2daccd38 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_wheel.py @@ -0,0 +1,690 @@ +"""wheel tests""" + +from __future__ import annotations + +import contextlib +import glob +import inspect +import os +import pathlib +import stat +import subprocess +import sys +import sysconfig +import zipfile +from typing import Any + +import pytest +from jaraco import path +from packaging.tags import parse_tag + +from setuptools._importlib import metadata +from setuptools.wheel import Wheel + +from .contexts import tempdir +from .textwrap import DALS + +from distutils.sysconfig import get_config_var +from distutils.util import get_platform + +WHEEL_INFO_TESTS = ( + ('invalid.whl', ValueError), + ( + 'simplewheel-2.0-1-py2.py3-none-any.whl', + { + 'project_name': 'simplewheel', + 'version': '2.0', + 'build': '1', + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'simple.dist-0.1-py2.py3-none-any.whl', + { + 'project_name': 'simple.dist', + 'version': '0.1', + 'build': None, + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'example_pkg_a-1-py3-none-any.whl', + { + 'project_name': 'example_pkg_a', + 'version': '1', + 'build': None, + 'py_version': 'py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'PyQt5-5.9-5.9.1-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl', + { + 'project_name': 'PyQt5', + 'version': '5.9', + 'build': '5.9.1', + 'py_version': 'cp35.cp36.cp37', + 'abi': 'abi3', + 'platform': 'manylinux1_x86_64', + }, + ), +) + + +@pytest.mark.parametrize( + ('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS] +) +def test_wheel_info(filename, info): + if inspect.isclass(info): + with pytest.raises(info): + Wheel(filename) + return + w = Wheel(filename) + assert {k: getattr(w, k) for k in info.keys()} == info + + +@contextlib.contextmanager +def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + +def tree_set(root): + contents = set() + for dirpath, dirnames, filenames in os.walk(root): + for filename in filenames: + contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) + return contents + + +def flatten_tree(tree): + """Flatten nested dicts and lists into a full list of paths""" + output = set() + for node, contents in tree.items(): + if isinstance(contents, dict): + contents = flatten_tree(contents) + + for elem in contents: + if isinstance(elem, dict): + output |= {os.path.join(node, val) for val in flatten_tree(elem)} + else: + output.add(os.path.join(node, elem)) + return output + + +def format_install_tree(tree): + return { + x.format( + py_version=sysconfig.get_python_version(), + platform=get_platform(), + shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO'), + ) + for x in tree + } + + +def _check_wheel_install( + filename, install_dir, install_tree_includes, project_name, version, requires_txt +): + w = Wheel(filename) + egg_path = os.path.join(install_dir, w.egg_name()) + w.install_as_egg(egg_path) + if install_tree_includes is not None: + install_tree = format_install_tree(install_tree_includes) + exp = tree_set(install_dir) + assert install_tree.issubset(exp), install_tree - exp + + (dist,) = metadata.Distribution.discover(path=[egg_path]) + + # pyright is nitpicky; fine to assume dist.metadata.__getitem__ will fail or return None + # (https://github.com/pypa/setuptools/pull/5006#issuecomment-2894774288) + assert dist.metadata['Name'] == project_name # pyright: ignore # noqa: PGH003 + assert dist.metadata['Version'] == version # pyright: ignore # noqa: PGH003 + assert dist.read_text('requires.txt') == requires_txt + + +class Record: + def __init__(self, id, **kwargs): + self._id = id + self._fields = kwargs + + def __repr__(self) -> str: + return f'{self._id}(**{self._fields!r})' + + +# Using Any to avoid possible type union issues later in test +# making a TypedDict is not worth in a test and anonymous/inline TypedDict are experimental +# https://github.com/python/mypy/issues/9884 +WHEEL_INSTALL_TESTS: tuple[dict[str, Any], ...] = ( + dict( + id='basic', + file_defs={'foo': {'__init__.py': ''}}, + setup_kwargs=dict( + packages=['foo'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'foo': ['__init__.py'], + } + }), + ), + dict( + id='utf-8', + setup_kwargs=dict( + description='Description accentuée', + ), + ), + dict( + id='data', + file_defs={ + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + setup_kwargs=dict( + data_files=[('data_dir', ['data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'data_dir': ['data.txt'], + } + }), + ), + dict( + id='extension', + file_defs={ + 'extension.c': DALS( + """ + #include "Python.h" + + #if PY_MAJOR_VERSION >= 3 + + static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "extension", + NULL, + 0, + NULL, + NULL, + NULL, + NULL, + NULL + }; + + #define INITERROR return NULL + + PyMODINIT_FUNC PyInit_extension(void) + + #else + + #define INITERROR return + + void initextension(void) + + #endif + { + #if PY_MAJOR_VERSION >= 3 + PyObject *module = PyModule_Create(&moduledef); + #else + PyObject *module = Py_InitModule("extension", NULL); + #endif + if (module == NULL) + INITERROR; + #if PY_MAJOR_VERSION >= 3 + return module; + #endif + } + """ + ), + }, + setup_kwargs=dict( + ext_modules=[ + Record( + 'setuptools.Extension', name='extension', sources=['extension.c'] + ) + ], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}-{platform}.egg': [ + 'extension{shlib_ext}', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='header', + file_defs={ + 'header.h': DALS( + """ + """ + ), + }, + setup_kwargs=dict( + headers=['header.h'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'header.h', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ), + dict( + id='requires1', + install_requires='foobar==2.0', + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'requires.txt', + 'top_level.txt', + ] + } + }), + requires_txt=DALS( + """ + foobar==2.0 + """ + ), + ), + dict( + id='requires2', + install_requires=f""" + bar + foo<=2.0; {sys.platform!r} in sys_platform + """, + requires_txt=DALS( + """ + bar + foo<=2.0 + """ + ), + ), + dict( + id='requires3', + install_requires=f""" + bar; {sys.platform!r} != sys_platform + """, + ), + dict( + id='requires4', + install_requires=""" + foo + """, + extras_require={ + 'extra': 'foobar>3', + }, + requires_txt=DALS( + """ + foo + + [extra] + foobar>3 + """ + ), + ), + dict( + id='requires5', + extras_require={ + 'extra': f'foobar; {sys.platform!r} != sys_platform', + }, + requires_txt='\n' + + DALS( + """ + [extra] + """ + ), + ), + dict( + id='requires_ensure_order', + install_requires=""" + foo + bar + baz + qux + """, + extras_require={ + 'extra': """ + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """, + }, + requires_txt=DALS( + """ + foo + bar + baz + qux + + [extra] + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """ + ), + ), + dict( + id='namespace_package', + file_defs={ + 'foo': { + 'bar': {'__init__.py': ''}, + }, + }, + setup_kwargs=dict( + namespace_packages=['foo'], + packages=['foo.bar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foo': [ + '__init__.py', + {'bar': ['__init__.py']}, + ] + }, + ] + }), + ), + dict( + id='empty_namespace_package', + file_defs={ + 'foobar': { + '__init__.py': ( + "__import__('pkg_resources').declare_namespace(__name__)" + ) + }, + }, + setup_kwargs=dict( + namespace_packages=['foobar'], + packages=['foobar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foobar': [ + '__init__.py', + ] + }, + ] + }), + ), + dict( + id='data_in_package', + file_defs={ + 'foo': { + '__init__.py': '', + 'data_dir': { + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + } + }, + setup_kwargs=dict( + packages=['foo'], + data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ], + 'foo': [ + '__init__.py', + { + 'data_dir': [ + 'data.txt', + ] + }, + ], + } + }), + ), +) + + +@pytest.mark.parametrize( + 'params', + WHEEL_INSTALL_TESTS, + ids=[params['id'] for params in WHEEL_INSTALL_TESTS], +) +def test_wheel_install(params): + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_requires = params.get('install_requires', []) + extras_require = params.get('extras_require', {}) + requires_txt = params.get('requires_txt', None) + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + with ( + build_wheel( + name=project_name, + version=version, + install_requires=install_requires, + extras_require=extras_require, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, requires_txt + ) + + +def test_wheel_no_dist_dir(): + project_name = 'nodistinfo' + version = '1.0' + wheel_name = f'{project_name}-{version}-py2.py3-none-any.whl' + with tempdir() as source_dir: + wheel_path = os.path.join(source_dir, wheel_name) + # create an empty zip file + zipfile.ZipFile(wheel_path, 'w').close() + with tempdir() as install_dir: + with pytest.raises(ValueError): + _check_wheel_install( + wheel_path, install_dir, None, project_name, version, None + ) + + +def test_wheel_is_compatible(monkeypatch): + def sys_tags(): + return { + (t.interpreter, t.abi, t.platform) + for t in parse_tag('cp36-cp36m-manylinux1_x86_64') + } + + monkeypatch.setattr('setuptools.wheel._get_supported_tags', sys_tags) + assert Wheel('onnxruntime-0.1.2-cp36-cp36m-manylinux1_x86_64.whl').is_compatible() + + +def test_wheel_mode(): + @contextlib.contextmanager + def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + runsh = pathlib.Path(source_dir) / "script.sh" + os.chmod(runsh, 0o777) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + params = dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ) + + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + + with ( + build_wheel( + name=project_name, + version=version, + install_requires=[], + extras_require={}, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, None + ) + w = Wheel(filename) + base = pathlib.Path(install_dir) / w.egg_name() + script_sh = base / "EGG-INFO" / "scripts" / "script.sh" + assert script_sh.exists() + if sys.platform != 'win32': + # Editable file mode has no effect on Windows + assert oct(stat.S_IMODE(script_sh.stat().st_mode)) == "0o777" diff --git a/python_embeded/Lib/site-packages/setuptools/tests/test_windows_wrappers.py b/python_embeded/Lib/site-packages/setuptools/tests/test_windows_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4f990eb1c3cc67c61ea17f791430651e91040f18 --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/test_windows_wrappers.py @@ -0,0 +1,258 @@ +""" +Python Script Wrapper for Windows +================================= + +setuptools includes wrappers for Python scripts that allows them to be +executed like regular windows programs. There are 2 wrappers, one +for command-line programs, cli.exe, and one for graphical programs, +gui.exe. These programs are almost identical, function pretty much +the same way, and are generated from the same source file. The +wrapper programs are used by copying them to the directory containing +the script they are to wrap and with the same name as the script they +are to wrap. +""" + +import pathlib +import platform +import subprocess +import sys +import textwrap + +import pytest + +from setuptools._importlib import resources + +pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only") + + +class WrapperTester: + @classmethod + def prep_script(cls, template): + python_exe = subprocess.list2cmdline([sys.executable]) + return template % locals() + + @classmethod + def create_script(cls, tmpdir): + """ + Create a simple script, foo-script.py + + Note that the script starts with a Unix-style '#!' line saying which + Python executable to run. The wrapper will use this line to find the + correct Python executable. + """ + + script = cls.prep_script(cls.script_tmpl) + + with (tmpdir / cls.script_name).open('w') as f: + f.write(script) + + # also copy cli.exe to the sample directory + with (tmpdir / cls.wrapper_name).open('wb') as f: + w = resources.files('setuptools').joinpath(cls.wrapper_source).read_bytes() + f.write(w) + + +def win_launcher_exe(prefix): + """A simple routine to select launcher script based on platform.""" + assert prefix in ('cli', 'gui') + if platform.machine() == "ARM64": + return f"{prefix}-arm64.exe" + else: + return f"{prefix}-32.exe" + + +class TestCLI(WrapperTester): + script_name = 'foo-script.py' + wrapper_name = 'foo.exe' + wrapper_source = win_launcher_exe('cli') + + script_tmpl = textwrap.dedent( + """ + #!%(python_exe)s + import sys + input = repr(sys.stdin.read()) + print(sys.argv[0][-14:]) + print(sys.argv[1:]) + print(input) + if __debug__: + print('non-optimized') + """ + ).lstrip() + + def test_basic(self, tmpdir): + """ + When the copy of cli.exe, foo.exe in this example, runs, it examines + the path name it was run with and computes a Python script path name + by removing the '.exe' suffix and adding the '-script.py' suffix. (For + GUI programs, the suffix '-script.pyw' is added.) This is why we + named out script the way we did. Now we can run out script by running + the wrapper: + + This example was a little pathological in that it exercised windows + (MS C runtime) quoting rules: + + - Strings containing spaces are surrounded by double quotes. + + - Double quotes in strings need to be escaped by preceding them with + back slashes. + + - One or more backslashes preceding double quotes need to be escaped + by preceding each of them with back slashes. + """ + self.create_script(tmpdir) + cmd = [ + str(tmpdir / 'foo.exe'), + 'arg1', + 'arg 2', + 'arg "2\\"', + 'arg 4\\', + 'arg5 a\\\\b', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate('hello\nworld\n') + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] + 'hello\nworld\n' + non-optimized + """ + ).lstrip() + assert actual == expected + + def test_symlink(self, tmpdir): + """ + Ensure that symlink for the foo.exe is working correctly. + """ + script_dir = tmpdir / "script_dir" + script_dir.mkdir() + self.create_script(script_dir) + symlink = pathlib.Path(tmpdir / "foo.exe") + symlink.symlink_to(script_dir / "foo.exe") + + cmd = [ + str(tmpdir / 'foo.exe'), + 'arg1', + 'arg 2', + 'arg "2\\"', + 'arg 4\\', + 'arg5 a\\\\b', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate('hello\nworld\n') + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] + 'hello\nworld\n' + non-optimized + """ + ).lstrip() + assert actual == expected + + def test_with_options(self, tmpdir): + """ + Specifying Python Command-line Options + -------------------------------------- + + You can specify a single argument on the '#!' line. This can be used + to specify Python options like -O, to run in optimized mode or -i + to start the interactive interpreter. You can combine multiple + options as usual. For example, to run in optimized mode and + enter the interpreter after running the script, you could use -Oi: + """ + self.create_script(tmpdir) + tmpl = textwrap.dedent( + """ + #!%(python_exe)s -Oi + import sys + input = repr(sys.stdin.read()) + print(sys.argv[0][-14:]) + print(sys.argv[1:]) + print(input) + if __debug__: + print('non-optimized') + sys.ps1 = '---' + """ + ).lstrip() + with (tmpdir / 'foo-script.py').open('w') as f: + f.write(self.prep_script(tmpl)) + cmd = [str(tmpdir / 'foo.exe')] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + ) + stdout, _stderr = proc.communicate() + actual = stdout.replace('\r\n', '\n') + expected = textwrap.dedent( + r""" + \foo-script.py + [] + '' + --- + """ + ).lstrip() + assert actual == expected + + +class TestGUI(WrapperTester): + """ + Testing the GUI Version + ----------------------- + """ + + script_name = 'bar-script.pyw' + wrapper_source = win_launcher_exe('gui') + wrapper_name = 'bar.exe' + + script_tmpl = textwrap.dedent( + """ + #!%(python_exe)s + import sys + f = open(sys.argv[1], 'wb') + bytes_written = f.write(repr(sys.argv[2]).encode('utf-8')) + f.close() + """ + ).strip() + + def test_basic(self, tmpdir): + """Test the GUI version with the simple script, bar-script.py""" + self.create_script(tmpdir) + + cmd = [ + str(tmpdir / 'bar.exe'), + str(tmpdir / 'test_output.txt'), + 'Test Argument', + ] + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + ) + stdout, stderr = proc.communicate() + assert not stdout + assert not stderr + with (tmpdir / 'test_output.txt').open('rb') as f_out: + actual = f_out.read().decode('ascii') + assert actual == repr('Test Argument') diff --git a/python_embeded/Lib/site-packages/setuptools/tests/text.py b/python_embeded/Lib/site-packages/setuptools/tests/text.py new file mode 100644 index 0000000000000000000000000000000000000000..e05cc633ede9e5ce4f74b66a7bf76327c2000caa --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/text.py @@ -0,0 +1,4 @@ +class Filenames: + unicode = 'smörbröd.py' + latin_1 = unicode.encode('latin-1') + utf_8 = unicode.encode('utf-8') diff --git a/python_embeded/Lib/site-packages/setuptools/tests/textwrap.py b/python_embeded/Lib/site-packages/setuptools/tests/textwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..5e39618dca4ad6c3f0d4c8cb20af59ab85fb0eba --- /dev/null +++ b/python_embeded/Lib/site-packages/setuptools/tests/textwrap.py @@ -0,0 +1,6 @@ +import textwrap + + +def DALS(s): + "dedent and left-strip" + return textwrap.dedent(s).lstrip() diff --git a/python_embeded/Lib/site-packages/skimage/draw/__init__.py b/python_embeded/Lib/site-packages/skimage/draw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..86b41878a37dce7cfcda39163ee765d6a7088a0d --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/draw/__init__.py @@ -0,0 +1,5 @@ +"""Drawing primitives, such as lines, circles, text, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/draw/__init__.pyi b/python_embeded/Lib/site-packages/skimage/draw/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..548e93d0f988c2aa936b1d6f0028151b03185ee1 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/draw/__init__.pyi @@ -0,0 +1,45 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'line', + 'line_aa', + 'line_nd', + 'bezier_curve', + 'polygon', + 'polygon_perimeter', + 'ellipse', + 'ellipse_perimeter', + 'ellipsoid', + 'ellipsoid_stats', + 'circle_perimeter', + 'circle_perimeter_aa', + 'disk', + 'set_color', + 'random_shapes', + 'rectangle', + 'rectangle_perimeter', + 'polygon2mask', +] + +from .draw3d import ellipsoid, ellipsoid_stats +from ._draw import _bezier_segment +from ._random_shapes import random_shapes +from ._polygon2mask import polygon2mask +from .draw_nd import line_nd +from .draw import ( + ellipse, + set_color, + polygon_perimeter, + line, + line_aa, + polygon, + ellipse_perimeter, + circle_perimeter, + circle_perimeter_aa, + disk, + bezier_curve, + rectangle, + rectangle_perimeter, +) diff --git a/python_embeded/Lib/site-packages/skimage/draw/_draw.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/draw/_draw.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..1f87f99729cd7bcb6bb89d2733931bbc9beccbfa Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/draw/_draw.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/draw/_random_shapes.py b/python_embeded/Lib/site-packages/skimage/draw/_random_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..a8437a6a2c67e45e133f9836aa1eacfcc4f9fd69 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/draw/_random_shapes.py @@ -0,0 +1,459 @@ +import math + +import numpy as np + +from .draw import polygon as draw_polygon, disk as draw_disk, ellipse as draw_ellipse +from .._shared.utils import warn + + +def _generate_rectangle_mask(point, image, shape, random): + """Generate a mask for a filled rectangle shape. + + The height and width of the rectangle are generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape + is placed. + shape : tuple + The minimum and maximum size of the shape to fit. + random : `numpy.random.Generator` + + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + + """ + available_width = min(image[1] - point[1], shape[1]) - shape[0] + available_height = min(image[0] - point[0], shape[1]) - shape[0] + + # Pick random widths and heights. + r = shape[0] + random.integers(max(1, available_height)) - 1 + c = shape[0] + random.integers(max(1, available_width)) - 1 + rectangle = draw_polygon( + [ + point[0], + point[0] + r, + point[0] + r, + point[0], + ], + [ + point[1], + point[1], + point[1] + c, + point[1] + c, + ], + ) + label = ('rectangle', ((point[0], point[0] + r + 1), (point[1], point[1] + c + 1))) + + return rectangle, label + + +def _generate_circle_mask(point, image, shape, random): + """Generate a mask for a filled circle shape. + + The radius of the circle is generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape is placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('size must be > 1 for circles') + min_radius = shape[0] // 2.0 + max_radius = shape[1] // 2.0 + left = point[1] + right = image[1] - point[1] + top = point[0] + bottom = image[0] - point[0] + available_radius = min(left, right, top, bottom, max_radius) - min_radius + if available_radius < 0: + raise ArithmeticError('cannot fit shape to image') + radius = int(min_radius + random.integers(max(1, available_radius))) + # TODO: think about how to deprecate this + # while draw_circle was deprecated in favor of draw_disk + # switching to a label of 'disk' here + # would be a breaking change for downstream libraries + # See discussion on naming convention here + # https://github.com/scikit-image/scikit-image/pull/4428 + disk = draw_disk((point[0], point[1]), radius) + # Until a deprecation path is decided, always return `'circle'` + label = ( + 'circle', + ( + (point[0] - radius + 1, point[0] + radius), + (point[1] - radius + 1, point[1] + radius), + ), + ) + + return disk, label + + +def _generate_triangle_mask(point, image, shape, random): + """Generate a mask for a filled equilateral triangle shape. + + The length of the sides of the triangle is generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of a up-pointing triangle. + image : tuple + The height, width and depth of the image into which the shape + is placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('dimension must be > 1 for triangles') + available_side = min(image[1] - point[1], point[0], shape[1]) - shape[0] + side = shape[0] + random.integers(max(1, available_side)) - 1 + triangle_height = int(np.ceil(np.sqrt(3 / 4.0) * side)) + triangle = draw_polygon( + [ + point[0], + point[0] - triangle_height, + point[0], + ], + [ + point[1], + point[1] + side // 2, + point[1] + side, + ], + ) + label = ( + 'triangle', + ((point[0] - triangle_height, point[0] + 1), (point[1], point[1] + side + 1)), + ) + + return triangle, label + + +def _generate_ellipse_mask(point, image, shape, random): + """Generate a mask for a filled ellipse shape. + + The rotation, major and minor semi-axes of the ellipse are generated + randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape is + placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('size must be > 1 for ellipses') + min_radius = shape[0] / 2.0 + max_radius = shape[1] / 2.0 + left = point[1] + right = image[1] - point[1] + top = point[0] + bottom = image[0] - point[0] + available_radius = min(left, right, top, bottom, max_radius) + if available_radius < min_radius: + raise ArithmeticError('cannot fit shape to image') + # NOTE: very conservative because we could take into account the fact that + # we have 2 different radii, but this is a good first approximation. + # Also, we can afford to have a uniform sampling because the ellipse will + # be rotated. + r_radius = random.uniform(min_radius, available_radius + 1) + c_radius = random.uniform(min_radius, available_radius + 1) + rotation = random.uniform(-np.pi, np.pi) + ellipse = draw_ellipse( + point[0], + point[1], + r_radius, + c_radius, + shape=image[:2], + rotation=rotation, + ) + max_radius = math.ceil(max(r_radius, c_radius)) + min_x = np.min(ellipse[0]) + max_x = np.max(ellipse[0]) + 1 + min_y = np.min(ellipse[1]) + max_y = np.max(ellipse[1]) + 1 + label = ('ellipse', ((min_x, max_x), (min_y, max_y))) + + return ellipse, label + + +# Allows lookup by key as well as random selection. +SHAPE_GENERATORS = dict( + rectangle=_generate_rectangle_mask, + circle=_generate_circle_mask, + triangle=_generate_triangle_mask, + ellipse=_generate_ellipse_mask, +) +SHAPE_CHOICES = list(SHAPE_GENERATORS.values()) + + +def _generate_random_colors(num_colors, num_channels, intensity_range, random): + """Generate an array of random colors. + + Parameters + ---------- + num_colors : int + Number of colors to generate. + num_channels : int + Number of elements representing color. + intensity_range : {tuple of tuples of ints, tuple of ints}, optional + The range of values to sample pixel values from. For grayscale images + the format is (min, max). For multichannel - ((min, max),) if the + ranges are equal across the channels, and + ((min_0, max_0), ... (min_N, max_N)) if they differ. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ValueError + When the `intensity_range` is not in the interval (0, 255). + + Returns + ------- + colors : array + An array of shape (num_colors, num_channels), where the values for + each channel are drawn from the corresponding `intensity_range`. + + """ + if num_channels == 1: + intensity_range = (intensity_range,) + elif len(intensity_range) == 1: + intensity_range = intensity_range * num_channels + colors = [random.integers(r[0], r[1] + 1, size=num_colors) for r in intensity_range] + return np.transpose(colors) + + +def random_shapes( + image_shape, + max_shapes, + min_shapes=1, + min_size=2, + max_size=None, + num_channels=3, + shape=None, + intensity_range=None, + allow_overlap=False, + num_trials=100, + rng=None, + *, + channel_axis=-1, +): + """Generate an image with random shapes, labeled with bounding boxes. + + The image is populated with random shapes with random sizes, random + locations, and random colors, with or without overlap. + + Shapes have random (row, col) starting coordinates and random sizes bounded + by `min_size` and `max_size`. It can occur that a randomly generated shape + will not fit the image at all. In that case, the algorithm will try again + with new starting coordinates a certain number of times. However, it also + means that some shapes may be skipped altogether. In that case, this + function will generate fewer shapes than requested. + + Parameters + ---------- + image_shape : tuple + The number of rows and columns of the image to generate. + max_shapes : int + The maximum number of shapes to (attempt to) fit into the shape. + min_shapes : int, optional + The minimum number of shapes to (attempt to) fit into the shape. + min_size : int, optional + The minimum dimension of each shape to fit into the image. + max_size : int, optional + The maximum dimension of each shape to fit into the image. + num_channels : int, optional + Number of channels in the generated image. If 1, generate monochrome + images, else color images with multiple channels. Ignored if + ``multichannel`` is set to False. + shape : {rectangle, circle, triangle, ellipse, None} str, optional + The name of the shape to generate or `None` to pick random ones. + intensity_range : {tuple of tuples of uint8, tuple of uint8}, optional + The range of values to sample pixel values from. For grayscale + images the format is (min, max). For multichannel - ((min, max),) + if the ranges are equal across the channels, and + ((min_0, max_0), ... (min_N, max_N)) if they differ. As the + function supports generation of uint8 arrays only, the maximum + range is (0, 255). If None, set to (0, 254) for each channel + reserving color of intensity = 255 for background. + allow_overlap : bool, optional + If `True`, allow shapes to overlap. + num_trials : int, optional + How often to attempt to fit a shape into the image before skipping it. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + image : uint8 array + An image with the fitted shapes. + labels : list + A list of labels, one per shape in the image. Each label is a + (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + + Examples + -------- + >>> import skimage.draw + >>> image, labels = skimage.draw.random_shapes((32, 32), max_shapes=3) + >>> image # doctest: +SKIP + array([ + [[255, 255, 255], + [255, 255, 255], + [255, 255, 255], + ..., + [255, 255, 255], + [255, 255, 255], + [255, 255, 255]]], dtype=uint8) + >>> labels # doctest: +SKIP + [('circle', ((22, 18), (25, 21))), + ('triangle', ((5, 6), (13, 13)))] + """ + if min_size > image_shape[0] or min_size > image_shape[1]: + raise ValueError('Minimum dimension must be less than ncols and nrows') + max_size = max_size or max(image_shape[0], image_shape[1]) + + if channel_axis is None: + num_channels = 1 + + if intensity_range is None: + intensity_range = (0, 254) if num_channels == 1 else ((0, 254),) + else: + tmp = (intensity_range,) if num_channels == 1 else intensity_range + for intensity_pair in tmp: + for intensity in intensity_pair: + if not (0 <= intensity <= 255): + msg = 'Intensity range must lie within (0, 255) interval' + raise ValueError(msg) + + rng = np.random.default_rng(rng) + user_shape = shape + image_shape = (image_shape[0], image_shape[1], num_channels) + image = np.full(image_shape, 255, dtype=np.uint8) + filled = np.zeros(image_shape, dtype=bool) + labels = [] + + num_shapes = rng.integers(min_shapes, max_shapes + 1) + colors = _generate_random_colors(num_shapes, num_channels, intensity_range, rng) + shape = (min_size, max_size) + for shape_idx in range(num_shapes): + if user_shape is None: + shape_generator = rng.choice(SHAPE_CHOICES) + else: + shape_generator = SHAPE_GENERATORS[user_shape] + for _ in range(num_trials): + # Pick start coordinates. + column = rng.integers(max(1, image_shape[1] - min_size)) + row = rng.integers(max(1, image_shape[0] - min_size)) + point = (row, column) + try: + indices, label = shape_generator(point, image_shape, shape, rng) + except ArithmeticError: + # Couldn't fit the shape, skip it. + indices = [] + continue + # Check if there is an overlap where the mask is nonzero. + if allow_overlap or not filled[indices].any(): + image[indices] = colors[shape_idx] + filled[indices] = True + labels.append(label) + break + else: + warn( + 'Could not fit any shapes to image, ' + 'consider reducing the minimum dimension' + ) + + if channel_axis is None: + image = np.squeeze(image, axis=2) + else: + image = np.moveaxis(image, -1, channel_axis) + + return image, labels diff --git a/python_embeded/Lib/site-packages/skimage/draw/draw_nd.py b/python_embeded/Lib/site-packages/skimage/draw/draw_nd.py new file mode 100644 index 0000000000000000000000000000000000000000..ca421b88ecc49dbf52fbfe880cd58286aa67816c --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/draw/draw_nd.py @@ -0,0 +1,108 @@ +import numpy as np + + +def _round_safe(coords): + """Round coords while ensuring successive values are less than 1 apart. + + When rounding coordinates for `line_nd`, we want coordinates that are less + than 1 apart (always the case, by design) to remain less than one apart. + However, NumPy rounds values to the nearest *even* integer, so: + + >>> np.round([0.5, 1.5, 2.5, 3.5, 4.5]) + array([0., 2., 2., 4., 4.]) + + So, for our application, we detect whether the above case occurs, and use + ``np.floor`` if so. It is sufficient to detect that the first coordinate + falls on 0.5 and that the second coordinate is 1.0 apart, since we assume + by construction that the inter-point distance is less than or equal to 1 + and that all successive points are equidistant. + + Parameters + ---------- + coords : 1D array of float + The coordinates array. We assume that all successive values are + equidistant (``np.all(np.diff(coords) = coords[1] - coords[0])``) + and that this distance is no more than 1 + (``np.abs(coords[1] - coords[0]) <= 1``). + + Returns + ------- + rounded : 1D array of int + The array correctly rounded for an indexing operation, such that no + successive indices will be more than 1 apart. + + Examples + -------- + >>> coords0 = np.array([0.5, 1.25, 2., 2.75, 3.5]) + >>> _round_safe(coords0) + array([0, 1, 2, 3, 4]) + >>> coords1 = np.arange(0.5, 8, 1) + >>> coords1 + array([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]) + >>> _round_safe(coords1) + array([0, 1, 2, 3, 4, 5, 6, 7]) + """ + if len(coords) > 1 and coords[0] % 1 == 0.5 and coords[1] - coords[0] == 1: + _round_function = np.floor + else: + _round_function = np.round + return _round_function(coords).astype(int) + + +def line_nd(start, stop, *, endpoint=False, integer=True): + """Draw a single-pixel thick line in n dimensions. + + The line produced will be ndim-connected. That is, two subsequent + pixels in the line will be either direct or diagonal neighbors in + n dimensions. + + Parameters + ---------- + start : array-like, shape (N,) + The start coordinates of the line. + stop : array-like, shape (N,) + The end coordinates of the line. + endpoint : bool, optional + Whether to include the endpoint in the returned line. Defaults + to False, which allows for easy drawing of multi-point paths. + integer : bool, optional + Whether to round the coordinates to integer. If True (default), + the returned coordinates can be used to directly index into an + array. `False` could be used for e.g. vector drawing. + + Returns + ------- + coords : tuple of arrays + The coordinates of points on the line. + + Examples + -------- + >>> lin = line_nd((1, 1), (5, 2.5), endpoint=False) + >>> lin + (array([1, 2, 3, 4]), array([1, 1, 2, 2])) + >>> im = np.zeros((6, 5), dtype=int) + >>> im[lin] = 1 + >>> im + array([[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + >>> line_nd([2, 1, 1], [5, 5, 2.5], endpoint=True) + (array([2, 3, 4, 4, 5]), array([1, 2, 3, 4, 5]), array([1, 1, 2, 2, 2])) + """ + start = np.asarray(start) + stop = np.asarray(stop) + npoints = int(np.ceil(np.max(np.abs(stop - start)))) + if endpoint: + npoints += 1 + + coords = np.linspace(start, stop, num=npoints, endpoint=endpoint).T + if integer: + for dim in range(len(start)): + coords[dim, :] = _round_safe(coords[dim, :]) + + coords = coords.astype(int) + + return tuple(coords) diff --git a/python_embeded/Lib/site-packages/skimage/exposure/__init__.py b/python_embeded/Lib/site-packages/skimage/exposure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62a4dc7cec3d44ae5f0842f5e76f4d6c991cbde0 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/exposure/__init__.py @@ -0,0 +1,5 @@ +"""Image intensity adjustment, e.g., histogram equalization, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/exposure/__init__.pyi b/python_embeded/Lib/site-packages/skimage/exposure/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8ab9b4e28309a13b77d5110597543dec1244059b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/exposure/__init__.pyi @@ -0,0 +1,29 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'histogram', + 'equalize_hist', + 'equalize_adapthist', + 'rescale_intensity', + 'cumulative_distribution', + 'adjust_gamma', + 'adjust_sigmoid', + 'adjust_log', + 'is_low_contrast', + 'match_histograms', +] + +from ._adapthist import equalize_adapthist +from .histogram_matching import match_histograms +from .exposure import ( + histogram, + equalize_hist, + rescale_intensity, + cumulative_distribution, + adjust_gamma, + adjust_sigmoid, + adjust_log, + is_low_contrast, +) diff --git a/python_embeded/Lib/site-packages/skimage/exposure/_adapthist.py b/python_embeded/Lib/site-packages/skimage/exposure/_adapthist.py new file mode 100644 index 0000000000000000000000000000000000000000..a55abfb4d0a259d613832092c5db9b5bf4292200 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/exposure/_adapthist.py @@ -0,0 +1,317 @@ +""" +Adapted from "Contrast Limited Adaptive Histogram Equalization" by Karel +Zuiderveld, Graphics Gems IV, Academic Press, 1994. + +http://tog.acm.org/resources/GraphicsGems/ + +Relicensed with permission of the author under the Modified BSD license. +""" + +import math +import numbers + +import numpy as np + +from .._shared.utils import _supported_float_type +from ..color.adapt_rgb import adapt_rgb, hsv_value +from .exposure import rescale_intensity +from ..util import img_as_uint + +NR_OF_GRAY = 2**14 # number of grayscale levels to use in CLAHE algorithm + + +@adapt_rgb(hsv_value) +def equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256): + """Contrast Limited Adaptive Histogram Equalization (CLAHE). + + An algorithm for local contrast enhancement, that uses histograms computed + over different tile regions of the image. Local details can therefore be + enhanced even in regions that are darker or lighter than most of the image. + + Parameters + ---------- + image : (M[, ...][, C]) ndarray + Input image. + kernel_size : int or array_like, optional + Defines the shape of contextual regions used in the algorithm. If + iterable is passed, it must have the same number of elements as + ``image.ndim`` (without color channel). If integer, it is broadcasted + to each `image` dimension. By default, ``kernel_size`` is 1/8 of + ``image`` height by 1/8 of its width. + clip_limit : float, optional + Clipping limit, normalized between 0 and 1 (higher values give more + contrast). + nbins : int, optional + Number of gray bins for histogram ("data range"). + + Returns + ------- + out : (M[, ...][, C]) ndarray + Equalized image with float64 dtype. + + See Also + -------- + equalize_hist, rescale_intensity + + Notes + ----- + * For color images, the following steps are performed: + - The image is converted to HSV color space + - The CLAHE algorithm is run on the V (Value) channel + - The image is converted back to RGB space and returned + * For RGBA images, the original alpha channel is removed. + + .. versionchanged:: 0.17 + The values returned by this function are slightly shifted upwards + because of an internal change in rounding behavior. + + References + ---------- + .. [1] http://tog.acm.org/resources/GraphicsGems/ + .. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE + """ + + float_dtype = _supported_float_type(image.dtype) + image = img_as_uint(image) + image = np.round(rescale_intensity(image, out_range=(0, NR_OF_GRAY - 1))).astype( + np.min_scalar_type(NR_OF_GRAY) + ) + + if kernel_size is None: + kernel_size = tuple([max(s // 8, 1) for s in image.shape]) + elif isinstance(kernel_size, numbers.Number): + kernel_size = (kernel_size,) * image.ndim + elif len(kernel_size) != image.ndim: + raise ValueError(f'Incorrect value of `kernel_size`: {kernel_size}') + + kernel_size = [int(k) for k in kernel_size] + + image = _clahe(image, kernel_size, clip_limit, nbins) + image = image.astype(float_dtype, copy=False) + return rescale_intensity(image) + + +def _clahe(image, kernel_size, clip_limit, nbins): + """Contrast Limited Adaptive Histogram Equalization. + + Parameters + ---------- + image : (M[, ...]) ndarray + Input image. + kernel_size : int or N-tuple of int + Defines the shape of contextual regions used in the algorithm. + clip_limit : float + Normalized clipping limit between 0 and 1 (higher values give more + contrast). + nbins : int + Number of gray bins for histogram ("data range"). + + Returns + ------- + out : (M[, ...]) ndarray + Equalized image. + + The number of "effective" graylevels in the output image is set by `nbins`; + selecting a small value (e.g. 128) speeds up processing and still produces + an output image of good quality. A clip limit of 0 or larger than or equal + to 1 results in standard (non-contrast limited) AHE. + """ + ndim = image.ndim + dtype = image.dtype + + # pad the image such that the shape in each dimension + # - is a multiple of the kernel_size and + # - is preceded by half a kernel size + pad_start_per_dim = [k // 2 for k in kernel_size] + + pad_end_per_dim = [ + (k - s % k) % k + int(np.ceil(k / 2.0)) + for k, s in zip(kernel_size, image.shape) + ] + + image = np.pad( + image, + [[p_i, p_f] for p_i, p_f in zip(pad_start_per_dim, pad_end_per_dim)], + mode='reflect', + ) + + # determine gray value bins + bin_size = 1 + NR_OF_GRAY // nbins + lut = np.arange(NR_OF_GRAY, dtype=np.min_scalar_type(NR_OF_GRAY)) + lut //= bin_size + + image = lut[image] + + # calculate graylevel mappings for each contextual region + # rearrange image into flattened contextual regions + ns_hist = [int(s / k) - 1 for s, k in zip(image.shape, kernel_size)] + hist_blocks_shape = np.array([ns_hist, kernel_size]).T.flatten() + hist_blocks_axis_order = np.array( + [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)] + ).flatten() + hist_slices = [slice(k // 2, k // 2 + n * k) for k, n in zip(kernel_size, ns_hist)] + hist_blocks = image[tuple(hist_slices)].reshape(hist_blocks_shape) + hist_blocks = np.transpose(hist_blocks, axes=hist_blocks_axis_order) + hist_block_assembled_shape = hist_blocks.shape + hist_blocks = hist_blocks.reshape((math.prod(ns_hist), -1)) + + # Calculate actual clip limit + kernel_elements = math.prod(kernel_size) + if clip_limit > 0.0: + clim = int(np.clip(clip_limit * kernel_elements, 1, None)) + else: + # largest possible value, i.e., do not clip (AHE) + clim = kernel_elements + + hist = np.apply_along_axis(np.bincount, -1, hist_blocks, minlength=nbins) + hist = np.apply_along_axis(clip_histogram, -1, hist, clip_limit=clim) + hist = map_histogram(hist, 0, NR_OF_GRAY - 1, kernel_elements) + hist = hist.reshape(hist_block_assembled_shape[:ndim] + (-1,)) + + # duplicate leading mappings in each dim + map_array = np.pad(hist, [[1, 1] for _ in range(ndim)] + [[0, 0]], mode='edge') + + # Perform multilinear interpolation of graylevel mappings + # using the convention described here: + # https://en.wikipedia.org/w/index.php?title=Adaptive_histogram_ + # equalization&oldid=936814673#Efficient_computation_by_interpolation + + # rearrange image into blocks for vectorized processing + ns_proc = [int(s / k) for s, k in zip(image.shape, kernel_size)] + blocks_shape = np.array([ns_proc, kernel_size]).T.flatten() + blocks_axis_order = np.array( + [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)] + ).flatten() + blocks = image.reshape(blocks_shape) + blocks = np.transpose(blocks, axes=blocks_axis_order) + blocks_flattened_shape = blocks.shape + blocks = np.reshape(blocks, (math.prod(ns_proc), math.prod(blocks.shape[ndim:]))) + + # calculate interpolation coefficients + coeffs = np.meshgrid( + *tuple([np.arange(k) / k for k in kernel_size[::-1]]), indexing='ij' + ) + coeffs = [np.transpose(c).flatten() for c in coeffs] + inv_coeffs = [1 - c for dim, c in enumerate(coeffs)] + + # sum over contributions of neighboring contextual + # regions in each direction + result = np.zeros(blocks.shape, dtype=np.float32) + for iedge, edge in enumerate(np.ndindex(*([2] * ndim))): + edge_maps = map_array[tuple([slice(e, e + n) for e, n in zip(edge, ns_proc)])] + edge_maps = edge_maps.reshape((math.prod(ns_proc), -1)) + + # apply map + edge_mapped = np.take_along_axis(edge_maps, blocks, axis=-1) + + # interpolate + edge_coeffs = np.prod( + [[inv_coeffs, coeffs][e][d] for d, e in enumerate(edge[::-1])], 0 + ) + + result += (edge_mapped * edge_coeffs).astype(result.dtype) + + result = result.astype(dtype) + + # rebuild result image from blocks + result = result.reshape(blocks_flattened_shape) + blocks_axis_rebuild_order = np.array( + [np.arange(0, ndim), np.arange(ndim, ndim * 2)] + ).T.flatten() + result = np.transpose(result, axes=blocks_axis_rebuild_order) + result = result.reshape(image.shape) + + # undo padding + unpad_slices = tuple( + [ + slice(p_i, s - p_f) + for p_i, p_f, s in zip(pad_start_per_dim, pad_end_per_dim, image.shape) + ] + ) + result = result[unpad_slices] + + return result + + +def clip_histogram(hist, clip_limit): + """Perform clipping of the histogram and redistribution of bins. + + The histogram is clipped and the number of excess pixels is counted. + Afterwards the excess pixels are equally redistributed across the + whole histogram (providing the bin count is smaller than the cliplimit). + + Parameters + ---------- + hist : ndarray + Histogram array. + clip_limit : int + Maximum allowed bin count. + + Returns + ------- + hist : ndarray + Clipped histogram. + """ + # calculate total number of excess pixels + excess_mask = hist > clip_limit + excess = hist[excess_mask] + n_excess = excess.sum() - excess.size * clip_limit + hist[excess_mask] = clip_limit + + # Second part: clip histogram and redistribute excess pixels in each bin + bin_incr = n_excess // hist.size # average binincrement + upper = clip_limit - bin_incr # Bins larger than upper set to cliplimit + + low_mask = hist < upper + n_excess -= hist[low_mask].size * bin_incr + hist[low_mask] += bin_incr + + mid_mask = np.logical_and(hist >= upper, hist < clip_limit) + mid = hist[mid_mask] + n_excess += mid.sum() - mid.size * clip_limit + hist[mid_mask] = clip_limit + + while n_excess > 0: # Redistribute remaining excess + prev_n_excess = n_excess + for index in range(hist.size): + under_mask = hist < clip_limit + step_size = max(1, np.count_nonzero(under_mask) // n_excess) + under_mask = under_mask[index::step_size] + hist[index::step_size][under_mask] += 1 + n_excess -= np.count_nonzero(under_mask) + if n_excess <= 0: + break + if prev_n_excess == n_excess: + break + + return hist + + +def map_histogram(hist, min_val, max_val, n_pixels): + """Calculate the equalized lookup table (mapping). + + It does so by cumulating the input histogram. + Histogram bins are assumed to be represented by the last array dimension. + + Parameters + ---------- + hist : ndarray + Clipped histogram. + min_val : int + Minimum value for mapping. + max_val : int + Maximum value for mapping. + n_pixels : int + Number of pixels in the region. + + Returns + ------- + out : ndarray + Mapped intensity LUT. + """ + out = np.cumsum(hist, axis=-1).astype(float) + out *= (max_val - min_val) / n_pixels + out += min_val + np.clip(out, a_min=None, a_max=max_val, out=out) + + return out.astype(int) diff --git a/python_embeded/Lib/site-packages/skimage/exposure/exposure.py b/python_embeded/Lib/site-packages/skimage/exposure/exposure.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ca21eac8370628962483f4b1c9f369fa216603 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/exposure/exposure.py @@ -0,0 +1,849 @@ +import numpy as np + +from ..util.dtype import dtype_range, dtype_limits +from .._shared import utils + + +__all__ = [ + 'histogram', + 'cumulative_distribution', + 'equalize_hist', + 'rescale_intensity', + 'adjust_gamma', + 'adjust_log', + 'adjust_sigmoid', +] + + +DTYPE_RANGE = dtype_range.copy() +DTYPE_RANGE.update((d.__name__, limits) for d, limits in dtype_range.items()) +DTYPE_RANGE.update( + { + 'uint10': (0, 2**10 - 1), + 'uint12': (0, 2**12 - 1), + 'uint14': (0, 2**14 - 1), + 'bool': dtype_range[bool], + 'float': dtype_range[np.float64], + } +) + + +def _offset_array(arr, low_boundary, high_boundary): + """Offset the array to get the lowest value at 0 if negative.""" + if low_boundary < 0: + offset = low_boundary + dyn_range = high_boundary - low_boundary + # get smallest dtype that can hold both minimum and offset maximum + offset_dtype = np.promote_types( + np.min_scalar_type(dyn_range), np.min_scalar_type(low_boundary) + ) + if arr.dtype != offset_dtype: + # prevent overflow errors when offsetting + arr = arr.astype(offset_dtype) + arr = arr - offset + return arr + + +def _bincount_histogram_centers(image, source_range): + """Compute bin centers for bincount-based histogram.""" + if source_range not in ['image', 'dtype']: + raise ValueError(f'Incorrect value for `source_range` argument: {source_range}') + if source_range == 'image': + image_min = int(image.min().astype(np.int64)) + image_max = int(image.max().astype(np.int64)) + elif source_range == 'dtype': + image_min, image_max = dtype_limits(image, clip_negative=False) + bin_centers = np.arange(image_min, image_max + 1) + return bin_centers + + +def _bincount_histogram(image, source_range, bin_centers=None): + """ + Efficient histogram calculation for an image of integers. + + This function is significantly more efficient than np.histogram but + works only on images of integers. It is based on np.bincount. + + Parameters + ---------- + image : array + Input image. + source_range : string + 'image' determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + + Returns + ------- + hist : array + The values of the histogram. + bin_centers : array + The values at the center of the bins. + """ + if bin_centers is None: + bin_centers = _bincount_histogram_centers(image, source_range) + image_min, image_max = bin_centers[0], bin_centers[-1] + image = _offset_array(image, image_min, image_max) + hist = np.bincount(image.ravel(), minlength=image_max - min(image_min, 0) + 1) + if source_range == 'image': + idx = max(image_min, 0) + hist = hist[idx:] + return hist, bin_centers + + +def _get_outer_edges(image, hist_range): + """Determine the outer bin edges to use for `numpy.histogram`. + + These are obtained from either the image or hist_range. + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + hist_range: 2-tuple of int or None + Range of values covered by the histogram bins. If None, the minimum + and maximum values of `image` are used. + + Returns + ------- + first_edge, last_edge : int + The range spanned by the histogram bins. + + Notes + ----- + This function is adapted from ``np.lib.histograms._get_outer_edges``. + """ + if hist_range is not None: + first_edge, last_edge = hist_range + if first_edge > last_edge: + raise ValueError("max must be larger than min in hist_range parameter.") + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f'supplied hist_range of [{first_edge}, {last_edge}] is ' f'not finite' + ) + elif image.size == 0: + # handle empty arrays. Can't determine hist_range, so use 0-1. + first_edge, last_edge = 0, 1 + else: + first_edge, last_edge = image.min(), image.max() + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f'autodetected hist_range of [{first_edge}, {last_edge}] is ' + f'not finite' + ) + + # expand empty hist_range to avoid divide by zero + if first_edge == last_edge: + first_edge = first_edge - 0.5 + last_edge = last_edge + 0.5 + + return first_edge, last_edge + + +def _get_bin_edges(image, nbins, hist_range): + """Computes histogram bins for use with `numpy.histogram`. + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + nbins : int + The number of bins. + hist_range: 2-tuple of int + Range of values covered by the histogram bins. + + Returns + ------- + bin_edges : ndarray + The histogram bin edges. + + Notes + ----- + This function is a simplified version of + ``np.lib.histograms._get_bin_edges`` that only supports uniform bins. + """ + first_edge, last_edge = _get_outer_edges(image, hist_range) + # numpy/gh-10322 means that type resolution rules are dependent on array + # shapes. To avoid this causing problems, we pick a type now and stick + # with it throughout. + bin_type = np.result_type(first_edge, last_edge, image) + if np.issubdtype(bin_type, np.integer): + bin_type = np.result_type(bin_type, float) + + # compute bin edges + bin_edges = np.linspace( + first_edge, last_edge, nbins + 1, endpoint=True, dtype=bin_type + ) + return bin_edges + + +def _get_numpy_hist_range(image, source_range): + if source_range == 'image': + hist_range = None + elif source_range == 'dtype': + hist_range = dtype_limits(image, clip_negative=False) + else: + raise ValueError(f'Incorrect value for `source_range` argument: {source_range}') + return hist_range + + +@utils.channel_as_last_axis(multichannel_output=False) +def histogram( + image, nbins=256, source_range='image', normalize=False, *, channel_axis=None +): + """Return histogram of image. + + Unlike `numpy.histogram`, this function returns the centers of bins and + does not rebin integer arrays. For integer arrays, each integer value has + its own bin, which improves speed and intensity-resolution. + + If `channel_axis` is not set, the histogram is computed on the flattened + image. For color or multichannel images, set ``channel_axis`` to use a + common binning for all channels. Alternatively, one may apply the function + separately on each channel to obtain a histogram for each color channel + with separate binning. + + Parameters + ---------- + image : array + Input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + source_range : string, optional + 'image' (default) determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + normalize : bool, optional + If True, normalize the histogram by the sum of its values. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + hist : array + The values of the histogram. When ``channel_axis`` is not None, hist + will be a 2D array where the first axis corresponds to channels. + bin_centers : array + The values at the center of the bins. + + See Also + -------- + cumulative_distribution + + Examples + -------- + >>> from skimage import data, exposure, img_as_float + >>> image = img_as_float(data.camera()) + >>> np.histogram(image, bins=2) + (array([ 93585, 168559]), array([0. , 0.5, 1. ])) + >>> exposure.histogram(image, nbins=2) + (array([ 93585, 168559]), array([0.25, 0.75])) + """ + sh = image.shape + if len(sh) == 3 and sh[-1] < 4 and channel_axis is None: + utils.warn( + 'This might be a color image. The histogram will be ' + 'computed on the flattened image. You can instead ' + 'apply this function to each color channel, or set ' + 'channel_axis.' + ) + + if channel_axis is not None: + channels = sh[-1] + hist = [] + + # compute bins based on the raveled array + if np.issubdtype(image.dtype, np.integer): + # here bins corresponds to the bin centers + bins = _bincount_histogram_centers(image, source_range) + else: + # determine the bin edges for np.histogram + hist_range = _get_numpy_hist_range(image, source_range) + bins = _get_bin_edges(image, nbins, hist_range) + + for chan in range(channels): + h, bc = _histogram(image[..., chan], bins, source_range, normalize) + hist.append(h) + # Convert to numpy arrays + bin_centers = np.asarray(bc) + hist = np.stack(hist, axis=0) + else: + hist, bin_centers = _histogram(image, nbins, source_range, normalize) + + return hist, bin_centers + + +def _histogram(image, bins, source_range, normalize): + """ + + Parameters + ---------- + image : ndarray + Image for which the histogram is to be computed. + bins : int or ndarray + The number of histogram bins. For images with integer dtype, an array + containing the bin centers can also be provided. For images with + floating point dtype, this can be an array of bin_edges for use by + ``np.histogram``. + source_range : string, optional + 'image' (default) determines the range from the input image. + 'dtype' determines the range from the expected range of the images + of that data type. + normalize : bool, optional + If True, normalize the histogram by the sum of its values. + """ + + image = image.flatten() + # For integer types, histogramming with bincount is more efficient. + if np.issubdtype(image.dtype, np.integer): + bin_centers = bins if isinstance(bins, np.ndarray) else None + hist, bin_centers = _bincount_histogram(image, source_range, bin_centers) + else: + hist_range = _get_numpy_hist_range(image, source_range) + hist, bin_edges = np.histogram(image, bins=bins, range=hist_range) + bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.0 + + if normalize: + hist = hist / np.sum(hist) + return hist, bin_centers + + +def cumulative_distribution(image, nbins=256): + """Return cumulative distribution function (cdf) for the given image. + + Parameters + ---------- + image : array + Image array. + nbins : int, optional + Number of bins for image histogram. + + Returns + ------- + img_cdf : array + Values of cumulative distribution function. + bin_centers : array + Centers of bins. + + See Also + -------- + histogram + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Cumulative_distribution_function + + Examples + -------- + >>> from skimage import data, exposure, img_as_float + >>> image = img_as_float(data.camera()) + >>> hi = exposure.histogram(image) + >>> cdf = exposure.cumulative_distribution(image) + >>> all(cdf[0] == np.cumsum(hi[0])/float(image.size)) + True + """ + hist, bin_centers = histogram(image, nbins) + img_cdf = hist.cumsum() + img_cdf = img_cdf / float(img_cdf[-1]) + + # cast img_cdf to single precision for float32 or float16 inputs + cdf_dtype = utils._supported_float_type(image.dtype) + img_cdf = img_cdf.astype(cdf_dtype, copy=False) + + return img_cdf, bin_centers + + +def equalize_hist(image, nbins=256, mask=None): + """Return image after histogram equalization. + + Parameters + ---------- + image : array + Image array. + nbins : int, optional + Number of bins for image histogram. Note: this argument is + ignored for integer images, for which each integer is its own + bin. + mask : ndarray of bools or 0s and 1s, optional + Array of same shape as `image`. Only points at which mask == True + are used for the equalization, which is applied to the whole image. + + Returns + ------- + out : float array + Image array after histogram equalization. + + Notes + ----- + This function is adapted from [1]_ with the author's permission. + + References + ---------- + .. [1] http://www.janeriksolem.net/histogram-equalization-with-python-and.html + .. [2] https://en.wikipedia.org/wiki/Histogram_equalization + + """ + if mask is not None: + mask = np.array(mask, dtype=bool) + cdf, bin_centers = cumulative_distribution(image[mask], nbins) + else: + cdf, bin_centers = cumulative_distribution(image, nbins) + out = np.interp(image.flat, bin_centers, cdf) + out = out.reshape(image.shape) + # Unfortunately, np.interp currently always promotes to float64, so we + # have to cast back to single precision when float32 output is desired + return out.astype(utils._supported_float_type(image.dtype), copy=False) + + +def intensity_range(image, range_values='image', clip_negative=False): + """Return image intensity range (min, max) based on desired value type. + + Parameters + ---------- + image : array + Input image. + range_values : str or 2-tuple, optional + The image intensity range is configured by this parameter. + The possible values for this parameter are enumerated below. + + 'image' + Return image min/max as the range. + 'dtype' + Return min/max of the image's dtype as the range. + dtype-name + Return intensity range based on desired `dtype`. Must be valid key + in `DTYPE_RANGE`. Note: `image` is ignored for this range type. + 2-tuple + Return `range_values` as min/max intensities. Note that there's no + reason to use this function if you just want to specify the + intensity range explicitly. This option is included for functions + that use `intensity_range` to support all desired range types. + + clip_negative : bool, optional + If True, clip the negative range (i.e. return 0 for min intensity) + even if the image dtype allows negative values. + """ + if range_values == 'dtype': + range_values = image.dtype.type + + if range_values == 'image': + i_min = np.min(image) + i_max = np.max(image) + elif range_values in DTYPE_RANGE: + i_min, i_max = DTYPE_RANGE[range_values] + if clip_negative: + i_min = 0 + else: + i_min, i_max = range_values + return i_min, i_max + + +def _output_dtype(dtype_or_range, image_dtype): + """Determine the output dtype for rescale_intensity. + + The dtype is determined according to the following rules: + - if ``dtype_or_range`` is a dtype, that is the output dtype. + - if ``dtype_or_range`` is a dtype string, that is the dtype used, unless + it is not a NumPy data type (e.g. 'uint12' for 12-bit unsigned integers), + in which case the data type that can contain it will be used + (e.g. uint16 in this case). + - if ``dtype_or_range`` is a pair of values, the output data type will be + ``_supported_float_type(image_dtype)``. This preserves float32 output for + float32 inputs. + + Parameters + ---------- + dtype_or_range : type, string, or 2-tuple of int/float + The desired range for the output, expressed as either a NumPy dtype or + as a (min, max) pair of numbers. + image_dtype : np.dtype + The input image dtype. + + Returns + ------- + out_dtype : type + The data type appropriate for the desired output. + """ + if type(dtype_or_range) in [list, tuple, np.ndarray]: + # pair of values: always return float. + return utils._supported_float_type(image_dtype) + if type(dtype_or_range) == type: + # already a type: return it + return dtype_or_range + if dtype_or_range in DTYPE_RANGE: + # string key in DTYPE_RANGE dictionary + try: + # if it's a canonical numpy dtype, convert + return np.dtype(dtype_or_range).type + except TypeError: # uint10, uint12, uint14 + # otherwise, return uint16 + return np.uint16 + else: + raise ValueError( + 'Incorrect value for out_range, should be a valid image data ' + f'type or a pair of values, got {dtype_or_range}.' + ) + + +def rescale_intensity(image, in_range='image', out_range='dtype'): + """Return image after stretching or shrinking its intensity levels. + + The desired intensity range of the input and output, `in_range` and + `out_range` respectively, are used to stretch or shrink the intensity range + of the input image. See examples below. + + Parameters + ---------- + image : array + Image array. + in_range, out_range : str or 2-tuple, optional + Min and max intensity values of input and output image. + The possible values for this parameter are enumerated below. + + 'image' + Use image min/max as the intensity range. + 'dtype' + Use min/max of the image's dtype as the intensity range. + dtype-name + Use intensity range based on desired `dtype`. Must be valid key + in `DTYPE_RANGE`. + 2-tuple + Use `range_values` as explicit min/max intensities. + + Returns + ------- + out : array + Image array after rescaling its intensity. This image is the same dtype + as the input image. + + Notes + ----- + .. versionchanged:: 0.17 + The dtype of the output array has changed to match the input dtype, or + float if the output range is specified by a pair of values. + + See Also + -------- + equalize_hist + + Examples + -------- + By default, the min/max intensities of the input image are stretched to + the limits allowed by the image's dtype, since `in_range` defaults to + 'image' and `out_range` defaults to 'dtype': + + >>> image = np.array([51, 102, 153], dtype=np.uint8) + >>> rescale_intensity(image) + array([ 0, 127, 255], dtype=uint8) + + It's easy to accidentally convert an image dtype from uint8 to float: + + >>> 1.0 * image + array([ 51., 102., 153.]) + + Use `rescale_intensity` to rescale to the proper range for float dtypes: + + >>> image_float = 1.0 * image + >>> rescale_intensity(image_float) + array([0. , 0.5, 1. ]) + + To maintain the low contrast of the original, use the `in_range` parameter: + + >>> rescale_intensity(image_float, in_range=(0, 255)) + array([0.2, 0.4, 0.6]) + + If the min/max value of `in_range` is more/less than the min/max image + intensity, then the intensity levels are clipped: + + >>> rescale_intensity(image_float, in_range=(0, 102)) + array([0.5, 1. , 1. ]) + + If you have an image with signed integers but want to rescale the image to + just the positive range, use the `out_range` parameter. In that case, the + output dtype will be float: + + >>> image = np.array([-10, 0, 10], dtype=np.int8) + >>> rescale_intensity(image, out_range=(0, 127)) + array([ 0. , 63.5, 127. ]) + + To get the desired range with a specific dtype, use ``.astype()``: + + >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8) + array([ 0, 63, 127], dtype=int8) + + If the input image is constant, the output will be clipped directly to the + output range: + >>> image = np.array([130, 130, 130], dtype=np.int32) + >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32) + array([127, 127, 127], dtype=int32) + """ + if out_range in ['dtype', 'image']: + out_dtype = _output_dtype(image.dtype.type, image.dtype) + else: + out_dtype = _output_dtype(out_range, image.dtype) + + imin, imax = map(float, intensity_range(image, in_range)) + omin, omax = map( + float, intensity_range(image, out_range, clip_negative=(imin >= 0)) + ) + + if np.any(np.isnan([imin, imax, omin, omax])): + utils.warn( + "One or more intensity levels are NaN. Rescaling will broadcast " + "NaN to the full image. Provide intensity levels yourself to " + "avoid this. E.g. with np.nanmin(image), np.nanmax(image).", + stacklevel=2, + ) + + image = np.clip(image, imin, imax) + + if imin != imax: + image = (image - imin) / (imax - imin) + return (image * (omax - omin) + omin).astype(out_dtype) + else: + return np.clip(image, omin, omax).astype(out_dtype) + + +def _assert_non_negative(image): + if np.any(image < 0): + raise ValueError( + 'Image Correction methods work correctly only on ' + 'images with non-negative values. Use ' + 'skimage.exposure.rescale_intensity.' + ) + + +def _adjust_gamma_u8(image, gamma, gain): + """LUT based implementation of gamma adjustment.""" + lut = 255 * gain * (np.linspace(0, 1, 256) ** gamma) + lut = np.minimum(np.rint(lut), 255).astype('uint8') + return lut[image] + + +def adjust_gamma(image, gamma=1, gain=1): + """Performs Gamma Correction on the input image. + + Also known as Power Law Transform. + This function transforms the input image pixelwise according to the + equation ``O = I**gamma`` after scaling each pixel to the range 0 to 1. + + Parameters + ---------- + image : ndarray + Input image. + gamma : float, optional + Non negative real number. Default value is 1. + gain : float, optional + The constant multiplier. Default value is 1. + + Returns + ------- + out : ndarray + Gamma corrected output image. + + See Also + -------- + adjust_log + + Notes + ----- + For gamma greater than 1, the histogram will shift towards left and + the output image will be darker than the input image. + + For gamma less than 1, the histogram will shift towards right and + the output image will be brighter than the input image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gamma_correction + + Examples + -------- + >>> from skimage import data, exposure, img_as_float + >>> image = img_as_float(data.moon()) + >>> gamma_corrected = exposure.adjust_gamma(image, 2) + >>> # Output is darker for gamma > 1 + >>> image.mean() > gamma_corrected.mean() + True + """ + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number.") + + dtype = image.dtype.type + + if dtype is np.uint8: + out = _adjust_gamma_u8(image, gamma, gain) + else: + _assert_non_negative(image) + + scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0]) + + out = (((image / scale) ** gamma) * scale * gain).astype(dtype) + + return out + + +def adjust_log(image, gain=1, inv=False): + """Performs Logarithmic correction on the input image. + + This function transforms the input image pixelwise according to the + equation ``O = gain*log(1 + I)`` after scaling each pixel to the range + 0 to 1. For inverse logarithmic correction, the equation is + ``O = gain*(2**I - 1)``. + + Parameters + ---------- + image : ndarray + Input image. + gain : float, optional + The constant multiplier. Default value is 1. + inv : float, optional + If True, it performs inverse logarithmic correction, + else correction will be logarithmic. Defaults to False. + + Returns + ------- + out : ndarray + Logarithm corrected output image. + + See Also + -------- + adjust_gamma + + References + ---------- + .. [1] http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf + + """ + _assert_non_negative(image) + dtype = image.dtype.type + scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0]) + + if inv: + out = (2 ** (image / scale) - 1) * scale * gain + return dtype(out) + + out = np.log2(1 + image / scale) * scale * gain + return out.astype(dtype) + + +def adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False): + """Performs Sigmoid Correction on the input image. + + Also known as Contrast Adjustment. + This function transforms the input image pixelwise according to the + equation ``O = 1/(1 + exp*(gain*(cutoff - I)))`` after scaling each pixel + to the range 0 to 1. + + Parameters + ---------- + image : ndarray + Input image. + cutoff : float, optional + Cutoff of the sigmoid function that shifts the characteristic curve + in horizontal direction. Default value is 0.5. + gain : float, optional + The constant multiplier in exponential's power of sigmoid function. + Default value is 10. + inv : bool, optional + If True, returns the negative sigmoid correction. Defaults to False. + + Returns + ------- + out : ndarray + Sigmoid corrected output image. + + See Also + -------- + adjust_gamma + + References + ---------- + .. [1] Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast + Enhancement Functions", + http://markfairchild.org/PDFs/PAP07.pdf + + """ + _assert_non_negative(image) + dtype = image.dtype.type + scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0]) + + if inv: + out = (1 - 1 / (1 + np.exp(gain * (cutoff - image / scale)))) * scale + return dtype(out) + + out = (1 / (1 + np.exp(gain * (cutoff - image / scale)))) * scale + return out.astype(dtype) + + +def is_low_contrast( + image, + fraction_threshold=0.05, + lower_percentile=1, + upper_percentile=99, + method='linear', +): + """Determine if an image is low contrast. + + Parameters + ---------- + image : array-like + The image under test. + fraction_threshold : float, optional + The low contrast fraction threshold. An image is considered low- + contrast when its range of brightness spans less than this + fraction of its data type's full range. [1]_ + lower_percentile : float, optional + Disregard values below this percentile when computing image contrast. + upper_percentile : float, optional + Disregard values above this percentile when computing image contrast. + method : str, optional + The contrast determination method. Right now the only available + option is "linear". + + Returns + ------- + out : bool + True when the image is determined to be low contrast. + + Notes + ----- + For boolean images, this function returns False only if all values are + the same (the method, threshold, and percentile arguments are ignored). + + References + ---------- + .. [1] https://scikit-image.org/docs/dev/user_guide/data_types.html + + Examples + -------- + >>> image = np.linspace(0, 0.04, 100) + >>> is_low_contrast(image) + True + >>> image[-1] = 1 + >>> is_low_contrast(image) + True + >>> is_low_contrast(image, upper_percentile=100) + False + """ + image = np.asanyarray(image) + + if image.dtype == bool: + return not ((image.max() == 1) and (image.min() == 0)) + + if image.ndim == 3: + from ..color import rgb2gray, rgba2rgb # avoid circular import + + if image.shape[2] == 4: + image = rgba2rgb(image) + if image.shape[2] == 3: + image = rgb2gray(image) + + dlimits = dtype_limits(image, clip_negative=False) + limits = np.percentile(image, [lower_percentile, upper_percentile]) + ratio = (limits[1] - limits[0]) / (dlimits[1] - dlimits[0]) + + return ratio < fraction_threshold diff --git a/python_embeded/Lib/site-packages/skimage/exposure/histogram_matching.py b/python_embeded/Lib/site-packages/skimage/exposure/histogram_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..b840a56b7f9de2a89e48b98447a40e8d7875b7be --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/exposure/histogram_matching.py @@ -0,0 +1,93 @@ +import numpy as np + +from .._shared import utils + + +def _match_cumulative_cdf(source, template): + """ + Return modified source array so that the cumulative density function of + its values matches the cumulative density function of the template. + """ + if source.dtype.kind == 'u': + src_lookup = source.reshape(-1) + src_counts = np.bincount(src_lookup) + tmpl_counts = np.bincount(template.reshape(-1)) + + # omit values where the count was 0 + tmpl_values = np.nonzero(tmpl_counts)[0] + tmpl_counts = tmpl_counts[tmpl_values] + else: + src_values, src_lookup, src_counts = np.unique( + source.reshape(-1), return_inverse=True, return_counts=True + ) + tmpl_values, tmpl_counts = np.unique(template.reshape(-1), return_counts=True) + + # calculate normalized quantiles for each array + src_quantiles = np.cumsum(src_counts) / source.size + tmpl_quantiles = np.cumsum(tmpl_counts) / template.size + + interp_a_values = np.interp(src_quantiles, tmpl_quantiles, tmpl_values) + return interp_a_values[src_lookup].reshape(source.shape) + + +@utils.channel_as_last_axis(channel_arg_positions=(0, 1)) +def match_histograms(image, reference, *, channel_axis=None): + """Adjust an image so that its cumulative histogram matches that of another. + + The adjustment is applied separately for each channel. + + Parameters + ---------- + image : ndarray + Input image. Can be gray-scale or in color. + reference : ndarray + Image to match histogram of. Must have the same number of channels as + image. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + Returns + ------- + matched : ndarray + Transformed input image. + + Raises + ------ + ValueError + Thrown when the number of channels in the input image and the reference + differ. + + References + ---------- + .. [1] http://paulbourke.net/miscellaneous/equalisation/ + + """ + if image.ndim != reference.ndim: + raise ValueError( + 'Image and reference must have the same number ' 'of channels.' + ) + + if channel_axis is not None: + if image.shape[-1] != reference.shape[-1]: + raise ValueError( + 'Number of channels in the input image and ' + 'reference image must match!' + ) + + matched = np.empty(image.shape, dtype=image.dtype) + for channel in range(image.shape[-1]): + matched_channel = _match_cumulative_cdf( + image[..., channel], reference[..., channel] + ) + matched[..., channel] = matched_channel + else: + # _match_cumulative_cdf will always return float64 due to np.interp + matched = _match_cumulative_cdf(image, reference) + + if matched.dtype.kind == 'f': + # output a float32 result when the input is float16 or float32 + out_dtype = utils._supported_float_type(image.dtype) + matched = matched.astype(out_dtype, copy=False) + return matched diff --git a/python_embeded/Lib/site-packages/skimage/feature/__init__.py b/python_embeded/Lib/site-packages/skimage/feature/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2bee8a2f78a7ac4d073f5328d24ac3b49c87126 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/__init__.py @@ -0,0 +1,5 @@ +"""Feature detection and extraction, e.g., texture analysis, corners, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/feature/__init__.pyi b/python_embeded/Lib/site-packages/skimage/feature/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc8aa2b792913f7fd7e97e869259910cbe2a93dd --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/__init__.pyi @@ -0,0 +1,88 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'canny', + 'Cascade', + 'daisy', + 'hog', + 'graycomatrix', + 'graycoprops', + 'local_binary_pattern', + 'multiblock_lbp', + 'draw_multiblock_lbp', + 'peak_local_max', + 'structure_tensor', + 'structure_tensor_eigenvalues', + 'hessian_matrix', + 'hessian_matrix_det', + 'hessian_matrix_eigvals', + 'shape_index', + 'corner_kitchen_rosenfeld', + 'corner_harris', + 'corner_shi_tomasi', + 'corner_foerstner', + 'corner_subpix', + 'corner_peaks', + 'corner_moravec', + 'corner_fast', + 'corner_orientations', + 'match_template', + 'BRIEF', + 'CENSURE', + 'ORB', + 'SIFT', + 'match_descriptors', + 'plot_matched_features', + 'blob_dog', + 'blob_doh', + 'blob_log', + 'haar_like_feature', + 'haar_like_feature_coord', + 'draw_haar_like_feature', + 'multiscale_basic_features', + 'learn_gmm', + 'fisher_vector', +] + +from ._canny import canny +from ._cascade import Cascade +from ._daisy import daisy +from ._hog import hog +from .texture import ( + graycomatrix, + graycoprops, + local_binary_pattern, + multiblock_lbp, + draw_multiblock_lbp, +) +from .peak import peak_local_max +from .corner import ( + corner_kitchen_rosenfeld, + corner_harris, + corner_shi_tomasi, + corner_foerstner, + corner_subpix, + corner_peaks, + corner_fast, + structure_tensor, + structure_tensor_eigenvalues, + hessian_matrix, + hessian_matrix_eigvals, + hessian_matrix_det, + corner_moravec, + corner_orientations, + shape_index, +) +from .template import match_template +from .brief import BRIEF +from .censure import CENSURE +from .orb import ORB +from .sift import SIFT +from .match import match_descriptors +from .util import plot_matched_features +from .blob import blob_dog, blob_log, blob_doh +from .haar import haar_like_feature, haar_like_feature_coord, draw_haar_like_feature +from ._basic_features import multiscale_basic_features +from ._fisher_vector import learn_gmm, fisher_vector diff --git a/python_embeded/Lib/site-packages/skimage/feature/_basic_features.py b/python_embeded/Lib/site-packages/skimage/feature/_basic_features.py new file mode 100644 index 0000000000000000000000000000000000000000..1df9db734f9afe3fedc16e878f4a41302ab60d36 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_basic_features.py @@ -0,0 +1,198 @@ +from itertools import combinations_with_replacement +import itertools +import numpy as np +from skimage import filters, feature +from skimage.util.dtype import img_as_float32 +from .._shared._dependency_checks import is_wasm + +if not is_wasm: + from concurrent.futures import ThreadPoolExecutor as PoolExecutor +else: + from contextlib import AbstractContextManager + + # Threading isn't supported on WASM, mock ThreadPoolExecutor as a fallback + class PoolExecutor(AbstractContextManager): + def __init__(self, *_, **__): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + def map(self, fn, iterables): + return map(fn, iterables) + + +def _texture_filter(gaussian_filtered): + H_elems = [ + np.gradient(np.gradient(gaussian_filtered)[ax0], axis=ax1) + for ax0, ax1 in combinations_with_replacement(range(gaussian_filtered.ndim), 2) + ] + eigvals = feature.hessian_matrix_eigvals(H_elems) + return eigvals + + +def _singlescale_basic_features_singlechannel( + img, sigma, intensity=True, edges=True, texture=True +): + results = () + gaussian_filtered = filters.gaussian(img, sigma=sigma, preserve_range=False) + if intensity: + results += (gaussian_filtered,) + if edges: + results += (filters.sobel(gaussian_filtered),) + if texture: + results += (*_texture_filter(gaussian_filtered),) + return results + + +def _mutiscale_basic_features_singlechannel( + img, + intensity=True, + edges=True, + texture=True, + sigma_min=0.5, + sigma_max=16, + num_sigma=None, + num_workers=None, +): + """Features for a single channel nd image. + + Parameters + ---------- + img : ndarray + Input image, which can be grayscale or multichannel. + intensity : bool, default True + If True, pixel intensities averaged over the different scales + are added to the feature set. + edges : bool, default True + If True, intensities of local gradients averaged over the different + scales are added to the feature set. + texture : bool, default True + If True, eigenvalues of the Hessian matrix after Gaussian blurring + at different scales are added to the feature set. + sigma_min : float, optional + Smallest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + sigma_max : float, optional + Largest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + num_sigma : int, optional + Number of values of the Gaussian kernel between sigma_min and sigma_max. + If None, sigma_min multiplied by powers of 2 are used. + num_workers : int or None, optional + The number of parallel threads to use. If set to ``None``, the full + set of available cores are used. + + Returns + ------- + features : list + List of features, each element of the list is an array of shape as img. + """ + # computations are faster as float32 + img = np.ascontiguousarray(img_as_float32(img)) + if num_sigma is None: + num_sigma = int(np.log2(sigma_max) - np.log2(sigma_min) + 1) + sigmas = np.logspace( + np.log2(sigma_min), + np.log2(sigma_max), + num=num_sigma, + base=2, + endpoint=True, + ) + with PoolExecutor(max_workers=num_workers) as ex: + out_sigmas = list( + ex.map( + lambda s: _singlescale_basic_features_singlechannel( + img, s, intensity=intensity, edges=edges, texture=texture + ), + sigmas, + ) + ) + features = itertools.chain.from_iterable(out_sigmas) + return features + + +def multiscale_basic_features( + image, + intensity=True, + edges=True, + texture=True, + sigma_min=0.5, + sigma_max=16, + num_sigma=None, + num_workers=None, + *, + channel_axis=None, +): + """Local features for a single- or multi-channel nd image. + + Intensity, gradient intensity and local structure are computed at + different scales thanks to Gaussian blurring. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel. + intensity : bool, default True + If True, pixel intensities averaged over the different scales + are added to the feature set. + edges : bool, default True + If True, intensities of local gradients averaged over the different + scales are added to the feature set. + texture : bool, default True + If True, eigenvalues of the Hessian matrix after Gaussian blurring + at different scales are added to the feature set. + sigma_min : float, optional + Smallest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + sigma_max : float, optional + Largest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + num_sigma : int, optional + Number of values of the Gaussian kernel between sigma_min and sigma_max. + If None, sigma_min multiplied by powers of 2 are used. + num_workers : int or None, optional + The number of parallel threads to use. If set to ``None``, the full + set of available cores are used. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + features : np.ndarray + Array of shape ``image.shape + (n_features,)``. When `channel_axis` is + not None, all channels are concatenated along the features dimension. + (i.e. ``n_features == n_features_singlechannel * n_channels``) + """ + if not any([intensity, edges, texture]): + raise ValueError( + "At least one of `intensity`, `edges` or `textures`" + "must be True for features to be computed." + ) + if channel_axis is None: + image = image[..., np.newaxis] + channel_axis = -1 + elif channel_axis != -1: + image = np.moveaxis(image, channel_axis, -1) + + all_results = ( + _mutiscale_basic_features_singlechannel( + image[..., dim], + intensity=intensity, + edges=edges, + texture=texture, + sigma_min=sigma_min, + sigma_max=sigma_max, + num_sigma=num_sigma, + num_workers=num_workers, + ) + for dim in range(image.shape[-1]) + ) + features = list(itertools.chain.from_iterable(all_results)) + out = np.stack(features, axis=-1) + return out diff --git a/python_embeded/Lib/site-packages/skimage/feature/_canny.py b/python_embeded/Lib/site-packages/skimage/feature/_canny.py new file mode 100644 index 0000000000000000000000000000000000000000..88adf7a922453bbb7a345fee0ce793d2ff2bf5f9 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_canny.py @@ -0,0 +1,262 @@ +""" +canny.py - Canny Edge detector + +Reference: Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 +""" + +import numpy as np +import scipy.ndimage as ndi + +from ..util.dtype import dtype_limits +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_nD +from ._canny_cy import _nonmaximum_suppression_bilinear + + +def _preprocess(image, mask, sigma, mode, cval): + """Generate a smoothed image and an eroded mask. + + The image is smoothed using a gaussian filter ignoring masked + pixels and the mask is eroded. + + Parameters + ---------- + image : array + Image to be smoothed. + mask : array + Mask with 1's for significant pixels, 0's for masked pixels. + 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. + mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'} + The ``mode`` parameter determines how the array borders are + handled, where ``cval`` is the value when mode is equal to + 'constant'. + cval : float, optional + Value to fill past edges of input if `mode` is 'constant'. + + Returns + ------- + smoothed_image : ndarray + The smoothed array + eroded_mask : ndarray + The eroded mask. + + Notes + ----- + This function calculates the fractional contribution of masked pixels + by applying the function to the mask (which gets you the fraction of + the pixel data that's due to significant points). We then mask the image + and apply the function. The resulting values will be lower by the + bleed-over fraction, so you can recalibrate by dividing by the function + on the mask to recover the effect of smoothing from just the significant + pixels. + """ + gaussian_kwargs = dict(sigma=sigma, mode=mode, cval=cval, preserve_range=False) + compute_bleedover = mode == 'constant' or mask is not None + float_type = _supported_float_type(image.dtype) + if mask is None: + if compute_bleedover: + mask = np.ones(image.shape, dtype=float_type) + masked_image = image + + eroded_mask = np.ones(image.shape, dtype=bool) + eroded_mask[:1, :] = 0 + eroded_mask[-1:, :] = 0 + eroded_mask[:, :1] = 0 + eroded_mask[:, -1:] = 0 + + else: + mask = mask.astype(bool, copy=False) + masked_image = np.zeros_like(image) + masked_image[mask] = image[mask] + + # Make the eroded mask. Setting the border value to zero will wipe + # out the image edges for us. + s = ndi.generate_binary_structure(2, 2) + eroded_mask = ndi.binary_erosion(mask, s, border_value=0) + + if compute_bleedover: + # Compute the fractional contribution of masked pixels by applying + # the function to the mask (which gets you the fraction of the + # pixel data that's due to significant points) + bleed_over = ( + gaussian(mask.astype(float_type, copy=False), **gaussian_kwargs) + + np.finfo(float_type).eps + ) + + # Smooth the masked image + smoothed_image = gaussian(masked_image, **gaussian_kwargs) + + # Lower the result by the bleed-over fraction, so you can + # recalibrate by dividing by the function on the mask to recover + # the effect of smoothing from just the significant pixels. + if compute_bleedover: + smoothed_image /= bleed_over + + return smoothed_image, eroded_mask + + +def canny( + image, + sigma=1.0, + low_threshold=None, + high_threshold=None, + mask=None, + use_quantiles=False, + *, + mode='constant', + cval=0.0, +): + """Edge filter an image using the Canny algorithm. + + Parameters + ---------- + image : 2D array + Grayscale input image to detect edges on; can be of any dtype. + sigma : float, optional + Standard deviation of the Gaussian filter. + low_threshold : float, optional + Lower bound for hysteresis thresholding (linking edges). + If None, low_threshold is set to 10% of dtype's max. + high_threshold : float, optional + Upper bound for hysteresis thresholding (linking edges). + If None, high_threshold is set to 20% of dtype's max. + mask : array, dtype=bool, optional + Mask to limit the application of Canny to a certain area. + use_quantiles : bool, optional + If ``True`` then treat low_threshold and high_threshold as + quantiles of the edge magnitude image, rather than absolute + edge magnitude values. If ``True`` then the thresholds must be + in the range [0, 1]. + mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'} + The ``mode`` parameter determines how the array borders are + handled during Gaussian filtering, where ``cval`` is the value when + mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if `mode` is 'constant'. + + Returns + ------- + output : 2D array (image) + The binary edge map. + + See also + -------- + skimage.filters.sobel + + Notes + ----- + The steps of the algorithm are as follows: + + * Smooth the image using a Gaussian with ``sigma`` width. + + * Apply the horizontal and vertical Sobel operators to get the gradients + within the image. The edge strength is the norm of the gradient. + + * Thin potential edges to 1-pixel wide curves. First, find the normal + to the edge at each point. This is done by looking at the + signs and the relative magnitude of the X-Sobel and Y-Sobel + to sort the points into 4 categories: horizontal, vertical, + diagonal and antidiagonal. Then look in the normal and reverse + directions to see if the values in either of those directions are + greater than the point in question. Use interpolation to get a mix of + points instead of picking the one that's the closest to the normal. + + * Perform a hysteresis thresholding: first label all points above the + high threshold as edges. Then recursively label any point above the + low threshold that is 8-connected to a labeled point as an edge. + + References + ---------- + .. [1] Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 + :DOI:`10.1109/TPAMI.1986.4767851` + .. [2] William Green's Canny tutorial + https://en.wikipedia.org/wiki/Canny_edge_detector + + Examples + -------- + >>> from skimage import feature + >>> rng = np.random.default_rng() + >>> # Generate noisy image of a square + >>> im = np.zeros((256, 256)) + >>> im[64:-64, 64:-64] = 1 + >>> im += 0.2 * rng.random(im.shape) + >>> # First trial with the Canny filter, with the default smoothing + >>> edges1 = feature.canny(im) + >>> # Increase the smoothing for better results + >>> edges2 = feature.canny(im, sigma=3) + + """ + + # Regarding masks, any point touching a masked point will have a gradient + # that is "infected" by the masked point, so it's enough to erode the + # mask by one and then mask the output. We also mask out the border points + # because who knows what lies beyond the edge of the image? + + if np.issubdtype(image.dtype, np.int64) or np.issubdtype(image.dtype, np.uint64): + raise ValueError("64-bit integer images are not supported") + + check_nD(image, 2) + dtype_max = dtype_limits(image, clip_negative=False)[1] + + if low_threshold is None: + low_threshold = 0.1 + elif use_quantiles: + if not (0.0 <= low_threshold <= 1.0): + raise ValueError("Quantile thresholds must be between 0 and 1.") + else: + low_threshold /= dtype_max + + if high_threshold is None: + high_threshold = 0.2 + elif use_quantiles: + if not (0.0 <= high_threshold <= 1.0): + raise ValueError("Quantile thresholds must be between 0 and 1.") + else: + high_threshold /= dtype_max + + if high_threshold < low_threshold: + raise ValueError("low_threshold should be lower then high_threshold") + + # Image filtering + smoothed, eroded_mask = _preprocess(image, mask, sigma, mode, cval) + + # Gradient magnitude estimation + jsobel = ndi.sobel(smoothed, axis=1) + isobel = ndi.sobel(smoothed, axis=0) + magnitude = isobel * isobel + magnitude += jsobel * jsobel + np.sqrt(magnitude, out=magnitude) + + if use_quantiles: + low_threshold, high_threshold = np.percentile( + magnitude, [100.0 * low_threshold, 100.0 * high_threshold] + ) + + # Non-maximum suppression + low_masked = _nonmaximum_suppression_bilinear( + isobel, jsobel, magnitude, eroded_mask, low_threshold + ) + + # Double thresholding and edge tracking + # + # Segment the low-mask, then only keep low-segments that have + # some high_mask component in them + # + low_mask = low_masked > 0 + strel = np.ones((3, 3), bool) + labels, count = ndi.label(low_mask, strel) + if count == 0: + return low_mask + + high_mask = low_mask & (low_masked >= high_threshold) + nonzero_sums = np.unique(labels[high_mask]) + good_label = np.zeros((count + 1,), bool) + good_label[nonzero_sums] = True + output_mask = good_label[labels] + return output_mask diff --git a/python_embeded/Lib/site-packages/skimage/feature/_canny_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_canny_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..0e36be21223950215ecf6d20dc0e7f7e81089192 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_canny_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_cascade.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_cascade.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..cade86a820556db59cc7e42466ab93d2218394e9 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_cascade.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_daisy.py b/python_embeded/Lib/site-packages/skimage/feature/_daisy.py new file mode 100644 index 0000000000000000000000000000000000000000..81803ea05df3ed4415b10ea7521be394984f59e3 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_daisy.py @@ -0,0 +1,249 @@ +import math + +import numpy as np +from numpy import arctan2, exp, pi, sqrt + +from .. import draw +from ..util.dtype import img_as_float +from .._shared.filters import gaussian +from .._shared.utils import check_nD +from ..color import gray2rgb + + +def daisy( + image, + step=4, + radius=15, + rings=3, + histograms=8, + orientations=8, + normalization='l1', + sigmas=None, + ring_radii=None, + visualize=False, +): + '''Extract DAISY feature descriptors densely for the given image. + + DAISY is a feature descriptor similar to SIFT formulated in a way that + allows for fast dense extraction. Typically, this is practical for + bag-of-features image representations. + + The implementation follows Tola et al. [1]_ but deviate on the following + points: + + * Histogram bin contribution are smoothed with a circular Gaussian + window over the tonal range (the angular range). + * The sigma values of the spatial Gaussian smoothing in this code do not + match the sigma values in the original code by Tola et al. [2]_. In + their code, spatial smoothing is applied to both the input image and + the center histogram. However, this smoothing is not documented in [1]_ + and, therefore, it is omitted. + + Parameters + ---------- + image : (M, N) array + Input image (grayscale). + step : int, optional + Distance between descriptor sampling points. + radius : int, optional + Radius (in pixels) of the outermost ring. + rings : int, optional + Number of rings. + histograms : int, optional + Number of histograms sampled per ring. + orientations : int, optional + Number of orientations (bins) per histogram. + normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional + How to normalize the descriptors + + * 'l1': L1-normalization of each descriptor. + * 'l2': L2-normalization of each descriptor. + * 'daisy': L2-normalization of individual histograms. + * 'off': Disable normalization. + + sigmas : 1D array of float, optional + Standard deviation of spatial Gaussian smoothing for the center + histogram and for each ring of histograms. The array of sigmas should + be sorted from the center and out. I.e. the first sigma value defines + the spatial smoothing of the center histogram and the last sigma value + defines the spatial smoothing of the outermost ring. Specifying sigmas + overrides the following parameter. + + ``rings = len(sigmas) - 1`` + + ring_radii : 1D array of int, optional + Radius (in pixels) for each ring. Specifying ring_radii overrides the + following two parameters. + + ``rings = len(ring_radii)`` + ``radius = ring_radii[-1]`` + + If both sigmas and ring_radii are given, they must satisfy the + following predicate since no radius is needed for the center + histogram. + + ``len(ring_radii) == len(sigmas) + 1`` + + visualize : bool, optional + Generate a visualization of the DAISY descriptors + + Returns + ------- + descs : array + Grid of DAISY descriptors for the given image as an array + dimensionality (P, Q, R) where + + ``P = ceil((M - radius*2) / step)`` + ``Q = ceil((N - radius*2) / step)`` + ``R = (rings * histograms + 1) * orientations`` + + descs_img : (M, N, 3) array (only if visualize==True) + Visualization of the DAISY descriptors. + + References + ---------- + .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide- + baseline stereo." Pattern Analysis and Machine Intelligence, IEEE + Transactions on 32.5 (2010): 815-830. + .. [2] http://cvlab.epfl.ch/software/daisy + ''' + + check_nD(image, 2, 'img') + + image = img_as_float(image) + float_dtype = image.dtype + + # Validate parameters. + if ( + sigmas is not None + and ring_radii is not None + and len(sigmas) - 1 != len(ring_radii) + ): + raise ValueError('`len(sigmas)-1 != len(ring_radii)`') + if ring_radii is not None: + rings = len(ring_radii) + radius = ring_radii[-1] + if sigmas is not None: + rings = len(sigmas) - 1 + if sigmas is None: + sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)] + if ring_radii is None: + ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)] + if normalization not in ['l1', 'l2', 'daisy', 'off']: + raise ValueError('Invalid normalization method.') + + # Compute image derivatives. + dx = np.zeros(image.shape, dtype=float_dtype) + dy = np.zeros(image.shape, dtype=float_dtype) + dx[:, :-1] = np.diff(image, n=1, axis=1) + dy[:-1, :] = np.diff(image, n=1, axis=0) + + # Compute gradient orientation and magnitude and their contribution + # to the histograms. + grad_mag = sqrt(dx**2 + dy**2) + grad_ori = arctan2(dy, dx) + orientation_kappa = orientations / pi + orientation_angles = [2 * o * pi / orientations - pi for o in range(orientations)] + hist = np.empty((orientations,) + image.shape, dtype=float_dtype) + for i, o in enumerate(orientation_angles): + # Weigh bin contribution by the circular normal distribution + hist[i, :, :] = exp(orientation_kappa * np.cos(grad_ori - o)) + # Weigh bin contribution by the gradient magnitude + hist[i, :, :] = np.multiply(hist[i, :, :], grad_mag) + + # Smooth orientation histograms for the center and all rings. + sigmas = [sigmas[0]] + sigmas + hist_smooth = np.empty((rings + 1,) + hist.shape, dtype=float_dtype) + for i in range(rings + 1): + for j in range(orientations): + hist_smooth[i, j, :, :] = gaussian( + hist[j, :, :], sigma=sigmas[i], mode='reflect' + ) + + # Assemble descriptor grid. + theta = [2 * pi * j / histograms for j in range(histograms)] + desc_dims = (rings * histograms + 1) * orientations + descs = np.empty( + (desc_dims, image.shape[0] - 2 * radius, image.shape[1] - 2 * radius), + dtype=float_dtype, + ) + descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius, radius:-radius] + idx = orientations + for i in range(rings): + for j in range(histograms): + y_min = radius + int(round(ring_radii[i] * math.sin(theta[j]))) + y_max = descs.shape[1] + y_min + x_min = radius + int(round(ring_radii[i] * math.cos(theta[j]))) + x_max = descs.shape[2] + x_min + descs[idx : idx + orientations, :, :] = hist_smooth[ + i + 1, :, y_min:y_max, x_min:x_max + ] + idx += orientations + descs = descs[:, ::step, ::step] + descs = descs.swapaxes(0, 1).swapaxes(1, 2) + + # Normalize descriptors. + if normalization != 'off': + descs += 1e-10 + if normalization == 'l1': + descs /= np.sum(descs, axis=2)[:, :, np.newaxis] + elif normalization == 'l2': + descs /= sqrt(np.sum(descs**2, axis=2))[:, :, np.newaxis] + elif normalization == 'daisy': + for i in range(0, desc_dims, orientations): + norms = sqrt(np.sum(descs[:, :, i : i + orientations] ** 2, axis=2)) + descs[:, :, i : i + orientations] /= norms[:, :, np.newaxis] + + if visualize: + descs_img = gray2rgb(image) + for i in range(descs.shape[0]): + for j in range(descs.shape[1]): + # Draw center histogram sigma + color = [1, 0, 0] + desc_y = i * step + radius + desc_x = j * step + radius + rows, cols, val = draw.circle_perimeter_aa( + desc_y, desc_x, int(sigmas[0]) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + max_bin = np.max(descs[i, j, :]) + for o_num, o in enumerate(orientation_angles): + # Draw center histogram bins + bin_size = descs[i, j, o_num] / max_bin + dy = sigmas[0] * bin_size * math.sin(o) + dx = sigmas[0] * bin_size * math.cos(o) + rows, cols, val = draw.line_aa( + desc_y, desc_x, int(desc_y + dy), int(desc_x + dx) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + for r_num, r in enumerate(ring_radii): + color_offset = float(1 + r_num) / rings + color = (1 - color_offset, 1, color_offset) + for t_num, t in enumerate(theta): + # Draw ring histogram sigmas + hist_y = desc_y + int(round(r * math.sin(t))) + hist_x = desc_x + int(round(r * math.cos(t))) + rows, cols, val = draw.circle_perimeter_aa( + hist_y, hist_x, int(sigmas[r_num + 1]) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + for o_num, o in enumerate(orientation_angles): + # Draw histogram bins + bin_size = descs[ + i, + j, + orientations + + r_num * histograms * orientations + + t_num * orientations + + o_num, + ] + bin_size /= max_bin + dy = sigmas[r_num + 1] * bin_size * math.sin(o) + dx = sigmas[r_num + 1] * bin_size * math.cos(o) + rows, cols, val = draw.line_aa( + hist_y, hist_x, int(hist_y + dy), int(hist_x + dx) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + return descs, descs_img + else: + return descs diff --git a/python_embeded/Lib/site-packages/skimage/feature/_fisher_vector.py b/python_embeded/Lib/site-packages/skimage/feature/_fisher_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..1525dea6154a46916384884df2e2d9d1e6849c54 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_fisher_vector.py @@ -0,0 +1,265 @@ +""" +fisher_vector.py - Implementation of the Fisher vector encoding algorithm + +This module contains the source code for Fisher vector computation. The +computation is separated into two distinct steps, which are called separately +by the user, namely: + +learn_gmm: Used to estimate the GMM for all vectors/descriptors computed for + all examples in the dataset (e.g. estimated using all the SIFT + vectors computed for all images in the dataset, or at least a subset + of this). + +fisher_vector: Used to compute the Fisher vector representation for a + single set of descriptors/vector (e.g. the SIFT + descriptors for a single image in your dataset, or + perhaps a test image). + +Reference: Perronnin, F. and Dance, C. Fisher kernels on Visual Vocabularies + for Image Categorization, IEEE Conference on Computer Vision and + Pattern Recognition, 2007 + +Origin Author: Dan Oneata (Author of the original implementation for the Fisher +vector computation using scikit-learn and NumPy. Subsequently ported to +scikit-image (here) by other authors.) +""" + +import numpy as np + + +class FisherVectorException(Exception): + pass + + +class DescriptorException(FisherVectorException): + pass + + +def learn_gmm(descriptors, *, n_modes=32, gm_args=None): + """Estimate a Gaussian mixture model (GMM) given a set of descriptors and + number of modes (i.e. Gaussians). This function is essentially a wrapper + around the scikit-learn implementation of GMM, namely the + :class:`sklearn.mixture.GaussianMixture` class. + + Due to the nature of the Fisher vector, the only enforced parameter of the + underlying scikit-learn class is the covariance_type, which must be 'diag'. + + There is no simple way to know what value to use for `n_modes` a-priori. + Typically, the value is usually one of ``{16, 32, 64, 128}``. One may train + a few GMMs and choose the one that maximises the log probability of the + GMM, or choose `n_modes` such that the downstream classifier trained on + the resultant Fisher vectors has maximal performance. + + Parameters + ---------- + descriptors : np.ndarray (N, M) or list [(N1, M), (N2, M), ...] + List of NumPy arrays, or a single NumPy array, of the descriptors + used to estimate the GMM. The reason a list of NumPy arrays is + permissible is because often when using a Fisher vector encoding, + descriptors/vectors are computed separately for each sample/image in + the dataset, such as SIFT vectors for each image. If a list if passed + in, then each element must be a NumPy array in which the number of + rows may differ (e.g. different number of SIFT vector for each image), + but the number of columns for each must be the same (i.e. the + dimensionality must be the same). + n_modes : int + The number of modes/Gaussians to estimate during the GMM estimate. + gm_args : dict + Keyword arguments that can be passed into the underlying scikit-learn + :class:`sklearn.mixture.GaussianMixture` class. + + Returns + ------- + gmm : :class:`sklearn.mixture.GaussianMixture` + The estimated GMM object, which contains the necessary parameters + needed to compute the Fisher vector. + + References + ---------- + .. [1] https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('sklearn') + + >>> from skimage.feature import fisher_vector + >>> rng = np.random.Generator(np.random.PCG64()) + >>> sift_for_images = [rng.standard_normal((10, 128)) for _ in range(10)] + >>> num_modes = 16 + >>> # Estimate 16-mode GMM with these synthetic SIFT vectors + >>> gmm = learn_gmm(sift_for_images, n_modes=num_modes) + """ + + try: + from sklearn.mixture import GaussianMixture + except ImportError: + raise ImportError( + 'scikit-learn is not installed. Please ensure it is installed in ' + 'order to use the Fisher vector functionality.' + ) + + if not isinstance(descriptors, (list, np.ndarray)): + raise DescriptorException( + 'Please ensure descriptors are either a NumPy array, ' + 'or a list of NumPy arrays.' + ) + + d_mat_1 = descriptors[0] + if isinstance(descriptors, list) and not isinstance(d_mat_1, np.ndarray): + raise DescriptorException( + 'Please ensure descriptors are a list of NumPy arrays.' + ) + + if isinstance(descriptors, list): + expected_shape = descriptors[0].shape + ranks = [len(e.shape) == len(expected_shape) for e in descriptors] + if not all(ranks): + raise DescriptorException( + 'Please ensure all elements of your descriptor list ' 'are of rank 2.' + ) + dims = [e.shape[1] == descriptors[0].shape[1] for e in descriptors] + if not all(dims): + raise DescriptorException( + 'Please ensure all descriptors are of the same dimensionality.' + ) + + if not isinstance(n_modes, int) or n_modes <= 0: + raise FisherVectorException('Please ensure n_modes is a positive integer.') + + if gm_args: + has_cov_type = 'covariance_type' in gm_args + cov_type_not_diag = gm_args['covariance_type'] != 'diag' + if has_cov_type and cov_type_not_diag: + raise FisherVectorException('Covariance type must be "diag".') + + if isinstance(descriptors, list): + descriptors = np.vstack(descriptors) + + if gm_args: + has_cov_type = 'covariance_type' in gm_args + if has_cov_type: + gmm = GaussianMixture(n_components=n_modes, **gm_args) + else: + gmm = GaussianMixture( + n_components=n_modes, covariance_type='diag', **gm_args + ) + else: + gmm = GaussianMixture(n_components=n_modes, covariance_type='diag') + + gmm.fit(descriptors) + + return gmm + + +def fisher_vector(descriptors, gmm, *, improved=False, alpha=0.5): + """Compute the Fisher vector given some descriptors/vectors, + and an associated estimated GMM. + + Parameters + ---------- + descriptors : np.ndarray, shape=(n_descriptors, descriptor_length) + NumPy array of the descriptors for which the Fisher vector + representation is to be computed. + gmm : :class:`sklearn.mixture.GaussianMixture` + An estimated GMM object, which contains the necessary parameters needed + to compute the Fisher vector. + improved : bool, default=False + Flag denoting whether to compute improved Fisher vectors or not. + Improved Fisher vectors are L2 and power normalized. Power + normalization is simply f(z) = sign(z) pow(abs(z), alpha) for some + 0 <= alpha <= 1. + alpha : float, default=0.5 + The parameter for the power normalization step. Ignored if + improved=False. + + Returns + ------- + fisher_vector : np.ndarray + The computation Fisher vector, which is given by a concatenation of the + gradients of a GMM with respect to its parameters (mixture weights, + means, and covariance matrices). For D-dimensional input descriptors or + vectors, and a K-mode GMM, the Fisher vector dimensionality will be + 2KD + K. Thus, its dimensionality is invariant to the number of + descriptors/vectors. + + References + ---------- + .. [1] Perronnin, F. and Dance, C. Fisher kernels on Visual Vocabularies + for Image Categorization, IEEE Conference on Computer Vision and + Pattern Recognition, 2007 + .. [2] Perronnin, F. and Sanchez, J. and Mensink T. Improving the Fisher + Kernel for Large-Scale Image Classification, ECCV, 2010 + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('sklearn') + + >>> from skimage.feature import fisher_vector, learn_gmm + >>> sift_for_images = [np.random.random((10, 128)) for _ in range(10)] + >>> num_modes = 16 + >>> # Estimate 16-mode GMM with these synthetic SIFT vectors + >>> gmm = learn_gmm(sift_for_images, n_modes=num_modes) + >>> test_image_descriptors = np.random.random((25, 128)) + >>> # Compute the Fisher vector + >>> fv = fisher_vector(test_image_descriptors, gmm) + """ + try: + from sklearn.mixture import GaussianMixture + except ImportError: + raise ImportError( + 'scikit-learn is not installed. Please ensure it is installed in ' + 'order to use the Fisher vector functionality.' + ) + + if not isinstance(descriptors, np.ndarray): + raise DescriptorException('Please ensure descriptors is a NumPy array.') + + if not isinstance(gmm, GaussianMixture): + raise FisherVectorException( + 'Please ensure gmm is a sklearn.mixture.GaussianMixture object.' + ) + + if improved and not isinstance(alpha, float): + raise FisherVectorException( + 'Please ensure that the alpha parameter is a float.' + ) + + num_descriptors = len(descriptors) + + mixture_weights = gmm.weights_ + means = gmm.means_ + covariances = gmm.covariances_ + + posterior_probabilities = gmm.predict_proba(descriptors) + + # Statistics necessary to compute GMM gradients wrt its parameters + pp_sum = posterior_probabilities.mean(axis=0, keepdims=True).T + pp_x = posterior_probabilities.T.dot(descriptors) / num_descriptors + pp_x_2 = posterior_probabilities.T.dot(np.power(descriptors, 2)) / num_descriptors + + # Compute GMM gradients wrt its parameters + d_pi = pp_sum.squeeze() - mixture_weights + + d_mu = pp_x - pp_sum * means + + d_sigma_t1 = pp_sum * np.power(means, 2) + d_sigma_t2 = pp_sum * covariances + d_sigma_t3 = 2 * pp_x * means + d_sigma = -pp_x_2 - d_sigma_t1 + d_sigma_t2 + d_sigma_t3 + + # Apply analytical diagonal normalization + sqrt_mixture_weights = np.sqrt(mixture_weights) + d_pi /= sqrt_mixture_weights + d_mu /= sqrt_mixture_weights[:, np.newaxis] * np.sqrt(covariances) + d_sigma /= np.sqrt(2) * sqrt_mixture_weights[:, np.newaxis] * covariances + + # Concatenate GMM gradients to form Fisher vector representation + fisher_vector = np.hstack((d_pi, d_mu.ravel(), d_sigma.ravel())) + + if improved: + fisher_vector = np.sign(fisher_vector) * np.power(np.abs(fisher_vector), alpha) + fisher_vector = fisher_vector / np.linalg.norm(fisher_vector) + + return fisher_vector diff --git a/python_embeded/Lib/site-packages/skimage/feature/_haar.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_haar.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..cd2ff6f6393272838a5800c6cab1c5546debc635 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_haar.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_hessian_det_appx.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_hessian_det_appx.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..b2c71ed3b52ca53337495ee8df342d8235096220 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_hessian_det_appx.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_hog.py b/python_embeded/Lib/site-packages/skimage/feature/_hog.py new file mode 100644 index 0000000000000000000000000000000000000000..80a456dbf0c44aa2b8d1be76176cf7982f11ff50 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_hog.py @@ -0,0 +1,341 @@ +import numpy as np + +from . import _hoghistogram +from .._shared import utils + + +def _hog_normalize_block(block, method, eps=1e-5): + if method == 'L1': + out = block / (np.sum(np.abs(block)) + eps) + elif method == 'L1-sqrt': + out = np.sqrt(block / (np.sum(np.abs(block)) + eps)) + elif method == 'L2': + out = block / np.sqrt(np.sum(block**2) + eps**2) + elif method == 'L2-Hys': + out = block / np.sqrt(np.sum(block**2) + eps**2) + out = np.minimum(out, 0.2) + out = out / np.sqrt(np.sum(out**2) + eps**2) + else: + raise ValueError('Selected block normalization method is invalid.') + + return out + + +def _hog_channel_gradient(channel): + """Compute unnormalized gradient image along `row` and `col` axes. + + Parameters + ---------- + channel : (M, N) ndarray + Grayscale image or one of image channel. + + Returns + ------- + g_row, g_col : channel gradient along `row` and `col` axes correspondingly. + """ + g_row = np.empty(channel.shape, dtype=channel.dtype) + g_row[0, :] = 0 + g_row[-1, :] = 0 + g_row[1:-1, :] = channel[2:, :] - channel[:-2, :] + g_col = np.empty(channel.shape, dtype=channel.dtype) + g_col[:, 0] = 0 + g_col[:, -1] = 0 + g_col[:, 1:-1] = channel[:, 2:] - channel[:, :-2] + + return g_row, g_col + + +@utils.channel_as_last_axis(multichannel_output=False) +def hog( + image, + orientations=9, + pixels_per_cell=(8, 8), + cells_per_block=(3, 3), + block_norm='L2-Hys', + visualize=False, + transform_sqrt=False, + feature_vector=True, + *, + channel_axis=None, +): + """Extract Histogram of Oriented Gradients (HOG) for a given image. + + Compute a Histogram of Oriented Gradients (HOG) by + + 1. (optional) global image normalization + 2. computing the gradient image in `row` and `col` + 3. computing gradient histograms + 4. normalizing across blocks + 5. flattening into a feature vector + + Parameters + ---------- + image : (M, N[, C]) ndarray + Input image. + orientations : int, optional + Number of orientation bins. + pixels_per_cell : 2-tuple (int, int), optional + Size (in pixels) of a cell. + cells_per_block : 2-tuple (int, int), optional + Number of cells in each block. + block_norm : str {'L1', 'L1-sqrt', 'L2', 'L2-Hys'}, optional + Block normalization method: + + ``L1`` + Normalization using L1-norm. + ``L1-sqrt`` + Normalization using L1-norm, followed by square root. + ``L2`` + Normalization using L2-norm. + ``L2-Hys`` + Normalization using L2-norm, followed by limiting the + maximum values to 0.2 (`Hys` stands for `hysteresis`) and + renormalization using L2-norm. (default) + For details, see [3]_, [4]_. + + visualize : bool, optional + Also return an image of the HOG. For each cell and orientation bin, + the image contains a line segment that is centered at the cell center, + is perpendicular to the midpoint of the range of angles spanned by the + orientation bin, and has intensity proportional to the corresponding + histogram value. + transform_sqrt : bool, optional + Apply power law compression to normalize the image before + processing. DO NOT use this if the image contains negative + values. Also see `notes` section below. + feature_vector : bool, optional + Return the data as a feature vector by calling .ravel() on the result + just before returning. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + `channel_axis` was added in 0.19. + + Returns + ------- + out : (n_blocks_row, n_blocks_col, n_cells_row, n_cells_col, n_orient) ndarray + HOG descriptor for the image. If `feature_vector` is True, a 1D + (flattened) array is returned. + hog_image : (M, N) ndarray, optional + A visualisation of the HOG image. Only provided if `visualize` is True. + + Raises + ------ + ValueError + If the image is too small given the values of pixels_per_cell and + cells_per_block. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients + + .. [2] Dalal, N and Triggs, B, Histograms of Oriented Gradients for + Human Detection, IEEE Computer Society Conference on Computer + Vision and Pattern Recognition 2005 San Diego, CA, USA, + https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf, + :DOI:`10.1109/CVPR.2005.177` + + .. [3] Lowe, D.G., Distinctive image features from scale-invatiant + keypoints, International Journal of Computer Vision (2004) 60: 91, + http://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf, + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + .. [4] Dalal, N, Finding People in Images and Videos, + Human-Computer Interaction [cs.HC], Institut National Polytechnique + de Grenoble - INPG, 2006, + https://tel.archives-ouvertes.fr/tel-00390303/file/NavneetDalalThesis.pdf + + Notes + ----- + The presented code implements the HOG extraction method from [2]_ with + the following changes: (I) blocks of (3, 3) cells are used ((2, 2) in the + paper); (II) no smoothing within cells (Gaussian spatial window with sigma=8pix + in the paper); (III) L1 block normalization is used (L2-Hys in the paper). + + Power law compression, also known as Gamma correction, is used to reduce + the effects of shadowing and illumination variations. The compression makes + the dark regions lighter. When the kwarg `transform_sqrt` is set to + ``True``, the function computes the square root of each color channel + and then applies the hog algorithm to the image. + """ + image = np.atleast_2d(image) + float_dtype = utils._supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + multichannel = channel_axis is not None + ndim_spatial = image.ndim - 1 if multichannel else image.ndim + if ndim_spatial != 2: + raise ValueError( + 'Only images with two spatial dimensions are ' + 'supported. If using with color/multichannel ' + 'images, specify `channel_axis`.' + ) + + """ + The first stage applies an optional global image normalization + equalisation that is designed to reduce the influence of illumination + effects. In practice we use gamma (power law) compression, either + computing the square root or the log of each color channel. + Image texture strength is typically proportional to the local surface + illumination so this compression helps to reduce the effects of local + shadowing and illumination variations. + """ + + if transform_sqrt: + image = np.sqrt(image) + + """ + The second stage computes first order image gradients. These capture + contour, silhouette and some texture information, while providing + further resistance to illumination variations. The locally dominant + color channel is used, which provides color invariance to a large + extent. Variant methods may also include second order image derivatives, + which act as primitive bar detectors - a useful feature for capturing, + e.g. bar like structures in bicycles and limbs in humans. + """ + + if multichannel: + g_row_by_ch = np.empty_like(image, dtype=float_dtype) + g_col_by_ch = np.empty_like(image, dtype=float_dtype) + g_magn = np.empty_like(image, dtype=float_dtype) + + for idx_ch in range(image.shape[2]): + ( + g_row_by_ch[:, :, idx_ch], + g_col_by_ch[:, :, idx_ch], + ) = _hog_channel_gradient(image[:, :, idx_ch]) + g_magn[:, :, idx_ch] = np.hypot( + g_row_by_ch[:, :, idx_ch], g_col_by_ch[:, :, idx_ch] + ) + + # For each pixel select the channel with the highest gradient magnitude + idcs_max = g_magn.argmax(axis=2) + rr, cc = np.meshgrid( + np.arange(image.shape[0]), + np.arange(image.shape[1]), + indexing='ij', + sparse=True, + ) + g_row = g_row_by_ch[rr, cc, idcs_max] + g_col = g_col_by_ch[rr, cc, idcs_max] + else: + g_row, g_col = _hog_channel_gradient(image) + + """ + The third stage aims to produce an encoding that is sensitive to + local image content while remaining resistant to small changes in + pose or appearance. The adopted method pools gradient orientation + information locally in the same way as the SIFT [Lowe 2004] + feature. The image window is divided into small spatial regions, + called "cells". For each cell we accumulate a local 1-D histogram + of gradient or edge orientations over all the pixels in the + cell. This combined cell-level 1-D histogram forms the basic + "orientation histogram" representation. Each orientation histogram + divides the gradient angle range into a fixed number of + predetermined bins. The gradient magnitudes of the pixels in the + cell are used to vote into the orientation histogram. + """ + + s_row, s_col = image.shape[:2] + c_row, c_col = pixels_per_cell + b_row, b_col = cells_per_block + + n_cells_row = int(s_row // c_row) # number of cells along row-axis + n_cells_col = int(s_col // c_col) # number of cells along col-axis + + # compute orientations integral images + orientation_histogram = np.zeros( + (n_cells_row, n_cells_col, orientations), dtype=float + ) + g_row = g_row.astype(float, copy=False) + g_col = g_col.astype(float, copy=False) + + _hoghistogram.hog_histograms( + g_col, + g_row, + c_col, + c_row, + s_col, + s_row, + n_cells_col, + n_cells_row, + orientations, + orientation_histogram, + ) + + # now compute the histogram for each cell + hog_image = None + + if visualize: + from .. import draw + + radius = min(c_row, c_col) // 2 - 1 + orientations_arr = np.arange(orientations) + # set dr_arr, dc_arr to correspond to midpoints of orientation bins + orientation_bin_midpoints = np.pi * (orientations_arr + 0.5) / orientations + dr_arr = radius * np.sin(orientation_bin_midpoints) + dc_arr = radius * np.cos(orientation_bin_midpoints) + hog_image = np.zeros((s_row, s_col), dtype=float_dtype) + for r in range(n_cells_row): + for c in range(n_cells_col): + for o, dr, dc in zip(orientations_arr, dr_arr, dc_arr): + centre = tuple([r * c_row + c_row // 2, c * c_col + c_col // 2]) + rr, cc = draw.line( + int(centre[0] - dc), + int(centre[1] + dr), + int(centre[0] + dc), + int(centre[1] - dr), + ) + hog_image[rr, cc] += orientation_histogram[r, c, o] + + """ + The fourth stage computes normalization, which takes local groups of + cells and contrast normalizes their overall responses before passing + to next stage. Normalization introduces better invariance to illumination, + shadowing, and edge contrast. It is performed by accumulating a measure + of local histogram "energy" over local groups of cells that we call + "blocks". The result is used to normalize each cell in the block. + Typically each individual cell is shared between several blocks, but + its normalizations are block dependent and thus different. The cell + thus appears several times in the final output vector with different + normalizations. This may seem redundant but it improves the performance. + We refer to the normalized block descriptors as Histogram of Oriented + Gradient (HOG) descriptors. + """ + + n_blocks_row = (n_cells_row - b_row) + 1 + n_blocks_col = (n_cells_col - b_col) + 1 + if n_blocks_col <= 0 or n_blocks_row <= 0: + min_row = b_row * c_row + min_col = b_col * c_col + raise ValueError( + 'The input image is too small given the values of ' + 'pixels_per_cell and cells_per_block. ' + 'It should have at least: ' + f'{min_row} rows and {min_col} cols.' + ) + normalized_blocks = np.zeros( + (n_blocks_row, n_blocks_col, b_row, b_col, orientations), dtype=float_dtype + ) + + for r in range(n_blocks_row): + for c in range(n_blocks_col): + block = orientation_histogram[r : r + b_row, c : c + b_col, :] + normalized_blocks[r, c, :] = _hog_normalize_block(block, method=block_norm) + + """ + The final step collects the HOG descriptors from all blocks of a dense + overlapping grid of blocks covering the detection window into a combined + feature vector for use in the window classifier. + """ + + if feature_vector: + normalized_blocks = normalized_blocks.ravel() + + if visualize: + return normalized_blocks, hog_image + else: + return normalized_blocks diff --git a/python_embeded/Lib/site-packages/skimage/feature/_hoghistogram.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_hoghistogram.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..5f9a97c7939ea051a22ba2b6a141df00c0de6d78 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_hoghistogram.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_orb_descriptor_positions.py b/python_embeded/Lib/site-packages/skimage/feature/_orb_descriptor_positions.py new file mode 100644 index 0000000000000000000000000000000000000000..c7042b9d6f1daacb6a6262c9c9fb2ac041aeec1b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/_orb_descriptor_positions.py @@ -0,0 +1,10 @@ +import os +import numpy as np + +# Putting this in cython was giving strange bugs for different versions +# of cython which seemed to indicate troubles with the __file__ variable +# not being defined. Keeping it in pure python makes it more reliable +this_dir = os.path.dirname(__file__) +POS = np.loadtxt(os.path.join(this_dir, "orb_descriptor_positions.txt"), dtype=np.int8) +POS0 = np.ascontiguousarray(POS[:, :2]) +POS1 = np.ascontiguousarray(POS[:, 2:]) diff --git a/python_embeded/Lib/site-packages/skimage/feature/_sift.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_sift.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..97826704e194bacbf01ddf4150366b1eddb33f26 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_sift.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/_texture.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/_texture.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..d9935fddfe730e44236606bdc4fb91563882870e Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/_texture.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/blob.py b/python_embeded/Lib/site-packages/skimage/feature/blob.py new file mode 100644 index 0000000000000000000000000000000000000000..462e513b29dc1f9ba2b0fb1e36aacd03536bab7f --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/blob.py @@ -0,0 +1,715 @@ +import math + +import numpy as np +import scipy.ndimage as ndi +from scipy import spatial + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_nD +from ..transform import integral_image +from ..util import img_as_float +from ._hessian_det_appx import _hessian_matrix_det +from .peak import peak_local_max + +# This basic blob detection algorithm is based on: +# http://www.cs.utah.edu/~jfishbau/advimproc/project1/ (04.04.2013) +# Theory behind: https://en.wikipedia.org/wiki/Blob_detection (04.04.2013) + + +def _compute_disk_overlap(d, r1, r2): + """ + Compute fraction of surface overlap between two disks of radii + ``r1`` and ``r2``, with centers separated by a distance ``d``. + + Parameters + ---------- + d : float + Distance between centers. + r1 : float + Radius of the first disk. + r2 : float + Radius of the second disk. + + Returns + ------- + fraction: float + Fraction of area of the overlap between the two disks. + """ + + ratio1 = (d**2 + r1**2 - r2**2) / (2 * d * r1) + ratio1 = np.clip(ratio1, -1, 1) + acos1 = math.acos(ratio1) + + ratio2 = (d**2 + r2**2 - r1**2) / (2 * d * r2) + ratio2 = np.clip(ratio2, -1, 1) + acos2 = math.acos(ratio2) + + a = -d + r2 + r1 + b = d - r2 + r1 + c = d + r2 - r1 + d = d + r2 + r1 + area = r1**2 * acos1 + r2**2 * acos2 - 0.5 * math.sqrt(abs(a * b * c * d)) + return area / (math.pi * (min(r1, r2) ** 2)) + + +def _compute_sphere_overlap(d, r1, r2): + """ + Compute volume overlap fraction between two spheres of radii + ``r1`` and ``r2``, with centers separated by a distance ``d``. + + Parameters + ---------- + d : float + Distance between centers. + r1 : float + Radius of the first sphere. + r2 : float + Radius of the second sphere. + + Returns + ------- + fraction: float + Fraction of volume of the overlap between the two spheres. + + Notes + ----- + See for example http://mathworld.wolfram.com/Sphere-SphereIntersection.html + for more details. + """ + vol = ( + math.pi + / (12 * d) + * (r1 + r2 - d) ** 2 + * (d**2 + 2 * d * (r1 + r2) - 3 * (r1**2 + r2**2) + 6 * r1 * r2) + ) + return vol / (4.0 / 3 * math.pi * min(r1, r2) ** 3) + + +def _blob_overlap(blob1, blob2, *, sigma_dim=1): + """Finds the overlapping area fraction between two blobs. + + Returns a float representing fraction of overlapped area. Note that 0.0 + is *always* returned for dimension greater than 3. + + Parameters + ---------- + blob1 : sequence of arrays + A sequence of ``(row, col, sigma)`` or ``(pln, row, col, sigma)``, + where ``row, col`` (or ``(pln, row, col)``) are coordinates + of blob and ``sigma`` is the standard deviation of the Gaussian kernel + which detected the blob. + blob2 : sequence of arrays + A sequence of ``(row, col, sigma)`` or ``(pln, row, col, sigma)``, + where ``row, col`` (or ``(pln, row, col)``) are coordinates + of blob and ``sigma`` is the standard deviation of the Gaussian kernel + which detected the blob. + sigma_dim : int, optional + The dimensionality of the sigma value. Can be 1 or the same as the + dimensionality of the blob space (2 or 3). + + Returns + ------- + f : float + Fraction of overlapped area (or volume in 3D). + """ + ndim = len(blob1) - sigma_dim + if ndim > 3: + return 0.0 + root_ndim = math.sqrt(ndim) + + # we divide coordinates by sigma * sqrt(ndim) to rescale space to isotropy, + # giving spheres of radius = 1 or < 1. + if blob1[-1] == blob2[-1] == 0: + return 0.0 + elif blob1[-1] > blob2[-1]: + max_sigma = blob1[-sigma_dim:] + r1 = 1 + r2 = blob2[-1] / blob1[-1] + else: + max_sigma = blob2[-sigma_dim:] + r2 = 1 + r1 = blob1[-1] / blob2[-1] + pos1 = blob1[:ndim] / (max_sigma * root_ndim) + pos2 = blob2[:ndim] / (max_sigma * root_ndim) + + d = np.sqrt(np.sum((pos2 - pos1) ** 2)) + if d > r1 + r2: # centers farther than sum of radii, so no overlap + return 0.0 + + # one blob is inside the other + if d <= abs(r1 - r2): + return 1.0 + + if ndim == 2: + return _compute_disk_overlap(d, r1, r2) + + else: # ndim=3 http://mathworld.wolfram.com/Sphere-SphereIntersection.html + return _compute_sphere_overlap(d, r1, r2) + + +def _prune_blobs(blobs_array, overlap, *, sigma_dim=1): + """Eliminated blobs with area overlap. + + Parameters + ---------- + blobs_array : ndarray + A 2d array with each row representing 3 (or 4) values, + ``(row, col, sigma)`` or ``(pln, row, col, sigma)`` in 3D, + where ``(row, col)`` (``(pln, row, col)``) are coordinates of the blob + and ``sigma`` is the standard deviation of the Gaussian kernel which + detected the blob. + This array must not have a dimension of size 0. + overlap : float + A value between 0 and 1. If the fraction of area overlapping for 2 + blobs is greater than `overlap` the smaller blob is eliminated. + sigma_dim : int, optional + The number of columns in ``blobs_array`` corresponding to sigmas rather + than positions. + + Returns + ------- + A : ndarray + `array` with overlapping blobs removed. + """ + sigma = blobs_array[:, -sigma_dim:].max() + distance = 2 * sigma * math.sqrt(blobs_array.shape[1] - sigma_dim) + tree = spatial.cKDTree(blobs_array[:, :-sigma_dim]) + pairs = np.array(list(tree.query_pairs(distance))) + if len(pairs) == 0: + return blobs_array + else: + for i, j in pairs: + blob1, blob2 = blobs_array[i], blobs_array[j] + if _blob_overlap(blob1, blob2, sigma_dim=sigma_dim) > overlap: + # note: this test works even in the anisotropic case because + # all sigmas increase together. + if blob1[-1] > blob2[-1]: + blob2[-1] = 0 + else: + blob1[-1] = 0 + + return np.stack([b for b in blobs_array if b[-1] > 0]) + + +def _format_exclude_border(img_ndim, exclude_border): + """Format an ``exclude_border`` argument as a tuple of ints for calling + ``peak_local_max``. + """ + if isinstance(exclude_border, tuple): + if len(exclude_border) != img_ndim: + raise ValueError( + "`exclude_border` should have the same length as the " + "dimensionality of the image." + ) + for exclude in exclude_border: + if not isinstance(exclude, int): + raise ValueError( + "exclude border, when expressed as a tuple, must only " + "contain ints." + ) + return exclude_border + (0,) + elif isinstance(exclude_border, int): + return (exclude_border,) * img_ndim + (0,) + elif exclude_border is True: + raise ValueError("exclude_border cannot be True") + elif exclude_border is False: + return (0,) * (img_ndim + 1) + else: + raise ValueError(f'Unsupported value ({exclude_border}) for exclude_border') + + +def blob_dog( + image, + min_sigma=1, + max_sigma=50, + sigma_ratio=1.6, + threshold=0.5, + overlap=0.5, + *, + threshold_rel=None, + exclude_border=False, +): + r"""Finds blobs in the given grayscale image. + + Blobs are found using the Difference of Gaussian (DoG) method [1]_, [2]_. + For each blob found, the method returns its coordinates and the standard + deviation of the Gaussian kernel that detected the blob. + + Parameters + ---------- + image : ndarray + Input grayscale image, blobs are assumed to be light on dark + background (white on black). + min_sigma : scalar or sequence of scalars, optional + The minimum standard deviation for Gaussian kernel. Keep this low to + detect smaller blobs. 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. + max_sigma : scalar or sequence of scalars, optional + The maximum standard deviation for Gaussian kernel. Keep this high to + detect larger blobs. 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. + sigma_ratio : float, optional + The ratio between the standard deviation of Gaussian Kernels used for + computing the Difference of Gaussians + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(dog_space) * threshold_rel``, where ``dog_space`` refers to the + stack of Difference-of-Gaussian (DoG) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + exclude_border : tuple of ints, int, or False, optional + If tuple of ints, the length of the tuple must match the input array's + dimensionality. Each element of the tuple will exclude peaks from + within `exclude_border`-pixels of the border of the image along that + dimension. + If nonzero int, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If zero or False, peaks are identified regardless of their + distance from the border. + + Returns + ------- + A : (n, image.ndim + sigma) ndarray + A 2d array with each row representing 2 coordinate values for a 2D + image, or 3 coordinate values for a 3D image, plus the sigma(s) used. + When a single sigma is passed, outputs are: + ``(r, c, sigma)`` or ``(p, r, c, sigma)`` where ``(r, c)`` or + ``(p, r, c)`` are coordinates of the blob and ``sigma`` is the standard + deviation of the Gaussian kernel which detected the blob. When an + anisotropic gaussian is used (sigmas per dimension), the detected sigma + is returned for each dimension. + + See also + -------- + skimage.filters.difference_of_gaussians + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach + .. [2] Lowe, D. G. "Distinctive Image Features from Scale-Invariant + Keypoints." International Journal of Computer Vision 60, 91–110 (2004). + https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + Examples + -------- + >>> from skimage import data, feature + >>> coins = data.coins() + >>> feature.blob_dog(coins, threshold=.05, min_sigma=10, max_sigma=40) + array([[128., 155., 10.], + [198., 155., 10.], + [124., 338., 10.], + [127., 102., 10.], + [193., 281., 10.], + [126., 208., 10.], + [267., 115., 10.], + [197., 102., 10.], + [198., 215., 10.], + [123., 279., 10.], + [126., 46., 10.], + [259., 247., 10.], + [196., 43., 10.], + [ 54., 276., 10.], + [267., 358., 10.], + [ 58., 100., 10.], + [259., 305., 10.], + [185., 347., 16.], + [261., 174., 16.], + [ 46., 336., 16.], + [ 54., 217., 10.], + [ 55., 157., 10.], + [ 57., 41., 10.], + [260., 47., 16.]]) + + Notes + ----- + The radius of each blob is approximately :math:`\sqrt{2}\sigma` for + a 2-D image and :math:`\sqrt{3}\sigma` for a 3-D image. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + # if both min and max sigma are scalar, function returns only one sigma + scalar_sigma = np.isscalar(max_sigma) and np.isscalar(min_sigma) + + # Gaussian filter requires that sequence-type sigmas have same + # dimensionality as image. This broadcasts scalar kernels + if np.isscalar(max_sigma): + max_sigma = np.full(image.ndim, max_sigma, dtype=float_dtype) + if np.isscalar(min_sigma): + min_sigma = np.full(image.ndim, min_sigma, dtype=float_dtype) + + # Convert sequence types to array + min_sigma = np.asarray(min_sigma, dtype=float_dtype) + max_sigma = np.asarray(max_sigma, dtype=float_dtype) + + if sigma_ratio <= 1.0: + raise ValueError('sigma_ratio must be > 1.0') + + # k such that min_sigma*(sigma_ratio**k) > max_sigma + k = int(np.mean(np.log(max_sigma / min_sigma) / np.log(sigma_ratio) + 1)) + + # a geometric progression of standard deviations for gaussian kernels + sigma_list = np.array([min_sigma * (sigma_ratio**i) for i in range(k + 1)]) + + # computing difference between two successive Gaussian blurred images + # to obtain an approximation of the scale invariant Laplacian of the + # Gaussian operator + dog_image_cube = np.empty(image.shape + (k,), dtype=float_dtype) + gaussian_previous = gaussian(image, sigma=sigma_list[0], mode='reflect') + for i, s in enumerate(sigma_list[1:]): + gaussian_current = gaussian(image, sigma=s, mode='reflect') + dog_image_cube[..., i] = gaussian_previous - gaussian_current + gaussian_previous = gaussian_current + + # normalization factor for consistency in DoG magnitude + sf = 1 / (sigma_ratio - 1) + dog_image_cube *= sf + + exclude_border = _format_exclude_border(image.ndim, exclude_border) + local_maxima = peak_local_max( + dog_image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + footprint=np.ones((3,) * (image.ndim + 1)), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, image.ndim + (1 if scalar_sigma else image.ndim))) + + # Convert local_maxima to float64 + lm = local_maxima.astype(float_dtype) + + # translate final column of lm, which contains the index of the + # sigma that produced the maximum intensity value, into the sigma + sigmas_of_peaks = sigma_list[local_maxima[:, -1]] + + if scalar_sigma: + # select one sigma column, keeping dimension + sigmas_of_peaks = sigmas_of_peaks[:, 0:1] + + # Remove sigma index and replace with sigmas + lm = np.hstack([lm[:, :-1], sigmas_of_peaks]) + + sigma_dim = sigmas_of_peaks.shape[1] + + return _prune_blobs(lm, overlap, sigma_dim=sigma_dim) + + +def blob_log( + image, + min_sigma=1, + max_sigma=50, + num_sigma=10, + threshold=0.2, + overlap=0.5, + log_scale=False, + *, + threshold_rel=None, + exclude_border=False, +): + r"""Finds blobs in the given grayscale image. + + Blobs are found using the Laplacian of Gaussian (LoG) method [1]_. + For each blob found, the method returns its coordinates and the standard + deviation of the Gaussian kernel that detected the blob. + + Parameters + ---------- + image : ndarray + Input grayscale image, blobs are assumed to be light on dark + background (white on black). + min_sigma : scalar or sequence of scalars, optional + the minimum standard deviation for Gaussian kernel. Keep this low to + detect smaller blobs. 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. + max_sigma : scalar or sequence of scalars, optional + The maximum standard deviation for Gaussian kernel. Keep this high to + detect larger blobs. 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. + num_sigma : int, optional + The number of intermediate values of standard deviations to consider + between `min_sigma` and `max_sigma`. + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + log_scale : bool, optional + If set intermediate values of standard deviations are interpolated + using a logarithmic scale to the base `10`. If not, linear + interpolation is used. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(log_space) * threshold_rel``, where ``log_space`` refers to the + stack of Laplacian-of-Gaussian (LoG) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + exclude_border : tuple of ints, int, or False, optional + If tuple of ints, the length of the tuple must match the input array's + dimensionality. Each element of the tuple will exclude peaks from + within `exclude_border`-pixels of the border of the image along that + dimension. + If nonzero int, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If zero or False, peaks are identified regardless of their + distance from the border. + + Returns + ------- + A : (n, image.ndim + sigma) ndarray + A 2d array with each row representing 2 coordinate values for a 2D + image, or 3 coordinate values for a 3D image, plus the sigma(s) used. + When a single sigma is passed, outputs are: + ``(r, c, sigma)`` or ``(p, r, c, sigma)`` where ``(r, c)`` or + ``(p, r, c)`` are coordinates of the blob and ``sigma`` is the standard + deviation of the Gaussian kernel which detected the blob. When an + anisotropic gaussian is used (sigmas per dimension), the detected sigma + is returned for each dimension. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian + + Examples + -------- + >>> from skimage import data, feature, exposure + >>> img = data.coins() + >>> img = exposure.equalize_hist(img) # improves detection + >>> feature.blob_log(img, threshold = .3) + array([[124. , 336. , 11.88888889], + [198. , 155. , 11.88888889], + [194. , 213. , 17.33333333], + [121. , 272. , 17.33333333], + [263. , 244. , 17.33333333], + [194. , 276. , 17.33333333], + [266. , 115. , 11.88888889], + [128. , 154. , 11.88888889], + [260. , 174. , 17.33333333], + [198. , 103. , 11.88888889], + [126. , 208. , 11.88888889], + [127. , 102. , 11.88888889], + [263. , 302. , 17.33333333], + [197. , 44. , 11.88888889], + [185. , 344. , 17.33333333], + [126. , 46. , 11.88888889], + [113. , 323. , 1. ]]) + + Notes + ----- + The radius of each blob is approximately :math:`\sqrt{2}\sigma` for + a 2-D image and :math:`\sqrt{3}\sigma` for a 3-D image. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + # if both min and max sigma are scalar, function returns only one sigma + scalar_sigma = True if np.isscalar(max_sigma) and np.isscalar(min_sigma) else False + + # Gaussian filter requires that sequence-type sigmas have same + # dimensionality as image. This broadcasts scalar kernels + if np.isscalar(max_sigma): + max_sigma = np.full(image.ndim, max_sigma, dtype=float_dtype) + if np.isscalar(min_sigma): + min_sigma = np.full(image.ndim, min_sigma, dtype=float_dtype) + + # Convert sequence types to array + min_sigma = np.asarray(min_sigma, dtype=float_dtype) + max_sigma = np.asarray(max_sigma, dtype=float_dtype) + + if log_scale: + start = np.log10(min_sigma) + stop = np.log10(max_sigma) + sigma_list = np.logspace(start, stop, num_sigma) + else: + sigma_list = np.linspace(min_sigma, max_sigma, num_sigma) + + # computing gaussian laplace + image_cube = np.empty(image.shape + (len(sigma_list),), dtype=float_dtype) + for i, s in enumerate(sigma_list): + # average s**2 provides scale invariance + image_cube[..., i] = -ndi.gaussian_laplace(image, s) * np.mean(s) ** 2 + + exclude_border = _format_exclude_border(image.ndim, exclude_border) + local_maxima = peak_local_max( + image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + footprint=np.ones((3,) * (image.ndim + 1)), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, image.ndim + (1 if scalar_sigma else image.ndim))) + + # Convert local_maxima to float64 + lm = local_maxima.astype(float_dtype) + + # translate final column of lm, which contains the index of the + # sigma that produced the maximum intensity value, into the sigma + sigmas_of_peaks = sigma_list[local_maxima[:, -1]] + + if scalar_sigma: + # select one sigma column, keeping dimension + sigmas_of_peaks = sigmas_of_peaks[:, 0:1] + + # Remove sigma index and replace with sigmas + lm = np.hstack([lm[:, :-1], sigmas_of_peaks]) + + sigma_dim = sigmas_of_peaks.shape[1] + + return _prune_blobs(lm, overlap, sigma_dim=sigma_dim) + + +def blob_doh( + image, + min_sigma=1, + max_sigma=30, + num_sigma=10, + threshold=0.01, + overlap=0.5, + log_scale=False, + *, + threshold_rel=None, +): + """Finds blobs in the given grayscale image. + + Blobs are found using the Determinant of Hessian method [1]_. For each blob + found, the method returns its coordinates and the standard deviation + of the Gaussian Kernel used for the Hessian matrix whose determinant + detected the blob. Determinant of Hessians is approximated using [2]_. + + Parameters + ---------- + image : 2D ndarray + Input grayscale image.Blobs can either be light on dark or vice versa. + min_sigma : float, optional + The minimum standard deviation for Gaussian Kernel used to compute + Hessian matrix. Keep this low to detect smaller blobs. + max_sigma : float, optional + The maximum standard deviation for Gaussian Kernel used to compute + Hessian matrix. Keep this high to detect larger blobs. + num_sigma : int, optional + The number of intermediate values of standard deviations to consider + between `min_sigma` and `max_sigma`. + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + log_scale : bool, optional + If set intermediate values of standard deviations are interpolated + using a logarithmic scale to the base `10`. If not, linear + interpolation is used. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(doh_space) * threshold_rel``, where ``doh_space`` refers to the + stack of Determinant-of-Hessian (DoH) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + + Returns + ------- + A : (n, 3) ndarray + A 2d array with each row representing 3 values, ``(y,x,sigma)`` + where ``(y,x)`` are coordinates of the blob and ``sigma`` is the + standard deviation of the Gaussian kernel of the Hessian Matrix whose + determinant detected the blob. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_determinant_of_the_Hessian + .. [2] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, + "SURF: Speeded Up Robust Features" + ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf + + Examples + -------- + >>> from skimage import data, feature + >>> img = data.coins() + >>> feature.blob_doh(img) + array([[197. , 153. , 20.33333333], + [124. , 336. , 20.33333333], + [126. , 153. , 20.33333333], + [195. , 100. , 23.55555556], + [192. , 212. , 23.55555556], + [121. , 271. , 30. ], + [126. , 101. , 20.33333333], + [193. , 275. , 23.55555556], + [123. , 205. , 20.33333333], + [270. , 363. , 30. ], + [265. , 113. , 23.55555556], + [262. , 243. , 23.55555556], + [185. , 348. , 30. ], + [156. , 302. , 30. ], + [123. , 44. , 23.55555556], + [260. , 173. , 30. ], + [197. , 44. , 20.33333333]]) + + Notes + ----- + The radius of each blob is approximately `sigma`. + Computation of Determinant of Hessians is independent of the standard + deviation. Therefore detecting larger blobs won't take more time. In + methods line :py:meth:`blob_dog` and :py:meth:`blob_log` the computation + of Gaussians for larger `sigma` takes more time. The downside is that + this method can't be used for detecting blobs of radius less than `3px` + due to the box filters used in the approximation of Hessian Determinant. + """ + check_nD(image, 2) + + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + image = integral_image(image) + + if log_scale: + start, stop = math.log(min_sigma, 10), math.log(max_sigma, 10) + sigma_list = np.logspace(start, stop, num_sigma) + else: + sigma_list = np.linspace(min_sigma, max_sigma, num_sigma) + + image_cube = np.empty(shape=image.shape + (len(sigma_list),), dtype=float_dtype) + for j, s in enumerate(sigma_list): + image_cube[..., j] = _hessian_matrix_det(image, s) + + local_maxima = peak_local_max( + image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=False, + footprint=np.ones((3,) * image_cube.ndim), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, 3)) + # Convert local_maxima to float64 + lm = local_maxima.astype(np.float64) + # Convert the last index to its corresponding scale value + lm[:, -1] = sigma_list[local_maxima[:, -1]] + return _prune_blobs(lm, overlap) diff --git a/python_embeded/Lib/site-packages/skimage/feature/brief.py b/python_embeded/Lib/site-packages/skimage/feature/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..995204d7c69c79cd26c90a7dabb706e4226f645d --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/brief.py @@ -0,0 +1,216 @@ +import copy + +import numpy as np +from packaging.version import Version + +from .._shared.filters import gaussian +from .._shared.utils import check_nD +from .brief_cy import _brief_loop +from .util import ( + DescriptorExtractor, + _mask_border_keypoints, + _prepare_grayscale_input_2D, +) + + +np2 = Version(np.__version__) >= Version('2') + + +class BRIEF(DescriptorExtractor): + """BRIEF binary descriptor extractor. + + BRIEF (Binary Robust Independent Elementary Features) is an efficient + feature point descriptor. It is highly discriminative even when using + relatively few bits and is computed using simple intensity difference + tests. + + For each keypoint, intensity comparisons are carried out for a specifically + distributed number N of pixel-pairs resulting in a binary descriptor of + length N. For binary descriptors the Hamming distance can be used for + feature matching, which leads to lower computational cost in comparison to + the L2 norm. + + Parameters + ---------- + descriptor_size : int, optional + Size of BRIEF descriptor for each keypoint. Sizes 128, 256 and 512 + recommended by the authors. Default is 256. + patch_size : int, optional + Length of the two dimensional square patch sampling region around + the keypoints. Default is 49. + mode : {'normal', 'uniform'}, optional + Probability distribution for sampling location of decision pixel-pairs + around keypoints. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator (RNG). + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG is used for the random sampling of the decision + pixel-pairs. From a square window with length `patch_size`, + pixel pairs are sampled using the `mode` parameter to build + the descriptors using intensity comparison. + + For matching across images, the same `rng` should be used to construct + descriptors. To facilitate this: + + (a) `rng` defaults to 1 + (b) Subsequent calls of the ``extract`` method will use the same rng/seed. + sigma : float, optional + Standard deviation of the Gaussian low-pass filter applied to the image + to alleviate noise sensitivity, which is strongly recommended to obtain + discriminative and good descriptors. + + Attributes + ---------- + descriptors : (Q, `descriptor_size`) array of dtype bool + 2D ndarray of binary descriptors of size `descriptor_size` for Q + keypoints after filtering out border keypoints with value at an + index ``(i, j)`` either being ``True`` or ``False`` representing + the outcome of the intensity comparison for i-th keypoint on j-th + decision pixel-pair. It is ``Q == np.sum(mask)``. + mask : (N,) array of dtype bool + Mask indicating whether a keypoint has been filtered out + (``False``) or is described in the `descriptors` array (``True``). + + Examples + -------- + >>> from skimage.feature import (corner_harris, corner_peaks, BRIEF, + ... match_descriptors) + >>> import numpy as np + >>> square1 = np.zeros((8, 8), dtype=np.int32) + >>> square1[2:6, 2:6] = 1 + >>> square1 + array([[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, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) + >>> square2 = np.zeros((9, 9), dtype=np.int32) + >>> square2[2:7, 2:7] = 1 + >>> square2 + array([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) + >>> keypoints1 = corner_peaks(corner_harris(square1), min_distance=1) + >>> keypoints2 = corner_peaks(corner_harris(square2), min_distance=1) + >>> extractor = BRIEF(patch_size=5) + >>> extractor.extract(square1, keypoints1) + >>> descriptors1 = extractor.descriptors + >>> extractor.extract(square2, keypoints2) + >>> descriptors2 = extractor.descriptors + >>> matches = match_descriptors(descriptors1, descriptors2) + >>> matches + array([[0, 0], + [1, 1], + [2, 2], + [3, 3]]) + >>> keypoints1[matches[:, 0]] + array([[2, 2], + [2, 5], + [5, 2], + [5, 5]]) + >>> keypoints2[matches[:, 1]] + array([[2, 2], + [2, 6], + [6, 2], + [6, 6]]) + + """ + + def __init__( + self, descriptor_size=256, patch_size=49, mode='normal', sigma=1, rng=1 + ): + mode = mode.lower() + if mode not in ('normal', 'uniform'): + raise ValueError("`mode` must be 'normal' or 'uniform'.") + + self.descriptor_size = descriptor_size + self.patch_size = patch_size + self.mode = mode + self.sigma = sigma + + if isinstance(rng, np.random.Generator): + # Spawn an independent RNG from parent RNG provided by the user. + # This is necessary so that we can safely deepcopy the RNG. + # See https://github.com/scikit-learn/scikit-learn/issues/16988#issuecomment-1518037853 + bg = rng._bit_generator + ss = bg._seed_seq + (child_ss,) = ss.spawn(1) + self.rng = np.random.Generator(type(bg)(child_ss)) + elif rng is None: + self.rng = np.random.default_rng(np.random.SeedSequence()) + else: + self.rng = np.random.default_rng(rng) + + self.descriptors = None + self.mask = None + + def extract(self, image, keypoints): + """Extract BRIEF binary descriptors for given keypoints in image. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + + """ + check_nD(image, 2) + + # Copy RNG so we can repeatedly call extract with the same random values + rng = copy.deepcopy(self.rng) + + image = _prepare_grayscale_input_2D(image) + + # Gaussian low-pass filtering to alleviate noise sensitivity + image = np.ascontiguousarray(gaussian(image, sigma=self.sigma, mode='reflect')) + + # Sampling pairs of decision pixels in patch_size x patch_size window + desc_size = self.descriptor_size + patch_size = self.patch_size + if self.mode == 'normal': + samples = (patch_size / 5.0) * rng.standard_normal(desc_size * 8) + samples = np.array(samples, dtype=np.int32) + samples = samples[ + (samples < (patch_size // 2)) & (samples > -(patch_size - 2) // 2) + ] + + pos1 = samples[: desc_size * 2].reshape(desc_size, 2) + pos2 = samples[desc_size * 2 : desc_size * 4].reshape(desc_size, 2) + elif self.mode == 'uniform': + samples = rng.integers( + -(patch_size - 2) // 2, (patch_size // 2) + 1, (desc_size * 2, 2) + ) + samples = np.array(samples, dtype=np.int32) + pos1, pos2 = np.split(samples, 2) + + pos1 = np.ascontiguousarray(pos1) + pos2 = np.ascontiguousarray(pos2) + + # Removing keypoints that are within (patch_size / 2) distance from the + # image border + self.mask = _mask_border_keypoints(image.shape, keypoints, patch_size // 2) + + keypoints = np.array( + keypoints[self.mask, :], + dtype=np.int64, + order='C', + copy=None if np2 else False, + ) + + self.descriptors = np.zeros( + (keypoints.shape[0], desc_size), dtype=bool, order='C' + ) + + _brief_loop(image, self.descriptors.view(np.uint8), keypoints, pos1, pos2) diff --git a/python_embeded/Lib/site-packages/skimage/feature/brief_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/brief_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..963df5c60471d9e3d7411f9159e0d5d115b5519f Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/brief_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/censure.py b/python_embeded/Lib/site-packages/skimage/feature/censure.py new file mode 100644 index 0000000000000000000000000000000000000000..70d19d3daa09ae2d8fdd8098fdca3c9662ca67d4 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/censure.py @@ -0,0 +1,343 @@ +import numpy as np +from scipy.ndimage import maximum_filter, minimum_filter, convolve + +from ..transform import integral_image +from .corner import structure_tensor +from ..morphology import octagon, star +from .censure_cy import _censure_dob_loop +from ..feature.util import ( + FeatureDetector, + _prepare_grayscale_input_2D, + _mask_border_keypoints, +) +from .._shared.utils import check_nD + +# The paper(Reference [1]) mentions the sizes of the Octagon shaped filter +# kernel for the first seven scales only. The sizes of the later scales +# have been extrapolated based on the following statement in the paper. +# "These octagons scale linearly and were experimentally chosen to correspond +# to the seven DOBs described in the previous section." +OCTAGON_OUTER_SHAPE = [ + (5, 2), + (5, 3), + (7, 3), + (9, 4), + (9, 7), + (13, 7), + (15, 10), + (15, 11), + (15, 12), + (17, 13), + (17, 14), +] +OCTAGON_INNER_SHAPE = [ + (3, 0), + (3, 1), + (3, 2), + (5, 2), + (5, 3), + (5, 4), + (5, 5), + (7, 5), + (7, 6), + (9, 6), + (9, 7), +] + +# The sizes for the STAR shaped filter kernel for different scales have been +# taken from the OpenCV implementation. +STAR_SHAPE = [1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 23, 32, 45, 46, 64, 90, 128] +STAR_FILTER_SHAPE = [ + (1, 0), + (3, 1), + (4, 2), + (5, 3), + (7, 4), + (8, 5), + (9, 6), + (11, 8), + (13, 10), + (14, 11), + (15, 12), + (16, 14), +] + + +def _filter_image(image, min_scale, max_scale, mode): + response = np.zeros( + (image.shape[0], image.shape[1], max_scale - min_scale + 1), dtype=np.float64 + ) + + if mode == 'dob': + # make response[:, :, i] contiguous memory block + item_size = response.itemsize + response.strides = ( + item_size * response.shape[1], + item_size, + item_size * response.shape[0] * response.shape[1], + ) + + integral_img = integral_image(image) + + for i in range(max_scale - min_scale + 1): + n = min_scale + i + + # Constant multipliers for the outer region and the inner region + # of the bi-level filters with the constraint of keeping the + # DC bias 0. + inner_weight = 1.0 / (2 * n + 1) ** 2 + outer_weight = 1.0 / (12 * n**2 + 4 * n) + + _censure_dob_loop( + n, integral_img, response[:, :, i], inner_weight, outer_weight + ) + + # NOTE : For the Octagon shaped filter, we implemented and evaluated the + # slanted integral image based image filtering but the performance was + # more or less equal to image filtering using + # scipy.ndimage.filters.convolve(). Hence we have decided to use the + # later for a much cleaner implementation. + elif mode == 'octagon': + # TODO : Decide the shapes of Octagon filters for scales > 7 + + for i in range(max_scale - min_scale + 1): + mo, no = OCTAGON_OUTER_SHAPE[min_scale + i - 1] + mi, ni = OCTAGON_INNER_SHAPE[min_scale + i - 1] + response[:, :, i] = convolve(image, _octagon_kernel(mo, no, mi, ni)) + + elif mode == 'star': + for i in range(max_scale - min_scale + 1): + m = STAR_SHAPE[STAR_FILTER_SHAPE[min_scale + i - 1][0]] + n = STAR_SHAPE[STAR_FILTER_SHAPE[min_scale + i - 1][1]] + response[:, :, i] = convolve(image, _star_kernel(m, n)) + + return response + + +def _octagon_kernel(mo, no, mi, ni): + outer = (mo + 2 * no) ** 2 - 2 * no * (no + 1) + inner = (mi + 2 * ni) ** 2 - 2 * ni * (ni + 1) + outer_weight = 1.0 / (outer - inner) + inner_weight = 1.0 / inner + c = ((mo + 2 * no) - (mi + 2 * ni)) // 2 + outer_oct = octagon(mo, no) + inner_oct = np.zeros((mo + 2 * no, mo + 2 * no)) + inner_oct[c:-c, c:-c] = octagon(mi, ni) + bfilter = outer_weight * outer_oct - (outer_weight + inner_weight) * inner_oct + return bfilter + + +def _star_kernel(m, n): + c = m + m // 2 - n - n // 2 + outer_star = star(m) + inner_star = np.zeros_like(outer_star) + inner_star[c:-c, c:-c] = star(n) + outer_weight = 1.0 / (np.sum(outer_star - inner_star)) + inner_weight = 1.0 / np.sum(inner_star) + bfilter = outer_weight * outer_star - (outer_weight + inner_weight) * inner_star + return bfilter + + +def _suppress_lines(feature_mask, image, sigma, line_threshold): + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + feature_mask[(Arr + Acc) ** 2 > line_threshold * (Arr * Acc - Arc**2)] = False + + +class CENSURE(FeatureDetector): + """CENSURE keypoint detector. + + min_scale : int, optional + Minimum scale to extract keypoints from. + max_scale : int, optional + Maximum scale to extract keypoints from. The keypoints will be + extracted from all the scales except the first and the last i.e. + from the scales in the range [min_scale + 1, max_scale - 1]. The filter + sizes for different scales is such that the two adjacent scales + comprise of an octave. + mode : {'DoB', 'Octagon', 'STAR'}, optional + Type of bi-level filter used to get the scales of the input image. + Possible values are 'DoB', 'Octagon' and 'STAR'. The three modes + represent the shape of the bi-level filters i.e. box(square), octagon + and star respectively. For instance, a bi-level octagon filter consists + of a smaller inner octagon and a larger outer octagon with the filter + weights being uniformly negative in both the inner octagon while + uniformly positive in the difference region. Use STAR and Octagon for + better features and DoB for better performance. + non_max_threshold : float, optional + Threshold value used to suppress maximas and minimas with a weak + magnitude response obtained after Non-Maximal Suppression. + line_threshold : float, optional + Threshold for rejecting interest points which have ratio of principal + curvatures greater than this value. + + Attributes + ---------- + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + + References + ---------- + .. [1] Motilal Agrawal, Kurt Konolige and Morten Rufus Blas + "CENSURE: Center Surround Extremas for Realtime Feature + Detection and Matching", + https://link.springer.com/chapter/10.1007/978-3-540-88693-8_8 + :DOI:`10.1007/978-3-540-88693-8_8` + + .. [2] Adam Schmidt, Marek Kraft, Michal Fularz and Zuzanna Domagala + "Comparative Assessment of Point Feature Detectors and + Descriptors in the Context of Robot Navigation" + http://yadda.icm.edu.pl/yadda/element/bwmeta1.element.baztech-268aaf28-0faf-4872-a4df-7e2e61cb364c/c/Schmidt_comparative.pdf + :DOI:`10.1.1.465.1117` + + Examples + -------- + >>> from skimage.data import astronaut + >>> from skimage.color import rgb2gray + >>> from skimage.feature import CENSURE + >>> img = rgb2gray(astronaut()[100:300, 100:300]) + >>> censure = CENSURE() + >>> censure.detect(img) + >>> censure.keypoints + array([[ 4, 148], + [ 12, 73], + [ 21, 176], + [ 91, 22], + [ 93, 56], + [ 94, 22], + [ 95, 54], + [100, 51], + [103, 51], + [106, 67], + [108, 15], + [117, 20], + [122, 60], + [125, 37], + [129, 37], + [133, 76], + [145, 44], + [146, 94], + [150, 114], + [153, 33], + [154, 156], + [155, 151], + [184, 63]]) + >>> censure.scales + array([2, 6, 6, 2, 4, 3, 2, 3, 2, 6, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 4, 2, + 2]) + + """ + + def __init__( + self, + min_scale=1, + max_scale=7, + mode='DoB', + non_max_threshold=0.15, + line_threshold=10, + ): + mode = mode.lower() + if mode not in ('dob', 'octagon', 'star'): + raise ValueError("`mode` must be one of 'DoB', 'Octagon', 'STAR'.") + + if min_scale < 1 or max_scale < 1 or max_scale - min_scale < 2: + raise ValueError( + 'The scales must be >= 1 and the number of ' 'scales should be >= 3.' + ) + + self.min_scale = min_scale + self.max_scale = max_scale + self.mode = mode + self.non_max_threshold = non_max_threshold + self.line_threshold = line_threshold + + self.keypoints = None + self.scales = None + + def detect(self, image): + """Detect CENSURE keypoints along with the corresponding scale. + + Parameters + ---------- + image : 2D ndarray + Input image. + + """ + + # (1) First we generate the required scales on the input grayscale + # image using a bi-level filter and stack them up in `filter_response`. + + # (2) We then perform Non-Maximal suppression in 3 x 3 x 3 window on + # the filter_response to suppress points that are neither minima or + # maxima in 3 x 3 x 3 neighborhood. We obtain a boolean ndarray + # `feature_mask` containing all the minimas and maximas in + # `filter_response` as True. + # (3) Then we suppress all the points in the `feature_mask` for which + # the corresponding point in the image at a particular scale has the + # ratio of principal curvatures greater than `line_threshold`. + # (4) Finally, we remove the border keypoints and return the keypoints + # along with its corresponding scale. + + check_nD(image, 2) + + num_scales = self.max_scale - self.min_scale + + image = np.ascontiguousarray(_prepare_grayscale_input_2D(image)) + + # Generating all the scales + filter_response = _filter_image( + image, self.min_scale, self.max_scale, self.mode + ) + + # Suppressing points that are neither minima or maxima in their + # 3 x 3 x 3 neighborhood to zero + minimas = minimum_filter(filter_response, (3, 3, 3)) == filter_response + maximas = maximum_filter(filter_response, (3, 3, 3)) == filter_response + + feature_mask = minimas | maximas + feature_mask[filter_response < self.non_max_threshold] = False + + for i in range(1, num_scales): + # sigma = (window_size - 1) / 6.0, so the window covers > 99% of + # the kernel's distribution + # window_size = 7 + 2 * (min_scale - 1 + i) + # Hence sigma = 1 + (min_scale - 1 + i)/ 3.0 + _suppress_lines( + feature_mask[:, :, i], + image, + (1 + (self.min_scale + i - 1) / 3.0), + self.line_threshold, + ) + + rows, cols, scales = np.nonzero(feature_mask[..., 1:num_scales]) + keypoints = np.column_stack([rows, cols]) + scales = scales + self.min_scale + 1 + + if self.mode == 'dob': + self.keypoints = keypoints + self.scales = scales + return + + cumulative_mask = np.zeros(keypoints.shape[0], dtype=bool) + + if self.mode == 'octagon': + for i in range(self.min_scale + 1, self.max_scale): + c = (OCTAGON_OUTER_SHAPE[i - 1][0] - 1) // 2 + OCTAGON_OUTER_SHAPE[ + i - 1 + ][1] + cumulative_mask |= _mask_border_keypoints(image.shape, keypoints, c) & ( + scales == i + ) + elif self.mode == 'star': + for i in range(self.min_scale + 1, self.max_scale): + c = ( + STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] + + STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] // 2 + ) + cumulative_mask |= _mask_border_keypoints(image.shape, keypoints, c) & ( + scales == i + ) + + self.keypoints = keypoints[cumulative_mask] + self.scales = scales[cumulative_mask] diff --git a/python_embeded/Lib/site-packages/skimage/feature/censure_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/censure_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..5740318341eb7e4422ff41237b7580637b7d9bea Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/censure_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/corner.py b/python_embeded/Lib/site-packages/skimage/feature/corner.py new file mode 100644 index 0000000000000000000000000000000000000000..03076e0e9b2a241a39f6c67acd1c0e0f4c6de70a --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/corner.py @@ -0,0 +1,1355 @@ +import functools +import math +from itertools import combinations_with_replacement + +import numpy as np +from scipy import ndimage as ndi +from scipy import spatial, stats + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, safe_as_int, warn +from ..transform import integral_image +from ..util import img_as_float +from ._hessian_det_appx import _hessian_matrix_det +from .corner_cy import _corner_fast, _corner_moravec, _corner_orientations +from .peak import peak_local_max +from .util import _prepare_grayscale_input_2D, _prepare_grayscale_input_nD + + +def _compute_derivatives(image, mode='constant', cval=0): + """Compute derivatives in axis directions using the Sobel operator. + + Parameters + ---------- + image : ndarray + Input image. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + derivatives : list of ndarray + Derivatives in each axis direction. + + """ + + derivatives = [ + ndi.sobel(image, axis=i, mode=mode, cval=cval) for i in range(image.ndim) + ] + + return derivatives + + +def structure_tensor(image, sigma=1, mode='constant', cval=0, order='rc'): + """Compute structure tensor using sum of squared differences. + + The (2-dimensional) structure tensor A is defined as:: + + A = [Arr Arc] + [Arc Acc] + + which is approximated by the weighted sum of squared differences in a local + window around each pixel in the image. This formula can be extended to a + larger number of dimensions (see [1]_). + + Parameters + ---------- + image : ndarray + Input image. + sigma : float or array-like of float, optional + Standard deviation used for the Gaussian kernel, which is used as a + weighting function for the local summation of squared differences. + If sigma is an iterable, its length must be equal to `image.ndim` and + each element is used for the Gaussian kernel applied along its + respective axis. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + NOTE: 'xy' is only an option for 2D images, higher dimensions must + always use 'rc' order. This parameter allows for the use of reverse or + forward order of the image axes in gradient computation. 'rc' indicates + the use of the first axis initially (Arr, Arc, Acc), whilst 'xy' + indicates the usage of the last axis initially (Axx, Axy, Ayy). + + Returns + ------- + A_elems : list of ndarray + Upper-diagonal elements of the structure tensor for each pixel in the + input image. + + Examples + -------- + >>> from skimage.feature import structure_tensor + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 1 + >>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc') + >>> Acc + array([[0., 0., 0., 0., 0.], + [0., 1., 0., 1., 0.], + [0., 4., 0., 4., 0.], + [0., 1., 0., 1., 0.], + [0., 0., 0., 0., 0.]]) + + See also + -------- + structure_tensor_eigenvalues + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Structure_tensor + """ + if order == 'xy' and image.ndim > 2: + raise ValueError('Only "rc" order is supported for dim > 2.') + + if order not in ['rc', 'xy']: + raise ValueError(f'order {order} is invalid. Must be either "rc" or "xy"') + + if not np.isscalar(sigma): + sigma = tuple(sigma) + if len(sigma) != image.ndim: + raise ValueError('sigma must have as many elements as image ' 'has axes') + + image = _prepare_grayscale_input_nD(image) + + derivatives = _compute_derivatives(image, mode=mode, cval=cval) + + if order == 'xy': + derivatives = reversed(derivatives) + + # structure tensor + A_elems = [ + gaussian(der0 * der1, sigma=sigma, mode=mode, cval=cval) + for der0, der1 in combinations_with_replacement(derivatives, 2) + ] + + return A_elems + + +def _hessian_matrix_with_gaussian(image, sigma=1, mode='reflect', cval=0, order='rc'): + """Compute the Hessian via convolutions with Gaussian derivatives. + + In 2D, the Hessian matrix is defined as: + H = [Hrr Hrc] + [Hrc Hcc] + + which is computed by convolving the image with the second derivatives + of the Gaussian kernel in the respective r- and c-directions. + + The implementation here also supports n-dimensional data. + + Parameters + ---------- + image : ndarray + Input image. + sigma : float or sequence of float, optional + Standard deviation used for the Gaussian kernel, which sets the + amount of smoothing in terms of pixel-distances. It is + advised to not choose a sigma much less than 1.0, otherwise + aliasing artifacts may occur. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + This parameter allows for the use of reverse or forward order of + the image axes in gradient computation. 'rc' indicates the use of + the first axis initially (Hrr, Hrc, Hcc), whilst 'xy' indicates the + usage of the last axis initially (Hxx, Hxy, Hyy) + + Returns + ------- + H_elems : list of ndarray + Upper-diagonal elements of the hessian matrix for each pixel in the + input image. In 2D, this will be a three element list containing [Hrr, + Hrc, Hcc]. In nD, the list will contain ``(n**2 + n) / 2`` arrays. + + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim > 2 and order == "xy": + raise ValueError("order='xy' is only supported for 2D images.") + if order not in ["rc", "xy"]: + raise ValueError(f"unrecognized order: {order}") + + if np.isscalar(sigma): + sigma = (sigma,) * image.ndim + + # This function uses `scipy.ndimage.gaussian_filter` with the order + # argument to compute convolutions. For example, specifying + # ``order=[1, 0]`` would apply convolution with a first-order derivative of + # the Gaussian along the first axis and simple Gaussian smoothing along the + # second. + + # For small sigma, the SciPy Gaussian filter suffers from aliasing and edge + # artifacts, given that the filter will approximate a sinc or sinc + # derivative which only goes to 0 very slowly (order 1/n**2). Thus, we use + # a much larger truncate value to reduce any edge artifacts. + truncate = 8 if all(s > 1 for s in sigma) else 100 + sq1_2 = 1 / math.sqrt(2) + sigma_scaled = tuple(sq1_2 * s for s in sigma) + common_kwargs = dict(sigma=sigma_scaled, mode=mode, cval=cval, truncate=truncate) + gaussian_ = functools.partial(ndi.gaussian_filter, **common_kwargs) + + # Apply two successive first order Gaussian derivative operations, as + # detailed in: + # https://dsp.stackexchange.com/questions/78280/are-scipy-second-order-gaussian-derivatives-correct + + # 1.) First order along one axis while smoothing (order=0) along the other + ndim = image.ndim + + # orders in 2D = ([1, 0], [0, 1]) + # in 3D = ([1, 0, 0], [0, 1, 0], [0, 0, 1]) + # etc. + orders = tuple([0] * d + [1] + [0] * (ndim - d - 1) for d in range(ndim)) + gradients = [gaussian_(image, order=orders[d]) for d in range(ndim)] + + # 2.) apply the derivative along another axis as well + axes = range(ndim) + if order == 'xy': + axes = reversed(axes) + H_elems = [ + gaussian_(gradients[ax0], order=orders[ax1]) + for ax0, ax1 in combinations_with_replacement(axes, 2) + ] + return H_elems + + +def hessian_matrix( + image, sigma=1, mode='constant', cval=0, order='rc', use_gaussian_derivatives=None +): + r"""Compute the Hessian matrix. + + In 2D, the Hessian matrix is defined as:: + + H = [Hrr Hrc] + [Hrc Hcc] + + which is computed by convolving the image with the second derivatives + of the Gaussian kernel in the respective r- and c-directions. + + The implementation here also supports n-dimensional data. + + Parameters + ---------- + image : ndarray + Input image. + sigma : float + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + For 2D images, this parameter allows for the use of reverse or forward + order of the image axes in gradient computation. 'rc' indicates the use + of the first axis initially (Hrr, Hrc, Hcc), whilst 'xy' indicates the + usage of the last axis initially (Hxx, Hxy, Hyy). Images with higher + dimension must always use 'rc' order. + use_gaussian_derivatives : boolean, optional + Indicates whether the Hessian is computed by convolving with Gaussian + derivatives, or by a simple finite-difference operation. + + Returns + ------- + H_elems : list of ndarray + Upper-diagonal elements of the hessian matrix for each pixel in the + input image. In 2D, this will be a three element list containing [Hrr, + Hrc, Hcc]. In nD, the list will contain ``(n**2 + n) / 2`` arrays. + + + Notes + ----- + The distributive property of derivatives and convolutions allows us to + restate the derivative of an image, I, smoothed with a Gaussian kernel, G, + as the convolution of the image with the derivative of G. + + .. math:: + + \frac{\partial }{\partial x_i}(I * G) = + I * \left( \frac{\partial }{\partial x_i} G \right) + + When ``use_gaussian_derivatives`` is ``True``, this property is used to + compute the second order derivatives that make up the Hessian matrix. + + When ``use_gaussian_derivatives`` is ``False``, simple finite differences + on a Gaussian-smoothed image are used instead. + + Examples + -------- + >>> from skimage.feature import hessian_matrix + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> Hrr, Hrc, Hcc = hessian_matrix(square, sigma=0.1, order='rc', + ... use_gaussian_derivatives=False) + >>> Hrc + array([[ 0., 0., 0., 0., 0.], + [ 0., 1., 0., -1., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., -1., 0., 1., 0.], + [ 0., 0., 0., 0., 0.]]) + + """ + + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim > 2 and order == "xy": + raise ValueError("order='xy' is only supported for 2D images.") + if order not in ["rc", "xy"]: + raise ValueError(f"unrecognized order: {order}") + + if use_gaussian_derivatives is None: + use_gaussian_derivatives = False + warn( + "use_gaussian_derivatives currently defaults to False, but will " + "change to True in a future version. Please specify this " + "argument explicitly to maintain the current behavior", + category=FutureWarning, + stacklevel=2, + ) + + if use_gaussian_derivatives: + return _hessian_matrix_with_gaussian( + image, sigma=sigma, mode=mode, cval=cval, order=order + ) + + gaussian_filtered = gaussian(image, sigma=sigma, mode=mode, cval=cval) + + gradients = np.gradient(gaussian_filtered) + axes = range(image.ndim) + + if order == 'xy': + axes = reversed(axes) + + H_elems = [ + np.gradient(gradients[ax0], axis=ax1) + for ax0, ax1 in combinations_with_replacement(axes, 2) + ] + return H_elems + + +def hessian_matrix_det(image, sigma=1, approximate=True): + """Compute the approximate Hessian Determinant over an image. + + The 2D approximate method uses box filters over integral images to + compute the approximate Hessian Determinant. + + Parameters + ---------- + image : ndarray + The image over which to compute the Hessian Determinant. + sigma : float, optional + Standard deviation of the Gaussian kernel used for the Hessian + matrix. + approximate : bool, optional + If ``True`` and the image is 2D, use a much faster approximate + computation. This argument has no effect on 3D and higher images. + + Returns + ------- + out : array + The array of the Determinant of Hessians. + + References + ---------- + .. [1] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, + "SURF: Speeded Up Robust Features" + ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf + + Notes + ----- + For 2D images when ``approximate=True``, the running time of this method + only depends on size of the image. It is independent of `sigma` as one + would expect. The downside is that the result for `sigma` less than `3` + is not accurate, i.e., not similar to the result obtained if someone + computed the Hessian and took its determinant. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim == 2 and approximate: + integral = integral_image(image) + return np.array(_hessian_matrix_det(integral, sigma)) + else: # slower brute-force implementation for nD images + hessian_mat_array = _symmetric_image( + hessian_matrix(image, sigma, use_gaussian_derivatives=False) + ) + return np.linalg.det(hessian_mat_array) + + +def _symmetric_compute_eigenvalues(S_elems): + """Compute eigenvalues from the upper-diagonal entries of a symmetric + matrix. + + Parameters + ---------- + S_elems : list of ndarray + The upper-diagonal elements of the matrix, as returned by + `hessian_matrix` or `structure_tensor`. + + Returns + ------- + eigs : ndarray + The eigenvalues of the matrix, in decreasing order. The eigenvalues are + the leading dimension. That is, ``eigs[i, j, k]`` contains the + ith-largest eigenvalue at position (j, k). + """ + + if len(S_elems) == 3: # Fast explicit formulas for 2D. + M00, M01, M11 = S_elems + eigs = np.empty((2, *M00.shape), M00.dtype) + eigs[:] = (M00 + M11) / 2 + hsqrtdet = np.sqrt(M01**2 + ((M00 - M11) / 2) ** 2) + eigs[0] += hsqrtdet + eigs[1] -= hsqrtdet + return eigs + else: + matrices = _symmetric_image(S_elems) + # eigvalsh returns eigenvalues in increasing order. We want decreasing + eigs = np.linalg.eigvalsh(matrices)[..., ::-1] + leading_axes = tuple(range(eigs.ndim - 1)) + return np.transpose(eigs, (eigs.ndim - 1,) + leading_axes) + + +def _symmetric_image(S_elems): + """Convert the upper-diagonal elements of a matrix to the full + symmetric matrix. + + Parameters + ---------- + S_elems : list of array + The upper-diagonal elements of the matrix, as returned by + `hessian_matrix` or `structure_tensor`. + + Returns + ------- + image : array + An array of shape ``(M, N[, ...], image.ndim, image.ndim)``, + containing the matrix corresponding to each coordinate. + """ + image = S_elems[0] + symmetric_image = np.zeros( + image.shape + (image.ndim, image.ndim), dtype=S_elems[0].dtype + ) + for idx, (row, col) in enumerate( + combinations_with_replacement(range(image.ndim), 2) + ): + symmetric_image[..., row, col] = S_elems[idx] + symmetric_image[..., col, row] = S_elems[idx] + return symmetric_image + + +def structure_tensor_eigenvalues(A_elems): + """Compute eigenvalues of structure tensor. + + Parameters + ---------- + A_elems : list of ndarray + The upper-diagonal elements of the structure tensor, as returned + by `structure_tensor`. + + Returns + ------- + ndarray + The eigenvalues of the structure tensor, in decreasing order. The + eigenvalues are the leading dimension. That is, the coordinate + [i, j, k] corresponds to the ith-largest eigenvalue at position (j, k). + + Examples + -------- + >>> from skimage.feature import structure_tensor + >>> from skimage.feature import structure_tensor_eigenvalues + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 1 + >>> A_elems = structure_tensor(square, sigma=0.1, order='rc') + >>> structure_tensor_eigenvalues(A_elems)[0] + array([[0., 0., 0., 0., 0.], + [0., 2., 4., 2., 0.], + [0., 4., 0., 4., 0.], + [0., 2., 4., 2., 0.], + [0., 0., 0., 0., 0.]]) + + See also + -------- + structure_tensor + """ + return _symmetric_compute_eigenvalues(A_elems) + + +def hessian_matrix_eigvals(H_elems): + """Compute eigenvalues of Hessian matrix. + + Parameters + ---------- + H_elems : list of ndarray + The upper-diagonal elements of the Hessian matrix, as returned + by `hessian_matrix`. + + Returns + ------- + eigs : ndarray + The eigenvalues of the Hessian matrix, in decreasing order. The + eigenvalues are the leading dimension. That is, ``eigs[i, j, k]`` + contains the ith-largest eigenvalue at position (j, k). + + Examples + -------- + >>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> H_elems = hessian_matrix(square, sigma=0.1, order='rc', + ... use_gaussian_derivatives=False) + >>> hessian_matrix_eigvals(H_elems)[0] + array([[ 0., 0., 2., 0., 0.], + [ 0., 1., 0., 1., 0.], + [ 2., 0., -2., 0., 2.], + [ 0., 1., 0., 1., 0.], + [ 0., 0., 2., 0., 0.]]) + """ + return _symmetric_compute_eigenvalues(H_elems) + + +def shape_index(image, sigma=1, mode='constant', cval=0): + """Compute the shape index. + + The shape index, as defined by Koenderink & van Doorn [1]_, is a + single valued measure of local curvature, assuming the image as a 3D plane + with intensities representing heights. + + It is derived from the eigenvalues of the Hessian, and its + value ranges from -1 to 1 (and is undefined (=NaN) in *flat* regions), + with following ranges representing following shapes: + + .. table:: Ranges of the shape index and corresponding shapes. + + =================== ============= + Interval (s in ...) Shape + =================== ============= + [ -1, -7/8) Spherical cup + [-7/8, -5/8) Through + [-5/8, -3/8) Rut + [-3/8, -1/8) Saddle rut + [-1/8, +1/8) Saddle + [+1/8, +3/8) Saddle ridge + [+3/8, +5/8) Ridge + [+5/8, +7/8) Dome + [+7/8, +1] Spherical cap + =================== ============= + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used for + smoothing the input data before Hessian eigen value calculation. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + s : ndarray + Shape index + + References + ---------- + .. [1] Koenderink, J. J. & van Doorn, A. J., + "Surface shape and curvature scales", + Image and Vision Computing, 1992, 10, 557-564. + :DOI:`10.1016/0262-8856(92)90076-F` + + Examples + -------- + >>> from skimage.feature import shape_index + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> s = shape_index(square, sigma=0.1) + >>> s + array([[ nan, nan, -0.5, nan, nan], + [ nan, -0. , nan, -0. , nan], + [-0.5, nan, -1. , nan, -0.5], + [ nan, -0. , nan, -0. , nan], + [ nan, nan, -0.5, nan, nan]]) + """ + + H = hessian_matrix( + image, + sigma=sigma, + mode=mode, + cval=cval, + order='rc', + use_gaussian_derivatives=False, + ) + l1, l2 = hessian_matrix_eigvals(H) + + # don't warn on divide by 0 as occurs in the docstring example + with np.errstate(divide='ignore', invalid='ignore'): + return (2.0 / np.pi) * np.arctan((l2 + l1) / (l2 - l1)) + + +def corner_kitchen_rosenfeld(image, mode='constant', cval=0): + """Compute Kitchen and Rosenfeld corner measure response image. + + The corner measure is calculated as follows:: + + (imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy) + / (imx**2 + imy**2) + + Where imx and imy are the first and imxx, imxy, imyy the second + derivatives. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + response : ndarray + Kitchen and Rosenfeld response image. + + References + ---------- + .. [1] Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection. + Pattern recognition letters, 1(2), 95-102. + :DOI:`10.1016/0167-8655(82)90020-4` + """ + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + imy, imx = _compute_derivatives(image, mode=mode, cval=cval) + imxy, imxx = _compute_derivatives(imx, mode=mode, cval=cval) + imyy, imyx = _compute_derivatives(imy, mode=mode, cval=cval) + + numerator = imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy + denominator = imx**2 + imy**2 + + response = np.zeros_like(image, dtype=float_dtype) + + mask = denominator != 0 + response[mask] = numerator[mask] / denominator[mask] + + return response + + +def corner_harris(image, method='k', k=0.05, eps=1e-6, sigma=1): + """Compute Harris corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as:: + + det(A) - k * trace(A)**2 + + or:: + + 2 * det(A) / (trace(A) + eps) + + Parameters + ---------- + image : (M, N) ndarray + Input image. + method : {'k', 'eps'}, optional + Method to compute the response image from the auto-correlation matrix. + k : float, optional + Sensitivity factor to separate corners from edges, typically in range + `[0, 0.2]`. Small values of k result in detection of sharp corners. + eps : float, optional + Normalisation factor (Noble's corner measure). + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + response : ndarray + Harris response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_harris, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.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, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> corner_peaks(corner_harris(square), min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # determinant + detA = Arr * Acc - Arc**2 + # trace + traceA = Arr + Acc + + if method == 'k': + response = detA - k * traceA**2 + else: + response = 2 * detA / (traceA + eps) + + return response + + +def corner_shi_tomasi(image, sigma=1): + """Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as the smaller eigenvalue of A:: + + ((Axx + Ayy) - sqrt((Axx - Ayy)**2 + 4 * Axy**2)) / 2 + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + response : ndarray + Shi-Tomasi response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_shi_tomasi, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.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, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> corner_peaks(corner_shi_tomasi(square), min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # minimum eigenvalue of A + response = ((Arr + Acc) - np.sqrt((Arr - Acc) ** 2 + 4 * Arc**2)) / 2 + + return response + + +def corner_foerstner(image, sigma=1): + """Compute Foerstner corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as:: + + w = det(A) / trace(A) (size of error ellipse) + q = 4 * det(A) / trace(A)**2 (roundness of error ellipse) + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + w : ndarray + Error ellipse sizes. + q : ndarray + Roundness of error ellipse. + + References + ---------- + .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for + detection and precise location of distinct points, corners and + centres of circular features. In Proc. ISPRS intercommission + conference on fast processing of photogrammetric data (pp. 281-305). + https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf + .. [2] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_foerstner, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.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, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> w, q = corner_foerstner(square) + >>> accuracy_thresh = 0.5 + >>> roundness_thresh = 0.3 + >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w + >>> corner_peaks(foerstner, min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # determinant + detA = Arr * Acc - Arc**2 + # trace + traceA = Arr + Acc + + w = np.zeros_like(image, dtype=detA.dtype) + q = np.zeros_like(w) + + mask = traceA != 0 + + w[mask] = detA[mask] / traceA[mask] + q[mask] = 4 * detA[mask] / traceA[mask] ** 2 + + return w, q + + +def corner_fast(image, n=12, threshold=0.15): + """Extract FAST corners for a given image. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + n : int, optional + Minimum number of consecutive pixels out of 16 pixels on the circle + that should all be either brighter or darker w.r.t testpixel. + A point c on the circle is darker w.r.t test pixel p if + `Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also + stands for the n in `FAST-n` corner detector. + threshold : float, optional + Threshold used in deciding whether the pixels on the circle are + brighter, darker or similar w.r.t. the test pixel. Decrease the + threshold when more corners are desired and vice-versa. + + Returns + ------- + response : ndarray + FAST corner response image. + + References + ---------- + .. [1] Rosten, E., & Drummond, T. (2006, May). Machine learning for + high-speed corner detection. In European conference on computer + vision (pp. 430-443). Springer, Berlin, Heidelberg. + :DOI:`10.1007/11744023_34` + http://www.edwardrosten.com/work/rosten_2006_machine.pdf + .. [2] Wikipedia, "Features from accelerated segment test", + https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test + + Examples + -------- + >>> from skimage.feature import corner_fast, corner_peaks + >>> square = np.zeros((12, 12)) + >>> square[3:9, 3:9] = 1 + >>> square.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], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 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, 0, 0, 0]]) + >>> corner_peaks(corner_fast(square, 9), min_distance=1) + array([[3, 3], + [3, 8], + [8, 3], + [8, 8]]) + + """ + image = _prepare_grayscale_input_2D(image) + + image = np.ascontiguousarray(image) + response = _corner_fast(image, n, threshold) + return response + + +def corner_subpix(image, corners, window_size=11, alpha=0.99): + """Determine subpixel position of corners. + + A statistical test decides whether the corner is defined as the + intersection of two edges or a single peak. Depending on the classification + result, the subpixel corner location is determined based on the local + covariance of the grey-values. If the significance level for either + statistical test is not sufficient, the corner cannot be classified, and + the output subpixel position is set to NaN. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + corners : (K, 2) ndarray + Corner coordinates `(row, col)`. + window_size : int, optional + Search window size for subpixel estimation. + alpha : float, optional + Significance level for corner classification. + + Returns + ------- + positions : (K, 2) ndarray + Subpixel corner positions. NaN for "not classified" corners. + + References + ---------- + .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for + detection and precise location of distinct points, corners and + centres of circular features. In Proc. ISPRS intercommission + conference on fast processing of photogrammetric data (pp. 281-305). + https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf + .. [2] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_harris, corner_peaks, corner_subpix + >>> img = np.zeros((10, 10)) + >>> img[:5, :5] = 1 + >>> img[5:, 5:] = 1 + >>> img.astype(int) + array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]) + >>> coords = corner_peaks(corner_harris(img), min_distance=2) + >>> coords_subpix = corner_subpix(img, coords, window_size=7) + >>> coords_subpix + array([[4.5, 4.5]]) + + """ + + # window extent in one direction + wext = (window_size - 1) // 2 + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + image = np.pad(image, pad_width=wext, mode='constant', constant_values=0) + + # add pad width, make sure to not modify the input values in-place + corners = safe_as_int(corners + wext) + + # normal equation arrays + N_dot = np.zeros((2, 2), dtype=float_dtype) + N_edge = np.zeros((2, 2), dtype=float_dtype) + b_dot = np.zeros((2,), dtype=float_dtype) + b_edge = np.zeros((2,), dtype=float_dtype) + + # critical statistical test values + redundancy = window_size**2 - 2 + t_crit_dot = stats.f.isf(1 - alpha, redundancy, redundancy) + t_crit_edge = stats.f.isf(alpha, redundancy, redundancy) + + # coordinates of pixels within window + y, x = np.mgrid[-wext : wext + 1, -wext : wext + 1] + + corners_subpix = np.zeros_like(corners, dtype=float_dtype) + + for i, (y0, x0) in enumerate(corners): + # crop window around corner + border for sobel operator + miny = y0 - wext - 1 + maxy = y0 + wext + 2 + minx = x0 - wext - 1 + maxx = x0 + wext + 2 + window = image[miny:maxy, minx:maxx] + + winy, winx = _compute_derivatives(window, mode='constant', cval=0) + + # compute gradient squares and remove border + winx_winx = (winx * winx)[1:-1, 1:-1] + winx_winy = (winx * winy)[1:-1, 1:-1] + winy_winy = (winy * winy)[1:-1, 1:-1] + + # sum of squared differences (mean instead of gaussian filter) + Axx = np.sum(winx_winx) + Axy = np.sum(winx_winy) + Ayy = np.sum(winy_winy) + + # sum of squared differences weighted with coordinates + # (mean instead of gaussian filter) + bxx_x = np.sum(winx_winx * x) + bxx_y = np.sum(winx_winx * y) + bxy_x = np.sum(winx_winy * x) + bxy_y = np.sum(winx_winy * y) + byy_x = np.sum(winy_winy * x) + byy_y = np.sum(winy_winy * y) + + # normal equations for subpixel position + N_dot[0, 0] = Axx + N_dot[0, 1] = N_dot[1, 0] = -Axy + N_dot[1, 1] = Ayy + + N_edge[0, 0] = Ayy + N_edge[0, 1] = N_edge[1, 0] = Axy + N_edge[1, 1] = Axx + + b_dot[:] = bxx_y - bxy_x, byy_x - bxy_y + b_edge[:] = byy_y + bxy_x, bxx_x + bxy_y + + # estimated positions + try: + est_dot = np.linalg.solve(N_dot, b_dot) + est_edge = np.linalg.solve(N_edge, b_edge) + except np.linalg.LinAlgError: + # if image is constant the system is singular + corners_subpix[i, :] = np.nan, np.nan + continue + + # residuals + ry_dot = y - est_dot[0] + rx_dot = x - est_dot[1] + ry_edge = y - est_edge[0] + rx_edge = x - est_edge[1] + # squared residuals + rxx_dot = rx_dot * rx_dot + rxy_dot = rx_dot * ry_dot + ryy_dot = ry_dot * ry_dot + rxx_edge = rx_edge * rx_edge + rxy_edge = rx_edge * ry_edge + ryy_edge = ry_edge * ry_edge + + # determine corner class (dot or edge) + # variance for different models + var_dot = np.sum( + winx_winx * ryy_dot - 2 * winx_winy * rxy_dot + winy_winy * rxx_dot + ) + var_edge = np.sum( + winy_winy * ryy_edge + 2 * winx_winy * rxy_edge + winx_winx * rxx_edge + ) + + # test value (F-distributed) + if var_dot < np.spacing(1) and var_edge < np.spacing(1): + t = np.nan + elif var_dot == 0: + t = np.inf + else: + t = var_edge / var_dot + + # 1 for edge, -1 for dot, 0 for "not classified" + corner_class = int(t < t_crit_edge) - int(t > t_crit_dot) + + if corner_class == -1: + corners_subpix[i, :] = y0 + est_dot[0], x0 + est_dot[1] + elif corner_class == 0: + corners_subpix[i, :] = np.nan, np.nan + elif corner_class == 1: + corners_subpix[i, :] = y0 + est_edge[0], x0 + est_edge[1] + + # subtract pad width + corners_subpix -= wext + + return corners_subpix + + +def corner_peaks( + image, + min_distance=1, + threshold_abs=None, + threshold_rel=None, + exclude_border=True, + indices=True, + num_peaks=np.inf, + footprint=None, + labels=None, + *, + num_peaks_per_label=np.inf, + p_norm=np.inf, +): + """Find peaks in corner measure response image. + + This differs from `skimage.feature.peak_local_max` in that it suppresses + multiple connected peaks with the same accumulator value. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + min_distance : int, optional + The minimal allowed distance separating peaks. + * : * + See :py:meth:`skimage.feature.peak_local_max`. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + + Returns + ------- + output : ndarray or ndarray of bools + + * If `indices = True` : (row, column, ...) coordinates of peaks. + * If `indices = False` : Boolean array shaped like `image`, with peaks + represented by True values. + + See also + -------- + skimage.feature.peak_local_max + + Notes + ----- + .. versionchanged:: 0.18 + The default value of `threshold_rel` has changed to None, which + corresponds to letting `skimage.feature.peak_local_max` decide on the + default. This is equivalent to `threshold_rel=0`. + + The `num_peaks` limit is applied before suppression of connected peaks. + To limit the number of peaks after suppression, set `num_peaks=np.inf` and + post-process the output of this function. + + Examples + -------- + >>> from skimage.feature import peak_local_max + >>> response = np.zeros((5, 5)) + >>> response[2:4, 2:4] = 1 + >>> response + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 1., 1., 0.], + [0., 0., 1., 1., 0.], + [0., 0., 0., 0., 0.]]) + >>> peak_local_max(response) + array([[2, 2], + [2, 3], + [3, 2], + [3, 3]]) + >>> corner_peaks(response) + array([[2, 2]]) + + """ + if np.isinf(num_peaks): + num_peaks = None + + # Get the coordinates of the detected peaks + coords = peak_local_max( + image, + min_distance=min_distance, + threshold_abs=threshold_abs, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + num_peaks=np.inf, + footprint=footprint, + labels=labels, + num_peaks_per_label=num_peaks_per_label, + ) + + if len(coords): + # Use KDtree to find the peaks that are too close to each other + tree = spatial.cKDTree(coords) + + rejected_peaks_indices = set() + for idx, point in enumerate(coords): + if idx not in rejected_peaks_indices: + candidates = tree.query_ball_point(point, r=min_distance, p=p_norm) + candidates.remove(idx) + rejected_peaks_indices.update(candidates) + + # Remove the peaks that are too close to each other + coords = np.delete(coords, tuple(rejected_peaks_indices), axis=0)[:num_peaks] + + if indices: + return coords + + peaks = np.zeros_like(image, dtype=bool) + peaks[tuple(coords.T)] = True + + return peaks + + +def corner_moravec(image, window_size=1): + """Compute Moravec corner measure response image. + + This is one of the simplest corner detectors and is comparatively fast but + has several limitations (e.g. not rotation invariant). + + Parameters + ---------- + image : (M, N) ndarray + Input image. + window_size : int, optional + Window size. + + Returns + ------- + response : ndarray + Moravec response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_moravec + >>> square = np.zeros([7, 7]) + >>> square[3, 3] = 1 + >>> square.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, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> corner_moravec(square).astype(int) + 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, 2, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + return _corner_moravec(np.ascontiguousarray(image), window_size) + + +def corner_orientations(image, corners, mask): + """Compute the orientation of corners. + + The orientation of corners is computed using the first order central moment + i.e. the center of mass approach. The corner orientation is the angle of + the vector from the corner coordinate to the intensity centroid in the + local neighborhood around the corner calculated using first order central + moment. + + Parameters + ---------- + image : (M, N) array + Input grayscale image. + corners : (K, 2) array + Corner coordinates as ``(row, col)``. + mask : 2D array + Mask defining the local neighborhood of the corner used for the + calculation of the central moment. + + Returns + ------- + orientations : (K, 1) array + Orientations of corners in the range [-pi, pi]. + + References + ---------- + .. [1] Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski + "ORB : An efficient alternative to SIFT and SURF" + http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf + .. [2] Paul L. Rosin, "Measuring Corner Properties" + http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf + + Examples + -------- + >>> from skimage.morphology import octagon + >>> from skimage.feature import (corner_fast, corner_peaks, + ... corner_orientations) + >>> square = np.zeros((12, 12)) + >>> square[3:9, 3:9] = 1 + >>> square.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], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 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, 0, 0, 0]]) + >>> corners = corner_peaks(corner_fast(square, 9), min_distance=1) + >>> corners + array([[3, 3], + [3, 8], + [8, 3], + [8, 8]]) + >>> orientations = corner_orientations(square, corners, octagon(3, 2)) + >>> np.rad2deg(orientations) + array([ 45., 135., -45., -135.]) + + """ + image = _prepare_grayscale_input_2D(image) + return _corner_orientations(image, corners, mask) diff --git a/python_embeded/Lib/site-packages/skimage/feature/corner_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/corner_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..e6c4589f7c0c7412dc3b84e5388a96a630bdc944 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/corner_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/haar.py b/python_embeded/Lib/site-packages/skimage/feature/haar.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9ed934e4fd138a685a6525aca1fe5091cc3528 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/haar.py @@ -0,0 +1,339 @@ +from itertools import chain +from operator import add + +import numpy as np + +from ._haar import haar_like_feature_coord_wrapper +from ._haar import haar_like_feature_wrapper +from ..color import gray2rgb +from ..draw import rectangle +from ..util import img_as_float + +FEATURE_TYPE = ('type-2-x', 'type-2-y', 'type-3-x', 'type-3-y', 'type-4') + + +def _validate_feature_type(feature_type): + """Transform feature type to an iterable and check that it exists.""" + if feature_type is None: + feature_type_ = FEATURE_TYPE + else: + if isinstance(feature_type, str): + feature_type_ = [feature_type] + else: + feature_type_ = feature_type + for feat_t in feature_type_: + if feat_t not in FEATURE_TYPE: + raise ValueError( + f'The given feature type is unknown. Got {feat_t} instead of one ' + f'of {FEATURE_TYPE}.' + ) + return feature_type_ + + +def haar_like_feature_coord(width, height, feature_type=None): + """Compute the coordinates of Haar-like features. + + Parameters + ---------- + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_type : str or list of str or None, optional + The type of feature to consider: + + - 'type-2-x': 2 rectangles varying along the x axis; + - 'type-2-y': 2 rectangles varying along the y axis; + - 'type-3-x': 3 rectangles varying along the x axis; + - 'type-3-y': 3 rectangles varying along the y axis; + - 'type-4': 4 rectangles varying along x and y axis. + + By default all features are extracted. + + Returns + ------- + feature_coord : (n_features, n_rectangles, 2, 2), ndarray of list of \ +tuple coord + Coordinates of the rectangles for each feature. + feature_type : (n_features,), ndarray of str + The corresponding type for each feature. + + Examples + -------- + >>> import numpy as np + >>> from skimage.transform import integral_image + >>> from skimage.feature import haar_like_feature_coord + >>> feat_coord, feat_type = haar_like_feature_coord(2, 2, 'type-4') + >>> feat_coord # doctest: +SKIP + array([ list([[(0, 0), (0, 0)], [(0, 1), (0, 1)], + [(1, 1), (1, 1)], [(1, 0), (1, 0)]])], dtype=object) + >>> feat_type + array(['type-4'], dtype=object) + + """ + feature_type_ = _validate_feature_type(feature_type) + + feat_coord, feat_type = zip( + *[ + haar_like_feature_coord_wrapper(width, height, feat_t) + for feat_t in feature_type_ + ] + ) + + return np.concatenate(feat_coord), np.hstack(feat_type) + + +def haar_like_feature( + int_image, r, c, width, height, feature_type=None, feature_coord=None +): + """Compute the Haar-like features for a region of interest (ROI) of an + integral image. + + Haar-like features have been successfully used for image classification and + object detection [1]_. It has been used for real-time face detection + algorithm proposed in [2]_. + + Parameters + ---------- + int_image : (M, N) ndarray + Integral image for which the features need to be computed. + r : int + Row-coordinate of top left corner of the detection window. + c : int + Column-coordinate of top left corner of the detection window. + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_type : str or list of str or None, optional + The type of feature to consider: + + - 'type-2-x': 2 rectangles varying along the x axis; + - 'type-2-y': 2 rectangles varying along the y axis; + - 'type-3-x': 3 rectangles varying along the x axis; + - 'type-3-y': 3 rectangles varying along the y axis; + - 'type-4': 4 rectangles varying along x and y axis. + + By default all features are extracted. + + If using with `feature_coord`, it should correspond to the feature + type of each associated coordinate feature. + feature_coord : ndarray of list of tuples or None, optional + The array of coordinates to be extracted. This is useful when you want + to recompute only a subset of features. In this case `feature_type` + needs to be an array containing the type of each feature, as returned + by :func:`haar_like_feature_coord`. By default, all coordinates are + computed. + + Returns + ------- + haar_features : (n_features,) ndarray of int or float + Resulting Haar-like features. Each value is equal to the subtraction of + sums of the positive and negative rectangles. The data type depends of + the data type of `int_image`: `int` when the data type of `int_image` + is `uint` or `int` and `float` when the data type of `int_image` is + `float`. + + Notes + ----- + When extracting those features in parallel, be aware that the choice of the + backend (i.e. multiprocessing vs threading) will have an impact on the + performance. The rule of thumb is as follows: use multiprocessing when + extracting features for all possible ROI in an image; use threading when + extracting the feature at specific location for a limited number of ROIs. + Refer to the example + :ref:`sphx_glr_auto_examples_applications_plot_haar_extraction_selection_classification.py` + for more insights. + + Examples + -------- + >>> import numpy as np + >>> from skimage.transform import integral_image + >>> from skimage.feature import haar_like_feature + >>> img = np.ones((5, 5), dtype=np.uint8) + >>> img_ii = integral_image(img) + >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-x') + >>> feature + array([-1, -2, -3, -4, -5, -1, -2, -3, -4, -5, -1, -2, -3, -4, -5, -1, -2, + -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -1, -2, -3, -1, + -2, -3, -1, -2, -1, -2, -1, -2, -1, -1, -1]) + + You can compute the feature for some pre-computed coordinates. + + >>> from skimage.feature import haar_like_feature_coord + >>> feature_coord, feature_type = zip( + ... *[haar_like_feature_coord(5, 5, feat_t) + ... for feat_t in ('type-2-x', 'type-3-x')]) + >>> # only select one feature over two + >>> feature_coord = np.concatenate([x[::2] for x in feature_coord]) + >>> feature_type = np.concatenate([x[::2] for x in feature_type]) + >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, + ... feature_type=feature_type, + ... feature_coord=feature_coord) + >>> feature + 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, -1, -3, -5, -2, -4, -1, + -3, -5, -2, -4, -2, -4, -2, -4, -2, -1, -3, -2, -1, -1, -1, -1, -1]) + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Haar-like_feature + .. [2] Oren, M., Papageorgiou, C., Sinha, P., Osuna, E., & Poggio, T. + (1997, June). Pedestrian detection using wavelet templates. + In Computer Vision and Pattern Recognition, 1997. Proceedings., + 1997 IEEE Computer Society Conference on (pp. 193-199). IEEE. + http://tinyurl.com/y6ulxfta + :DOI:`10.1109/CVPR.1997.609319` + .. [3] Viola, Paul, and Michael J. Jones. "Robust real-time face + detection." International journal of computer vision 57.2 + (2004): 137-154. + https://www.merl.com/publications/docs/TR2004-043.pdf + :DOI:`10.1109/CVPR.2001.990517` + + """ + if feature_coord is None: + feature_type_ = _validate_feature_type(feature_type) + + return np.hstack( + list( + chain.from_iterable( + haar_like_feature_wrapper( + int_image, r, c, width, height, feat_t, feature_coord + ) + for feat_t in feature_type_ + ) + ) + ) + else: + if feature_coord.shape[0] != feature_type.shape[0]: + raise ValueError( + "Inconsistent size between feature coordinates" "and feature types." + ) + + mask_feature = [feature_type == feat_t for feat_t in FEATURE_TYPE] + haar_feature_idx, haar_feature = zip( + *[ + ( + np.flatnonzero(mask), + haar_like_feature_wrapper( + int_image, r, c, width, height, feat_t, feature_coord[mask] + ), + ) + for mask, feat_t in zip(mask_feature, FEATURE_TYPE) + if np.count_nonzero(mask) + ] + ) + + haar_feature_idx = np.concatenate(haar_feature_idx) + haar_feature = np.concatenate(haar_feature) + + haar_feature[haar_feature_idx] = haar_feature.copy() + return haar_feature + + +def draw_haar_like_feature( + image, + r, + c, + width, + height, + feature_coord, + color_positive_block=(1.0, 0.0, 0.0), + color_negative_block=(0.0, 1.0, 0.0), + alpha=0.5, + max_n_features=None, + rng=None, +): + """Visualization of Haar-like features. + + Parameters + ---------- + image : (M, N) ndarray + The region of an integral image for which the features need to be + computed. + r : int + Row-coordinate of top left corner of the detection window. + c : int + Column-coordinate of top left corner of the detection window. + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_coord : ndarray of list of tuples or None, optional + The array of coordinates to be extracted. This is useful when you want + to recompute only a subset of features. In this case `feature_type` + needs to be an array containing the type of each feature, as returned + by :func:`haar_like_feature_coord`. By default, all coordinates are + computed. + color_positive_block : tuple of 3 floats + Floats specifying the color for the positive block. Corresponding + values define (R, G, B) values. Default value is red (1, 0, 0). + color_negative_block : tuple of 3 floats + Floats specifying the color for the negative block Corresponding values + define (R, G, B) values. Default value is blue (0, 1, 0). + alpha : float + Value in the range [0, 1] that specifies opacity of visualization. 1 - + fully transparent, 0 - opaque. + max_n_features : int, default=None + The maximum number of features to be returned. + By default, all features are returned. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The rng is used when generating a set of features smaller than + the total number of available features. + + Returns + ------- + features : (M, N), ndarray + An image in which the different features will be added. + + Examples + -------- + >>> import numpy as np + >>> from skimage.feature import haar_like_feature_coord + >>> from skimage.feature import draw_haar_like_feature + >>> feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4') + >>> image = draw_haar_like_feature(np.zeros((2, 2)), + ... 0, 0, 2, 2, + ... feature_coord, + ... max_n_features=1) + >>> image + array([[[0. , 0.5, 0. ], + [0.5, 0. , 0. ]], + + [[0.5, 0. , 0. ], + [0. , 0.5, 0. ]]]) + + """ + rng = np.random.default_rng(rng) + color_positive_block = np.asarray(color_positive_block, dtype=np.float64) + color_negative_block = np.asarray(color_negative_block, dtype=np.float64) + + if max_n_features is None: + feature_coord_ = feature_coord + else: + feature_coord_ = rng.choice(feature_coord, size=max_n_features, replace=False) + + output = np.copy(image) + if len(image.shape) < 3: + output = gray2rgb(image) + output = img_as_float(output) + + for coord in feature_coord_: + for idx_rect, rect in enumerate(coord): + coord_start, coord_end = rect + coord_start = tuple(map(add, coord_start, [r, c])) + coord_end = tuple(map(add, coord_end, [r, c])) + rr, cc = rectangle(coord_start, coord_end) + + if ((idx_rect + 1) % 2) == 0: + new_value = (1 - alpha) * output[rr, cc] + alpha * color_positive_block + else: + new_value = (1 - alpha) * output[rr, cc] + alpha * color_negative_block + output[rr, cc] = new_value + + return output diff --git a/python_embeded/Lib/site-packages/skimage/feature/match.py b/python_embeded/Lib/site-packages/skimage/feature/match.py new file mode 100644 index 0000000000000000000000000000000000000000..364eaa848da0afa9cb41cfcb706ba752a7d4ca40 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/match.py @@ -0,0 +1,103 @@ +import numpy as np +from scipy.spatial.distance import cdist + + +def match_descriptors( + descriptors1, + descriptors2, + metric=None, + p=2, + max_distance=np.inf, + cross_check=True, + max_ratio=1.0, +): + """Brute-force matching of descriptors. + + For each descriptor in the first set this matcher finds the closest + descriptor in the second set (and vice-versa in the case of enabled + cross-checking). + + Parameters + ---------- + descriptors1 : (M, P) array + Descriptors of size P about M keypoints in the first image. + descriptors2 : (N, P) array + Descriptors of size P about N keypoints in the second image. + metric : {'euclidean', 'cityblock', 'minkowski', 'hamming', ...} , optional + The metric to compute the distance between two descriptors. See + `scipy.spatial.distance.cdist` for all possible types. The hamming + distance should be used for binary descriptors. By default the L2-norm + is used for all descriptors of dtype float or double and the Hamming + distance is used for binary descriptors automatically. + p : int, optional + The p-norm to apply for ``metric='minkowski'``. + max_distance : float, optional + Maximum allowed distance between descriptors of two keypoints + in separate images to be regarded as a match. + cross_check : bool, optional + If True, the matched keypoints are returned after cross checking i.e. a + matched pair (keypoint1, keypoint2) is returned if keypoint2 is the + best match for keypoint1 in second image and keypoint1 is the best + match for keypoint2 in first image. + max_ratio : float, optional + Maximum ratio of distances between first and second closest descriptor + in the second set of descriptors. This threshold is useful to filter + ambiguous matches between the two descriptor sets. The choice of this + value depends on the statistics of the chosen descriptor, e.g., + for SIFT descriptors a value of 0.8 is usually chosen, see + D.G. Lowe, "Distinctive Image Features from Scale-Invariant Keypoints", + International Journal of Computer Vision, 2004. + + Returns + ------- + matches : (Q, 2) array + Indices of corresponding matches in first and second set of + descriptors, where ``matches[:, 0]`` denote the indices in the first + and ``matches[:, 1]`` the indices in the second set of descriptors. + + """ + + if descriptors1.shape[1] != descriptors2.shape[1]: + raise ValueError("Descriptor length must equal.") + + if metric is None: + if np.issubdtype(descriptors1.dtype, bool): + metric = 'hamming' + else: + metric = 'euclidean' + + kwargs = {} + # Scipy raises an error if p is passed as an extra argument when it isn't + # necessary for the chosen metric. + if metric == 'minkowski': + kwargs['p'] = p + distances = cdist(descriptors1, descriptors2, metric=metric, **kwargs) + + indices1 = np.arange(descriptors1.shape[0]) + indices2 = np.argmin(distances, axis=1) + + if cross_check: + matches1 = np.argmin(distances, axis=0) + mask = indices1 == matches1[indices2] + indices1 = indices1[mask] + indices2 = indices2[mask] + + if max_distance < np.inf: + mask = distances[indices1, indices2] < max_distance + indices1 = indices1[mask] + indices2 = indices2[mask] + + if max_ratio < 1.0: + best_distances = distances[indices1, indices2] + distances[indices1, indices2] = np.inf + second_best_indices2 = np.argmin(distances[indices1], axis=1) + second_best_distances = distances[indices1, second_best_indices2] + second_best_distances[second_best_distances == 0] = np.finfo(np.float64).eps + ratio = best_distances / second_best_distances + mask = ratio < max_ratio + indices1 = indices1[mask] + indices2 = indices2[mask] + + matches = np.column_stack((indices1, indices2)) + + return matches diff --git a/python_embeded/Lib/site-packages/skimage/feature/orb.py b/python_embeded/Lib/site-packages/skimage/feature/orb.py new file mode 100644 index 0000000000000000000000000000000000000000..0ef65af03af976f3c9b3a143c19401d0bf87b928 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/orb.py @@ -0,0 +1,366 @@ +import numpy as np + +from ..feature.util import ( + FeatureDetector, + DescriptorExtractor, + _mask_border_keypoints, + _prepare_grayscale_input_2D, +) + +from .corner import corner_fast, corner_orientations, corner_peaks, corner_harris +from ..transform import pyramid_gaussian +from .._shared.utils import check_nD +from .._shared.compat import NP_COPY_IF_NEEDED + +from .orb_cy import _orb_loop + + +OFAST_MASK = np.zeros((31, 31)) +OFAST_UMAX = [15, 15, 15, 15, 14, 14, 14, 13, 13, 12, 11, 10, 9, 8, 6, 3] +for i in range(-15, 16): + for j in range(-OFAST_UMAX[abs(i)], OFAST_UMAX[abs(i)] + 1): + OFAST_MASK[15 + j, 15 + i] = 1 + + +class ORB(FeatureDetector, DescriptorExtractor): + """Oriented FAST and rotated BRIEF feature detector and binary descriptor + extractor. + + Parameters + ---------- + n_keypoints : int, optional + Number of keypoints to be returned. The function will return the best + `n_keypoints` according to the Harris corner response if more than + `n_keypoints` are detected. If not, then all the detected keypoints + are returned. + fast_n : int, optional + The `n` parameter in `skimage.feature.corner_fast`. Minimum number of + consecutive pixels out of 16 pixels on the circle that should all be + either brighter or darker w.r.t test-pixel. A point c on the circle is + darker w.r.t test pixel p if ``Ic < Ip - threshold`` and brighter if + ``Ic > Ip + threshold``. Also stands for the n in ``FAST-n`` corner + detector. + fast_threshold : float, optional + The ``threshold`` parameter in ``feature.corner_fast``. Threshold used + to decide whether the pixels on the circle are brighter, darker or + similar w.r.t. the test pixel. Decrease the threshold when more + corners are desired and vice-versa. + harris_k : float, optional + The `k` parameter in `skimage.feature.corner_harris`. Sensitivity + factor to separate corners from edges, typically in range ``[0, 0.2]``. + Small values of `k` result in detection of sharp corners. + downscale : float, optional + Downscale factor for the image pyramid. Default value 1.2 is chosen so + that there are more dense scales which enable robust scale invariance + for a subsequent feature description. + n_scales : int, optional + Maximum number of scales from the bottom of the image pyramid to + extract the features from. + + Attributes + ---------- + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + orientations : (N,) array + Corresponding orientations in radians. + responses : (N,) array + Corresponding Harris corner responses. + descriptors : (Q, `descriptor_size`) array of dtype bool + 2D array of binary descriptors of size `descriptor_size` for Q + keypoints after filtering out border keypoints with value at an + index ``(i, j)`` either being ``True`` or ``False`` representing + the outcome of the intensity comparison for i-th keypoint on j-th + decision pixel-pair. It is ``Q == np.sum(mask)``. + + References + ---------- + .. [1] Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski + "ORB: An efficient alternative to SIFT and SURF" + http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf + + Examples + -------- + >>> from skimage.feature import ORB, match_descriptors + >>> img1 = np.zeros((100, 100)) + >>> img2 = np.zeros_like(img1) + >>> rng = np.random.default_rng(19481137) # do not copy this value + >>> square = rng.random((20, 20)) + >>> img1[40:60, 40:60] = square + >>> img2[53:73, 53:73] = square + >>> detector_extractor1 = ORB(n_keypoints=5) + >>> detector_extractor2 = ORB(n_keypoints=5) + >>> detector_extractor1.detect_and_extract(img1) + >>> detector_extractor2.detect_and_extract(img2) + >>> matches = match_descriptors(detector_extractor1.descriptors, + ... detector_extractor2.descriptors) + >>> matches + array([[0, 0], + [1, 1], + [2, 2], + [3, 4], + [4, 3]]) + >>> detector_extractor1.keypoints[matches[:, 0]] + array([[59. , 59. ], + [40. , 40. ], + [57. , 40. ], + [46. , 58. ], + [58.8, 58.8]]) + >>> detector_extractor2.keypoints[matches[:, 1]] + array([[72., 72.], + [53., 53.], + [70., 53.], + [59., 71.], + [72., 72.]]) + + """ + + def __init__( + self, + downscale=1.2, + n_scales=8, + n_keypoints=500, + fast_n=9, + fast_threshold=0.08, + harris_k=0.04, + ): + self.downscale = downscale + self.n_scales = n_scales + self.n_keypoints = n_keypoints + self.fast_n = fast_n + self.fast_threshold = fast_threshold + self.harris_k = harris_k + + self.keypoints = None + self.scales = None + self.responses = None + self.orientations = None + self.descriptors = None + + def _build_pyramid(self, image): + image = _prepare_grayscale_input_2D(image) + return list( + pyramid_gaussian( + image, self.n_scales - 1, self.downscale, channel_axis=None + ) + ) + + def _detect_octave(self, octave_image): + dtype = octave_image.dtype + # Extract keypoints for current octave + fast_response = corner_fast(octave_image, self.fast_n, self.fast_threshold) + keypoints = corner_peaks(fast_response, min_distance=1) + + if len(keypoints) == 0: + return ( + np.zeros((0, 2), dtype=dtype), + np.zeros((0,), dtype=dtype), + np.zeros((0,), dtype=dtype), + ) + + mask = _mask_border_keypoints(octave_image.shape, keypoints, distance=16) + keypoints = keypoints[mask] + + orientations = corner_orientations(octave_image, keypoints, OFAST_MASK) + + harris_response = corner_harris(octave_image, method='k', k=self.harris_k) + responses = harris_response[keypoints[:, 0], keypoints[:, 1]] + + return keypoints, orientations, responses + + def detect(self, image): + """Detect oriented FAST keypoints along with the corresponding scale. + + Parameters + ---------- + image : 2D array + Input image. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + keypoints_list = [] + orientations_list = [] + scales_list = [] + responses_list = [] + + for octave in range(len(pyramid)): + octave_image = np.ascontiguousarray(pyramid[octave]) + + if np.squeeze(octave_image).ndim < 2: + # No further keypoints can be detected if the image is not really 2d + break + + keypoints, orientations, responses = self._detect_octave(octave_image) + + keypoints_list.append(keypoints * self.downscale**octave) + orientations_list.append(orientations) + scales_list.append( + np.full( + keypoints.shape[0], + self.downscale**octave, + dtype=octave_image.dtype, + ) + ) + responses_list.append(responses) + + keypoints = np.vstack(keypoints_list) + orientations = np.hstack(orientations_list) + scales = np.hstack(scales_list) + responses = np.hstack(responses_list) + + if keypoints.shape[0] < self.n_keypoints: + self.keypoints = keypoints + self.scales = scales + self.orientations = orientations + self.responses = responses + else: + # Choose best n_keypoints according to Harris corner response + best_indices = responses.argsort()[::-1][: self.n_keypoints] + self.keypoints = keypoints[best_indices] + self.scales = scales[best_indices] + self.orientations = orientations[best_indices] + self.responses = responses[best_indices] + + def _extract_octave(self, octave_image, keypoints, orientations): + mask = _mask_border_keypoints(octave_image.shape, keypoints, distance=20) + keypoints = np.array( + keypoints[mask], dtype=np.intp, order='C', copy=NP_COPY_IF_NEEDED + ) + orientations = np.array(orientations[mask], order='C', copy=False) + + descriptors = _orb_loop(octave_image, keypoints, orientations) + + return descriptors, mask + + def extract(self, image, keypoints, scales, orientations): + """Extract rBRIEF binary descriptors for given keypoints in image. + + Note that the keypoints must be extracted using the same `downscale` + and `n_scales` parameters. Additionally, if you want to extract both + keypoints and descriptors you should use the faster + `detect_and_extract`. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + orientations : (N,) array + Corresponding orientations in radians. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + descriptors_list = [] + mask_list = [] + + # Determine octaves from scales + octaves = (np.log(scales) / np.log(self.downscale)).astype(np.intp) + + for octave in range(len(pyramid)): + # Mask for all keypoints in current octave + octave_mask = octaves == octave + + if np.sum(octave_mask) > 0: + octave_image = np.ascontiguousarray(pyramid[octave]) + + octave_keypoints = keypoints[octave_mask] + octave_keypoints /= self.downscale**octave + octave_orientations = orientations[octave_mask] + + descriptors, mask = self._extract_octave( + octave_image, octave_keypoints, octave_orientations + ) + + descriptors_list.append(descriptors) + mask_list.append(mask) + + self.descriptors = np.vstack(descriptors_list).view(bool) + self.mask_ = np.hstack(mask_list) + + def detect_and_extract(self, image): + """Detect oriented FAST keypoints and extract rBRIEF descriptors. + + Note that this is faster than first calling `detect` and then + `extract`. + + Parameters + ---------- + image : 2D array + Input image. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + keypoints_list = [] + responses_list = [] + scales_list = [] + orientations_list = [] + descriptors_list = [] + + for octave in range(len(pyramid)): + octave_image = np.ascontiguousarray(pyramid[octave]) + + if np.squeeze(octave_image).ndim < 2: + # No further keypoints can be detected if the image is not really 2d + break + + keypoints, orientations, responses = self._detect_octave(octave_image) + + if len(keypoints) == 0: + keypoints_list.append(keypoints) + responses_list.append(responses) + descriptors_list.append(np.zeros((0, 256), dtype=bool)) + continue + + descriptors, mask = self._extract_octave( + octave_image, keypoints, orientations + ) + + scaled_keypoints = keypoints[mask] * self.downscale**octave + keypoints_list.append(scaled_keypoints) + responses_list.append(responses[mask]) + orientations_list.append(orientations[mask]) + scales_list.append( + self.downscale**octave + * np.ones(scaled_keypoints.shape[0], dtype=np.intp) + ) + descriptors_list.append(descriptors) + + if len(scales_list) == 0: + raise RuntimeError( + "ORB found no features. Try passing in an image containing " + "greater intensity contrasts between adjacent pixels." + ) + + keypoints = np.vstack(keypoints_list) + responses = np.hstack(responses_list) + scales = np.hstack(scales_list) + orientations = np.hstack(orientations_list) + descriptors = np.vstack(descriptors_list).view(bool) + + if keypoints.shape[0] < self.n_keypoints: + self.keypoints = keypoints + self.scales = scales + self.orientations = orientations + self.responses = responses + self.descriptors = descriptors + else: + # Choose best n_keypoints according to Harris corner response + best_indices = responses.argsort()[::-1][: self.n_keypoints] + self.keypoints = keypoints[best_indices] + self.scales = scales[best_indices] + self.orientations = orientations[best_indices] + self.responses = responses[best_indices] + self.descriptors = descriptors[best_indices] diff --git a/python_embeded/Lib/site-packages/skimage/feature/orb_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/feature/orb_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..2b73495fc2080acd5e9953cba4bd5b35a980c7d4 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/feature/orb_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/feature/orb_descriptor_positions.txt b/python_embeded/Lib/site-packages/skimage/feature/orb_descriptor_positions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6acd28ed89b50e6646165e009dc5c5d0d87cea91 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/orb_descriptor_positions.txt @@ -0,0 +1,256 @@ +8 -3 9 5 +4 2 7 -12 +-11 9 -8 2 +7 -12 12 -13 +2 -13 2 12 +1 -7 1 6 +-2 -10 -2 -4 +-13 -13 -11 -8 +-13 -3 -12 -9 +10 4 11 9 +-13 -8 -8 -9 +-11 7 -9 12 +7 7 12 6 +-4 -5 -3 0 +-13 2 -12 -3 +-9 0 -7 5 +12 -6 12 -1 +-3 6 -2 12 +-6 -13 -4 -8 +11 -13 12 -8 +4 7 5 1 +5 -3 10 -3 +3 -7 6 12 +-8 -7 -6 -2 +-2 11 -1 -10 +-13 12 -8 10 +-7 3 -5 -3 +-4 2 -3 7 +-10 -12 -6 11 +5 -12 6 -7 +5 -6 7 -1 +1 0 4 -5 +9 11 11 -13 +4 7 4 12 +2 -1 4 4 +-4 -12 -2 7 +-8 -5 -7 -10 +4 11 9 12 +0 -8 1 -13 +-13 -2 -8 2 +-3 -2 -2 3 +-6 9 -4 -9 +8 12 10 7 +0 9 1 3 +7 -5 11 -10 +-13 -6 -11 0 +10 7 12 1 +-6 -3 -6 12 +10 -9 12 -4 +-13 8 -8 -12 +-13 0 -8 -4 +3 3 7 8 +5 7 10 -7 +-1 7 1 -12 +3 -10 5 6 +2 -4 3 -10 +-13 0 -13 5 +-13 -7 -12 12 +-13 3 -11 8 +-7 12 -4 7 +6 -10 12 8 +-9 -1 -7 -6 +-2 -5 0 12 +-12 5 -7 5 +3 -10 8 -13 +-7 -7 -4 5 +-3 -2 -1 -7 +2 9 5 -11 +-11 -13 -5 -13 +-1 6 0 -1 +5 -3 5 2 +-4 -13 -4 12 +-9 -6 -9 6 +-12 -10 -8 -4 +10 2 12 -3 +7 12 12 12 +-7 -13 -6 5 +-4 9 -3 4 +7 -1 12 2 +-7 6 -5 1 +-13 11 -12 5 +-3 7 -2 -6 +7 -8 12 -7 +-13 -7 -11 -12 +1 -3 12 12 +2 -6 3 0 +-4 3 -2 -13 +-1 -13 1 9 +7 1 8 -6 +1 -1 3 12 +9 1 12 6 +-1 -9 -1 3 +-13 -13 -10 5 +7 7 10 12 +12 -5 12 9 +6 3 7 11 +5 -13 6 10 +2 -12 2 3 +3 8 4 -6 +2 6 12 -13 +9 -12 10 3 +-8 4 -7 9 +-11 12 -4 -6 +1 12 2 -8 +6 -9 7 -4 +2 3 3 -2 +6 3 11 0 +3 -3 8 -8 +7 8 9 3 +-11 -5 -6 -4 +-10 11 -5 10 +-5 -8 -3 12 +-10 5 -9 0 +8 -1 12 -6 +4 -6 6 -11 +-10 12 -8 7 +4 -2 6 7 +-2 0 -2 12 +-5 -8 -5 2 +7 -6 10 12 +-9 -13 -8 -8 +-5 -13 -5 -2 +8 -8 9 -13 +-9 -11 -9 0 +1 -8 1 -2 +7 -4 9 1 +-2 1 -1 -4 +11 -6 12 -11 +-12 -9 -6 4 +3 7 7 12 +5 5 10 8 +0 -4 2 8 +-9 12 -5 -13 +0 7 2 12 +-1 2 1 7 +5 11 7 -9 +3 5 6 -8 +-13 -4 -8 9 +-5 9 -3 -3 +-4 -7 -3 -12 +6 5 8 0 +-7 6 -6 12 +-13 6 -5 -2 +1 -10 3 10 +4 1 8 -4 +-2 -2 2 -13 +2 -12 12 12 +-2 -13 0 -6 +4 1 9 3 +-6 -10 -3 -5 +-3 -13 -1 1 +7 5 12 -11 +4 -2 5 -7 +-13 9 -9 -5 +7 1 8 6 +7 -8 7 6 +-7 -4 -7 1 +-8 11 -7 -8 +-13 6 -12 -8 +2 4 3 9 +10 -5 12 3 +-6 -5 -6 7 +8 -3 9 -8 +2 -12 2 8 +-11 -2 -10 3 +-12 -13 -7 -9 +-11 0 -10 -5 +5 -3 11 8 +-2 -13 -1 12 +-1 -8 0 9 +-13 -11 -12 -5 +-10 -2 -10 11 +-3 9 -2 -13 +2 -3 3 2 +-9 -13 -4 0 +-4 6 -3 -10 +-4 12 -2 -7 +-6 -11 -4 9 +6 -3 6 11 +-13 11 -5 5 +11 11 12 6 +7 -5 12 -2 +-1 12 0 7 +-4 -8 -3 -2 +-7 1 -6 7 +-13 -12 -8 -13 +-7 -2 -6 -8 +-8 5 -6 -9 +-5 -1 -4 5 +-13 7 -8 10 +1 5 5 -13 +1 0 10 -13 +9 12 10 -1 +5 -8 10 -9 +-1 11 1 -13 +-9 -3 -6 2 +-1 -10 1 12 +-13 1 -8 -10 +8 -11 10 -6 +2 -13 3 -6 +7 -13 12 -9 +-10 -10 -5 -7 +-10 -8 -8 -13 +4 -6 8 5 +3 12 8 -13 +-4 2 -3 -3 +5 -13 10 -12 +4 -13 5 -1 +-9 9 -4 3 +0 3 3 -9 +-12 1 -6 1 +3 2 4 -8 +-10 -10 -10 9 +8 -13 12 12 +-8 -12 -6 -5 +2 2 3 7 +10 6 11 -8 +6 8 8 -12 +-7 10 -6 5 +-3 -9 -3 9 +-1 -13 -1 5 +-3 -7 -3 4 +-8 -2 -8 3 +4 2 12 12 +2 -5 3 11 +6 -9 11 -13 +3 -1 7 12 +11 -1 12 4 +-3 0 -3 6 +4 -11 4 12 +2 -4 2 1 +-10 -6 -8 1 +-13 7 -11 1 +-13 12 -11 -13 +6 0 11 -13 +0 -1 1 4 +-13 3 -9 -2 +-9 8 -6 -3 +-13 -6 -8 -2 +5 -9 8 10 +2 7 3 -9 +-1 -6 -1 -1 +9 5 11 -2 +11 -3 12 -8 +3 0 3 5 +-1 4 0 10 +3 -6 4 5 +-13 0 -10 5 +5 8 12 11 +8 9 9 -6 +7 -4 8 -12 +-10 4 -10 9 +7 3 12 4 +9 -7 10 -2 +7 0 12 -2 +-1 -6 0 -11 diff --git a/python_embeded/Lib/site-packages/skimage/feature/peak.py b/python_embeded/Lib/site-packages/skimage/feature/peak.py new file mode 100644 index 0000000000000000000000000000000000000000..6c0c3ae063c6df08c633b508f365fddf330b9a75 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/peak.py @@ -0,0 +1,420 @@ +from warnings import warn + +import numpy as np +import scipy.ndimage as ndi + +from .. import measure +from .._shared.coord import ensure_spacing + + +def _get_high_intensity_peaks(image, mask, num_peaks, min_distance, p_norm): + """ + Return the highest intensity peak coordinates. + """ + # get coordinates of peaks + coord = np.nonzero(mask) + intensities = image[coord] + # Highest peak first + idx_maxsort = np.argsort(-intensities, kind="stable") + coord = np.transpose(coord)[idx_maxsort] + + if np.isfinite(num_peaks): + max_out = int(num_peaks) + else: + max_out = None + + if min_distance > 1: + coord = ensure_spacing( + coord, spacing=min_distance, p_norm=p_norm, max_out=max_out + ) + + if len(coord) > num_peaks: + coord = coord[:num_peaks] + + return coord + + +def _get_peak_mask(image, footprint, threshold, mask=None): + """ + Return the mask containing all peak candidates above thresholds. + """ + if footprint.size == 1 or image.size == 1: + return image > threshold + + image_max = ndi.maximum_filter(image, footprint=footprint, mode='nearest') + + out = image == image_max + + # no peak for a trivial image + image_is_trivial = np.all(out) if mask is None else np.all(out[mask]) + if image_is_trivial: + out[:] = False + if mask is not None: + # isolated pixels in masked area are returned as peaks + isolated_px = np.logical_xor(mask, ndi.binary_opening(mask)) + out[isolated_px] = True + + out &= image > threshold + return out + + +def _exclude_border(label, border_width): + """Set label border values to 0.""" + # zero out label borders + for i, width in enumerate(border_width): + if width == 0: + continue + label[(slice(None),) * i + (slice(None, width),)] = 0 + label[(slice(None),) * i + (slice(-width, None),)] = 0 + return label + + +def _get_threshold(image, threshold_abs, threshold_rel): + """Return the threshold value according to an absolute and a relative + value. + + """ + threshold = threshold_abs if threshold_abs is not None else image.min() + + if threshold_rel is not None: + threshold = max(threshold, threshold_rel * image.max()) + + return threshold + + +def _get_excluded_border_width(image, min_distance, exclude_border): + """Return border_width values relative to a min_distance if requested.""" + + if isinstance(exclude_border, bool): + border_width = (min_distance if exclude_border else 0,) * image.ndim + elif isinstance(exclude_border, int): + if exclude_border < 0: + raise ValueError("`exclude_border` cannot be a negative value") + border_width = (exclude_border,) * image.ndim + elif isinstance(exclude_border, tuple): + if len(exclude_border) != image.ndim: + raise ValueError( + "`exclude_border` should have the same length as the " + "dimensionality of the image." + ) + for exclude in exclude_border: + if not isinstance(exclude, int): + raise ValueError( + "`exclude_border`, when expressed as a tuple, must only " + "contain ints." + ) + if exclude < 0: + raise ValueError("`exclude_border` can not be a negative value") + border_width = exclude_border + else: + raise TypeError( + "`exclude_border` must be bool, int, or tuple with the same " + "length as the dimensionality of the image." + ) + + return border_width + + +def peak_local_max( + image, + min_distance=1, + threshold_abs=None, + threshold_rel=None, + exclude_border=True, + num_peaks=np.inf, + footprint=None, + labels=None, + num_peaks_per_label=np.inf, + p_norm=np.inf, +): + """Find peaks in an image as coordinate list. + + Peaks are the local maxima in a region of `2 * min_distance + 1` + (i.e. peaks are separated by at least `min_distance`). + + If both `threshold_abs` and `threshold_rel` are provided, the maximum + of the two is chosen as the minimum intensity threshold of peaks. + + .. versionchanged:: 0.18 + Prior to version 0.18, peaks of the same height within a radius of + `min_distance` were all returned, but this could cause unexpected + behaviour. From 0.18 onwards, an arbitrary peak within the region is + returned. See issue gh-2592. + + Parameters + ---------- + image : ndarray + Input image. + min_distance : int, optional + The minimal allowed distance separating peaks. To find the + maximum number of peaks, use `min_distance=1`. + threshold_abs : float or None, optional + Minimum intensity of peaks. By default, the absolute threshold is + the minimum intensity of the image. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(image) * threshold_rel``. + exclude_border : int, tuple of ints, or bool, optional + If positive integer, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If tuple of non-negative ints, the length of the tuple must match the + input array's dimensionality. Each element of the tuple will exclude + peaks from within `exclude_border`-pixels of the border of the image + along that dimension. + If True, takes the `min_distance` parameter as value. + If zero or False, peaks are identified regardless of their distance + from the border. + num_peaks : int, optional + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` peaks based on highest peak intensity. + footprint : ndarray of bools, optional + If provided, `footprint == 1` represents the local region within which + to search for peaks at every point in `image`. + labels : ndarray of ints, optional + If provided, each unique region `labels == value` represents a unique + region to search for peaks. Zero is reserved for background. + num_peaks_per_label : int, optional + Maximum number of peaks for each label. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + + Returns + ------- + output : ndarray + The coordinates of the peaks. + + Notes + ----- + The peak local maximum function returns the coordinates of local peaks + (maxima) in an image. Internally, a maximum filter is used for finding + local maxima. This operation dilates the original image. After comparison + of the dilated and original images, this function returns the coordinates + of the peaks where the dilated image equals the original image. + + See also + -------- + skimage.feature.corner_peaks + + Examples + -------- + >>> img1 = np.zeros((7, 7)) + >>> img1[3, 4] = 1 + >>> img1[3, 2] = 1.5 + >>> img1 + array([[0. , 0. , 0. , 0. , 0. , 0. , 0. ], + [0. , 0. , 0. , 0. , 0. , 0. , 0. ], + [0. , 0. , 0. , 0. , 0. , 0. , 0. ], + [0. , 0. , 1.5, 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. ]]) + + >>> peak_local_max(img1, min_distance=1) + array([[3, 2], + [3, 4]]) + + >>> peak_local_max(img1, min_distance=2) + array([[3, 2]]) + + >>> img2 = np.zeros((20, 20, 20)) + >>> img2[10, 10, 10] = 1 + >>> img2[15, 15, 15] = 1 + >>> peak_idx = peak_local_max(img2, exclude_border=0) + >>> peak_idx + array([[10, 10, 10], + [15, 15, 15]]) + + >>> peak_mask = np.zeros_like(img2, dtype=bool) + >>> peak_mask[tuple(peak_idx.T)] = True + >>> np.argwhere(peak_mask) + array([[10, 10, 10], + [15, 15, 15]]) + + """ + if (footprint is None or footprint.size == 1) and min_distance < 1: + warn( + "When min_distance < 1, peak_local_max acts as finding " + "image > max(threshold_abs, threshold_rel * max(image)).", + RuntimeWarning, + stacklevel=2, + ) + + border_width = _get_excluded_border_width(image, min_distance, exclude_border) + + threshold = _get_threshold(image, threshold_abs, threshold_rel) + + if footprint is None: + size = 2 * min_distance + 1 + footprint = np.ones((size,) * image.ndim, dtype=bool) + else: + footprint = np.asarray(footprint) + + if labels is None: + # Non maximum filter + mask = _get_peak_mask(image, footprint, threshold) + + mask = _exclude_border(mask, border_width) + + # Select highest intensities (num_peaks) + coordinates = _get_high_intensity_peaks( + image, mask, num_peaks, min_distance, p_norm + ) + + else: + _labels = _exclude_border(labels.astype(int, casting="safe"), border_width) + + if np.issubdtype(image.dtype, np.floating): + bg_val = np.finfo(image.dtype).min + else: + bg_val = np.iinfo(image.dtype).min + + # For each label, extract a smaller image enclosing the object of + # interest, identify num_peaks_per_label peaks + labels_peak_coord = [] + + for label_idx, roi in enumerate(ndi.find_objects(_labels)): + if roi is None: + continue + + # Get roi mask + label_mask = labels[roi] == label_idx + 1 + # Extract image roi + img_object = image[roi].copy() + # Ensure masked values don't affect roi's local peaks + img_object[np.logical_not(label_mask)] = bg_val + + mask = _get_peak_mask(img_object, footprint, threshold, label_mask) + + coordinates = _get_high_intensity_peaks( + img_object, mask, num_peaks_per_label, min_distance, p_norm + ) + + # transform coordinates in global image indices space + for idx, s in enumerate(roi): + coordinates[:, idx] += s.start + + labels_peak_coord.append(coordinates) + + if labels_peak_coord: + coordinates = np.vstack(labels_peak_coord) + else: + coordinates = np.empty((0, 2), dtype=int) + + if len(coordinates) > num_peaks: + out = np.zeros_like(image, dtype=bool) + out[tuple(coordinates.T)] = True + coordinates = _get_high_intensity_peaks( + image, out, num_peaks, min_distance, p_norm + ) + + return coordinates + + +def _prominent_peaks( + image, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=np.inf +): + """Return peaks with non-maximum suppression. + + Identifies most prominent features separated by certain distances. + Non-maximum suppression with different sizes is applied separately + in the first and second dimension of the image to identify peaks. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + min_xdistance : int + Minimum distance separating features in the x dimension. + min_ydistance : int + Minimum distance separating features in the y dimension. + threshold : float + Minimum intensity of peaks. Default is `0.5 * max(image)`. + num_peaks : int + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` coordinates based on peak intensity. + + Returns + ------- + intensity, xcoords, ycoords : tuple of array + Peak intensity values, x and y indices. + """ + + img = image.copy() + rows, cols = img.shape + + if threshold is None: + threshold = 0.5 * np.max(img) + + ycoords_size = 2 * min_ydistance + 1 + xcoords_size = 2 * min_xdistance + 1 + img_max = ndi.maximum_filter1d( + img, size=ycoords_size, axis=0, mode='constant', cval=0 + ) + img_max = ndi.maximum_filter1d( + img_max, size=xcoords_size, axis=1, mode='constant', cval=0 + ) + mask = img == img_max + img *= mask + img_t = img > threshold + + label_img = measure.label(img_t) + props = measure.regionprops(label_img, img_max) + + # Sort the list of peaks by intensity, not left-right, so larger peaks + # in Hough space cannot be arbitrarily suppressed by smaller neighbors + props = sorted(props, key=lambda x: x.intensity_max)[::-1] + coords = np.array([np.round(p.centroid) for p in props], dtype=int) + + img_peaks = [] + ycoords_peaks = [] + xcoords_peaks = [] + + # relative coordinate grid for local neighborhood suppression + ycoords_ext, xcoords_ext = np.mgrid[ + -min_ydistance : min_ydistance + 1, -min_xdistance : min_xdistance + 1 + ] + + for ycoords_idx, xcoords_idx in coords: + accum = img_max[ycoords_idx, xcoords_idx] + if accum > threshold: + # absolute coordinate grid for local neighborhood suppression + ycoords_nh = ycoords_idx + ycoords_ext + xcoords_nh = xcoords_idx + xcoords_ext + + # no reflection for distance neighborhood + ycoords_in = np.logical_and(ycoords_nh > 0, ycoords_nh < rows) + ycoords_nh = ycoords_nh[ycoords_in] + xcoords_nh = xcoords_nh[ycoords_in] + + # reflect xcoords and assume xcoords are continuous, + # e.g. for angles: + # (..., 88, 89, -90, -89, ..., 89, -90, -89, ...) + xcoords_low = xcoords_nh < 0 + ycoords_nh[xcoords_low] = rows - ycoords_nh[xcoords_low] + xcoords_nh[xcoords_low] += cols + xcoords_high = xcoords_nh >= cols + ycoords_nh[xcoords_high] = rows - ycoords_nh[xcoords_high] + xcoords_nh[xcoords_high] -= cols + + # suppress neighborhood + img_max[ycoords_nh, xcoords_nh] = 0 + + # add current feature to peaks + img_peaks.append(accum) + ycoords_peaks.append(ycoords_idx) + xcoords_peaks.append(xcoords_idx) + + img_peaks = np.array(img_peaks) + ycoords_peaks = np.array(ycoords_peaks) + xcoords_peaks = np.array(xcoords_peaks) + + if num_peaks < len(img_peaks): + idx_maxsort = np.argsort(img_peaks)[::-1][:num_peaks] + img_peaks = img_peaks[idx_maxsort] + ycoords_peaks = ycoords_peaks[idx_maxsort] + xcoords_peaks = xcoords_peaks[idx_maxsort] + + return img_peaks, xcoords_peaks, ycoords_peaks diff --git a/python_embeded/Lib/site-packages/skimage/feature/sift.py b/python_embeded/Lib/site-packages/skimage/feature/sift.py new file mode 100644 index 0000000000000000000000000000000000000000..a5208e3c83305847dd0eeaa9e423aa69ab4218fc --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/sift.py @@ -0,0 +1,771 @@ +import math + +import numpy as np +import scipy.ndimage as ndi + +from .._shared.utils import check_nD, _supported_float_type +from ..feature.util import DescriptorExtractor, FeatureDetector +from .._shared.filters import gaussian +from ..transform import rescale +from ..util import img_as_float +from ._sift import _local_max, _ori_distances, _update_histogram + + +def _edgeness(hxx, hyy, hxy): + """Compute edgeness (eq. 18 of Otero et. al. IPOL paper)""" + trace = hxx + hyy + determinant = hxx * hyy - hxy * hxy + return (trace * trace) / determinant + + +def _sparse_gradient(vol, positions): + """Gradient of a 3D volume at the provided `positions`. + + For SIFT we only need the gradient at specific positions and do not need + the gradient at the edge positions, so can just use this simple + implementation instead of numpy.gradient. + """ + p0 = positions[..., 0] + p1 = positions[..., 1] + p2 = positions[..., 2] + g0 = vol[p0 + 1, p1, p2] - vol[p0 - 1, p1, p2] + g0 *= 0.5 + g1 = vol[p0, p1 + 1, p2] - vol[p0, p1 - 1, p2] + g1 *= 0.5 + g2 = vol[p0, p1, p2 + 1] - vol[p0, p1, p2 - 1] + g2 *= 0.5 + return g0, g1, g2 + + +def _hessian(d, positions): + """Compute the non-redundant 3D Hessian terms at the requested positions. + + Source: "Anatomy of the SIFT Method" p.380 (13) + """ + p0 = positions[..., 0] + p1 = positions[..., 1] + p2 = positions[..., 2] + two_d0 = 2 * d[p0, p1, p2] + # 0 = row, 1 = col, 2 = octave + h00 = d[p0 - 1, p1, p2] + d[p0 + 1, p1, p2] - two_d0 + h11 = d[p0, p1 - 1, p2] + d[p0, p1 + 1, p2] - two_d0 + h22 = d[p0, p1, p2 - 1] + d[p0, p1, p2 + 1] - two_d0 + h01 = 0.25 * ( + d[p0 + 1, p1 + 1, p2] + - d[p0 - 1, p1 + 1, p2] + - d[p0 + 1, p1 - 1, p2] + + d[p0 - 1, p1 - 1, p2] + ) + h02 = 0.25 * ( + d[p0 + 1, p1, p2 + 1] + - d[p0 + 1, p1, p2 - 1] + + d[p0 - 1, p1, p2 - 1] + - d[p0 - 1, p1, p2 + 1] + ) + h12 = 0.25 * ( + d[p0, p1 + 1, p2 + 1] + - d[p0, p1 + 1, p2 - 1] + + d[p0, p1 - 1, p2 - 1] + - d[p0, p1 - 1, p2 + 1] + ) + return (h00, h11, h22, h01, h02, h12) + + +def _offsets(grad, hess): + """Compute position refinement offsets from gradient and Hessian. + + This is equivalent to np.linalg.solve(-H, J) where H is the Hessian + matrix and J is the gradient (Jacobian). + + This analytical solution is adapted from (BSD-licensed) C code by + Otero et. al (see SIFT docstring References). + """ + h00, h11, h22, h01, h02, h12 = hess + g0, g1, g2 = grad + det = h00 * h11 * h22 + det -= h00 * h12 * h12 + det -= h01 * h01 * h22 + det += 2 * h01 * h02 * h12 + det -= h02 * h02 * h11 + aa = (h11 * h22 - h12 * h12) / det + ab = (h02 * h12 - h01 * h22) / det + ac = (h01 * h12 - h02 * h11) / det + bb = (h00 * h22 - h02 * h02) / det + bc = (h01 * h02 - h00 * h12) / det + cc = (h00 * h11 - h01 * h01) / det + offset0 = -aa * g0 - ab * g1 - ac * g2 + offset1 = -ab * g0 - bb * g1 - bc * g2 + offset2 = -ac * g0 - bc * g1 - cc * g2 + return np.stack((offset0, offset1, offset2), axis=-1) + + +class SIFT(FeatureDetector, DescriptorExtractor): + """SIFT feature detection and descriptor extraction. + + Parameters + ---------- + upsampling : int, optional + Prior to the feature detection the image is upscaled by a factor + of 1 (no upscaling), 2 or 4. Method: Bi-cubic interpolation. + n_octaves : int, optional + Maximum number of octaves. With every octave the image size is + halved and the sigma doubled. The number of octaves will be + reduced as needed to keep at least 12 pixels along each dimension + at the smallest scale. + n_scales : int, optional + Maximum number of scales in every octave. + sigma_min : float, optional + The blur level of the seed image. If upsampling is enabled + sigma_min is scaled by factor 1/upsampling + sigma_in : float, optional + The assumed blur level of the input image. + c_dog : float, optional + Threshold to discard low contrast extrema in the DoG. It's final + value is dependent on n_scales by the relation: + final_c_dog = (2^(1/n_scales)-1) / (2^(1/3)-1) * c_dog + c_edge : float, optional + Threshold to discard extrema that lie in edges. If H is the + Hessian of an extremum, its "edgeness" is described by + tr(H)²/det(H). If the edgeness is higher than + (c_edge + 1)²/c_edge, the extremum is discarded. + n_bins : int, optional + Number of bins in the histogram that describes the gradient + orientations around keypoint. + lambda_ori : float, optional + The window used to find the reference orientation of a keypoint + has a width of 6 * lambda_ori * sigma and is weighted by a + standard deviation of 2 * lambda_ori * sigma. + c_max : float, optional + The threshold at which a secondary peak in the orientation + histogram is accepted as orientation + lambda_descr : float, optional + The window used to define the descriptor of a keypoint has a width + of 2 * lambda_descr * sigma * (n_hist+1)/n_hist and is weighted by + a standard deviation of lambda_descr * sigma. + n_hist : int, optional + The window used to define the descriptor of a keypoint consists of + n_hist * n_hist histograms. + n_ori : int, optional + The number of bins in the histograms of the descriptor patch. + + Attributes + ---------- + delta_min : float + The sampling distance of the first octave. It's final value is + 1/upsampling. + float_dtype : type + The datatype of the image. + scalespace_sigmas : (n_octaves, n_scales + 3) array + The sigma value of all scales in all octaves. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + positions : (N, 2) array + Subpixel-precision keypoint coordinates as ``(row, col)``. + sigmas : (N,) array + The corresponding sigma (blur) value of a keypoint. + scales : (N,) array + The corresponding scale of a keypoint. + orientations : (N,) array + The orientations of the gradient around every keypoint. + octaves : (N,) array + The corresponding octave of a keypoint. + descriptors : (N, n_hist*n_hist*n_ori) array + The descriptors of a keypoint. + + Notes + ----- + The SIFT algorithm was developed by David Lowe [1]_, [2]_ and later + patented by the University of British Columbia. Since the patent expired in + 2020 it's free to use. The implementation here closely follows the + detailed description in [3]_, including use of the same default parameters. + + References + ---------- + .. [1] D.G. Lowe. "Object recognition from local scale-invariant + features", Proceedings of the Seventh IEEE International + Conference on Computer Vision, 1999, vol.2, pp. 1150-1157. + :DOI:`10.1109/ICCV.1999.790410` + + .. [2] D.G. Lowe. "Distinctive Image Features from Scale-Invariant + Keypoints", International Journal of Computer Vision, 2004, + vol. 60, pp. 91–110. + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + .. [3] I. R. Otero and M. Delbracio. "Anatomy of the SIFT Method", + Image Processing On Line, 4 (2014), pp. 370–396. + :DOI:`10.5201/ipol.2014.82` + + Examples + -------- + >>> from skimage.feature import SIFT, match_descriptors + >>> from skimage.data import camera + >>> from skimage.transform import rotate + >>> img1 = camera() + >>> img2 = rotate(camera(), 90) + >>> detector_extractor1 = SIFT() + >>> detector_extractor2 = SIFT() + >>> detector_extractor1.detect_and_extract(img1) + >>> detector_extractor2.detect_and_extract(img2) + >>> matches = match_descriptors(detector_extractor1.descriptors, + ... detector_extractor2.descriptors, + ... max_ratio=0.6) + >>> matches[10:15] + array([[ 10, 412], + [ 11, 417], + [ 12, 407], + [ 13, 411], + [ 14, 406]]) + >>> detector_extractor1.keypoints[matches[10:15, 0]] + array([[ 95, 214], + [ 97, 211], + [ 97, 218], + [102, 215], + [104, 218]]) + >>> detector_extractor2.keypoints[matches[10:15, 1]] + array([[297, 95], + [301, 97], + [294, 97], + [297, 102], + [293, 104]]) + + """ + + def __init__( + self, + upsampling=2, + n_octaves=8, + n_scales=3, + sigma_min=1.6, + sigma_in=0.5, + c_dog=0.04 / 3, + c_edge=10, + n_bins=36, + lambda_ori=1.5, + c_max=0.8, + lambda_descr=6, + n_hist=4, + n_ori=8, + ): + if upsampling in [1, 2, 4]: + self.upsampling = upsampling + else: + raise ValueError("upsampling must be 1, 2 or 4") + self.n_octaves = n_octaves + self.n_scales = n_scales + self.sigma_min = sigma_min / upsampling + self.sigma_in = sigma_in + self.c_dog = (2 ** (1 / n_scales) - 1) / (2 ** (1 / 3) - 1) * c_dog + self.c_edge = c_edge + self.n_bins = n_bins + self.lambda_ori = lambda_ori + self.c_max = c_max + self.lambda_descr = lambda_descr + self.n_hist = n_hist + self.n_ori = n_ori + self.delta_min = 1 / upsampling + self.float_dtype = None + self.scalespace_sigmas = None + self.keypoints = None + self.positions = None + self.sigmas = None + self.scales = None + self.orientations = None + self.octaves = None + self.descriptors = None + + @property + def deltas(self): + """The sampling distances of all octaves""" + deltas = self.delta_min * np.power( + 2, np.arange(self.n_octaves), dtype=self.float_dtype + ) + return deltas + + def _set_number_of_octaves(self, image_shape): + size_min = 12 # minimum size of last octave + s0 = min(image_shape) * self.upsampling + max_octaves = int(math.log2(s0 / size_min) + 1) + if max_octaves < self.n_octaves: + self.n_octaves = max_octaves + + def _create_scalespace(self, image): + """Source: "Anatomy of the SIFT Method" Alg. 1 + Construction of the scalespace by gradually blurring (scales) and + downscaling (octaves) the image. + """ + scalespace = [] + if self.upsampling > 1: + image = rescale(image, self.upsampling, order=1) + + # smooth to sigma_min, assuming sigma_in + image = gaussian( + image, + sigma=self.upsampling * math.sqrt(self.sigma_min**2 - self.sigma_in**2), + mode='reflect', + ) + + # Eq. 10: sigmas.shape = (n_octaves, n_scales + 3). + # The three extra scales are: + # One for the differences needed for DoG and two auxiliary + # images (one at either end) for peak_local_max with exclude + # border = True (see Fig. 5) + # The smoothing doubles after n_scales steps. + tmp = np.power(2, np.arange(self.n_scales + 3) / self.n_scales) + tmp *= self.sigma_min + # all sigmas for the gaussian scalespace + sigmas = self.deltas[:, np.newaxis] / self.deltas[0] * tmp[np.newaxis, :] + self.scalespace_sigmas = sigmas + + # Eq. 7: Gaussian smoothing depends on difference with previous sigma + # gaussian_sigmas.shape = (n_octaves, n_scales + 2) + var_diff = np.diff(sigmas * sigmas, axis=1) + gaussian_sigmas = np.sqrt(var_diff) / self.deltas[:, np.newaxis] + + # one octave is represented by a 3D image with depth (n_scales+x) + for o in range(self.n_octaves): + # Temporarily put scales axis first so octave[i] is C-contiguous + # (this makes Gaussian filtering faster). + octave = np.empty( + (self.n_scales + 3,) + image.shape, dtype=self.float_dtype, order='C' + ) + octave[0] = image + for s in range(1, self.n_scales + 3): + # blur new scale assuming sigma of the last one + gaussian( + octave[s - 1], + sigma=gaussian_sigmas[o, s - 1], + mode='reflect', + out=octave[s], + ) + # move scales to last axis as expected by other methods + scalespace.append(np.moveaxis(octave, 0, -1)) + if o < self.n_octaves - 1: + # downscale the image by taking every second pixel + image = octave[self.n_scales][::2, ::2] + return scalespace + + def _inrange(self, a, dim): + return ( + (a[:, 0] > 0) + & (a[:, 0] < dim[0] - 1) + & (a[:, 1] > 0) + & (a[:, 1] < dim[1] - 1) + ) + + def _find_localize_evaluate(self, dogspace, img_shape): + """Source: "Anatomy of the SIFT Method" Alg. 4-9 + 1) first find all extrema of a (3, 3, 3) neighborhood + 2) use second order Taylor development to refine the positions to + sub-pixel precision + 3) filter out extrema that have low contrast and lie on edges or close + to the image borders + """ + extrema_pos = [] + extrema_scales = [] + extrema_sigmas = [] + threshold = self.c_dog * 0.8 + for o, (octave, delta) in enumerate(zip(dogspace, self.deltas)): + # find extrema + keys = _local_max(np.ascontiguousarray(octave), threshold) + if keys.size == 0: + extrema_pos.append(np.empty((0, 2))) + continue + + # localize extrema + oshape = octave.shape + refinement_iterations = 5 + offset_max = 0.6 + for i in range(refinement_iterations): + if i > 0: + # exclude any keys that have moved out of bounds + keys = keys[self._inrange(keys, oshape), :] + + # Jacobian and Hessian of all extrema + grad = _sparse_gradient(octave, keys) + hess = _hessian(octave, keys) + + # solve for offset of the extremum + off = _offsets(grad, hess) + if i == refinement_iterations - 1: + break + # offset is too big and an increase would not bring us out of + # bounds + wrong_position_pos = np.logical_and( + off > offset_max, keys + 1 < tuple([a - 1 for a in oshape]) + ) + wrong_position_neg = np.logical_and(off < -offset_max, keys - 1 > 0) + if not np.any(np.logical_or(wrong_position_neg, wrong_position_pos)): + break + keys[wrong_position_pos] += 1 + keys[wrong_position_neg] -= 1 + + # mask for all extrema that have been localized successfully + finished = np.all(np.abs(off) < offset_max, axis=1) + keys = keys[finished] + off = off[finished] + grad = [g[finished] for g in grad] + + # value of extremum in octave + vals = octave[keys[:, 0], keys[:, 1], keys[:, 2]] + # values at interpolated point + w = vals + for i in range(3): + w += 0.5 * grad[i] * off[:, i] + + h00, h11, h01 = hess[0][finished], hess[1][finished], hess[3][finished] + + sigmaratio = self.scalespace_sigmas[0, 1] / self.scalespace_sigmas[0, 0] + + # filter for contrast, edgeness and borders + contrast_threshold = self.c_dog + contrast_filter = np.abs(w) > contrast_threshold + + edge_threshold = np.square(self.c_edge + 1) / self.c_edge + edge_response = _edgeness( + h00[contrast_filter], h11[contrast_filter], h01[contrast_filter] + ) + edge_filter = np.abs(edge_response) <= edge_threshold + + keys = keys[contrast_filter][edge_filter] + off = off[contrast_filter][edge_filter] + yx = ((keys[:, :2] + off[:, :2]) * delta).astype(self.float_dtype) + + sigmas = self.scalespace_sigmas[o, keys[:, 2]] * np.power( + sigmaratio, off[:, 2] + ) + border_filter = np.all( + np.logical_and( + (yx - sigmas[:, np.newaxis]) > 0.0, + (yx + sigmas[:, np.newaxis]) < img_shape, + ), + axis=1, + ) + extrema_pos.append(yx[border_filter]) + extrema_scales.append(keys[border_filter, 2]) + extrema_sigmas.append(sigmas[border_filter]) + + octave_indices = np.concatenate( + [np.full(len(p), i) for i, p in enumerate(extrema_pos)] + ) + + if len(octave_indices) == 0: + raise RuntimeError( + "SIFT found no features. Try passing in an image containing " + "greater intensity contrasts between adjacent pixels." + ) + + extrema_pos = np.concatenate(extrema_pos) + extrema_scales = np.concatenate(extrema_scales) + extrema_sigmas = np.concatenate(extrema_sigmas) + return extrema_pos, extrema_scales, extrema_sigmas, octave_indices + + def _fit(self, h): + """Refine the position of the peak by fitting it to a parabola""" + return (h[0] - h[2]) / (2 * (h[0] + h[2] - 2 * h[1])) + + def _compute_orientation( + self, positions_oct, scales_oct, sigmas_oct, octaves, gaussian_scalespace + ): + """Source: "Anatomy of the SIFT Method" Alg. 11 + Calculates the orientation of the gradient around every keypoint + """ + gradient_space = [] + # list for keypoints that have more than one reference orientation + keypoint_indices = [] + keypoint_angles = [] + keypoint_octave = [] + orientations = np.zeros_like(sigmas_oct, dtype=self.float_dtype) + key_count = 0 + for o, (octave, delta) in enumerate(zip(gaussian_scalespace, self.deltas)): + gradient_space.append(np.gradient(octave)) + + in_oct = octaves == o + if not np.any(in_oct): + continue + positions = positions_oct[in_oct] + scales = scales_oct[in_oct] + sigmas = sigmas_oct[in_oct] + + oshape = octave.shape[:2] + # convert to octave's dimensions + yx = positions / delta + sigma = sigmas / delta + + # dimensions of the patch + radius = 3 * self.lambda_ori * sigma + p_min = np.maximum(0, yx - radius[:, np.newaxis] + 0.5).astype(int) + p_max = np.minimum( + yx + radius[:, np.newaxis] + 0.5, (oshape[0] - 1, oshape[1] - 1) + ).astype(int) + # orientation histogram + hist = np.empty(self.n_bins, dtype=self.float_dtype) + avg_kernel = np.full((3,), 1 / 3, dtype=self.float_dtype) + for k in range(len(yx)): + hist[:] = 0 + + # use the patch coordinates to get the gradient and then + # normalize them + r, c = np.meshgrid( + np.arange(p_min[k, 0], p_max[k, 0] + 1), + np.arange(p_min[k, 1], p_max[k, 1] + 1), + indexing='ij', + sparse=True, + ) + gradient_row = gradient_space[o][0][r, c, scales[k]] + gradient_col = gradient_space[o][1][r, c, scales[k]] + r = r.astype(self.float_dtype, copy=False) + c = c.astype(self.float_dtype, copy=False) + r -= yx[k, 0] + c -= yx[k, 1] + + # gradient magnitude and angles + magnitude = np.sqrt(np.square(gradient_row) + np.square(gradient_col)) + theta = np.mod(np.arctan2(gradient_col, gradient_row), 2 * np.pi) + + # more weight to center values + kernel = np.exp( + np.divide(r * r + c * c, -2 * (self.lambda_ori * sigma[k]) ** 2) + ) + + # fill the histogram + bins = np.floor( + (theta / (2 * np.pi) * self.n_bins + 0.5) % self.n_bins + ).astype(int) + np.add.at(hist, bins, kernel * magnitude) + + # smooth the histogram and find the maximum + hist = np.concatenate((hist[-6:], hist, hist[:6])) + for _ in range(6): # number of smoothings + hist = np.convolve(hist, avg_kernel, mode='same') + hist = hist[6:-6] + max_filter = ndi.maximum_filter(hist, [3], mode='wrap') + + # if an angle is in 80% percent range of the maximum, a + # new keypoint is created for it + maxima = np.nonzero( + np.logical_and( + hist >= (self.c_max * np.max(hist)), max_filter == hist + ) + ) + + # save the angles + for c, m in enumerate(maxima[0]): + neigh = np.arange(m - 1, m + 2) % len(hist) + # use neighbors to fit a parabola, to get more accurate + # result + ori = (m + self._fit(hist[neigh]) + 0.5) * 2 * np.pi / self.n_bins + if ori > np.pi: + ori -= 2 * np.pi + if c == 0: + orientations[key_count] = ori + else: + keypoint_indices.append(key_count) + keypoint_angles.append(ori) + keypoint_octave.append(o) + key_count += 1 + self.positions = np.concatenate( + (positions_oct, positions_oct[keypoint_indices]) + ) + self.scales = np.concatenate((scales_oct, scales_oct[keypoint_indices])) + self.sigmas = np.concatenate((sigmas_oct, sigmas_oct[keypoint_indices])) + self.orientations = np.concatenate((orientations, keypoint_angles)) + self.octaves = np.concatenate((octaves, keypoint_octave)) + # return the gradient_space to reuse it to find the descriptor + return gradient_space + + def _rotate(self, row, col, angle): + c = math.cos(angle) + s = math.sin(angle) + rot_row = c * row + s * col + rot_col = -s * row + c * col + return rot_row, rot_col + + def _compute_descriptor(self, gradient_space): + """Source: "Anatomy of the SIFT Method" Alg. 12 + Calculates the descriptor for every keypoint + """ + n_key = len(self.scales) + self.descriptors = np.empty( + (n_key, self.n_hist**2 * self.n_ori), dtype=np.uint8 + ) + + # indices of the histograms + hists = np.arange(1, self.n_hist + 1, dtype=self.float_dtype) + # indices of the bins + bins = np.arange(1, self.n_ori + 1, dtype=self.float_dtype) + + key_numbers = np.arange(n_key) + for o, (gradient, delta) in enumerate(zip(gradient_space, self.deltas)): + in_oct = self.octaves == o + if not np.any(in_oct): + continue + positions = self.positions[in_oct] + scales = self.scales[in_oct] + sigmas = self.sigmas[in_oct] + orientations = self.orientations[in_oct] + numbers = key_numbers[in_oct] + + dim = gradient[0].shape[:2] + center_pos = positions / delta + sigma = sigmas / delta + + # dimensions of the patch + radius = self.lambda_descr * (1 + 1 / self.n_hist) * sigma + radius_patch = math.sqrt(2) * radius + p_min = np.asarray( + np.maximum(0, center_pos - radius_patch[:, np.newaxis] + 0.5), dtype=int + ) + p_max = np.asarray( + np.minimum( + center_pos + radius_patch[:, np.newaxis] + 0.5, + (dim[0] - 1, dim[1] - 1), + ), + dtype=int, + ) + + for k in range(len(p_max)): + rad_k = float(radius[k]) + ori = float(orientations[k]) + histograms = np.zeros( + (self.n_hist, self.n_hist, self.n_ori), dtype=self.float_dtype + ) + # the patch + r, c = np.meshgrid( + np.arange(p_min[k, 0], p_max[k, 0]), + np.arange(p_min[k, 1], p_max[k, 1]), + indexing='ij', + sparse=True, + ) + # normalized coordinates + r_norm = np.subtract(r, center_pos[k, 0], dtype=self.float_dtype) + c_norm = np.subtract(c, center_pos[k, 1], dtype=self.float_dtype) + r_norm, c_norm = self._rotate(r_norm, c_norm, ori) + + # select coordinates and gradient values within the patch + inside = np.maximum(np.abs(r_norm), np.abs(c_norm)) < rad_k + r_norm, c_norm = r_norm[inside], c_norm[inside] + r_idx, c_idx = np.nonzero(inside) + r = r[r_idx, 0] + c = c[0, c_idx] + gradient_row = gradient[0][r, c, scales[k]] + gradient_col = gradient[1][r, c, scales[k]] + # compute the (relative) gradient orientation + theta = np.arctan2(gradient_col, gradient_row) - ori + lam_sig = self.lambda_descr * float(sigma[k]) + # Gaussian weighted kernel magnitude + kernel = np.exp((r_norm * r_norm + c_norm * c_norm) / (-2 * lam_sig**2)) + magnitude = ( + np.sqrt(gradient_row * gradient_row + gradient_col * gradient_col) + * kernel + ) + + lam_sig_ratio = 2 * lam_sig / self.n_hist + rc_bins = (hists - (1 + self.n_hist) / 2) * lam_sig_ratio + rc_bin_spacing = lam_sig_ratio + ori_bins = (2 * np.pi * bins) / self.n_ori + + # distances to the histograms and bins + dist_r = np.abs(np.subtract.outer(rc_bins, r_norm)) + dist_c = np.abs(np.subtract.outer(rc_bins, c_norm)) + + # the orientation histograms/bins that get the contribution + near_t, near_t_val = _ori_distances(ori_bins, theta) + + # create the histogram + _update_histogram( + histograms, + near_t, + near_t_val, + magnitude, + dist_r, + dist_c, + rc_bin_spacing, + ) + + # convert the histograms to a 1d descriptor + histograms = histograms.reshape(-1) + # saturate the descriptor + histograms = np.minimum(histograms, 0.2 * np.linalg.norm(histograms)) + # normalize the descriptor + descriptor = (512 * histograms) / np.linalg.norm(histograms) + # quantize the descriptor + descriptor = np.minimum(np.floor(descriptor), 255) + self.descriptors[numbers[k], :] = descriptor + + def _preprocess(self, image): + check_nD(image, 2) + image = img_as_float(image) + self.float_dtype = _supported_float_type(image.dtype) + image = image.astype(self.float_dtype, copy=False) + + self._set_number_of_octaves(image.shape) + return image + + def detect(self, image): + """Detect the keypoints. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + dog_scalespace = [np.diff(layer, axis=2) for layer in gaussian_scalespace] + + positions, scales, sigmas, octaves = self._find_localize_evaluate( + dog_scalespace, image.shape + ) + + self._compute_orientation( + positions, scales, sigmas, octaves, gaussian_scalespace + ) + + self.keypoints = self.positions.round().astype(int) + + def extract(self, image): + """Extract the descriptors for all keypoints in the image. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + gradient_space = [np.gradient(octave) for octave in gaussian_scalespace] + + self._compute_descriptor(gradient_space) + + def detect_and_extract(self, image): + """Detect the keypoints and extract their descriptors. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + dog_scalespace = [np.diff(layer, axis=2) for layer in gaussian_scalespace] + + positions, scales, sigmas, octaves = self._find_localize_evaluate( + dog_scalespace, image.shape + ) + + gradient_space = self._compute_orientation( + positions, scales, sigmas, octaves, gaussian_scalespace + ) + + self._compute_descriptor(gradient_space) + + self.keypoints = self.positions.round().astype(int) diff --git a/python_embeded/Lib/site-packages/skimage/feature/template.py b/python_embeded/Lib/site-packages/skimage/feature/template.py new file mode 100644 index 0000000000000000000000000000000000000000..f1361ad296adf9b7085d5eea7b0e3e47efadf91b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/template.py @@ -0,0 +1,186 @@ +import math + +import numpy as np +from scipy.signal import fftconvolve + +from .._shared.utils import check_nD, _supported_float_type + + +def _window_sum_2d(image, window_shape): + window_sum = np.cumsum(image, axis=0) + window_sum = window_sum[window_shape[0] : -1] - window_sum[: -window_shape[0] - 1] + + window_sum = np.cumsum(window_sum, axis=1) + window_sum = ( + window_sum[:, window_shape[1] : -1] - window_sum[:, : -window_shape[1] - 1] + ) + + return window_sum + + +def _window_sum_3d(image, window_shape): + window_sum = _window_sum_2d(image, window_shape) + + window_sum = np.cumsum(window_sum, axis=2) + window_sum = ( + window_sum[:, :, window_shape[2] : -1] + - window_sum[:, :, : -window_shape[2] - 1] + ) + + return window_sum + + +def match_template( + image, template, pad_input=False, mode='constant', constant_values=0 +): + """Match a template to a 2-D or 3-D image using normalized correlation. + + The output is an array with values between -1.0 and 1.0. The value at a + given position corresponds to the correlation coefficient between the image + and the template. + + For `pad_input=True` matches correspond to the center and otherwise to the + top-left corner of the template. To find the best match you must search for + peaks in the response (output) image. + + Parameters + ---------- + image : (M, N[, P]) array + 2-D or 3-D input image. + template : (m, n[, p]) array + Template to locate. It must be `(m <= M, n <= N[, p <= P])`. + pad_input : bool + If True, pad `image` so that output is the same size as the image, and + output values correspond to the template center. Otherwise, the output + is an array with shape `(M - m + 1, N - n + 1)` for an `(M, N)` image + and an `(m, n)` template, and matches correspond to origin + (top-left corner) of the template. + mode : see `numpy.pad`, optional + Padding mode. + constant_values : see `numpy.pad`, optional + Constant values used in conjunction with ``mode='constant'``. + + Returns + ------- + output : array + Response image with correlation coefficients. + + Notes + ----- + Details on the cross-correlation are presented in [1]_. This implementation + uses FFT convolutions of the image and the template. Reference [2]_ + presents similar derivations but the approximation presented in this + reference is not used in our implementation. + + References + ---------- + .. [1] J. P. Lewis, "Fast Normalized Cross-Correlation", Industrial Light + and Magic. + .. [2] Briechle and Hanebeck, "Template Matching using Fast Normalized + Cross Correlation", Proceedings of the SPIE (2001). + :DOI:`10.1117/12.421129` + + Examples + -------- + >>> template = np.zeros((3, 3)) + >>> template[1, 1] = 1 + >>> template + array([[0., 0., 0.], + [0., 1., 0.], + [0., 0., 0.]]) + >>> image = np.zeros((6, 6)) + >>> image[1, 1] = 1 + >>> image[4, 4] = -1 + >>> image + array([[ 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., -1., 0.], + [ 0., 0., 0., 0., 0., 0.]]) + >>> result = match_template(image, template) + >>> np.round(result, 3) + array([[ 1. , -0.125, 0. , 0. ], + [-0.125, -0.125, 0. , 0. ], + [ 0. , 0. , 0.125, 0.125], + [ 0. , 0. , 0.125, -1. ]]) + >>> result = match_template(image, template, pad_input=True) + >>> np.round(result, 3) + array([[-0.125, -0.125, -0.125, 0. , 0. , 0. ], + [-0.125, 1. , -0.125, 0. , 0. , 0. ], + [-0.125, -0.125, -0.125, 0. , 0. , 0. ], + [ 0. , 0. , 0. , 0.125, 0.125, 0.125], + [ 0. , 0. , 0. , 0.125, -1. , 0.125], + [ 0. , 0. , 0. , 0.125, 0.125, 0.125]]) + """ + check_nD(image, (2, 3)) + + if image.ndim < template.ndim: + raise ValueError( + "Dimensionality of template must be less than or " + "equal to the dimensionality of image." + ) + if np.any(np.less(image.shape, template.shape)): + raise ValueError("Image must be larger than template.") + + image_shape = image.shape + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + pad_width = tuple((width, width) for width in template.shape) + if mode == 'constant': + image = np.pad( + image, pad_width=pad_width, mode=mode, constant_values=constant_values + ) + else: + image = np.pad(image, pad_width=pad_width, mode=mode) + + # Use special case for 2-D images for much better performance in + # computation of integral images + if image.ndim == 2: + image_window_sum = _window_sum_2d(image, template.shape) + image_window_sum2 = _window_sum_2d(image**2, template.shape) + elif image.ndim == 3: + image_window_sum = _window_sum_3d(image, template.shape) + image_window_sum2 = _window_sum_3d(image**2, template.shape) + + template_mean = template.mean() + template_volume = math.prod(template.shape) + template_ssd = np.sum((template - template_mean) ** 2) + + if image.ndim == 2: + xcorr = fftconvolve(image, template[::-1, ::-1], mode="valid")[1:-1, 1:-1] + elif image.ndim == 3: + xcorr = fftconvolve(image, template[::-1, ::-1, ::-1], mode="valid")[ + 1:-1, 1:-1, 1:-1 + ] + + numerator = xcorr - image_window_sum * template_mean + + denominator = image_window_sum2 + np.multiply(image_window_sum, image_window_sum, out=image_window_sum) + np.divide(image_window_sum, template_volume, out=image_window_sum) + denominator -= image_window_sum + denominator *= template_ssd + np.maximum(denominator, 0, out=denominator) # sqrt of negative number not allowed + np.sqrt(denominator, out=denominator) + + response = np.zeros_like(xcorr, dtype=float_dtype) + + # avoid zero-division + mask = denominator > np.finfo(float_dtype).eps + + response[mask] = numerator[mask] / denominator[mask] + + slices = [] + for i in range(template.ndim): + if pad_input: + d0 = (template.shape[i] - 1) // 2 + d1 = d0 + image_shape[i] + else: + d0 = template.shape[i] - 1 + d1 = d0 + image_shape[i] - template.shape[i] + 1 + slices.append(slice(d0, d1)) + + return response[tuple(slices)] diff --git a/python_embeded/Lib/site-packages/skimage/feature/texture.py b/python_embeded/Lib/site-packages/skimage/feature/texture.py new file mode 100644 index 0000000000000000000000000000000000000000..c4de520606476744b7eff074943708dfe260b252 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/texture.py @@ -0,0 +1,562 @@ +""" +Methods to characterize image textures. +""" + +import warnings + +import numpy as np + +from .._shared.utils import check_nD +from ..color import gray2rgb +from ..util import img_as_float +from ._texture import _glcm_loop, _local_binary_pattern, _multiblock_lbp + + +def graycomatrix(image, distances, angles, levels=None, symmetric=False, normed=False): + """Calculate the gray-level co-occurrence matrix. + + A gray level co-occurrence matrix is a histogram of co-occurring + grayscale values at a given offset over an image. + + .. versionchanged:: 0.19 + `greymatrix` was renamed to `graymatrix` in 0.19. + + Parameters + ---------- + image : array_like + Integer typed input image. Only positive valued images are supported. + If type is other than uint8, the argument `levels` needs to be set. + distances : array_like + List of pixel pair distance offsets. + angles : array_like + List of pixel pair angles in radians. + levels : int, optional + The input image should contain integers in [0, `levels`-1], + where levels indicate the number of gray-levels counted + (typically 256 for an 8-bit image). This argument is required for + 16-bit images or higher and is typically the maximum of the image. + As the output matrix is at least `levels` x `levels`, it might + be preferable to use binning of the input image rather than + large values for `levels`. + symmetric : bool, optional + If True, the output matrix `P[:, :, d, theta]` is symmetric. This + is accomplished by ignoring the order of value pairs, so both + (i, j) and (j, i) are accumulated when (i, j) is encountered + for a given offset. The default is False. + normed : bool, optional + If True, normalize each matrix `P[:, :, d, theta]` by dividing + by the total number of accumulated co-occurrences for the given + offset. The elements of the resulting matrix sum to 1. The + default is False. + + Returns + ------- + P : 4-D ndarray + The gray-level co-occurrence histogram. The value + `P[i,j,d,theta]` is the number of times that gray-level `j` + occurs at a distance `d` and at an angle `theta` from + gray-level `i`. If `normed` is `False`, the output is of + type uint32, otherwise it is float64. The dimensions are: + levels x levels x number of distances x number of angles. + + References + ---------- + .. [1] M. Hall-Beyer, 2007. GLCM Texture: A Tutorial + https://prism.ucalgary.ca/handle/1880/51900 + DOI:`10.11575/PRISM/33280` + .. [2] R.M. Haralick, K. Shanmugam, and I. Dinstein, "Textural features for + image classification", IEEE Transactions on Systems, Man, and + Cybernetics, vol. SMC-3, no. 6, pp. 610-621, Nov. 1973. + :DOI:`10.1109/TSMC.1973.4309314` + .. [3] M. Nadler and E.P. Smith, Pattern Recognition Engineering, + Wiley-Interscience, 1993. + .. [4] Wikipedia, https://en.wikipedia.org/wiki/Co-occurrence_matrix + + + Examples + -------- + Compute 4 GLCMs using 1-pixel distance and 4 different angles. For example, + an angle of 0 radians refers to the neighboring pixel to the right; + pi/4 radians to the top-right diagonal neighbor; pi/2 radians to the pixel + above, and so forth. + + >>> image = np.array([[0, 0, 1, 1], + ... [0, 0, 1, 1], + ... [0, 2, 2, 2], + ... [2, 2, 3, 3]], dtype=np.uint8) + >>> result = graycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], + ... levels=4) + >>> result[:, :, 0, 0] + array([[2, 2, 1, 0], + [0, 2, 0, 0], + [0, 0, 3, 1], + [0, 0, 0, 1]], dtype=uint32) + >>> result[:, :, 0, 1] + array([[1, 1, 3, 0], + [0, 1, 1, 0], + [0, 0, 0, 2], + [0, 0, 0, 0]], dtype=uint32) + >>> result[:, :, 0, 2] + array([[3, 0, 2, 0], + [0, 2, 2, 0], + [0, 0, 1, 2], + [0, 0, 0, 0]], dtype=uint32) + >>> result[:, :, 0, 3] + array([[2, 0, 0, 0], + [1, 1, 2, 0], + [0, 0, 2, 1], + [0, 0, 0, 0]], dtype=uint32) + + """ + check_nD(image, 2) + check_nD(distances, 1, 'distances') + check_nD(angles, 1, 'angles') + + image = np.ascontiguousarray(image) + + image_max = image.max() + + if np.issubdtype(image.dtype, np.floating): + raise ValueError( + "Float images are not supported by graycomatrix. " + "Convert the image to an unsigned integer type." + ) + + # for image type > 8bit, levels must be set. + if image.dtype not in (np.uint8, np.int8) and levels is None: + raise ValueError( + "The levels argument is required for data types " + "other than uint8. The resulting matrix will be at " + "least levels ** 2 in size." + ) + + if np.issubdtype(image.dtype, np.signedinteger) and np.any(image < 0): + raise ValueError("Negative-valued images are not supported.") + + if levels is None: + levels = 256 + + if image_max >= levels: + raise ValueError( + "The maximum grayscale value in the image should be " + "smaller than the number of levels." + ) + + distances = np.ascontiguousarray(distances, dtype=np.float64) + angles = np.ascontiguousarray(angles, dtype=np.float64) + + P = np.zeros( + (levels, levels, len(distances), len(angles)), dtype=np.uint32, order='C' + ) + + # count co-occurences + _glcm_loop(image, distances, angles, levels, P) + + # make each GLMC symmetric + if symmetric: + Pt = np.transpose(P, (1, 0, 2, 3)) + P = P + Pt + + # normalize each GLCM + if normed: + P = P.astype(np.float64) + glcm_sums = np.sum(P, axis=(0, 1), keepdims=True) + glcm_sums[glcm_sums == 0] = 1 + P /= glcm_sums + + return P + + +def graycoprops(P, prop='contrast'): + """Calculate texture properties of a GLCM. + + Compute a feature of a gray level co-occurrence matrix to serve as + a compact summary of the matrix. The properties are computed as + follows: + + - 'contrast': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2` + - 'dissimilarity': :math:`\\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|` + - 'homogeneity': :math:`\\sum_{i,j=0}^{levels-1}\\frac{P_{i,j}}{1+(i-j)^2}` + - 'ASM': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}^2` + - 'energy': :math:`\\sqrt{ASM}` + - 'correlation': + .. math:: \\sum_{i,j=0}^{levels-1} P_{i,j}\\left[\\frac{(i-\\mu_i) \\ + (j-\\mu_j)}{\\sqrt{(\\sigma_i^2)(\\sigma_j^2)}}\\right] + - 'mean': :math:`\\sum_{i=0}^{levels-1} i*P_{i}` + - 'variance': :math:`\\sum_{i=0}^{levels-1} P_{i}*(i-mean)^2` + - 'std': :math:`\\sqrt{variance}` + - 'entropy': :math:`\\sum_{i,j=0}^{levels-1} -P_{i,j}*log(P_{i,j})` + + Each GLCM is normalized to have a sum of 1 before the computation of + texture properties. + + .. versionchanged:: 0.19 + `greycoprops` was renamed to `graycoprops` in 0.19. + + Parameters + ---------- + P : ndarray + Input array. `P` is the gray-level co-occurrence histogram + for which to compute the specified property. The value + `P[i,j,d,theta]` is the number of times that gray-level j + occurs at a distance d and at an angle theta from + gray-level i. + prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy', \ + 'correlation', 'ASM', 'mean', 'variance', 'std', 'entropy'}, optional + The property of the GLCM to compute. The default is 'contrast'. + + Returns + ------- + results : 2-D ndarray + 2-dimensional array. `results[d, a]` is the property 'prop' for + the d'th distance and the a'th angle. + + References + ---------- + .. [1] M. Hall-Beyer, 2007. GLCM Texture: A Tutorial v. 1.0 through 3.0. + The GLCM Tutorial Home Page, + https://prism.ucalgary.ca/handle/1880/51900 + DOI:`10.11575/PRISM/33280` + + Examples + -------- + Compute the contrast for GLCMs with distances [1, 2] and angles + [0 degrees, 90 degrees] + + >>> image = np.array([[0, 0, 1, 1], + ... [0, 0, 1, 1], + ... [0, 2, 2, 2], + ... [2, 2, 3, 3]], dtype=np.uint8) + >>> g = graycomatrix(image, [1, 2], [0, np.pi/2], levels=4, + ... normed=True, symmetric=True) + >>> contrast = graycoprops(g, 'contrast') + >>> contrast + array([[0.58333333, 1. ], + [1.25 , 2.75 ]]) + + """ + + def glcm_mean(): + I = np.arange(num_level).reshape((num_level, 1, 1, 1)) + mean = np.sum(I * P, axis=(0, 1)) + return I, mean + + check_nD(P, 4, 'P') + + (num_level, num_level2, num_dist, num_angle) = P.shape + if num_level != num_level2: + raise ValueError('num_level and num_level2 must be equal.') + if num_dist <= 0: + raise ValueError('num_dist must be positive.') + if num_angle <= 0: + raise ValueError('num_angle must be positive.') + + # normalize each GLCM + P = P.astype(np.float64) + glcm_sums = np.sum(P, axis=(0, 1), keepdims=True) + glcm_sums[glcm_sums == 0] = 1 + P /= glcm_sums + + # create weights for specified property + I, J = np.ogrid[0:num_level, 0:num_level] + if prop == 'contrast': + weights = (I - J) ** 2 + elif prop == 'dissimilarity': + weights = np.abs(I - J) + elif prop == 'homogeneity': + weights = 1.0 / (1.0 + (I - J) ** 2) + elif prop in ['ASM', 'energy', 'correlation', 'entropy', 'variance', 'mean', 'std']: + pass + else: + raise ValueError(f'{prop} is an invalid property') + + # compute property for each GLCM + if prop == 'energy': + asm = np.sum(P**2, axis=(0, 1)) + results = np.sqrt(asm) + elif prop == 'ASM': + results = np.sum(P**2, axis=(0, 1)) + elif prop == 'mean': + _, results = glcm_mean() + elif prop == 'variance': + I, mean = glcm_mean() + results = np.sum(P * ((I - mean) ** 2), axis=(0, 1)) + elif prop == 'std': + I, mean = glcm_mean() + var = np.sum(P * ((I - mean) ** 2), axis=(0, 1)) + results = np.sqrt(var) + elif prop == 'entropy': + ln = -np.log(P, where=(P != 0), out=np.zeros_like(P)) + results = np.sum(P * ln, axis=(0, 1)) + + elif prop == 'correlation': + results = np.zeros((num_dist, num_angle), dtype=np.float64) + I = np.array(range(num_level)).reshape((num_level, 1, 1, 1)) + J = np.array(range(num_level)).reshape((1, num_level, 1, 1)) + diff_i = I - np.sum(I * P, axis=(0, 1)) + diff_j = J - np.sum(J * P, axis=(0, 1)) + + std_i = np.sqrt(np.sum(P * (diff_i) ** 2, axis=(0, 1))) + std_j = np.sqrt(np.sum(P * (diff_j) ** 2, axis=(0, 1))) + cov = np.sum(P * (diff_i * diff_j), axis=(0, 1)) + + # handle the special case of standard deviations near zero + mask_0 = std_i < 1e-15 + mask_0[std_j < 1e-15] = True + results[mask_0] = 1 + + # handle the standard case + mask_1 = ~mask_0 + results[mask_1] = cov[mask_1] / (std_i[mask_1] * std_j[mask_1]) + elif prop in ['contrast', 'dissimilarity', 'homogeneity']: + weights = weights.reshape((num_level, num_level, 1, 1)) + results = np.sum(P * weights, axis=(0, 1)) + + return results + + +def local_binary_pattern(image, P, R, method='default'): + """Compute the local binary patterns (LBP) of an image. + + LBP is a visual descriptor often used in texture classification. + + Parameters + ---------- + image : (M, N) array + 2D grayscale image. + P : int + Number of circularly symmetric neighbor set points (quantization of + the angular space). + R : float + Radius of circle (spatial resolution of the operator). + method : str {'default', 'ror', 'uniform', 'nri_uniform', 'var'}, optional + Method to determine the pattern: + + ``default`` + Original local binary pattern which is grayscale invariant but not + rotation invariant. + ``ror`` + Extension of default pattern which is grayscale invariant and + rotation invariant. + ``uniform`` + Uniform pattern which is grayscale invariant and rotation + invariant, offering finer quantization of the angular space. + For details, see [1]_. + ``nri_uniform`` + Variant of uniform pattern which is grayscale invariant but not + rotation invariant. For details, see [2]_ and [3]_. + ``var`` + Variance of local image texture (related to contrast) + which is rotation invariant but not grayscale invariant. + + Returns + ------- + output : (M, N) array + LBP image. + + References + ---------- + .. [1] T. Ojala, M. Pietikainen, T. Maenpaa, "Multiresolution gray-scale + and rotation invariant texture classification with local binary + patterns", IEEE Transactions on Pattern Analysis and Machine + Intelligence, vol. 24, no. 7, pp. 971-987, July 2002 + :DOI:`10.1109/TPAMI.2002.1017623` + .. [2] T. Ahonen, A. Hadid and M. Pietikainen. "Face recognition with + local binary patterns", in Proc. Eighth European Conf. Computer + Vision, Prague, Czech Republic, May 11-14, 2004, pp. 469-481, 2004. + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851 + :DOI:`10.1007/978-3-540-24670-1_36` + .. [3] T. Ahonen, A. Hadid and M. Pietikainen, "Face Description with + Local Binary Patterns: Application to Face Recognition", + IEEE Transactions on Pattern Analysis and Machine Intelligence, + vol. 28, no. 12, pp. 2037-2041, Dec. 2006 + :DOI:`10.1109/TPAMI.2006.244` + """ + check_nD(image, 2) + + methods = { + 'default': ord('D'), + 'ror': ord('R'), + 'uniform': ord('U'), + 'nri_uniform': ord('N'), + 'var': ord('V'), + } + if np.issubdtype(image.dtype, np.floating): + warnings.warn( + "Applying `local_binary_pattern` to floating-point images may " + "give unexpected results when small numerical differences between " + "adjacent pixels are present. It is recommended to use this " + "function with images of integer dtype." + ) + image = np.ascontiguousarray(image, dtype=np.float64) + output = _local_binary_pattern(image, P, R, methods[method.lower()]) + return output + + +def multiblock_lbp(int_image, r, c, width, height): + """Multi-block local binary pattern (MB-LBP). + + The features are calculated similarly to local binary patterns (LBPs), + (See :py:meth:`local_binary_pattern`) except that summed blocks are + used instead of individual pixel values. + + MB-LBP is an extension of LBP that can be computed on multiple scales + in constant time using the integral image. Nine equally-sized rectangles + are used to compute a feature. For each rectangle, the sum of the pixel + intensities is computed. Comparisons of these sums to that of the central + rectangle determine the feature, similarly to LBP. + + Parameters + ---------- + int_image : (N, M) array + Integral image. + r : int + Row-coordinate of top left corner of a rectangle containing feature. + c : int + Column-coordinate of top left corner of a rectangle containing feature. + width : int + Width of one of the 9 equal rectangles that will be used to compute + a feature. + height : int + Height of one of the 9 equal rectangles that will be used to compute + a feature. + + Returns + ------- + output : int + 8-bit MB-LBP feature descriptor. + + References + ---------- + .. [1] L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. "Face Detection Based + on Multi-Block LBP Representation", In Proceedings: Advances in + Biometrics, International Conference, ICB 2007, Seoul, Korea. + http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf + :DOI:`10.1007/978-3-540-74549-5_2` + """ + + int_image = np.ascontiguousarray(int_image, dtype=np.float32) + lbp_code = _multiblock_lbp(int_image, r, c, width, height) + return lbp_code + + +def draw_multiblock_lbp( + image, + r, + c, + width, + height, + lbp_code=0, + color_greater_block=(1, 1, 1), + color_less_block=(0, 0.69, 0.96), + alpha=0.5, +): + """Multi-block local binary pattern visualization. + + Blocks with higher sums are colored with alpha-blended white rectangles, + whereas blocks with lower sums are colored alpha-blended cyan. Colors + and the `alpha` parameter can be changed. + + Parameters + ---------- + image : ndarray of float or uint + Image on which to visualize the pattern. + r : int + Row-coordinate of top left corner of a rectangle containing feature. + c : int + Column-coordinate of top left corner of a rectangle containing feature. + width : int + Width of one of 9 equal rectangles that will be used to compute + a feature. + height : int + Height of one of 9 equal rectangles that will be used to compute + a feature. + lbp_code : int + The descriptor of feature to visualize. If not provided, the + descriptor with 0 value will be used. + color_greater_block : tuple of 3 floats + Floats specifying the color for the block that has greater + intensity value. They should be in the range [0, 1]. + Corresponding values define (R, G, B) values. Default value + is white (1, 1, 1). + color_greater_block : tuple of 3 floats + Floats specifying the color for the block that has greater intensity + value. They should be in the range [0, 1]. Corresponding values define + (R, G, B) values. Default value is cyan (0, 0.69, 0.96). + alpha : float + Value in the range [0, 1] that specifies opacity of visualization. + 1 - fully transparent, 0 - opaque. + + Returns + ------- + output : ndarray of float + Image with MB-LBP visualization. + + References + ---------- + .. [1] L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. "Face Detection Based + on Multi-Block LBP Representation", In Proceedings: Advances in + Biometrics, International Conference, ICB 2007, Seoul, Korea. + http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf + :DOI:`10.1007/978-3-540-74549-5_2` + """ + + # Default colors for regions. + # White is for the blocks that are brighter. + # Cyan is for the blocks that has less intensity. + color_greater_block = np.asarray(color_greater_block, dtype=np.float64) + color_less_block = np.asarray(color_less_block, dtype=np.float64) + + # Copy array to avoid the changes to the original one. + output = np.copy(image) + + # As the visualization uses RGB color we need 3 bands. + if len(image.shape) < 3: + output = gray2rgb(image) + + # Colors are specified in floats. + output = img_as_float(output) + + # Offsets of neighbor rectangles relative to central one. + # It has order starting from top left and going clockwise. + neighbor_rect_offsets = ( + (-1, -1), + (-1, 0), + (-1, 1), + (0, 1), + (1, 1), + (1, 0), + (1, -1), + (0, -1), + ) + + # Pre-multiply the offsets with width and height. + neighbor_rect_offsets = np.array(neighbor_rect_offsets) + neighbor_rect_offsets[:, 0] *= height + neighbor_rect_offsets[:, 1] *= width + + # Top-left coordinates of central rectangle. + central_rect_r = r + height + central_rect_c = c + width + + for element_num, offset in enumerate(neighbor_rect_offsets): + offset_r, offset_c = offset + + curr_r = central_rect_r + offset_r + curr_c = central_rect_c + offset_c + + has_greater_value = lbp_code & (1 << (7 - element_num)) + + # Mix-in the visualization colors. + if has_greater_value: + new_value = (1 - alpha) * output[ + curr_r : curr_r + height, curr_c : curr_c + width + ] + alpha * color_greater_block + output[curr_r : curr_r + height, curr_c : curr_c + width] = new_value + else: + new_value = (1 - alpha) * output[ + curr_r : curr_r + height, curr_c : curr_c + width + ] + alpha * color_less_block + output[curr_r : curr_r + height, curr_c : curr_c + width] = new_value + + return output diff --git a/python_embeded/Lib/site-packages/skimage/feature/util.py b/python_embeded/Lib/site-packages/skimage/feature/util.py new file mode 100644 index 0000000000000000000000000000000000000000..3a89dd2e86312c3493011853f06b561ca5a6c6eb --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/feature/util.py @@ -0,0 +1,232 @@ +import numpy as np + +from ..util import img_as_float +from .._shared.utils import ( + _supported_float_type, + check_nD, +) + + +class FeatureDetector: + def __init__(self): + self.keypoints_ = np.array([]) + + def detect(self, image): + """Detect keypoints in image. + + Parameters + ---------- + image : 2D array + Input image. + + """ + raise NotImplementedError() + + +class DescriptorExtractor: + def __init__(self): + self.descriptors_ = np.array([]) + + def extract(self, image, keypoints): + """Extract feature descriptors in image for given keypoints. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint locations as ``(row, col)``. + + """ + raise NotImplementedError() + + +def plot_matched_features( + image0, + image1, + *, + keypoints0, + keypoints1, + matches, + ax, + keypoints_color='k', + matches_color=None, + only_matches=False, + alignment='horizontal', +): + """Plot matched features between two images. + + .. versionadded:: 0.23 + + Parameters + ---------- + image0 : (N, M [, 3]) array + First image. + image1 : (N, M [, 3]) array + Second image. + keypoints0 : (K1, 2) array + First keypoint coordinates as ``(row, col)``. + keypoints1 : (K2, 2) array + Second keypoint coordinates as ``(row, col)``. + matches : (Q, 2) array + Indices of corresponding matches in first and second sets of + descriptors, where `matches[:, 0]` (resp. `matches[:, 1]`) contains + the indices in the first (resp. second) set of descriptors. + ax : matplotlib.axes.Axes + The Axes object where the images and their matched features are drawn. + keypoints_color : matplotlib color, optional + Color for keypoint locations. + matches_color : matplotlib color or sequence thereof, optional + Single color or sequence of colors for each line defined by `matches`, + which connect keypoint matches. See [1]_ for an overview of supported + color formats. By default, colors are picked randomly. + only_matches : bool, optional + Set to True to plot matches only and not the keypoint locations. + alignment : {'horizontal', 'vertical'}, optional + Whether to show the two images side by side (`'horizontal'`), or one above + the other (`'vertical'`). + + References + ---------- + .. [1] https://matplotlib.org/stable/users/explain/colors/colors.html#specifying-colors + + Notes + ----- + To make a sequence of colors passed to `matches_color` work for any number of + `matches`, you can wrap that sequence in :func:`itertools.cycle`. + """ + image0 = img_as_float(image0) + image1 = img_as_float(image1) + + new_shape0 = list(image0.shape) + new_shape1 = list(image1.shape) + + if image0.shape[0] < image1.shape[0]: + new_shape0[0] = image1.shape[0] + elif image0.shape[0] > image1.shape[0]: + new_shape1[0] = image0.shape[0] + + if image0.shape[1] < image1.shape[1]: + new_shape0[1] = image1.shape[1] + elif image0.shape[1] > image1.shape[1]: + new_shape1[1] = image0.shape[1] + + if new_shape0 != image0.shape: + new_image0 = np.zeros(new_shape0, dtype=image0.dtype) + new_image0[: image0.shape[0], : image0.shape[1]] = image0 + image0 = new_image0 + + if new_shape1 != image1.shape: + new_image1 = np.zeros(new_shape1, dtype=image1.dtype) + new_image1[: image1.shape[0], : image1.shape[1]] = image1 + image1 = new_image1 + + offset = np.array(image0.shape) + if alignment == 'horizontal': + image = np.concatenate([image0, image1], axis=1) + offset[0] = 0 + elif alignment == 'vertical': + image = np.concatenate([image0, image1], axis=0) + offset[1] = 0 + else: + mesg = ( + f"`plot_matched_features` accepts either 'horizontal' or 'vertical' for " + f"alignment, but '{alignment}' was given. See " + f"https://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.plot_matched_features " + f"for details." + ) + raise ValueError(mesg) + + if not only_matches: + ax.scatter( + keypoints0[:, 1], + keypoints0[:, 0], + facecolors='none', + edgecolors=keypoints_color, + ) + ax.scatter( + keypoints1[:, 1] + offset[1], + keypoints1[:, 0] + offset[0], + facecolors='none', + edgecolors=keypoints_color, + ) + + ax.imshow(image, cmap='gray') + ax.axis((0, image0.shape[1] + offset[1], image0.shape[0] + offset[0], 0)) + + number_of_matches = matches.shape[0] + + from matplotlib.colors import is_color_like + + if matches_color is None: + rng = np.random.default_rng(seed=0) + colors = [rng.random(3) for _ in range(number_of_matches)] + elif is_color_like(matches_color): + colors = [matches_color for _ in range(number_of_matches)] + elif hasattr(matches_color, "__len__") and len(matches_color) == number_of_matches: + # No need to check each color, matplotlib does so for us + colors = matches_color + else: + error_message = ( + '`matches_color` needs to be a single color ' + 'or a sequence of length equal to the number of matches.' + ) + raise ValueError(error_message) + + for i, match in enumerate(matches): + idx0, idx1 = match + ax.plot( + (keypoints0[idx0, 1], keypoints1[idx1, 1] + offset[1]), + (keypoints0[idx0, 0], keypoints1[idx1, 0] + offset[0]), + '-', + color=colors[i], + ) + + +def _prepare_grayscale_input_2D(image): + image = np.squeeze(image) + check_nD(image, 2) + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + return image.astype(float_dtype, copy=False) + + +def _prepare_grayscale_input_nD(image): + image = np.squeeze(image) + check_nD(image, range(2, 6)) + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + return image.astype(float_dtype, copy=False) + + +def _mask_border_keypoints(image_shape, keypoints, distance): + """Mask coordinates that are within certain distance from the image border. + + Parameters + ---------- + image_shape : (2,) array_like + Shape of the image as ``(rows, cols)``. + keypoints : (N, 2) array + Keypoint coordinates as ``(rows, cols)``. + distance : int + Image border distance. + + Returns + ------- + mask : (N,) bool array + Mask indicating if pixels are within the image (``True``) or in the + border region of the image (``False``). + + """ + + rows = image_shape[0] + cols = image_shape[1] + + mask = ( + ((distance - 1) < keypoints[:, 0]) + & (keypoints[:, 0] < (rows - distance + 1)) + & ((distance - 1) < keypoints[:, 1]) + & (keypoints[:, 1] < (cols - distance + 1)) + ) + + return mask diff --git a/python_embeded/Lib/site-packages/skimage/filters/__init__.py b/python_embeded/Lib/site-packages/skimage/filters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87b04fca03e8beb619ab58c4fc6df055bb499767 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/__init__.py @@ -0,0 +1,5 @@ +"""Sharpening, edge finding, rank filters, thresholding, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/filters/__init__.pyi b/python_embeded/Lib/site-packages/skimage/filters/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..02885e77eb467f67c75ddd1ada9b213854ed0054 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/__init__.pyi @@ -0,0 +1,109 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + "LPIFilter2D", + "apply_hysteresis_threshold", + "butterworth", + "correlate_sparse", + "difference_of_gaussians", + "farid", + "farid_h", + "farid_v", + "filter_inverse", + "filter_forward", + "frangi", + "gabor", + "gabor_kernel", + "gaussian", + "hessian", + "laplace", + "median", + "meijering", + "prewitt", + "prewitt_h", + "prewitt_v", + "rank", + "rank_order", + "roberts", + "roberts_neg_diag", + "roberts_pos_diag", + "sato", + "scharr", + "scharr_h", + "scharr_v", + "sobel", + "sobel_h", + "sobel_v", + "threshold_isodata", + "threshold_li", + "threshold_local", + "threshold_mean", + "threshold_minimum", + "threshold_multiotsu", + "threshold_niblack", + "threshold_otsu", + "threshold_sauvola", + "threshold_triangle", + "threshold_yen", + "try_all_threshold", + "unsharp_mask", + "wiener", + "window", +] + +from . import rank +from ._fft_based import butterworth +from ._gabor import gabor, gabor_kernel +from ._gaussian import difference_of_gaussians, gaussian +from ._median import median +from ._rank_order import rank_order +from ._sparse import correlate_sparse +from ._unsharp_mask import unsharp_mask +from ._window import window +from .edges import ( + farid, + farid_h, + farid_v, + laplace, + prewitt, + prewitt_h, + prewitt_v, + roberts, + roberts_neg_diag, + roberts_pos_diag, + scharr, + scharr_h, + scharr_v, + sobel, + sobel_h, + sobel_v, +) +from .lpi_filter import ( + LPIFilter2D, + filter_inverse, + filter_forward, + wiener, +) +from .ridges import ( + frangi, + hessian, + meijering, + sato, +) +from .thresholding import ( + apply_hysteresis_threshold, + threshold_isodata, + threshold_li, + threshold_local, + threshold_mean, + threshold_minimum, + threshold_multiotsu, + threshold_niblack, + threshold_otsu, + threshold_sauvola, + threshold_triangle, + threshold_yen, + try_all_threshold, +) diff --git a/python_embeded/Lib/site-packages/skimage/filters/_fft_based.py b/python_embeded/Lib/site-packages/skimage/filters/_fft_based.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d7630ea26872ee619f6acaabde468d79486c09 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_fft_based.py @@ -0,0 +1,189 @@ +import functools + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type + + +def _get_nd_butterworth_filter( + shape, factor, order, high_pass, real, dtype=np.float64, squared_butterworth=True +): + """Create a N-dimensional Butterworth mask for an FFT + + Parameters + ---------- + shape : tuple of int + Shape of the n-dimensional FFT and mask. + factor : float + Fraction of mask dimensions where the cutoff should be. + order : float + Controls the slope in the cutoff region. + high_pass : bool + Whether the filter is high pass (low frequencies attenuated) or + low pass (high frequencies are attenuated). + real : bool + Whether the FFT is of a real (True) or complex (False) image + squared_butterworth : bool, optional + When True, the square of the Butterworth filter is used. + + Returns + ------- + wfilt : ndarray + The FFT mask. + + """ + ranges = [] + for i, d in enumerate(shape): + # start and stop ensures center of mask aligns with center of FFT + axis = np.arange(-(d - 1) // 2, (d - 1) // 2 + 1) / (d * factor) + ranges.append(fft.ifftshift(axis**2)) + # for real image FFT, halve the last axis + if real: + limit = d // 2 + 1 + ranges[-1] = ranges[-1][:limit] + # q2 = squared Euclidean distance grid + q2 = functools.reduce(np.add, np.meshgrid(*ranges, indexing="ij", sparse=True)) + q2 = q2.astype(dtype) + q2 = np.power(q2, order) + wfilt = 1 / (1 + q2) + if high_pass: + wfilt *= q2 + if not squared_butterworth: + np.sqrt(wfilt, out=wfilt) + return wfilt + + +def butterworth( + image, + cutoff_frequency_ratio=0.005, + high_pass=True, + order=2.0, + channel_axis=None, + *, + squared_butterworth=True, + npad=0, +): + """Apply a Butterworth filter to enhance high or low frequency features. + + This filter is defined in the Fourier domain. + + Parameters + ---------- + image : (M[, N[, ..., P]][, C]) ndarray + Input image. + cutoff_frequency_ratio : float, optional + Determines the position of the cut-off relative to the shape of the + FFT. Receives a value between [0, 0.5]. + high_pass : bool, optional + Whether to perform a high pass filter. If False, a low pass filter is + performed. + order : float, optional + Order of the filter which affects the slope near the cut-off. Higher + order means steeper slope in frequency space. + channel_axis : int, optional + If there is a channel dimension, provide the index here. If None + (default) then all axes are assumed to be spatial dimensions. + squared_butterworth : bool, optional + When True, the square of a Butterworth filter is used. See notes below + for more details. + npad : int, optional + Pad each edge of the image by `npad` pixels using `numpy.pad`'s + ``mode='edge'`` extension. + + Returns + ------- + result : ndarray + The Butterworth-filtered image. + + Notes + ----- + A band-pass filter can be achieved by combining a high-pass and low-pass + filter. The user can increase `npad` if boundary artifacts are apparent. + + The "Butterworth filter" used in image processing textbooks (e.g. [1]_, + [2]_) is often the square of the traditional Butterworth filters as + described by [3]_, [4]_. The squared version will be used here if + `squared_butterworth` is set to ``True``. The lowpass, squared Butterworth + filter is given by the following expression for the lowpass case: + + .. math:: + H_{low}(f) = \\frac{1}{1 + \\left(\\frac{f}{c f_s}\\right)^{2n}} + + with the highpass case given by + + .. math:: + H_{hi}(f) = 1 - H_{low}(f) + + where :math:`f=\\sqrt{\\sum_{d=0}^{\\mathrm{ndim}} f_{d}^{2}}` is the + absolute value of the spatial frequency, :math:`f_s` is the sampling + frequency, :math:`c` the ``cutoff_frequency_ratio``, and :math:`n` is the + filter `order` [1]_. When ``squared_butterworth=False``, the square root of + the above expressions are used instead. + + Note that ``cutoff_frequency_ratio`` is defined in terms of the sampling + frequency, :math:`f_s`. The FFT spectrum covers the Nyquist range + (:math:`[-f_s/2, f_s/2]`) so ``cutoff_frequency_ratio`` should have a value + between 0 and 0.5. The frequency response (gain) at the cutoff is 0.5 when + ``squared_butterworth`` is true and :math:`1/\\sqrt{2}` when it is false. + + Examples + -------- + Apply a high-pass and low-pass Butterworth filter to a grayscale and + color image respectively: + + >>> from skimage.data import camera, astronaut + >>> from skimage.filters import butterworth + >>> high_pass = butterworth(camera(), 0.07, True, 8) + >>> low_pass = butterworth(astronaut(), 0.01, False, 4, channel_axis=-1) + + References + ---------- + .. [1] Russ, John C., et al. The Image Processing Handbook, 3rd. Ed. + 1999, CRC Press, LLC. + .. [2] Birchfield, Stan. Image Processing and Analysis. 2018. Cengage + Learning. + .. [3] Butterworth, Stephen. "On the theory of filter amplifiers." + Wireless Engineer 7.6 (1930): 536-541. + .. [4] https://en.wikipedia.org/wiki/Butterworth_filter + + """ + if npad < 0: + raise ValueError("npad must be >= 0") + elif npad > 0: + center_slice = tuple(slice(npad, s + npad) for s in image.shape) + image = np.pad(image, npad, mode='edge') + fft_shape = ( + image.shape if channel_axis is None else np.delete(image.shape, channel_axis) + ) + is_real = np.isrealobj(image) + float_dtype = _supported_float_type(image.dtype, allow_complex=True) + if cutoff_frequency_ratio < 0 or cutoff_frequency_ratio > 0.5: + raise ValueError("cutoff_frequency_ratio should be in the range [0, 0.5]") + wfilt = _get_nd_butterworth_filter( + fft_shape, + cutoff_frequency_ratio, + order, + high_pass, + is_real, + float_dtype, + squared_butterworth, + ) + axes = np.arange(image.ndim) + if channel_axis is not None: + axes = np.delete(axes, channel_axis) + abs_channel = channel_axis % image.ndim + post = image.ndim - abs_channel - 1 + sl = (slice(None),) * abs_channel + (np.newaxis,) + (slice(None),) * post + wfilt = wfilt[sl] + if is_real: + butterfilt = fft.irfftn( + wfilt * fft.rfftn(image, axes=axes), s=fft_shape, axes=axes + ) + else: + butterfilt = fft.ifftn( + wfilt * fft.fftn(image, axes=axes), s=fft_shape, axes=axes + ) + if npad > 0: + butterfilt = butterfilt[center_slice] + return butterfilt diff --git a/python_embeded/Lib/site-packages/skimage/filters/_gabor.py b/python_embeded/Lib/site-packages/skimage/filters/_gabor.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b1e07609e304b41673d41bbae49080b5f98c5b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_gabor.py @@ -0,0 +1,220 @@ +import math + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type, check_nD + +__all__ = ['gabor_kernel', 'gabor'] + + +def _sigma_prefactor(bandwidth): + b = bandwidth + # See http://www.cs.rug.nl/~imaging/simplecell.html + return 1.0 / np.pi * math.sqrt(math.log(2) / 2.0) * (2.0**b + 1) / (2.0**b - 1) + + +def gabor_kernel( + frequency, + theta=0, + bandwidth=1, + sigma_x=None, + sigma_y=None, + n_stds=3, + offset=0, + dtype=np.complex128, +): + """Return complex 2D Gabor filter kernel. + + Gabor kernel is a Gaussian kernel modulated by a complex harmonic function. + Harmonic function consists of an imaginary sine function and a real + cosine function. Spatial frequency is inversely proportional to the + wavelength of the harmonic and to the standard deviation of a Gaussian + kernel. The bandwidth is also inversely proportional to the standard + deviation. + + Parameters + ---------- + frequency : float + Spatial frequency of the harmonic function. Specified in pixels. + theta : float, optional + Orientation in radians. If 0, the harmonic is in the x-direction. + bandwidth : float, optional + The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x`` + and ``sigma_y`` will decrease with increasing frequency. This value is + ignored if ``sigma_x`` and ``sigma_y`` are set by the user. + sigma_x, sigma_y : float, optional + Standard deviation in x- and y-directions. These directions apply to + the kernel *before* rotation. If `theta = pi/2`, then the kernel is + rotated 90 degrees so that ``sigma_x`` controls the *vertical* + direction. + n_stds : scalar, optional + The linear size of the kernel is n_stds (3 by default) standard + deviations + offset : float, optional + Phase offset of harmonic function in radians. + dtype : {np.complex64, np.complex128} + Specifies if the filter is single or double precision complex. + + Returns + ------- + g : complex array + Complex filter kernel. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gabor_filter + .. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf + + Examples + -------- + >>> from skimage.filters import gabor_kernel + >>> from matplotlib import pyplot as plt # doctest: +SKIP + + >>> gk = gabor_kernel(frequency=0.2) + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(gk.real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + >>> # more ripples (equivalent to increasing the size of the + >>> # Gaussian spread) + >>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1) + >>> fig, ax = plt.suplots() # doctest: +SKIP + >>> ax.imshow(gk.real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + if sigma_x is None: + sigma_x = _sigma_prefactor(bandwidth) / frequency + if sigma_y is None: + sigma_y = _sigma_prefactor(bandwidth) / frequency + + if np.dtype(dtype).kind != 'c': + raise ValueError("dtype must be complex") + + ct = math.cos(theta) + st = math.sin(theta) + x0 = math.ceil(max(abs(n_stds * sigma_x * ct), abs(n_stds * sigma_y * st), 1)) + y0 = math.ceil(max(abs(n_stds * sigma_y * ct), abs(n_stds * sigma_x * st), 1)) + y, x = np.meshgrid( + np.arange(-y0, y0 + 1), np.arange(-x0, x0 + 1), indexing='ij', sparse=True + ) + rotx = x * ct + y * st + roty = -x * st + y * ct + + g = np.empty(roty.shape, dtype=dtype) + np.exp( + -0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2) + + 1j * (2 * np.pi * frequency * rotx + offset), + out=g, + ) + g *= 1 / (2 * np.pi * sigma_x * sigma_y) + + return g + + +def gabor( + image, + frequency, + theta=0, + bandwidth=1, + sigma_x=None, + sigma_y=None, + n_stds=3, + offset=0, + mode='reflect', + cval=0, +): + """Return real and imaginary responses to Gabor filter. + + The real and imaginary parts of the Gabor filter kernel are applied to the + image and the response is returned as a pair of arrays. + + Gabor filter is a linear filter with a Gaussian kernel which is modulated + by a sinusoidal plane wave. Frequency and orientation representations of + the Gabor filter are similar to those of the human visual system. + Gabor filter banks are commonly used in computer vision and image + processing. They are especially suitable for edge detection and texture + classification. + + Parameters + ---------- + image : 2-D array + Input image. + frequency : float + Spatial frequency of the harmonic function. Specified in pixels. + theta : float, optional + Orientation in radians. If 0, the harmonic is in the x-direction. + bandwidth : float, optional + The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x`` + and ``sigma_y`` will decrease with increasing frequency. This value is + ignored if ``sigma_x`` and ``sigma_y`` are set by the user. + sigma_x, sigma_y : float, optional + Standard deviation in x- and y-directions. These directions apply to + the kernel *before* rotation. If `theta = pi/2`, then the kernel is + rotated 90 degrees so that ``sigma_x`` controls the *vertical* + direction. + n_stds : scalar, optional + The linear size of the kernel is n_stds (3 by default) standard + deviations. + offset : float, optional + Phase offset of harmonic function in radians. + mode : {'constant', 'nearest', 'reflect', 'mirror', 'wrap'}, optional + Mode used to convolve image with a kernel, passed to `ndi.convolve` + cval : scalar, optional + Value to fill past edges of input if ``mode`` of convolution is + 'constant'. The parameter is passed to `ndi.convolve`. + + Returns + ------- + real, imag : arrays + Filtered images using the real and imaginary parts of the Gabor filter + kernel. Images are of the same dimensions as the input one. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gabor_filter + .. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf + + Examples + -------- + >>> from skimage.filters import gabor + >>> from skimage import data + >>> from matplotlib import pyplot as plt # doctest: +SKIP + + >>> image = data.coins() + >>> # detecting edges in a coin image + >>> filt_real, filt_imag = gabor(image, frequency=0.6) + >>> fix, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(filt_real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + >>> # less sensitivity to finer details with the lower frequency kernel + >>> filt_real, filt_imag = gabor(image, frequency=0.1) + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(filt_real) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + check_nD(image, 2) + # do not cast integer types to float! + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + kernel_dtype = np.promote_types(image.dtype, np.complex64) + else: + kernel_dtype = np.complex128 + + g = gabor_kernel( + frequency, + theta, + bandwidth, + sigma_x, + sigma_y, + n_stds, + offset, + dtype=kernel_dtype, + ) + + filtered_real = ndi.convolve(image, np.real(g), mode=mode, cval=cval) + filtered_imag = ndi.convolve(image, np.imag(g), mode=mode, cval=cval) + + return filtered_real, filtered_imag diff --git a/python_embeded/Lib/site-packages/skimage/filters/_gaussian.py b/python_embeded/Lib/site-packages/skimage/filters/_gaussian.py new file mode 100644 index 0000000000000000000000000000000000000000..40a7021e3f8bdbe96344c816163850d7c693292b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_gaussian.py @@ -0,0 +1,168 @@ +import numpy as np + +from .._shared.filters import gaussian +from ..util import img_as_float + +__all__ = ['gaussian', 'difference_of_gaussians'] + + +def difference_of_gaussians( + image, + low_sigma, + high_sigma=None, + *, + mode='nearest', + cval=0, + channel_axis=None, + truncate=4.0, +): + """Find features between ``low_sigma`` and ``high_sigma`` in size. + + This function uses the Difference of Gaussians method for applying + band-pass filters to multi-dimensional arrays. The input array is + blurred with two Gaussian kernels of differing sigmas to produce two + intermediate, filtered images. The more-blurred image is then subtracted + from the less-blurred image. The final output image will therefore have + had high-frequency components attenuated by the smaller-sigma Gaussian, and + low frequency components will have been removed due to their presence in + the more-blurred intermediate. + + Parameters + ---------- + image : ndarray + Input array to filter. + low_sigma : scalar or sequence of scalars + Standard deviation(s) for the Gaussian kernel with the smaller sigmas + across all axes. The standard deviations are given for each axis as a + sequence, or as a single number, in which case the single number is + used as the standard deviation value for all axes. + high_sigma : scalar or sequence of scalars, optional (default is None) + Standard deviation(s) for the Gaussian kernel with the larger sigmas + across all axes. The standard deviations are given for each axis as a + sequence, or as a single number, in which case the single number is + used as the standard deviation value for all axes. If None is given + (default), sigmas for all axes are calculated as 1.6 * low_sigma. + 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 'nearest'. + cval : scalar, optional + Value to fill past edges of input if ``mode`` is 'constant'. Default + is 0.0 + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + truncate : float, optional (default is 4.0) + Truncate the filter at this many standard deviations. + + Returns + ------- + filtered_image : ndarray + the filtered array. + + See also + -------- + skimage.feature.blob_dog + + Notes + ----- + This function will subtract an array filtered with a Gaussian kernel + with sigmas given by ``high_sigma`` from an array filtered with a + Gaussian kernel with sigmas provided by ``low_sigma``. The values for + ``high_sigma`` must always be greater than or equal to the corresponding + values in ``low_sigma``, or a ``ValueError`` will be raised. + + When ``high_sigma`` is none, the values for ``high_sigma`` will be + calculated as 1.6x the corresponding values in ``low_sigma``. This ratio + was originally proposed by Marr and Hildreth (1980) [1]_ and is commonly + used when approximating the inverted Laplacian of Gaussian, which is used + in edge and blob detection. + + Input image is converted according to the conventions of ``img_as_float``. + + Except for sigma values, all parameters are used for both filters. + + Examples + -------- + Apply a simple Difference of Gaussians filter to a color image: + + >>> from skimage.data import astronaut + >>> from skimage.filters import difference_of_gaussians + >>> filtered_image = difference_of_gaussians(astronaut(), 2, 10, + ... channel_axis=-1) + + Apply a Laplacian of Gaussian filter as approximated by the Difference + of Gaussians filter: + + >>> filtered_image = difference_of_gaussians(astronaut(), 2, + ... channel_axis=-1) + + Apply a Difference of Gaussians filter to a grayscale image using different + sigma values for each axis: + + >>> from skimage.data import camera + >>> filtered_image = difference_of_gaussians(camera(), (2,5), (3,20)) + + References + ---------- + .. [1] Marr, D. and Hildreth, E. Theory of Edge Detection. Proc. R. Soc. + Lond. Series B 207, 187-217 (1980). + https://doi.org/10.1098/rspb.1980.0020 + + """ + image = img_as_float(image) + low_sigma = np.array(low_sigma, dtype='float', ndmin=1) + if high_sigma is None: + high_sigma = low_sigma * 1.6 + else: + high_sigma = np.array(high_sigma, dtype='float', ndmin=1) + + if channel_axis is not None: + spatial_dims = image.ndim - 1 + else: + spatial_dims = image.ndim + + if len(low_sigma) != 1 and len(low_sigma) != spatial_dims: + raise ValueError( + 'low_sigma must have length equal to number of' + ' spatial dimensions of input' + ) + if len(high_sigma) != 1 and len(high_sigma) != spatial_dims: + raise ValueError( + 'high_sigma must have length equal to number of' + ' spatial dimensions of input' + ) + + low_sigma = low_sigma * np.ones(spatial_dims) + high_sigma = high_sigma * np.ones(spatial_dims) + + if any(high_sigma < low_sigma): + raise ValueError( + 'high_sigma must be equal to or larger than' 'low_sigma for all axes' + ) + + im1 = gaussian( + image, + sigma=low_sigma, + mode=mode, + cval=cval, + channel_axis=channel_axis, + truncate=truncate, + preserve_range=False, + ) + + im2 = gaussian( + image, + sigma=high_sigma, + mode=mode, + cval=cval, + channel_axis=channel_axis, + truncate=truncate, + preserve_range=False, + ) + + return im1 - im2 diff --git a/python_embeded/Lib/site-packages/skimage/filters/_median.py b/python_embeded/Lib/site-packages/skimage/filters/_median.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ababd41ddef60c66c4334f540d01d9b2ddaf46 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_median.py @@ -0,0 +1,82 @@ +from warnings import warn + +import numpy as np +from scipy import ndimage as ndi + +from .rank import generic + + +def median( + image, footprint=None, out=None, mode='nearest', cval=0.0, behavior='ndimage' +): + """Return local median of an image. + + Parameters + ---------- + image : array-like + Input image. + footprint : ndarray, optional + If ``behavior=='rank'``, ``footprint`` is a 2-D array of 1's and 0's. + If ``behavior=='ndimage'``, ``footprint`` is a N-D array of 1's and 0's + with the same number of dimension than ``image``. + If None, ``footprint`` will be a N-D array with 3 elements for each + dimension (e.g., vector, square, cube, etc.) + out : ndarray, (same dtype as image), optional + If None, a new array is allocated. + 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 'nearest'. + + .. versionadded:: 0.15 + ``mode`` is used when ``behavior='ndimage'``. + cval : scalar, optional + Value to fill past edges of input if mode is 'constant'. Default is 0.0 + + .. versionadded:: 0.15 + ``cval`` was added in 0.15 is used when ``behavior='ndimage'``. + behavior : {'ndimage', 'rank'}, optional + Either to use the old behavior (i.e., < 0.15) or the new behavior. + The old behavior will call the :func:`skimage.filters.rank.median`. + The new behavior will call the :func:`scipy.ndimage.median_filter`. + Default is 'ndimage'. + + .. versionadded:: 0.15 + ``behavior`` is introduced in 0.15 + .. versionchanged:: 0.16 + Default ``behavior`` has been changed from 'rank' to 'ndimage' + + Returns + ------- + out : 2-D array (same dtype as input image) + Output image. + + See also + -------- + skimage.filters.rank.median : Rank-based implementation of the median + filtering offering more flexibility with additional parameters but + dedicated for unsigned integer images. + + Examples + -------- + >>> from skimage import data + >>> from skimage.morphology import disk + >>> from skimage.filters import median + >>> img = data.camera() + >>> med = median(img, disk(5)) + + """ + if behavior == 'rank': + if mode != 'nearest' or not np.isclose(cval, 0.0): + warn( + "Change 'behavior' to 'ndimage' if you want to use the " + "parameters 'mode' or 'cval'. They will be discarded " + "otherwise.", + stacklevel=2, + ) + return generic.median(image, footprint=footprint, out=out) + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, image.ndim) + return ndi.median_filter( + image, footprint=footprint, output=out, mode=mode, cval=cval + ) diff --git a/python_embeded/Lib/site-packages/skimage/filters/_multiotsu.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/filters/_multiotsu.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..6457bec50d4830a42b8ee315d8cd8514e9b93ef5 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/filters/_multiotsu.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/filters/_rank_order.py b/python_embeded/Lib/site-packages/skimage/filters/_rank_order.py new file mode 100644 index 0000000000000000000000000000000000000000..fdcc019eca74ab028cdbfc8610695037bb43db9b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_rank_order.py @@ -0,0 +1,57 @@ +""" +_rank_order.py - convert an image of any type to an image of ints whose +pixels have an identical rank order compared to the original image +""" + +import numpy as np + + +def rank_order(image): + """Return an image of the same shape where each pixel is the + index of the pixel value in the ascending order of the unique + values of ``image``, aka the rank-order value. + + Parameters + ---------- + image : ndarray + + Returns + ------- + labels : ndarray of unsigned integers, of shape image.shape + New array where each pixel has the rank-order value of the + corresponding pixel in ``image``. Pixel values are between 0 and + n - 1, where n is the number of distinct unique values in + ``image``. The dtype of this array will be determined by + ``np.min_scalar_type(image.size)``. + original_values : 1-D ndarray + Unique original values of ``image``. This will have the same dtype as + ``image``. + + Examples + -------- + >>> a = np.array([[1, 4, 5], [4, 4, 1], [5, 1, 1]]) + >>> a + array([[1, 4, 5], + [4, 4, 1], + [5, 1, 1]]) + >>> rank_order(a) + (array([[0, 1, 2], + [1, 1, 0], + [2, 0, 0]], dtype=uint8), array([1, 4, 5])) + >>> b = np.array([-1., 2.5, 3.1, 2.5]) + >>> rank_order(b) + (array([0, 1, 2, 1], dtype=uint8), array([-1. , 2.5, 3.1])) + """ + flat_image = image.reshape(-1) + unsigned_dtype = np.min_scalar_type(flat_image.size) + sort_order = flat_image.argsort().astype(unsigned_dtype, copy=False) + flat_image = flat_image[sort_order] + sort_rank = np.zeros_like(sort_order) + is_different = flat_image[:-1] != flat_image[1:] + np.cumsum(is_different, out=sort_rank[1:], dtype=sort_rank.dtype) + original_values = np.zeros((int(sort_rank[-1]) + 1,), image.dtype) + original_values[0] = flat_image[0] + original_values[1:] = flat_image[1:][is_different] + int_image = np.zeros_like(sort_order) + int_image[sort_order] = sort_rank + return (int_image.reshape(image.shape), original_values) diff --git a/python_embeded/Lib/site-packages/skimage/filters/_sparse.py b/python_embeded/Lib/site-packages/skimage/filters/_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc82324fb866906678f67d6f73128493f378671 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_sparse.py @@ -0,0 +1,139 @@ +import numpy as np + +from .._shared.utils import _supported_float_type, _to_np_mode + + +def _validate_window_size(axis_sizes): + """Ensure all sizes in ``axis_sizes`` are odd. + + Parameters + ---------- + axis_sizes : iterable of int + + Raises + ------ + ValueError + If any given axis size is even. + """ + for axis_size in axis_sizes: + if axis_size % 2 == 0: + msg = ( + f'Window size for `threshold_sauvola` or ' + f'`threshold_niblack` must not be even on any dimension. ' + f'Got {axis_sizes}' + ) + raise ValueError(msg) + + +def _get_view(padded, kernel_shape, idx, val): + """Get a view into `padded` that is offset by `idx` and scaled by `val`. + + If `padded` was created by padding the original image by `kernel_shape` as + in correlate_sparse, then the view created here will match the size of the + original image. + """ + sl_shift = tuple( + [ + slice(c, s - (w_ - 1 - c)) + for c, w_, s in zip(idx, kernel_shape, padded.shape) + ] + ) + v = padded[sl_shift] + if val == 1: + return v + return val * v + + +def _correlate_sparse(image, kernel_shape, kernel_indices, kernel_values): + """Perform correlation with a sparse kernel. + + Parameters + ---------- + image : ndarray + The (prepadded) image to be correlated. + kernel_shape : tuple of int + The shape of the sparse filter kernel. + kernel_indices : list of coordinate tuples + The indices of each non-zero kernel entry. + kernel_values : list of float + The kernel values at each location in kernel_indices. + + Returns + ------- + out : ndarray + The filtered image. + + Notes + ----- + This function only returns results for the 'valid' region of the + convolution, and thus `out` will be smaller than `image` by an amount + equal to the kernel size along each axis. + """ + idx, val = kernel_indices[0], kernel_values[0] + # implementation assumes this corner is first in kernel_indices_in_values + if tuple(idx) != (0,) * image.ndim: + raise RuntimeError("Unexpected initial index in kernel_indices") + # make a copy to avoid modifying the input image + out = _get_view(image, kernel_shape, idx, val).copy() + for idx, val in zip(kernel_indices[1:], kernel_values[1:]): + out += _get_view(image, kernel_shape, idx, val) + return out + + +def correlate_sparse(image, kernel, mode='reflect'): + """Compute valid cross-correlation of `padded_array` and `kernel`. + + This function is *fast* when `kernel` is large with many zeros. + + See ``scipy.ndimage.correlate`` for a description of cross-correlation. + + Parameters + ---------- + image : ndarray, dtype float, shape (M, N[, ...], P) + The input array. If mode is 'valid', this array should already be + padded, as a margin of the same shape as kernel will be stripped + off. + kernel : ndarray, dtype float, shape (Q, R[, ...], S) + The kernel to be correlated. Must have the same number of + dimensions as `padded_array`. For high performance, it should + be sparse (few nonzero entries). + mode : string, optional + See `scipy.ndimage.correlate` for valid modes. + Additionally, mode 'valid' is accepted, in which case no padding is + applied and the result is the result for the smaller image for which + the kernel is entirely inside the original data. + + Returns + ------- + result : array of float, shape (M, N[, ...], P) + The result of cross-correlating `image` with `kernel`. If mode + 'valid' is used, the resulting shape is (M-Q+1, N-R+1[, ...], P-S+1). + """ + kernel = np.asarray(kernel) + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if mode == 'valid': + padded_image = image + else: + np_mode = _to_np_mode(mode) + _validate_window_size(kernel.shape) + padded_image = np.pad( + image, + [(w // 2, w // 2) for w in kernel.shape], + mode=np_mode, + ) + + # extract the kernel's non-zero indices and corresponding values + indices = np.nonzero(kernel) + values = list(kernel[indices].astype(float_dtype, copy=False)) + indices = list(zip(*indices)) + + # _correlate_sparse requires an index at (0,) * kernel.ndim to be present + corner_index = (0,) * kernel.ndim + if corner_index not in indices: + indices = [corner_index] + indices + values = [0.0] + values + + return _correlate_sparse(padded_image, kernel.shape, indices, values) diff --git a/python_embeded/Lib/site-packages/skimage/filters/_unsharp_mask.py b/python_embeded/Lib/site-packages/skimage/filters/_unsharp_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..c99aebfb4ebdcf5efb82fae82795fa9bba5ed149 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_unsharp_mask.py @@ -0,0 +1,141 @@ +import numpy as np + +from ..util.dtype import img_as_float +from .._shared import utils +from .._shared.filters import gaussian + + +def _unsharp_mask_single_channel(image, radius, amount, vrange): + """Single channel implementation of the unsharp masking filter.""" + + blurred = gaussian(image, sigma=radius, mode='reflect') + + result = image + (image - blurred) * amount + if vrange is not None: + return np.clip(result, vrange[0], vrange[1], out=result) + return result + + +def unsharp_mask( + image, radius=1.0, amount=1.0, preserve_range=False, *, channel_axis=None +): + """Unsharp masking filter. + + The sharp details are identified as the difference between the original + image and its blurred version. These details are then scaled, and added + back to the original image. + + Parameters + ---------- + image : (M[, ...][, C]) ndarray + Input image. + radius : scalar or sequence of scalars, optional + If a scalar is given, then its value is used for all dimensions. + If sequence is given, then there must be exactly one radius + for each dimension except the last dimension for multichannel images. + Note that 0 radius means no blurring, and negative values are + not allowed. + amount : scalar, optional + The details will be amplified with this factor. The factor could be 0 + or negative. Typically, it is a small positive number, e.g. 1.0. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of ``img_as_float``. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + output : (M[, ...][, C]) ndarray of float + Image with unsharp mask applied. + + Notes + ----- + Unsharp masking is an image sharpening technique. It is a linear image + operation, and numerically stable, unlike deconvolution which is an + ill-posed problem. Because of this stability, it is often + preferred over deconvolution. + + The main idea is as follows: sharp details are identified as the + difference between the original image and its blurred version. + These details are added back to the original image after a scaling step: + + enhanced image = original + amount * (original - blurred) + + When applying this filter to several color layers independently, + color bleeding may occur. More visually pleasing result can be + achieved by processing only the brightness/lightness/intensity + channel in a suitable color space such as HSV, HSL, YUV, or YCbCr. + + Unsharp masking is described in most introductory digital image + processing books. This implementation is based on [1]_. + + Examples + -------- + >>> array = np.ones(shape=(5,5), dtype=np.uint8)*100 + >>> array[2,2] = 120 + >>> array + array([[100, 100, 100, 100, 100], + [100, 100, 100, 100, 100], + [100, 100, 120, 100, 100], + [100, 100, 100, 100, 100], + [100, 100, 100, 100, 100]], dtype=uint8) + >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) + array([[0.39, 0.39, 0.39, 0.39, 0.39], + [0.39, 0.39, 0.38, 0.39, 0.39], + [0.39, 0.38, 0.53, 0.38, 0.39], + [0.39, 0.39, 0.38, 0.39, 0.39], + [0.39, 0.39, 0.39, 0.39, 0.39]]) + + >>> array = np.ones(shape=(5,5), dtype=np.int8)*100 + >>> array[2,2] = 127 + >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) + array([[0.79, 0.79, 0.79, 0.79, 0.79], + [0.79, 0.78, 0.75, 0.78, 0.79], + [0.79, 0.75, 1. , 0.75, 0.79], + [0.79, 0.78, 0.75, 0.78, 0.79], + [0.79, 0.79, 0.79, 0.79, 0.79]]) + + >>> np.around(unsharp_mask(array, radius=0.5, amount=2, preserve_range=True), 2) + array([[100. , 100. , 99.99, 100. , 100. ], + [100. , 99.39, 95.48, 99.39, 100. ], + [ 99.99, 95.48, 147.59, 95.48, 99.99], + [100. , 99.39, 95.48, 99.39, 100. ], + [100. , 100. , 99.99, 100. , 100. ]]) + + + References + ---------- + .. [1] Maria Petrou, Costas Petrou + "Image Processing: The Fundamentals", (2010), ed ii., page 357, + ISBN 13: 9781119994398 :DOI:`10.1002/9781119994398` + .. [2] Wikipedia. Unsharp masking + https://en.wikipedia.org/wiki/Unsharp_masking + + """ + vrange = None # Range for valid values; used for clipping. + float_dtype = utils._supported_float_type(image.dtype) + if preserve_range: + fimg = image.astype(float_dtype, copy=False) + else: + fimg = img_as_float(image).astype(float_dtype, copy=False) + negative = np.any(fimg < 0) + if negative: + vrange = [-1.0, 1.0] + else: + vrange = [0.0, 1.0] + + if channel_axis is not None: + result = np.empty_like(fimg, dtype=float_dtype) + for channel in range(image.shape[channel_axis]): + sl = utils.slice_at_axis(channel, channel_axis) + result[sl] = _unsharp_mask_single_channel(fimg[sl], radius, amount, vrange) + return result + else: + return _unsharp_mask_single_channel(fimg, radius, amount, vrange) diff --git a/python_embeded/Lib/site-packages/skimage/filters/_window.py b/python_embeded/Lib/site-packages/skimage/filters/_window.py new file mode 100644 index 0000000000000000000000000000000000000000..058793905d68d4ffb7b00b026421fe18bd5c3e19 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/_window.py @@ -0,0 +1,131 @@ +import functools + +import numpy as np +from scipy.signal import get_window + +from .._shared.utils import safe_as_int +from ..transform import warp + + +def window(window_type, shape, warp_kwargs=None): + """Return an n-dimensional window of a given size and dimensionality. + + Parameters + ---------- + window_type : string, float, or tuple + The type of window to be created. Any window type supported by + ``scipy.signal.get_window`` is allowed here. See notes below for a + current list, or the SciPy documentation for the version of SciPy + on your machine. + shape : tuple of int or int + The shape of the window along each axis. If an integer is provided, + a 1D window is generated. + warp_kwargs : dict + Keyword arguments passed to `skimage.transform.warp` (e.g., + ``warp_kwargs={'order':3}`` to change interpolation method). + + Returns + ------- + nd_window : ndarray + A window of the specified ``shape``. ``dtype`` is ``np.float64``. + + Notes + ----- + This function is based on ``scipy.signal.get_window`` and thus can access + all of the window types available to that function + (e.g., ``"hann"``, ``"boxcar"``). Note that certain window types require + parameters that have to be supplied with the window name as a tuple + (e.g., ``("tukey", 0.8)``). If only a float is supplied, it is interpreted + as the beta parameter of the Kaiser window. + + See https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html + for more details. + + Note that this function generates a double precision array of the specified + ``shape`` and can thus generate very large arrays that consume a large + amount of available memory. + + The approach taken here to create nD windows is to first calculate the + Euclidean distance from the center of the intended nD window to each + position in the array. That distance is used to sample, with + interpolation, from a 1D window returned from ``scipy.signal.get_window``. + The method of interpolation can be changed with the ``order`` keyword + argument passed to `skimage.transform.warp`. + + Some coordinates in the output window will be outside of the original + signal; these will be filled in with zeros. + + Window types: + - boxcar + - triang + - blackman + - hamming + - hann + - bartlett + - flattop + - parzen + - bohman + - blackmanharris + - nuttall + - barthann + - kaiser (needs beta) + - gaussian (needs standard deviation) + - general_gaussian (needs power, width) + - slepian (needs width) + - dpss (needs normalized half-bandwidth) + - chebwin (needs attenuation) + - exponential (needs decay scale) + - tukey (needs taper fraction) + + Examples + -------- + Return a Hann window with shape (512, 512): + + >>> from skimage.filters import window + >>> w = window('hann', (512, 512)) + + Return a Kaiser window with beta parameter of 16 and shape (256, 256, 35): + + >>> w = window(16, (256, 256, 35)) + + Return a Tukey window with an alpha parameter of 0.8 and shape (100, 300): + + >>> w = window(('tukey', 0.8), (100, 300)) + + References + ---------- + .. [1] Two-dimensional window design, Wikipedia, + https://en.wikipedia.org/wiki/Two_dimensional_window_design + """ + + if np.isscalar(shape): + shape = (safe_as_int(shape),) + else: + shape = tuple(safe_as_int(shape)) + if any(s < 0 for s in shape): + raise ValueError("invalid shape") + + ndim = len(shape) + if ndim <= 0: + raise ValueError("Number of dimensions must be greater than zero") + + max_size = functools.reduce(max, shape) + w = get_window(window_type, max_size, fftbins=False) + w = np.reshape(w, (-1,) + (1,) * (ndim - 1)) + + # Create coords for warping following `ndimage.map_coordinates` convention. + L = [np.arange(s, dtype=np.float32) * (max_size / s) for s in shape] + + center = (max_size / 2) - 0.5 + dist = 0 + for g in np.meshgrid(*L, sparse=True, indexing='ij'): + g -= center + dist = dist + g * g + dist = np.sqrt(dist) + coords = np.zeros((ndim,) + dist.shape, dtype=np.float32) + coords[0] = dist + center + + if warp_kwargs is None: + warp_kwargs = {} + + return warp(w, coords, mode='constant', cval=0.0, **warp_kwargs) diff --git a/python_embeded/Lib/site-packages/skimage/filters/edges.py b/python_embeded/Lib/site-packages/skimage/filters/edges.py new file mode 100644 index 0000000000000000000000000000000000000000..cdeabbf5400a09c7121f6356227e17c0fccdeefe --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/edges.py @@ -0,0 +1,863 @@ +import numpy as np +from scipy import ndimage as ndi +from scipy.ndimage import binary_erosion, convolve + +from .._shared.utils import _supported_float_type, check_nD +from ..restoration.uft import laplacian +from ..util.dtype import img_as_float + +# n-dimensional filter weights +SOBEL_EDGE = np.array([1, 0, -1]) +SOBEL_SMOOTH = np.array([1, 2, 1]) / 4 +HSOBEL_WEIGHTS = SOBEL_EDGE.reshape((3, 1)) * SOBEL_SMOOTH.reshape((1, 3)) +VSOBEL_WEIGHTS = HSOBEL_WEIGHTS.T + +SCHARR_EDGE = np.array([1, 0, -1]) +SCHARR_SMOOTH = np.array([3, 10, 3]) / 16 +HSCHARR_WEIGHTS = SCHARR_EDGE.reshape((3, 1)) * SCHARR_SMOOTH.reshape((1, 3)) +VSCHARR_WEIGHTS = HSCHARR_WEIGHTS.T + +PREWITT_EDGE = np.array([1, 0, -1]) +PREWITT_SMOOTH = np.full((3,), 1 / 3) +HPREWITT_WEIGHTS = PREWITT_EDGE.reshape((3, 1)) * PREWITT_SMOOTH.reshape((1, 3)) +VPREWITT_WEIGHTS = HPREWITT_WEIGHTS.T + +# 2D-only filter weights +ROBERTS_PD_WEIGHTS = np.array([[1, 0], [0, -1]], dtype=np.float64) +ROBERTS_ND_WEIGHTS = np.array([[0, 1], [-1, 0]], dtype=np.float64) + +# These filter weights can be found in Farid & Simoncelli (2004), +# Table 1 (3rd and 4th row). Additional decimal places were computed +# using the code found at https://www.cs.dartmouth.edu/farid/ +farid_smooth = np.array( + [ + [ + 0.0376593171958126, + 0.249153396177344, + 0.426374573253687, + 0.249153396177344, + 0.0376593171958126, + ] + ] +) +farid_edge = np.array( + [[0.109603762960254, 0.276690988455557, 0, -0.276690988455557, -0.109603762960254]] +) +HFARID_WEIGHTS = farid_edge.T * farid_smooth +VFARID_WEIGHTS = np.copy(HFARID_WEIGHTS.T) + + +def _mask_filter_result(result, mask): + """Return result after masking. + + Input masks are eroded so that mask areas in the original image don't + affect values in the result. + """ + if mask is not None: + erosion_footprint = ndi.generate_binary_structure(mask.ndim, mask.ndim) + mask = binary_erosion(mask, erosion_footprint, border_value=0) + result *= mask + return result + + +def _kernel_shape(ndim, dim): + """Return list of `ndim` 1s except at position `dim`, where value is -1. + + Parameters + ---------- + ndim : int + The number of dimensions of the kernel shape. + dim : int + The axis of the kernel to expand to shape -1. + + Returns + ------- + shape : list of int + The requested shape. + + Examples + -------- + >>> _kernel_shape(2, 0) + [-1, 1] + >>> _kernel_shape(3, 1) + [1, -1, 1] + >>> _kernel_shape(4, -1) + [1, 1, 1, -1] + """ + shape = [ + 1, + ] * ndim + shape[dim] = -1 + return shape + + +def _reshape_nd(arr, ndim, dim): + """Reshape a 1D array to have n dimensions, all singletons but one. + + Parameters + ---------- + arr : array, shape (N,) + Input array + ndim : int + Number of desired dimensions of reshaped array. + dim : int + Which dimension/axis will not be singleton-sized. + + Returns + ------- + arr_reshaped : array, shape ([1, ...], N, [1,...]) + View of `arr` reshaped to the desired shape. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> arr = rng.random(7) + >>> _reshape_nd(arr, 2, 0).shape + (7, 1) + >>> _reshape_nd(arr, 3, 1).shape + (1, 7, 1) + >>> _reshape_nd(arr, 4, -1).shape + (1, 1, 1, 7) + """ + kernel_shape = _kernel_shape(ndim, dim) + return np.reshape(arr, kernel_shape) + + +def _generic_edge_filter( + image, + *, + smooth_weights, + edge_weights=[1, 0, -1], + axis=None, + mode='reflect', + cval=0.0, + mask=None, +): + """Apply a generic, n-dimensional edge filter. + + The filter is computed by applying the edge weights along one dimension + and the smoothing weights along all other dimensions. If no axis is given, + or a tuple of axes is given the filter is computed along all axes in turn, + and the magnitude is computed as the square root of the average square + magnitude of all the axes. + + Parameters + ---------- + image : array + The input image. + smooth_weights : array of float + The smoothing weights for the filter. These are applied to dimensions + orthogonal to the edge axis. + edge_weights : 1D array of float, optional + The weights to compute the edge along the chosen axes. + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + edge_mag = np.sqrt(sum([_generic_edge_filter(image, ..., axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + """ + ndim = image.ndim + if axis is None: + axes = list(range(ndim)) + elif np.isscalar(axis): + axes = [axis] + else: + axes = axis + return_magnitude = len(axes) > 1 + + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + output = np.zeros(image.shape, dtype=image.dtype) + + for edge_dim in axes: + kernel = _reshape_nd(edge_weights, ndim, edge_dim) + smooth_axes = list(set(range(ndim)) - {edge_dim}) + for smooth_dim in smooth_axes: + kernel = kernel * _reshape_nd(smooth_weights, ndim, smooth_dim) + ax_output = ndi.convolve(image, kernel, mode=mode) + if return_magnitude: + ax_output *= ax_output + output += ax_output + + if return_magnitude: + output = np.sqrt(output) / np.sqrt(ndim, dtype=output.dtype) + return output + + +def sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find edges in an image using the Sobel filter. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + sobel_mag = np.sqrt(sum([sobel(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Sobel edge map. + + See also + -------- + sobel_h, sobel_v : horizontal and vertical edge detection. + scharr, prewitt, farid, skimage.feature.canny + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + .. [2] https://en.wikipedia.org/wiki/Sobel_operator + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.sobel(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=SOBEL_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def sobel_h(image, mask=None): + """Find the horizontal edges of an image using the Sobel transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Sobel edge map. + + Notes + ----- + We use the following kernel:: + + 1 2 1 + 0 0 0 + -1 -2 -1 + + """ + check_nD(image, 2) + return sobel(image, mask=mask, axis=0) + + +def sobel_v(image, mask=None): + """Find the vertical edges of an image using the Sobel transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Sobel edge map. + + Notes + ----- + We use the following kernel:: + + 1 0 -1 + 2 0 -2 + 1 0 -1 + + """ + check_nD(image, 2) + return sobel(image, mask=mask, axis=1) + + +def scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Scharr transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + sch_mag = np.sqrt(sum([scharr(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Scharr edge map. + + See also + -------- + scharr_h, scharr_v : horizontal and vertical edge detection. + sobel, prewitt, farid, skimage.feature.canny + + Notes + ----- + The Scharr operator has a better rotation invariance than + other edge filters such as the Sobel or the Prewitt operators. + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + .. [2] https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.scharr(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=SCHARR_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def scharr_h(image, mask=None): + """Find the horizontal edges of an image using the Scharr transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Scharr edge map. + + Notes + ----- + We use the following kernel:: + + 3 10 3 + 0 0 0 + -3 -10 -3 + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + + """ + check_nD(image, 2) + return scharr(image, mask=mask, axis=0) + + +def scharr_v(image, mask=None): + """Find the vertical edges of an image using the Scharr transform. + + Parameters + ---------- + image : 2-D array + Image to process + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Scharr edge map. + + Notes + ----- + We use the following kernel:: + + 3 0 -3 + 10 0 -10 + 3 0 -3 + + References + ---------- + .. [1] D. Kroon, 2009, Short Paper University Twente, Numerical + Optimization of Kernel Based Image Derivatives. + """ + check_nD(image, 2) + return scharr(image, mask=mask, axis=1) + + +def prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Prewitt transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + prw_mag = np.sqrt(sum([prewitt(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Prewitt edge map. + + See also + -------- + prewitt_h, prewitt_v : horizontal and vertical edge detection. + sobel, scharr, farid, skimage.feature.canny + + Notes + ----- + The edge magnitude depends slightly on edge directions, since the + approximation of the gradient operator by the Prewitt operator is not + completely rotation invariant. For a better rotation invariance, the Scharr + operator should be used. The Sobel operator has a better rotation + invariance than the Prewitt operator, but a worse rotation invariance than + the Scharr operator. + + Examples + -------- + >>> from skimage import data + >>> from skimage import filters + >>> camera = data.camera() + >>> edges = filters.prewitt(camera) + """ + output = _generic_edge_filter( + image, smooth_weights=PREWITT_SMOOTH, axis=axis, mode=mode, cval=cval + ) + output = _mask_filter_result(output, mask) + return output + + +def prewitt_h(image, mask=None): + """Find the horizontal edges of an image using the Prewitt transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Prewitt edge map. + + Notes + ----- + We use the following kernel:: + + 1/3 1/3 1/3 + 0 0 0 + -1/3 -1/3 -1/3 + + """ + check_nD(image, 2) + return prewitt(image, mask=mask, axis=0) + + +def prewitt_v(image, mask=None): + """Find the vertical edges of an image using the Prewitt transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Prewitt edge map. + + Notes + ----- + We use the following kernel:: + + 1/3 0 -1/3 + 1/3 0 -1/3 + 1/3 0 -1/3 + + """ + check_nD(image, 2) + return prewitt(image, mask=mask, axis=1) + + +def roberts(image, mask=None): + """Find the edge magnitude using Roberts' cross operator. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Roberts' Cross edge map. + + See also + -------- + roberts_pos_diag, roberts_neg_diag : diagonal edge detection. + sobel, scharr, prewitt, skimage.feature.canny + + Examples + -------- + >>> from skimage import data + >>> camera = data.camera() + >>> from skimage import filters + >>> edges = filters.roberts(camera) + + """ + check_nD(image, 2) + out = np.sqrt( + roberts_pos_diag(image, mask) ** 2 + roberts_neg_diag(image, mask) ** 2 + ) + out /= np.sqrt(2) + return out + + +def roberts_pos_diag(image, mask=None): + """Find the cross edges of an image using Roberts' cross operator. + + The kernel is applied to the input image to produce separate measurements + of the gradient component one orientation. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Robert's edge map. + + Notes + ----- + We use the following kernel:: + + 1 0 + 0 -1 + + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, ROBERTS_PD_WEIGHTS) + return _mask_filter_result(result, mask) + + +def roberts_neg_diag(image, mask=None): + """Find the cross edges of an image using the Roberts' Cross operator. + + The kernel is applied to the input image to produce separate measurements + of the gradient component one orientation. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Robert's edge map. + + Notes + ----- + We use the following kernel:: + + 0 1 + -1 0 + + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, ROBERTS_ND_WEIGHTS) + return _mask_filter_result(result, mask) + + +def laplace(image, ksize=3, mask=None): + """Find the edges of an image using the Laplace operator. + + Parameters + ---------- + image : ndarray + Image to process. + ksize : int, optional + Define the size of the discrete Laplacian operator such that it + will have a size of (ksize,) * image.ndim. + mask : ndarray, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : ndarray + The Laplace edge map. + + Notes + ----- + The Laplacian operator is generated using the function + skimage.restoration.uft.laplacian(). + + """ + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + # Create the discrete Laplacian operator - We keep only the real part of + # the filter + _, laplace_op = laplacian(image.ndim, (ksize,) * image.ndim) + result = convolve(image, laplace_op) + return _mask_filter_result(result, mask) + + +def farid(image, mask=None, *, axis=None, mode='reflect', cval=0.0): + """Find the edge magnitude using the Farid transform. + + Parameters + ---------- + image : array + The input image. + mask : array of bool, optional + Clip the output image to this mask. (Values where mask=0 will be set + to 0.) + axis : int or sequence of int, optional + Compute the edge filter along this axis. If not provided, the edge + magnitude is computed. This is defined as:: + + farid_mag = np.sqrt(sum([farid(image, axis=i)**2 + for i in range(image.ndim)]) / image.ndim) + + The magnitude is also computed if axis is a sequence. + mode : str or sequence of str, optional + The boundary mode for the convolution. See `scipy.ndimage.convolve` + for a description of the modes. This can be either a single boundary + mode or one boundary mode per axis. + cval : float, optional + When `mode` is ``'constant'``, this is the constant used in values + outside the boundary of the image data. + + Returns + ------- + output : array of float + The Farid edge map. + + See also + -------- + farid_h, farid_v : horizontal and vertical edge detection. + scharr, sobel, prewitt, skimage.feature.canny + + Notes + ----- + Take the square root of the sum of the squares of the horizontal and + vertical derivatives to get a magnitude that is somewhat insensitive to + direction. Similar to the Scharr operator, this operator is designed with + a rotation invariance constraint. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + .. [2] Wikipedia, "Farid and Simoncelli Derivatives." Available at: + + + Examples + -------- + >>> from skimage import data + >>> camera = data.camera() + >>> from skimage import filters + >>> edges = filters.farid(camera) + """ + output = _generic_edge_filter( + image, + smooth_weights=farid_smooth, + edge_weights=farid_edge, + axis=axis, + mode=mode, + cval=cval, + ) + output = _mask_filter_result(output, mask) + return output + + +def farid_h(image, *, mask=None): + """Find the horizontal edges of an image using the Farid transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Farid edge map. + + Notes + ----- + The kernel was constructed using the 5-tap weights from [1]. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + .. [2] Farid, H. and Simoncelli, E. P. "Optimally rotation-equivariant + directional derivative kernels", In: 7th International Conference on + Computer Analysis of Images and Patterns, Kiel, Germany. Sep, 1997. + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, HFARID_WEIGHTS) + return _mask_filter_result(result, mask) + + +def farid_v(image, *, mask=None): + """Find the vertical edges of an image using the Farid transform. + + Parameters + ---------- + image : 2-D array + Image to process. + mask : 2-D array, optional + An optional mask to limit the application to a certain area. + Note that pixels surrounding masked regions are also masked to + prevent masked regions from affecting the result. + + Returns + ------- + output : 2-D array + The Farid edge map. + + Notes + ----- + The kernel was constructed using the 5-tap weights from [1]. + + References + ---------- + .. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete + multidimensional signals", IEEE Transactions on Image Processing + 13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819` + """ + check_nD(image, 2) + if image.dtype.kind == 'f': + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + else: + image = img_as_float(image) + result = convolve(image, VFARID_WEIGHTS) + return _mask_filter_result(result, mask) diff --git a/python_embeded/Lib/site-packages/skimage/filters/lpi_filter.py b/python_embeded/Lib/site-packages/skimage/filters/lpi_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8549617c5fa539fde368016c36eec044211446 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/lpi_filter.py @@ -0,0 +1,261 @@ +""" +:author: Stefan van der Walt, 2008 +:license: modified BSD +""" + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type, check_nD + + +def _min_limit(x, val=np.finfo(float).eps): + mask = np.abs(x) < val + x[mask] = np.sign(x[mask]) * val + + +def _center(x, oshape): + """Return an array of shape ``oshape`` from the center of array ``x``.""" + start = (np.array(x.shape) - np.array(oshape)) // 2 + out = x[tuple(slice(s, s + n) for s, n in zip(start, oshape))] + return out + + +def _pad(data, shape): + """Pad the data to the given shape with zeros. + + Parameters + ---------- + data : 2-d ndarray + Input data + shape : (2,) tuple + + """ + out = np.zeros(shape, dtype=data.dtype) + out[tuple(slice(0, n) for n in data.shape)] = data + return out + + +class LPIFilter2D: + """Linear Position-Invariant Filter (2-dimensional)""" + + def __init__(self, impulse_response, **filter_params): + """ + Parameters + ---------- + impulse_response : callable `f(r, c, **filter_params)` + Function that yields the impulse response. ``r`` and ``c`` are + 1-dimensional vectors that represent row and column positions, in + other words coordinates are (r[0],c[0]),(r[0],c[1]) etc. + `**filter_params` are passed through. + + In other words, ``impulse_response`` would be called like this: + + >>> def impulse_response(r, c, **filter_params): + ... pass + >>> + >>> r = [0,0,0,1,1,1,2,2,2] + >>> c = [0,1,2,0,1,2,0,1,2] + >>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3} + >>> impulse_response(r, c, **filter_params) + + + Examples + -------- + Gaussian filter without normalization of coefficients: + + >>> def filt_func(r, c, sigma=1): + ... return np.exp(-(r**2 + c**2)/(2 * sigma**2)) + >>> filter = LPIFilter2D(filt_func) + + """ + if not callable(impulse_response): + raise ValueError("Impulse response must be a callable.") + + self.impulse_response = impulse_response + self.filter_params = filter_params + self._cache = None + + def _prepare(self, data): + """Calculate filter and data FFT in preparation for filtering.""" + dshape = np.array(data.shape) + even_offset = (dshape % 2 == 0).astype(int) + dshape += even_offset # all filter dimensions must be uneven + oshape = np.array(data.shape) * 2 - 1 + + float_dtype = _supported_float_type(data.dtype) + data = data.astype(float_dtype, copy=False) + + if self._cache is None or np.any(self._cache.shape != oshape): + coords = np.mgrid[ + [ + slice(0 + offset, float(n + offset)) + for (n, offset) in zip(dshape, even_offset) + ] + ] + # this steps over two sets of coordinates, + # not over the coordinates individually + for k, coord in enumerate(coords): + coord -= (dshape[k] - 1) / 2.0 + coords = coords.reshape(2, -1).T # coordinate pairs (r,c) + coords = coords.astype(float_dtype, copy=False) + + f = self.impulse_response( + coords[:, 0], coords[:, 1], **self.filter_params + ).reshape(dshape) + + f = _pad(f, oshape) + F = fft.fftn(f) + self._cache = F + else: + F = self._cache + + data = _pad(data, oshape) + G = fft.fftn(data) + + return F, G + + def __call__(self, data): + """Apply the filter to the given data. + + Parameters + ---------- + data : (M, N) ndarray + + """ + check_nD(data, 2, 'data') + F, G = self._prepare(data) + out = fft.ifftn(F * G) + out = np.abs(_center(out, data.shape)) + return out + + +def filter_forward( + data, impulse_response=None, filter_params=None, predefined_filter=None +): + """Apply the given filter to data. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See LPIFilter2D.__init__. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + Examples + -------- + + Gaussian filter without normalization: + + >>> def filt_func(r, c, sigma=1): + ... return np.exp(-(r**2 + c**2)/(2 * sigma**2)) + >>> + >>> from skimage import data + >>> filtered = filter_forward(data.coins(), filt_func) + + """ + if filter_params is None: + filter_params = {} + check_nD(data, 2, 'data') + if predefined_filter is None: + predefined_filter = LPIFilter2D(impulse_response, **filter_params) + return predefined_filter(data) + + +def filter_inverse( + data, impulse_response=None, filter_params=None, max_gain=2, predefined_filter=None +): + """Apply the filter in reverse to the given data. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See :class:`~.LPIFilter2D`. This is a required + argument unless a `predifined_filter` is provided. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + max_gain : float, optional + Limit the filter gain. Often, the filter contains zeros, which would + cause the inverse filter to have infinite gain. High gain causes + amplification of artefacts, so a conservative limit is recommended. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D, optional + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + """ + if filter_params is None: + filter_params = {} + + check_nD(data, 2, 'data') + if predefined_filter is None: + filt = LPIFilter2D(impulse_response, **filter_params) + else: + filt = predefined_filter + + F, G = filt._prepare(data) + _min_limit(F, val=np.finfo(F.real.dtype).eps) + + F = 1 / F + mask = np.abs(F) > max_gain + F[mask] = np.sign(F[mask]) * max_gain + + return _center(np.abs(fft.ifftshift(fft.ifftn(G * F))), data.shape) + + +def wiener( + data, impulse_response=None, filter_params=None, K=0.25, predefined_filter=None +): + """Minimum Mean Square Error (Wiener) inverse filter. + + Parameters + ---------- + data : (M, N) ndarray + Input data. + K : float or (M, N) ndarray + Ratio between power spectrum of noise and undegraded + image. + impulse_response : callable `f(r, c, **filter_params)` + Impulse response of the filter. See LPIFilter2D.__init__. + filter_params : dict, optional + Additional keyword parameters to the impulse_response function. + + Other Parameters + ---------------- + predefined_filter : LPIFilter2D + If you need to apply the same filter multiple times over different + images, construct the LPIFilter2D and specify it here. + + """ + if filter_params is None: + filter_params = {} + + check_nD(data, 2, 'data') + + if not isinstance(K, float): + check_nD(K, 2, 'K') + + if predefined_filter is None: + filt = LPIFilter2D(impulse_response, **filter_params) + else: + filt = predefined_filter + + F, G = filt._prepare(data) + _min_limit(F, val=np.finfo(F.real.dtype).eps) + + H_mag_sqr = np.abs(F) ** 2 + F = 1 / F * H_mag_sqr / (H_mag_sqr + K) + + return _center(np.abs(fft.ifftshift(fft.ifftn(G * F))), data.shape) diff --git a/python_embeded/Lib/site-packages/skimage/filters/ridges.py b/python_embeded/Lib/site-packages/skimage/filters/ridges.py new file mode 100644 index 0000000000000000000000000000000000000000..e21f40b75671fbb5bdeaeeb4f384d7ec87e83a01 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/ridges.py @@ -0,0 +1,393 @@ +""" +Ridge filters. + +Ridge filters can be used to detect continuous edges, such as vessels, +neurites, wrinkles, rivers, and other tube-like structures. The present +class of ridge filters relies on the eigenvalues of the Hessian matrix of +image intensities to detect tube-like structures where the intensity changes +perpendicular but not along the structure. +""" + +from warnings import warn + +import numpy as np +from scipy import linalg + +from .._shared.utils import _supported_float_type, check_nD +from ..feature.corner import hessian_matrix, hessian_matrix_eigvals + + +def meijering( + image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0 +): + """ + Filter an image with the Meijering neuriteness filter. + + This filter can be used to detect continuous ridges, e.g. neurites, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Calculates the eigenvalues of the Hessian to compute the similarity of + an image region to neurites, according to the method described in [1]_. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter + alpha : float, optional + Shaping filter constant, that selects maximally flat elongated + features. The default, None, selects the optimal value -1/(ndim+1). + black_ridges : boolean, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, ...]) ndarray + Filtered image (maximum of pixels across all scales). + + See also + -------- + sato + frangi + hessian + + References + ---------- + .. [1] Meijering, E., Jacob, M., Sarria, J. C., Steiner, P., Hirling, H., + Unser, M. (2004). Design and validation of a tool for neurite tracing + and analysis in fluorescence microscopy images. Cytometry Part A, + 58(2), 167-176. + :DOI:`10.1002/cyto.a.20022` + """ + + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + if alpha is None: + alpha = 1 / (image.ndim + 1) + mtx = linalg.circulant([1, *[alpha] * (image.ndim - 1)]).astype(image.dtype) + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Compute normalized eigenvalues l_i = e_i + sum_{j!=i} alpha * e_j. + vals = np.tensordot(mtx, eigvals, 1) + # Get largest normalized eigenvalue (by magnitude) at each pixel. + vals = np.take_along_axis(vals, abs(vals).argmax(0)[None], 0).squeeze(0) + # Remove negative values. + vals = np.maximum(vals, 0) + # Normalize to max = 1 (unless everything is already zero). + max_val = vals.max() + if max_val > 0: + vals /= max_val + filtered_max = np.maximum(filtered_max, vals) + + return filtered_max # Return pixel-wise max over all sigmas. + + +def sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode='reflect', cval=0): + """ + Filter an image with the Sato tubeness filter. + + This filter can be used to detect continuous ridges, e.g. tubes, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Defined only for 2-D and 3-D images. Calculates the eigenvalues of the + Hessian to compute the similarity of an image region to tubes, according to + the method described in [1]_. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter. + black_ridges : boolean, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + See also + -------- + meijering + frangi + hessian + + References + ---------- + .. [1] Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., + Koller, T., ..., Kikinis, R. (1998). Three-dimensional multi-scale line + filter for segmentation and visualization of curvilinear structures in + medical images. Medical image analysis, 2(2), 143-168. + :DOI:`10.1016/S1361-8415(98)80009-1` + """ + + check_nD(image, [2, 3]) # Check image dimensions. + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Compute normalized tubeness (eqs. (9) and (22), ref. [1]_) as the + # geometric mean of eigvals other than the lowest one + # (hessian_matrix_eigvals returns eigvals in decreasing order), clipped + # to 0, multiplied by sigma^2. + eigvals = eigvals[:-1] + vals = sigma**2 * np.prod(np.maximum(eigvals, 0), 0) ** (1 / len(eigvals)) + filtered_max = np.maximum(filtered_max, vals) + return filtered_max # Return pixel-wise max over all sigmas. + + +def frangi( + image, + sigmas=range(1, 10, 2), + scale_range=None, + scale_step=None, + alpha=0.5, + beta=0.5, + gamma=None, + black_ridges=True, + mode='reflect', + cval=0, +): + """ + Filter an image with the Frangi vesselness filter. + + This filter can be used to detect continuous ridges, e.g. vessels, + wrinkles, rivers. It can be used to calculate the fraction of the + whole image containing such objects. + + Defined only for 2-D and 3-D images. Calculates the eigenvalues of the + Hessian to compute the similarity of an image region to vessels, according + to the method described in [1]_. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter, i.e., + np.arange(scale_range[0], scale_range[1], scale_step) + scale_range : 2-tuple of floats, optional + The range of sigmas used. + scale_step : float, optional + Step size between sigmas. + alpha : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a plate-like structure. + beta : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a blob-like structure. + gamma : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to areas of high variance/texture/structure. + The default, None, uses half of the maximum Hessian norm. + black_ridges : boolean, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + Notes + ----- + Earlier versions of this filter were implemented by Marc Schrijver, + (November 2001), D. J. Kroon, University of Twente (May 2009) [2]_, and + D. G. Ellis (January 2017) [3]_. + + See also + -------- + meijering + sato + hessian + + References + ---------- + .. [1] Frangi, A. F., Niessen, W. J., Vincken, K. L., & Viergever, M. A. + (1998,). Multiscale vessel enhancement filtering. In International + Conference on Medical Image Computing and Computer-Assisted + Intervention (pp. 130-137). Springer Berlin Heidelberg. + :DOI:`10.1007/BFb0056195` + .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter. + .. [3] Ellis, D. G.: https://github.com/ellisdg/frangi3d/tree/master/frangi + """ + if scale_range is not None and scale_step is not None: + warn( + 'Use keyword parameter `sigmas` instead of `scale_range` and ' + '`scale_range` which will be removed in version 0.17.', + stacklevel=2, + ) + sigmas = np.arange(scale_range[0], scale_range[1], scale_step) + + check_nD(image, [2, 3]) # Check image dimensions. + image = image.astype(_supported_float_type(image.dtype), copy=False) + if not black_ridges: # Normalize to black ridges. + image = -image + + # Generate empty array for storing maximum value + # from different (sigma) scales + filtered_max = np.zeros_like(image) + for sigma in sigmas: # Filter for all sigmas. + eigvals = hessian_matrix_eigvals( + hessian_matrix( + image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True + ) + ) + # Sort eigenvalues by magnitude. + eigvals = np.take_along_axis(eigvals, abs(eigvals).argsort(0), 0) + lambda1 = eigvals[0] + if image.ndim == 2: + (lambda2,) = np.maximum(eigvals[1:], 1e-10) + r_a = np.inf # implied by eq. (15). + r_b = abs(lambda1) / lambda2 # eq. (15). + else: # ndim == 3 + lambda2, lambda3 = np.maximum(eigvals[1:], 1e-10) + r_a = lambda2 / lambda3 # eq. (11). + r_b = abs(lambda1) / np.sqrt(lambda2 * lambda3) # eq. (10). + s = np.sqrt((eigvals**2).sum(0)) # eq. (12). + if gamma is None: + gamma = s.max() / 2 + if gamma == 0: + gamma = 1 # If s == 0 everywhere, gamma doesn't matter. + # Filtered image, eq. (13) and (15). Our implementation relies on the + # blobness exponential factor underflowing to zero whenever the second + # or third eigenvalues are negative (we clip them to 1e-10, to make r_b + # very large). + vals = 1.0 - np.exp( + -(r_a**2) / (2 * alpha**2), dtype=image.dtype + ) # plate sensitivity + vals *= np.exp(-(r_b**2) / (2 * beta**2), dtype=image.dtype) # blobness + vals *= 1.0 - np.exp( + -(s**2) / (2 * gamma**2), dtype=image.dtype + ) # structuredness + filtered_max = np.maximum(filtered_max, vals) + return filtered_max # Return pixel-wise max over all sigmas. + + +def hessian( + image, + sigmas=range(1, 10, 2), + scale_range=None, + scale_step=None, + alpha=0.5, + beta=0.5, + gamma=15, + black_ridges=True, + mode='reflect', + cval=0, +): + """Filter an image with the Hybrid Hessian filter. + + This filter can be used to detect continuous edges, e.g. vessels, + wrinkles, rivers. It can be used to calculate the fraction of the whole + image containing such objects. + + Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but + uses alternative method of smoothing. Refer to [1]_ to find the differences + between Frangi and Hessian filters. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Array with input image data. + sigmas : iterable of floats, optional + Sigmas used as scales of filter, i.e., + np.arange(scale_range[0], scale_range[1], scale_step) + scale_range : 2-tuple of floats, optional + The range of sigmas used. + scale_step : float, optional + Step size between sigmas. + beta : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to deviation from a blob-like structure. + gamma : float, optional + Frangi correction constant that adjusts the filter's + sensitivity to areas of high variance/texture/structure. + black_ridges : boolean, optional + When True (the default), the filter detects black ridges; when + False, it detects white ridges. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + out : (M, N[, P]) ndarray + Filtered image (maximum of pixels across all scales). + + Notes + ----- + Written by Marc Schrijver (November 2001) + Re-Written by D. J. Kroon University of Twente (May 2009) [2]_ + + See also + -------- + meijering + sato + frangi + + References + ---------- + .. [1] Ng, C. C., Yap, M. H., Costen, N., & Li, B. (2014,). Automatic + wrinkle detection using hybrid Hessian filter. In Asian Conference on + Computer Vision (pp. 609-622). Springer International Publishing. + :DOI:`10.1007/978-3-319-16811-1_40` + .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter. + """ + filtered = frangi( + image, + sigmas=sigmas, + scale_range=scale_range, + scale_step=scale_step, + alpha=alpha, + beta=beta, + gamma=gamma, + black_ridges=black_ridges, + mode=mode, + cval=cval, + ) + + filtered[filtered <= 0] = 1 + return filtered diff --git a/python_embeded/Lib/site-packages/skimage/filters/thresholding.py b/python_embeded/Lib/site-packages/skimage/filters/thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..7f17dab73baed46d282d168528864e612f1160a1 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/filters/thresholding.py @@ -0,0 +1,1339 @@ +import inspect +import itertools +import math +from collections import OrderedDict +from collections.abc import Iterable + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, warn +from .._shared.version_requirements import require +from ..exposure import histogram +from ..filters._multiotsu import ( + _get_multiotsu_thresh_indices, + _get_multiotsu_thresh_indices_lut, +) +from ..transform import integral_image +from ..util import dtype_limits +from ._sparse import _correlate_sparse, _validate_window_size + +__all__ = [ + 'try_all_threshold', + 'threshold_otsu', + 'threshold_yen', + 'threshold_isodata', + 'threshold_li', + 'threshold_local', + 'threshold_minimum', + 'threshold_mean', + 'threshold_niblack', + 'threshold_sauvola', + 'threshold_triangle', + 'apply_hysteresis_threshold', + 'threshold_multiotsu', +] + + +def _try_all(image, methods=None, figsize=None, num_cols=2, verbose=True): + """Returns a figure comparing the outputs of different methods. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + methods : dict, optional + Names and associated functions. + Functions must take and return an image. + figsize : tuple, optional + Figure size (in inches). + num_cols : int, optional + Number of columns. + verbose : bool, optional + Print function name for each method. + + Returns + ------- + fig, ax : tuple + Matplotlib figure and axes. + """ + from matplotlib import pyplot as plt + + # Compute the image histogram for better performances + nbins = 256 # Default in threshold functions + hist = histogram(image.reshape(-1), nbins, source_range='image') + + # Handle default value + methods = methods or {} + + num_rows = math.ceil((len(methods) + 1.0) / num_cols) + fig, ax = plt.subplots( + num_rows, num_cols, figsize=figsize, sharex=True, sharey=True + ) + ax = ax.reshape(-1) + + ax[0].imshow(image, cmap=plt.cm.gray) + ax[0].set_title('Original') + + i = 1 + for name, func in methods.items(): + # Use precomputed histogram for supporting functions + sig = inspect.signature(func) + _kwargs = dict(hist=hist) if 'hist' in sig.parameters else {} + + ax[i].set_title(name) + try: + ax[i].imshow(func(image, **_kwargs), cmap=plt.cm.gray) + except Exception as e: + ax[i].text( + 0.5, + 0.5, + f"{type(e).__name__}", + ha="center", + va="center", + transform=ax[i].transAxes, + ) + i += 1 + if verbose: + print(func.__orifunc__) + + for a in ax: + a.axis('off') + + fig.tight_layout() + return fig, ax + + +@require("matplotlib", ">=3.3") +def try_all_threshold(image, figsize=(8, 5), verbose=True): + """Returns a figure comparing the outputs of different thresholding methods. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + figsize : tuple, optional + Figure size (in inches). + verbose : bool, optional + Print function name for each method. + + Returns + ------- + fig, ax : tuple + Matplotlib figure and axes. + + Notes + ----- + The following algorithms are used: + + * isodata + * li + * mean + * minimum + * otsu + * triangle + * yen + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('matplotlib') + + >>> from skimage.data import text + >>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False) + """ + + def thresh(func): + """ + A wrapper function to return a thresholded image. + """ + + def wrapper(im): + return im > func(im) + + try: + wrapper.__orifunc__ = func.__orifunc__ + except AttributeError: + wrapper.__orifunc__ = func.__module__ + '.' + func.__name__ + return wrapper + + # Global algorithms. + methods = OrderedDict( + { + 'Isodata': thresh(threshold_isodata), + 'Li': thresh(threshold_li), + 'Mean': thresh(threshold_mean), + 'Minimum': thresh(threshold_minimum), + 'Otsu': thresh(threshold_otsu), + 'Triangle': thresh(threshold_triangle), + 'Yen': thresh(threshold_yen), + } + ) + + return _try_all(image, figsize=figsize, methods=methods, verbose=verbose) + + +def threshold_local( + image, block_size=3, method='gaussian', offset=0, mode='reflect', param=None, cval=0 +): + """Compute a threshold mask image based on local pixel neighborhood. + + Also known as adaptive or dynamic thresholding. The threshold value is + the weighted mean for the local neighborhood of a pixel subtracted by a + constant. Alternatively the threshold can be determined dynamically by a + given function, using the 'generic' method. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + block_size : int or sequence of int + Odd size of pixel neighborhood which is used to calculate the + threshold value (e.g. 3, 5, 7, ..., 21, ...). + method : {'generic', 'gaussian', 'mean', 'median'}, optional + Method used to determine adaptive threshold for local neighborhood in + weighted mean image. + + * 'generic': use custom function (see ``param`` parameter) + * 'gaussian': apply gaussian filter (see ``param`` parameter for custom\ + sigma value) + * 'mean': apply arithmetic mean filter + * 'median': apply median rank filter + + By default, the 'gaussian' method is used. + offset : float, optional + Constant subtracted from weighted mean of neighborhood to calculate + the local threshold value. Default offset is 0. + 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'. + param : {int, function}, optional + Either specify sigma for 'gaussian' method or function object for + 'generic' method. This functions takes the flat array of local + neighborhood as a single argument and returns the calculated + threshold for the centre pixel. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold image. All pixels in the input image higher than the + corresponding pixel in the threshold image are considered foreground. + + References + ---------- + .. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing + (2nd Edition)." Prentice-Hall Inc., 2002: 600--612. + ISBN: 0-201-18075-8 + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera()[:50, :50] + >>> binary_image1 = image > threshold_local(image, 15, 'mean') + >>> func = lambda arr: arr.mean() + >>> binary_image2 = image > threshold_local(image, 15, 'generic', + ... param=func) + + """ + + if np.isscalar(block_size): + block_size = (block_size,) * image.ndim + elif len(block_size) != image.ndim: + raise ValueError("len(block_size) must equal image.ndim.") + block_size = tuple(block_size) + if any(b % 2 == 0 for b in block_size): + raise ValueError( + f'block_size must be odd! Given block_size ' + f'{block_size} contains even values.' + ) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + thresh_image = np.zeros(image.shape, dtype=float_dtype) + if method == 'generic': + ndi.generic_filter( + image, param, block_size, output=thresh_image, mode=mode, cval=cval + ) + elif method == 'gaussian': + if param is None: + # automatically determine sigma which covers > 99% of distribution + sigma = tuple([(b - 1) / 6.0 for b in block_size]) + else: + sigma = param + gaussian(image, sigma=sigma, out=thresh_image, mode=mode, cval=cval) + elif method == 'mean': + ndi.uniform_filter(image, block_size, output=thresh_image, mode=mode, cval=cval) + elif method == 'median': + ndi.median_filter(image, block_size, output=thresh_image, mode=mode, cval=cval) + else: + raise ValueError( + "Invalid method specified. Please use `generic`, " + "`gaussian`, `mean`, or `median`." + ) + + return thresh_image - offset + + +def _validate_image_histogram(image, hist, nbins=None, normalize=False): + """Ensure that either image or hist were given, return valid histogram. + + If hist is given, image is ignored. + + Parameters + ---------- + image : array or None + Grayscale image. + hist : array, 2-tuple of array, or None + Histogram, either a 1D counts array, or an array of counts together + with an array of bin centers. + nbins : int, optional + The number of bins with which to compute the histogram, if `hist` is + None. + normalize : bool + If hist is not given, it will be computed by this function. This + parameter determines whether the computed histogram is normalized + (i.e. entries sum up to 1) or not. + + Returns + ------- + counts : 1D array of float + Each element is the number of pixels falling in each intensity bin. + bin_centers : 1D array + Each element is the value corresponding to the center of each intensity + bin. + + Raises + ------ + ValueError : if image and hist are both None + """ + if image is None and hist is None: + raise Exception("Either image or hist must be provided.") + + if hist is not None: + if isinstance(hist, (tuple, list)): + counts, bin_centers = hist + else: + counts = hist + bin_centers = np.arange(counts.size) + + if counts[0] == 0 or counts[-1] == 0: + # Trim histogram from both ends by removing starting and + # ending zeroes as in histogram(..., source_range="image") + cond = counts > 0 + start = np.argmax(cond) + end = cond.size - np.argmax(cond[::-1]) + counts, bin_centers = counts[start:end], bin_centers[start:end] + else: + counts, bin_centers = histogram( + image.reshape(-1), nbins, source_range='image', normalize=normalize + ) + return counts.astype('float32', copy=False), bin_centers + + +def threshold_otsu(image=None, nbins=256, *, hist=None): + """Return threshold value based on Otsu's method. + + Either image or hist must be provided. If hist is provided, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. If no hist provided, + this function will compute it from the image. + + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Wikipedia, https://en.wikipedia.org/wiki/Otsu's_Method + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_otsu(image) + >>> binary = image <= thresh + + Notes + ----- + The input image must be grayscale. + """ + if image is not None and image.ndim > 2 and image.shape[-1] in (3, 4): + warn( + f'threshold_otsu is expected to work correctly only for ' + f'grayscale images; image shape {image.shape} looks like ' + f'that of an RGB image.' + ) + + # Check if the image has more than one intensity value; if not, return that + # value + if image is not None: + first_pixel = image.reshape(-1)[0] + if np.all(image == first_pixel): + return first_pixel + + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # class probabilities for all possible thresholds + weight1 = np.cumsum(counts) + weight2 = np.cumsum(counts[::-1])[::-1] + # class means for all possible thresholds + mean1 = np.cumsum(counts * bin_centers) / weight1 + mean2 = (np.cumsum((counts * bin_centers)[::-1]) / weight2[::-1])[::-1] + + # Clip ends to align class 1 and class 2 variables: + # The last value of ``weight1``/``mean1`` should pair with zero values in + # ``weight2``/``mean2``, which do not exist. + variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2 + + idx = np.argmax(variance12) + threshold = bin_centers[idx] + + return threshold + + +def threshold_yen(image=None, nbins=256, *, hist=None): + """Return threshold value based on Yen's method. + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. + An alternative use of this function is to pass it only hist. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion + for Automatic Multilevel Thresholding" IEEE Trans. on Image + Processing, 4(3): 370-378. :DOI:`10.1109/83.366472` + .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165, :DOI:`10.1117/1.1631315` + http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf + .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_yen(image) + >>> binary = image <= thresh + """ + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # On blank images (e.g. filled with 0) with int dtype, `histogram()` + # returns ``bin_centers`` containing only one value. Speed up with it. + if bin_centers.size == 1: + return bin_centers[0] + + # Calculate probability mass function + pmf = counts.astype('float32', copy=False) / counts.sum() + P1 = np.cumsum(pmf) # Cumulative normalized histogram + P1_sq = np.cumsum(pmf**2) + # Get cumsum calculated from end of squared array: + P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1] + # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid + # '-inf' in crit. ImageJ Yen implementation replaces those values by zero. + crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) * (P1[:-1] * (1.0 - P1[:-1])) ** 2) + return bin_centers[crit.argmax()] + + +def threshold_isodata(image=None, nbins=256, return_all=False, *, hist=None): + """Return threshold value(s) based on ISODATA method. + + Histogram-based threshold, known as Ridler-Calvard method or inter-means. + Threshold values returned satisfy the following equality:: + + threshold = (image[image <= threshold].mean() + + image[image > threshold].mean()) / 2.0 + + That is, returned thresholds are intensities that separate the image into + two groups of pixels, where the threshold intensity is midway between the + mean intensities of these groups. + + For integer images, the above equality holds to within one; for floating- + point images, the equality holds to within the histogram bin-width. + + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + return_all : bool, optional + If False (default), return only the lowest threshold that satisfies + the above equality. If True, return all valid thresholds. + hist : array, or 2-tuple of arrays, optional + Histogram to determine the threshold from and a corresponding array + of bin center intensities. Alternatively, only the histogram can be + passed. + + Returns + ------- + threshold : float or int or array + Threshold value(s). + + References + ---------- + .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an + iterative selection method" + IEEE Transactions on Systems, Man and Cybernetics 8: 630-632, + :DOI:`10.1109/TSMC.1978.4310039` + .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165, + http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf + :DOI:`10.1117/1.1631315` + .. [3] ImageJ AutoThresholder code, + http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import coins + >>> image = coins() + >>> thresh = threshold_isodata(image) + >>> binary = image > thresh + """ + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + # image only contains one unique value + if len(bin_centers) == 1: + if return_all: + return bin_centers + else: + return bin_centers[0] + + counts = counts.astype('float32', copy=False) + + # csuml and csumh contain the count of pixels in that bin or lower, and + # in all bins strictly higher than that bin, respectively + csuml = np.cumsum(counts) + csumh = csuml[-1] - csuml + + # intensity_sum contains the total pixel intensity from each bin + intensity_sum = counts * bin_centers + + # l and h contain average value of all pixels in that bin or lower, and + # in all bins strictly higher than that bin, respectively. + # Note that since exp.histogram does not include empty bins at the low or + # high end of the range, csuml and csumh are strictly > 0, except in the + # last bin of csumh, which is zero by construction. + # So no worries about division by zero in the following lines, except + # for the last bin, but we can ignore that because no valid threshold + # can be in the top bin. + # To avoid the division by zero, we simply skip over the last element in + # all future computation. + csum_intensity = np.cumsum(intensity_sum) + lower = csum_intensity[:-1] / csuml[:-1] + higher = (csum_intensity[-1] - csum_intensity[:-1]) / csumh[:-1] + + # isodata finds threshold values that meet the criterion t = (l + m)/2 + # where l is the mean of all pixels <= t and h is the mean of all pixels + # > t, as calculated above. So we are looking for places where + # (l + m) / 2 equals the intensity value for which those l and m figures + # were calculated -- which is, of course, the histogram bin centers. + # We only require this equality to be within the precision of the bin + # width, of course. + all_mean = (lower + higher) / 2.0 + bin_width = bin_centers[1] - bin_centers[0] + + # Look only at thresholds that are below the actual all_mean value, + # for consistency with the threshold being included in the lower pixel + # group. Otherwise, can get thresholds that are not actually fixed-points + # of the isodata algorithm. For float images, this matters less, since + # there really can't be any guarantees anymore anyway. + distances = all_mean - bin_centers[:-1] + thresholds = bin_centers[:-1][(distances >= 0) & (distances < bin_width)] + + if return_all: + return thresholds + else: + return thresholds[0] + + +# Computing a histogram using np.histogram on a uint8 image with bins=256 +# doesn't work and results in aliasing problems. We use a fully specified set +# of bins to ensure that each uint8 value false into its own bin. +_DEFAULT_ENTROPY_BINS = tuple(np.arange(-0.5, 255.51, 1)) + + +def _cross_entropy(image, threshold, bins=_DEFAULT_ENTROPY_BINS): + """Compute cross-entropy between distributions above and below a threshold. + + Parameters + ---------- + image : array + The input array of values. + threshold : float + The value dividing the foreground and background in ``image``. + bins : int or array of float, optional + The number of bins or the bin edges. (Any valid value to the ``bins`` + argument of ``np.histogram`` will work here.) For an exact calculation, + each unique value should have its own bin. The default value for bins + ensures exact handling of uint8 images: ``bins=256`` results in + aliasing problems due to bin width not being equal to 1. + + Returns + ------- + nu : float + The cross-entropy target value as defined in [1]_. + + Notes + ----- + See Li and Lee, 1993 [1]_; this is the objective function ``threshold_li`` + minimizes. This function can be improved but this implementation most + closely matches equation 8 in [1]_ and equations 1-3 in [2]_. + + References + ---------- + .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding" + Pattern Recognition, 26(4): 617-625 + :DOI:`10.1016/0031-3203(93)90115-D` + .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum + Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776 + :DOI:`10.1016/S0167-8655(98)00057-9` + """ + histogram, bin_edges = np.histogram(image, bins=bins, density=True) + bin_centers = np.convolve(bin_edges, [0.5, 0.5], mode='valid') + t = np.flatnonzero(bin_centers > threshold)[0] + m0a = np.sum(histogram[:t]) # 0th moment, background + m0b = np.sum(histogram[t:]) + m1a = np.sum(histogram[:t] * bin_centers[:t]) # 1st moment, background + m1b = np.sum(histogram[t:] * bin_centers[t:]) + mua = m1a / m0a # mean value, background + mub = m1b / m0b + nu = -m1a * np.log(mua) - m1b * np.log(mub) + return nu + + +def threshold_li(image, *, tolerance=None, initial_guess=None, iter_callback=None): + """Compute threshold value by Li's iterative Minimum Cross Entropy method. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + tolerance : float, optional + Finish the computation when the change in the threshold in an iteration + is less than this value. By default, this is half the smallest + difference between intensity values in ``image``. + initial_guess : float or Callable[[array[float]], float], optional + Li's iterative method uses gradient descent to find the optimal + threshold. If the image intensity histogram contains more than two + modes (peaks), the gradient descent could get stuck in a local optimum. + An initial guess for the iteration can help the algorithm find the + globally-optimal threshold. A float value defines a specific start + point, while a callable should take in an array of image intensities + and return a float value. Example valid callables include + ``numpy.mean`` (default), ``lambda arr: numpy.quantile(arr, 0.95)``, + or even :func:`skimage.filters.threshold_otsu`. + iter_callback : Callable[[float], Any], optional + A function that will be called on the threshold at every iteration of + the algorithm. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding" + Pattern Recognition, 26(4): 617-625 + :DOI:`10.1016/0031-3203(93)90115-D` + .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum + Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776 + :DOI:`10.1016/S0167-8655(98)00057-9` + .. [3] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding + Techniques and Quantitative Performance Evaluation" Journal of + Electronic Imaging, 13(1): 146-165 + :DOI:`10.1117/1.1631315` + .. [4] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_li(image) + >>> binary = image > thresh + """ + # Remove nan: + image = image[~np.isnan(image)] + if image.size == 0: + return np.nan + + # Make sure image has more than one value; otherwise, return that value + # This works even for np.inf + if np.all(image == image.flat[0]): + return image.flat[0] + + # At this point, the image only contains np.inf, -np.inf, or valid numbers + image = image[np.isfinite(image)] + # if there are no finite values in the image, return 0. This is because + # at this point we *know* that there are *both* inf and -inf values, + # because inf == inf evaluates to True. We might as well separate them. + if image.size == 0: + return 0.0 + + # Li's algorithm requires positive image (because of log(mean)) + image_min = np.min(image) + image -= image_min + if image.dtype.kind in 'iu': + tolerance = tolerance or 0.5 + else: + tolerance = tolerance or np.min(np.diff(np.unique(image))) / 2 + + # Initial estimate for iteration. See "initial_guess" in the parameter list + if initial_guess is None: + t_next = np.mean(image) + elif callable(initial_guess): + t_next = initial_guess(image) + elif np.isscalar(initial_guess): # convert to new, positive image range + t_next = initial_guess - float(image_min) + image_max = np.max(image) + image_min + if not 0 < t_next < np.max(image): + msg = ( + f'The initial guess for threshold_li must be within the ' + f'range of the image. Got {initial_guess} for image min ' + f'{image_min} and max {image_max}.' + ) + raise ValueError(msg) + t_next = image.dtype.type(t_next) + else: + raise TypeError( + 'Incorrect type for `initial_guess`; should be ' + 'a floating point value, or a function mapping an ' + 'array to a floating point value.' + ) + + # initial value for t_curr must be different from t_next by at + # least the tolerance. Since the image is positive, we ensure this + # by setting to a large-enough negative number + t_curr = -2 * tolerance + + # Callback on initial iterations + if iter_callback is not None: + iter_callback(t_next + image_min) + + # Stop the iterations when the difference between the + # new and old threshold values is less than the tolerance + # or if the background mode has only one value left, + # since log(0) is not defined. + + if image.dtype.kind in 'iu': + hist, bin_centers = histogram(image.reshape(-1), source_range='image') + hist = hist.astype('float32', copy=False) + while abs(t_next - t_curr) > tolerance: + t_curr = t_next + foreground = bin_centers > t_curr + background = ~foreground + + mean_fore = np.average(bin_centers[foreground], weights=hist[foreground]) + mean_back = np.average(bin_centers[background], weights=hist[background]) + + if mean_back == 0: + break + + t_next = (mean_back - mean_fore) / (np.log(mean_back) - np.log(mean_fore)) + + if iter_callback is not None: + iter_callback(t_next + image_min) + + else: + while abs(t_next - t_curr) > tolerance: + t_curr = t_next + foreground = image > t_curr + mean_fore = np.mean(image[foreground]) + mean_back = np.mean(image[~foreground]) + + if mean_back == 0.0: + break + + t_next = (mean_back - mean_fore) / (np.log(mean_back) - np.log(mean_fore)) + + if iter_callback is not None: + iter_callback(t_next + image_min) + + threshold = t_next + image_min + return threshold + + +def threshold_minimum(image=None, nbins=256, max_num_iter=10000, *, hist=None): + """Return threshold value based on minimum method. + + The histogram of the input ``image`` is computed if not provided and + smoothed until there are only two maxima. Then the minimum in between is + the threshold value. + + Either image or hist must be provided. In case hist is given, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + max_num_iter : int, optional + Maximum number of iterations to smooth the histogram. + hist : array, or 2-tuple of arrays, optional + Histogram to determine the threshold from and a corresponding array + of bin center intensities. Alternatively, only the histogram can be + passed. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + Raises + ------ + RuntimeError + If unable to find two local maxima in the histogram or if the + smoothing takes more than 1e4 iterations. + + References + ---------- + .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding + algorithms," CVGIP: Graphical Models and Image Processing, + vol. 55, pp. 532-537, 1993. + .. [2] Prewitt, JMS & Mendelsohn, ML (1966), "The analysis of cell + images", Annals of the New York Academy of Sciences 128: 1035-1053 + :DOI:`10.1111/j.1749-6632.1965.tb11715.x` + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_minimum(image) + >>> binary = image > thresh + """ + + def find_local_maxima_idx(hist): + # We can't use scipy.signal.argrelmax + # as it fails on plateaus + maximum_idxs = list() + direction = 1 + + for i in range(hist.shape[0] - 1): + if direction > 0: + if hist[i + 1] < hist[i]: + direction = -1 + maximum_idxs.append(i) + else: + if hist[i + 1] > hist[i]: + direction = 1 + + return maximum_idxs + + counts, bin_centers = _validate_image_histogram(image, hist, nbins) + + smooth_hist = counts.astype('float32', copy=False) + + for counter in range(max_num_iter): + smooth_hist = ndi.uniform_filter1d(smooth_hist, 3) + maximum_idxs = find_local_maxima_idx(smooth_hist) + if len(maximum_idxs) < 3: + break + + if len(maximum_idxs) != 2: + raise RuntimeError('Unable to find two maxima in histogram') + elif counter == max_num_iter - 1: + raise RuntimeError('Maximum iteration reached for histogram' 'smoothing') + + # Find the lowest point between the maxima + threshold_idx = np.argmin(smooth_hist[maximum_idxs[0] : maximum_idxs[1] + 1]) + + return bin_centers[maximum_idxs[0] + threshold_idx] + + +def threshold_mean(image): + """Return threshold value based on the mean of grayscale values. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding + algorithms," CVGIP: Graphical Models and Image Processing, + vol. 55, pp. 532-537, 1993. + :DOI:`10.1006/cgip.1993.1040` + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_mean(image) + >>> binary = image > thresh + """ + return np.mean(image) + + +def threshold_triangle(image, nbins=256): + """Return threshold value based on the triangle algorithm. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + nbins : int, optional + Number of bins used to calculate histogram. This value is ignored for + integer arrays. + + Returns + ------- + threshold : float + Upper threshold value. All pixels with an intensity higher than + this value are assumed to be foreground. + + References + ---------- + .. [1] Zack, G. W., Rogers, W. E. and Latt, S. A., 1977, + Automatic Measurement of Sister Chromatid Exchange Frequency, + Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753 + :DOI:`10.1177/25.7.70454` + .. [2] ImageJ AutoThresholder code, + http://fiji.sc/wiki/index.php/Auto_Threshold + + Examples + -------- + >>> from skimage.data import camera + >>> image = camera() + >>> thresh = threshold_triangle(image) + >>> binary = image > thresh + """ + # nbins is ignored for integer arrays + # so, we recalculate the effective nbins. + hist, bin_centers = histogram(image.reshape(-1), nbins, source_range='image') + nbins = len(hist) + + # Find peak, lowest and highest gray levels. + arg_peak_height = np.argmax(hist) + peak_height = hist[arg_peak_height] + arg_low_level, arg_high_level = np.flatnonzero(hist)[[0, -1]] + + if arg_low_level == arg_high_level: + # Image has constant intensity. + return image.ravel()[0] + + # Flip is True if left tail is shorter. + flip = arg_peak_height - arg_low_level < arg_high_level - arg_peak_height + if flip: + hist = hist[::-1] + arg_low_level = nbins - arg_high_level - 1 + arg_peak_height = nbins - arg_peak_height - 1 + + # If flip == True, arg_high_level becomes incorrect + # but we don't need it anymore. + del arg_high_level + + # Set up the coordinate system. + width = arg_peak_height - arg_low_level + x1 = np.arange(width) + y1 = hist[x1 + arg_low_level] + + # Normalize. + norm = np.sqrt(peak_height**2 + width**2) + peak_height /= norm + width /= norm + + # Maximize the length. + # The ImageJ implementation includes an additional constant when calculating + # the length, but here we omit it as it does not affect the location of the + # minimum. + length = peak_height * x1 - width * y1 + arg_level = np.argmax(length) + arg_low_level + + if flip: + arg_level = nbins - arg_level - 1 + + return bin_centers[arg_level] + + +def _mean_std(image, w): + """Return local mean and standard deviation of each pixel using a + neighborhood defined by a rectangular window size ``w``. + The algorithm uses integral images to speedup computation. This is + used by :func:`threshold_niblack` and :func:`threshold_sauvola`. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + w : int, or iterable of int + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + + Returns + ------- + m : ndarray of float, same shape as ``image`` + Local mean of the image. + s : ndarray of float, same shape as ``image`` + Local standard deviation of the image. + + References + ---------- + .. [1] F. Shafait, D. Keysers, and T. M. Breuel, "Efficient + implementation of local adaptive thresholding techniques + using integral images." in Document Recognition and + Retrieval XV, (San Jose, USA), Jan. 2008. + :DOI:`10.1117/12.767755` + """ + + if not isinstance(w, Iterable): + w = (w,) * image.ndim + _validate_window_size(w) + + float_dtype = _supported_float_type(image.dtype) + pad_width = tuple((k // 2 + 1, k // 2) for k in w) + padded = np.pad(image.astype(float_dtype, copy=False), pad_width, mode='reflect') + + # Note: keep float64 integral images for accuracy. Outputs of + # _correlate_sparse can later be safely cast to float_dtype + integral = integral_image(padded, dtype=np.float64) + padded *= padded + integral_sq = integral_image(padded, dtype=np.float64) + + # Create lists of non-zero kernel indices and values + kernel_indices = list(itertools.product(*tuple([(0, _w) for _w in w]))) + kernel_values = [ + (-1) ** (image.ndim % 2 != np.sum(indices) % 2) for indices in kernel_indices + ] + + total_window_size = math.prod(w) + kernel_shape = tuple(_w + 1 for _w in w) + m = _correlate_sparse(integral, kernel_shape, kernel_indices, kernel_values) + m = m.astype(float_dtype, copy=False) + m /= total_window_size + g2 = _correlate_sparse(integral_sq, kernel_shape, kernel_indices, kernel_values) + g2 = g2.astype(float_dtype, copy=False) + g2 /= total_window_size + # Note: we use np.clip because g2 is not guaranteed to be greater than + # m*m when floating point error is considered + s = np.sqrt(np.clip(g2 - m * m, 0, None)) + return m, s + + +def threshold_niblack(image, window_size=15, k=0.2): + """Applies Niblack local threshold to an array. + + A threshold T is calculated for every pixel in the image using the + following formula:: + + T = m(x,y) - k * s(x,y) + + where m(x,y) and s(x,y) are the mean and standard deviation of + pixel (x,y) neighborhood defined by a rectangular window with size w + times w centered around the pixel. k is a configurable parameter + that weights the effect of standard deviation. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + window_size : int, or iterable of int, optional + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + k : float, optional + Value of parameter k in threshold formula. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold mask. All pixels with an intensity higher than + this value are assumed to be foreground. + + Notes + ----- + This algorithm is originally designed for text recognition. + + The Bradley threshold is a particular case of the Niblack + one, being equivalent to + + >>> from skimage import data + >>> image = data.page() + >>> q = 1 + >>> threshold_image = threshold_niblack(image, k=0) * q + + for some value ``q``. By default, Bradley and Roth use ``q=1``. + + + References + ---------- + .. [1] W. Niblack, An introduction to Digital Image Processing, + Prentice-Hall, 1986. + .. [2] D. Bradley and G. Roth, "Adaptive thresholding using Integral + Image", Journal of Graphics Tools 12(2), pp. 13-21, 2007. + :DOI:`10.1080/2151237X.2007.10129236` + + Examples + -------- + >>> from skimage import data + >>> image = data.page() + >>> threshold_image = threshold_niblack(image, window_size=7, k=0.1) + """ + m, s = _mean_std(image, window_size) + return m - k * s + + +def threshold_sauvola(image, window_size=15, k=0.2, r=None): + """Applies Sauvola local threshold to an array. Sauvola is a + modification of Niblack technique. + + In the original method a threshold T is calculated for every pixel + in the image using the following formula:: + + T = m(x,y) * (1 + k * ((s(x,y) / R) - 1)) + + where m(x,y) and s(x,y) are the mean and standard deviation of + pixel (x,y) neighborhood defined by a rectangular window with size w + times w centered around the pixel. k is a configurable parameter + that weights the effect of standard deviation. + R is the maximum standard deviation of a grayscale image. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Grayscale input image. + window_size : int, or iterable of int, optional + Window size specified as a single odd integer (3, 5, 7, …), + or an iterable of length ``image.ndim`` containing only odd + integers (e.g. ``(1, 5, 5)``). + k : float, optional + Value of the positive parameter k. + r : float, optional + Value of R, the dynamic range of standard deviation. + If None, set to the half of the image dtype range. + + Returns + ------- + threshold : (M, N[, ...]) ndarray + Threshold mask. All pixels with an intensity higher than + this value are assumed to be foreground. + + Notes + ----- + This algorithm is originally designed for text recognition. + + References + ---------- + .. [1] J. Sauvola and M. Pietikainen, "Adaptive document image + binarization," Pattern Recognition 33(2), + pp. 225-236, 2000. + :DOI:`10.1016/S0031-3203(99)00055-2` + + Examples + -------- + >>> from skimage import data + >>> image = data.page() + >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2) + >>> binary_image = image > t_sauvola + """ + if r is None: + imin, imax = dtype_limits(image, clip_negative=False) + r = 0.5 * (imax - imin) + m, s = _mean_std(image, window_size) + return m * (1 + k * ((s / r) - 1)) + + +def apply_hysteresis_threshold(image, low, high): + """Apply hysteresis thresholding to ``image``. + + This algorithm finds regions where ``image`` is greater than ``high`` + OR ``image`` is greater than ``low`` *and* that region is connected to + a region greater than ``high``. + + Parameters + ---------- + image : (M[, ...]) ndarray + Grayscale input image. + low : float, or array of same shape as ``image`` + Lower threshold. + high : float, or array of same shape as ``image`` + Higher threshold. + + Returns + ------- + thresholded : (M[, ...]) array of bool + Array in which ``True`` indicates the locations where ``image`` + was above the hysteresis threshold. + + Examples + -------- + >>> image = np.array([1, 2, 3, 2, 1, 2, 1, 3, 2]) + >>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int) + array([0, 1, 1, 1, 0, 0, 0, 1, 1]) + + References + ---------- + .. [1] J. Canny. A computational approach to edge detection. + IEEE Transactions on Pattern Analysis and Machine Intelligence. + 1986; vol. 8, pp.679-698. + :DOI:`10.1109/TPAMI.1986.4767851` + """ + low = np.clip(low, a_min=None, a_max=high) # ensure low always below high + mask_low = image > low + mask_high = image > high + # Connected components of mask_low + labels_low, num_labels = ndi.label(mask_low) + # Check which connected components contain pixels from mask_high + sums = ndi.sum(mask_high, labels_low, np.arange(num_labels + 1)) + connected_to_high = sums > 0 + thresholded = connected_to_high[labels_low] + return thresholded + + +def threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None): + r"""Generate `classes`-1 threshold values to divide gray levels in `image`, + following Otsu's method for multiple classes. + + The threshold values are chosen to maximize the total sum of pairwise + variances between the thresholded graylevel classes. See Notes and [1]_ + for more details. + + Either image or hist must be provided. If hist is provided, the actual + histogram of the image is ignored. + + Parameters + ---------- + image : (M, N[, ...]) ndarray, optional + Grayscale input image. + classes : int, optional + Number of classes to be thresholded, i.e. the number of resulting + regions. + nbins : int, optional + Number of bins used to calculate the histogram. This value is ignored + for integer arrays. + hist : array, or 2-tuple of arrays, optional + Histogram from which to determine the threshold, and optionally a + corresponding array of bin center intensities. If no hist provided, + this function will compute it from the image (see notes). + + Returns + ------- + thresh : array + Array containing the threshold values for the desired classes. + + Raises + ------ + ValueError + If ``image`` contains less grayscale value then the desired + number of classes. + + Notes + ----- + This implementation relies on a Cython function whose complexity + is :math:`O\left(\frac{Ch^{C-1}}{(C-1)!}\right)`, where :math:`h` + is the number of histogram bins and :math:`C` is the number of + classes desired. + + If no hist is given, this function will make use of + `skimage.exposure.histogram`, which behaves differently than + `np.histogram`. While both allowed, use the former for consistent + behaviour. + + The input image must be grayscale. + + References + ---------- + .. [1] Liao, P-S., Chen, T-S. and Chung, P-C., "A fast algorithm for + multilevel thresholding", Journal of Information Science and + Engineering 17 (5): 713-727, 2001. Available at: + + :DOI:`10.6688/JISE.2001.17.5.1` + .. [2] Tosa, Y., "Multi-Otsu Threshold", a java plugin for ImageJ. + Available at: + + + Examples + -------- + >>> from skimage.color import label2rgb + >>> from skimage import data + >>> image = data.camera() + >>> thresholds = threshold_multiotsu(image) + >>> regions = np.digitize(image, bins=thresholds) + >>> regions_colorized = label2rgb(regions) + """ + if image is not None and image.ndim > 2 and image.shape[-1] in (3, 4): + warn( + f'threshold_multiotsu is expected to work correctly only for ' + f'grayscale images; image shape {image.shape} looks like ' + f'that of an RGB image.' + ) + + # calculating the histogram and the probability of each gray level. + prob, bin_centers = _validate_image_histogram(image, hist, nbins, normalize=True) + prob = prob.astype('float32', copy=False) + + nvalues = np.count_nonzero(prob) + if nvalues < classes: + msg = ( + f'After discretization into bins, the input image has ' + f'only {nvalues} different values. It cannot be thresholded ' + f'in {classes} classes. If there are more unique values ' + f'before discretization, try increasing the number of bins ' + f'(`nbins`).' + ) + raise ValueError(msg) + elif nvalues == classes: + thresh_idx = np.flatnonzero(prob)[:-1] + else: + # Get threshold indices + try: + thresh_idx = _get_multiotsu_thresh_indices_lut(prob, classes - 1) + except MemoryError: + # Don't use LUT if the number of bins is too large (if the + # image is uint16 for example): in this case, the + # allocated memory is too large. + thresh_idx = _get_multiotsu_thresh_indices(prob, classes - 1) + + thresh = bin_centers[thresh_idx] + + return thresh diff --git a/python_embeded/Lib/site-packages/skimage/future/__init__.py b/python_embeded/Lib/site-packages/skimage/future/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c31eb942a8b9b4a19ce219d85b489bd03dc0c6bc --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/future/__init__.py @@ -0,0 +1,13 @@ +"""Functionality with an experimental API. + +.. warning:: + Although you can count on the functions in this package being + around in the future, the API may change with any version update + **and will not follow the skimage two-version deprecation path**. + Therefore, use the functions herein with care, and do not use them + in production code that will depend on updated skimage versions. +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/future/__init__.pyi b/python_embeded/Lib/site-packages/skimage/future/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b69e9cbf1fd28ffd32cee07eda1fed91a7f8217e --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/future/__init__.pyi @@ -0,0 +1,14 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + "manual_lasso_segmentation", + "manual_polygon_segmentation", + "fit_segmenter", + "predict_segmenter", + "TrainableSegmenter", +] + +from .manual_segmentation import manual_lasso_segmentation, manual_polygon_segmentation +from .trainable_segmentation import TrainableSegmenter, fit_segmenter, predict_segmenter diff --git a/python_embeded/Lib/site-packages/skimage/future/manual_segmentation.py b/python_embeded/Lib/site-packages/skimage/future/manual_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..b6edaff9e78b2efc75abd9f451c2d59e5005f2f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/future/manual_segmentation.py @@ -0,0 +1,235 @@ +from functools import reduce +import numpy as np +from ..draw import polygon +from .._shared.version_requirements import require + + +LEFT_CLICK = 1 +RIGHT_CLICK = 3 + + +def _mask_from_vertices(vertices, shape, label): + mask = np.zeros(shape, dtype=int) + pr = [y for x, y in vertices] + pc = [x for x, y in vertices] + rr, cc = polygon(pr, pc, shape) + mask[rr, cc] = label + return mask + + +@require("matplotlib", ">=3.3") +def _draw_polygon(ax, vertices, alpha=0.4): + from matplotlib.patches import Polygon + from matplotlib.collections import PatchCollection + import matplotlib.pyplot as plt + + polygon = Polygon(vertices, closed=True) + p = PatchCollection([polygon], match_original=True, alpha=alpha) + polygon_object = ax.add_collection(p) + plt.draw() + return polygon_object + + +@require("matplotlib", ">=3.3") +def manual_polygon_segmentation(image, alpha=0.4, return_all=False): + """Return a label image based on polygon selections made with the mouse. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + + alpha : float, optional + Transparency value for polygons drawn over the image. + + return_all : bool, optional + If True, an array containing each separate polygon drawn is returned. + (The polygons may overlap.) If False (default), latter polygons + "overwrite" earlier ones where they overlap. + + Returns + ------- + labels : array of int, shape ([Q, ]M, N) + The segmented regions. If mode is `'separate'`, the leading dimension + of the array corresponds to the number of regions that the user drew. + + Notes + ----- + Use left click to select the vertices of the polygon + and right click to confirm the selection once all vertices are selected. + + Examples + -------- + >>> from skimage import data, future + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> camera = data.camera() + >>> mask = future.manual_polygon_segmentation(camera) # doctest: +SKIP + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(mask) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + import matplotlib + import matplotlib.pyplot as plt + + list_of_vertex_lists = [] + polygons_drawn = [] + + temp_list = [] + preview_polygon_drawn = [] + + if image.ndim not in (2, 3): + raise ValueError('Only 2D grayscale or RGB images are supported.') + + fig, ax = plt.subplots() + fig.subplots_adjust(bottom=0.2) + ax.imshow(image, cmap="gray") + ax.set_axis_off() + + def _undo(*args, **kwargs): + if list_of_vertex_lists: + list_of_vertex_lists.pop() + # Remove last polygon from list of polygons... + last_poly = polygons_drawn.pop() + # ... then from the plot + last_poly.remove() + fig.canvas.draw_idle() + + undo_pos = fig.add_axes([0.85, 0.05, 0.075, 0.075]) + undo_button = matplotlib.widgets.Button(undo_pos, '\u27f2') + undo_button.on_clicked(_undo) + + def _extend_polygon(event): + # Do not record click events outside axis or in undo button + if event.inaxes is None or event.inaxes is undo_pos: + return + # Do not record click events when toolbar is active + if ax.get_navigate_mode(): + return + + if event.button == LEFT_CLICK: # Select vertex + temp_list.append([event.xdata, event.ydata]) + # Remove previously drawn preview polygon if any. + if preview_polygon_drawn: + poly = preview_polygon_drawn.pop() + poly.remove() + + # Preview polygon with selected vertices. + polygon = _draw_polygon(ax, temp_list, alpha=(alpha / 1.4)) + preview_polygon_drawn.append(polygon) + + elif event.button == RIGHT_CLICK: # Confirm the selection + if not temp_list: + return + + # Store the vertices of the polygon as shown in preview. + # Redraw polygon and store it in polygons_drawn so that + # `_undo` works correctly. + list_of_vertex_lists.append(temp_list[:]) + polygon_object = _draw_polygon(ax, temp_list, alpha=alpha) + polygons_drawn.append(polygon_object) + + # Empty the temporary variables. + preview_poly = preview_polygon_drawn.pop() + preview_poly.remove() + del temp_list[:] + + plt.draw() + + fig.canvas.mpl_connect('button_press_event', _extend_polygon) + + plt.show(block=True) + + labels = ( + _mask_from_vertices(vertices, image.shape[:2], i) + for i, vertices in enumerate(list_of_vertex_lists, start=1) + ) + if return_all: + return np.stack(labels) + else: + return reduce(np.maximum, labels, np.broadcast_to(0, image.shape[:2])) + + +@require("matplotlib", ">=3.3") +def manual_lasso_segmentation(image, alpha=0.4, return_all=False): + """Return a label image based on freeform selections made with the mouse. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + + alpha : float, optional + Transparency value for polygons drawn over the image. + + return_all : bool, optional + If True, an array containing each separate polygon drawn is returned. + (The polygons may overlap.) If False (default), latter polygons + "overwrite" earlier ones where they overlap. + + Returns + ------- + labels : array of int, shape ([Q, ]M, N) + The segmented regions. If mode is `'separate'`, the leading dimension + of the array corresponds to the number of regions that the user drew. + + Notes + ----- + Press and hold the left mouse button to draw around each object. + + Examples + -------- + >>> from skimage import data, future + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> camera = data.camera() + >>> mask = future.manual_lasso_segmentation(camera) # doctest: +SKIP + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(mask) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + import matplotlib + import matplotlib.pyplot as plt + + list_of_vertex_lists = [] + polygons_drawn = [] + + if image.ndim not in (2, 3): + raise ValueError('Only 2D grayscale or RGB images are supported.') + + fig, ax = plt.subplots() + fig.subplots_adjust(bottom=0.2) + ax.imshow(image, cmap="gray") + ax.set_axis_off() + + def _undo(*args, **kwargs): + if list_of_vertex_lists: + list_of_vertex_lists.pop() + # Remove last polygon from list of polygons... + last_poly = polygons_drawn.pop() + # ... then from the plot + last_poly.remove() + fig.canvas.draw_idle() + + undo_pos = fig.add_axes([0.85, 0.05, 0.075, 0.075]) + undo_button = matplotlib.widgets.Button(undo_pos, '\u27f2') + undo_button.on_clicked(_undo) + + def _on_lasso_selection(vertices): + if len(vertices) < 3: + return + list_of_vertex_lists.append(vertices) + polygon_object = _draw_polygon(ax, vertices, alpha=alpha) + polygons_drawn.append(polygon_object) + plt.draw() + + matplotlib.widgets.LassoSelector(ax, _on_lasso_selection) + + plt.show(block=True) + + labels = ( + _mask_from_vertices(vertices, image.shape[:2], i) + for i, vertices in enumerate(list_of_vertex_lists, start=1) + ) + if return_all: + return np.stack(labels) + else: + return reduce(np.maximum, labels, np.broadcast_to(0, image.shape[:2])) diff --git a/python_embeded/Lib/site-packages/skimage/future/trainable_segmentation.py b/python_embeded/Lib/site-packages/skimage/future/trainable_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..331384ad77c29d010e45a37a3821992bae0a3203 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/future/trainable_segmentation.py @@ -0,0 +1,164 @@ +from skimage.feature import multiscale_basic_features + +try: + from sklearn.exceptions import NotFittedError + from sklearn.ensemble import RandomForestClassifier + + has_sklearn = True +except ImportError: + has_sklearn = False + + class NotFittedError(Exception): + pass + + +class TrainableSegmenter: + """Estimator for classifying pixels. + + Parameters + ---------- + clf : classifier object, optional + classifier object, exposing a ``fit`` and a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. + features_func : function, optional + function computing features on all pixels of the image, to be passed + to the classifier. The output should be of shape + ``(m_features, *labels.shape)``. If None, + :func:`skimage.feature.multiscale_basic_features` is used. + + Methods + ------- + compute_features + fit + predict + """ + + def __init__(self, clf=None, features_func=None): + if clf is None: + if has_sklearn: + self.clf = RandomForestClassifier(n_estimators=100, n_jobs=-1) + else: + raise ImportError( + "Please install scikit-learn or pass a classifier instance" + "to TrainableSegmenter." + ) + else: + self.clf = clf + self.features_func = features_func + + def compute_features(self, image): + if self.features_func is None: + self.features_func = multiscale_basic_features + self.features = self.features_func(image) + + def fit(self, image, labels): + """Train classifier using partially labeled (annotated) image. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel, and must have a + number of dimensions compatible with ``self.features_func``. + labels : ndarray of ints + Labeled array of shape compatible with ``image`` (same shape for a + single-channel image). Labels >= 1 correspond to the training set and + label 0 to unlabeled pixels to be segmented. + """ + self.compute_features(image) + fit_segmenter(labels, self.features, self.clf) + + def predict(self, image): + """Segment new image using trained internal classifier. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel, and must have a + number of dimensions compatible with ``self.features_func``. + + Raises + ------ + NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``). + """ + if self.features_func is None: + self.features_func = multiscale_basic_features + features = self.features_func(image) + return predict_segmenter(features, self.clf) + + +def fit_segmenter(labels, features, clf): + """Segmentation using labeled parts of the image and a classifier. + + Parameters + ---------- + labels : ndarray of ints + Image of labels. Labels >= 1 correspond to the training set and + label 0 to unlabeled pixels to be segmented. + features : ndarray + Array of features, with the first dimension corresponding to the number + of features, and the other dimensions correspond to ``labels.shape``. + clf : classifier object + classifier object, exposing a ``fit`` and a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. + + Returns + ------- + clf : classifier object + classifier trained on ``labels`` + + Raises + ------ + NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``). + """ + mask = labels > 0 + training_data = features[mask] + training_labels = labels[mask].ravel() + clf.fit(training_data, training_labels) + return clf + + +def predict_segmenter(features, clf): + """Segmentation of images using a pretrained classifier. + + Parameters + ---------- + features : ndarray + Array of features, with the last dimension corresponding to the number + of features, and the other dimensions are compatible with the shape of + the image to segment, or a flattened image. + clf : classifier object + trained classifier object, exposing a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. The + classifier must be already trained, for example with + :func:`skimage.future.fit_segmenter`. + + Returns + ------- + output : ndarray + Labeled array, built from the prediction of the classifier. + """ + sh = features.shape + if features.ndim > 2: + features = features.reshape((-1, sh[-1])) + + try: + predicted_labels = clf.predict(features) + except NotFittedError: + raise NotFittedError( + "You must train the classifier `clf` first" + "for example with the `fit_segmenter` function." + ) + except ValueError as err: + if err.args and 'x must consist of vectors of length' in err.args[0]: + raise ValueError( + err.args[0] + + '\n' + + "Maybe you did not use the same type of features for training the classifier." + ) + else: + raise err + output = predicted_labels.reshape(sh[:-1]) + return output diff --git a/python_embeded/Lib/site-packages/skimage/graph/__init__.py b/python_embeded/Lib/site-packages/skimage/graph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fba502027d404a73d68581fae30790d89aa72fdf --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/__init__.py @@ -0,0 +1,12 @@ +""" +Graph-based operations, e.g., shortest paths. + +This includes creating adjacency graphs of pixels in an image, finding the +central pixel in an image, finding (minimum-cost) paths across pixels, merging +and cutting of graphs, etc. + +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/graph/__init__.pyi b/python_embeded/Lib/site-packages/skimage/graph/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ddacc2edf64efe4cc2c419b86e05daad2fe12e89 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/__init__.pyi @@ -0,0 +1,27 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'pixel_graph', + 'central_pixel', + 'shortest_path', + 'MCP', + 'MCP_Geometric', + 'MCP_Connect', + 'MCP_Flexible', + 'route_through_array', + 'rag_mean_color', + 'rag_boundary', + 'cut_threshold', + 'cut_normalized', + 'merge_hierarchical', + 'RAG', +] + +from ._graph import pixel_graph, central_pixel +from ._graph_cut import cut_threshold, cut_normalized +from ._graph_merge import merge_hierarchical +from ._rag import rag_mean_color, RAG, show_rag, rag_boundary +from .spath import shortest_path +from .mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible, route_through_array diff --git a/python_embeded/Lib/site-packages/skimage/graph/_graph.py b/python_embeded/Lib/site-packages/skimage/graph/_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f5d099d0a2c665d2eaaa9731085a2837156955 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/_graph.py @@ -0,0 +1,220 @@ +import numpy as np +from scipy import sparse +from scipy.sparse import csgraph +from ..morphology._util import _raveled_offsets_and_distances +from ..util._map_array import map_array +from ..segmentation.random_walker_segmentation import _safe_downcast_indices + + +def _weighted_abs_diff(values0, values1, distances): + """A default edge function for complete image graphs. + + A pixel graph on an image with no edge values and no mask is a very + boring regular lattice, so we define a default edge weight to be the + absolute difference between values *weighted* by the distance + between them. + + Parameters + ---------- + values0 : array + The pixel values for each node. + values1 : array + The pixel values for each neighbor. + distances : array + The distance between each node and its neighbor. + + Returns + ------- + edge_values : array of float + The computed values: abs(values0 - values1) * distances. + """ + return np.abs(values0 - values1) * distances + + +def pixel_graph( + image, + *, + mask=None, + edge_function=None, + connectivity=1, + spacing=None, + sparse_type="matrix", +): + """Create an adjacency graph of pixels in an image. + + Pixels where the mask is True are nodes in the returned graph, and they are + connected by edges to their neighbors according to the connectivity + parameter. By default, the *value* of an edge when a mask is given, or when + the image is itself the mask, is the Euclidean distance between the pixels. + + However, if an int- or float-valued image is given with no mask, the value + of the edges is the absolute difference in intensity between adjacent + pixels, weighted by the Euclidean distance. + + Parameters + ---------- + image : array + The input image. If the image is of type bool, it will be used as the + mask as well. + mask : array of bool + Which pixels to use. If None, the graph for the whole image is used. + edge_function : callable + A function taking an array of pixel values, and an array of neighbor + pixel values, and an array of distances, and returning a value for the + edge. If no function is given, the value of an edge is just the + distance. + connectivity : int + The square connectivity of the pixel neighborhood: the number of + orthogonal steps allowed to consider a pixel a neighbor. See + `scipy.ndimage.generate_binary_structure` for details. + spacing : tuple of float + The spacing between pixels along each axis. + sparse_type : {"matrix", "array"}, optional + The return type of `graph`, either `scipy.sparse.csr_array` or + `scipy.sparse.csr_matrix` (default). + + Returns + ------- + graph : scipy.sparse.csr_matrix or scipy.sparse.csr_array + A sparse adjacency matrix in which entry (i, j) is 1 if nodes i and j + are neighbors, 0 otherwise. Depending on `sparse_type`, this can be + returned as a `scipy.sparse.csr_array`. + nodes : array of int + The nodes of the graph. These correspond to the raveled indices of the + nonzero pixels in the mask. + """ + if mask is None: + if image.dtype == bool: + mask = image + else: + mask = np.ones_like(image, dtype=bool) + + if edge_function is None: + if image.dtype == bool: + + def edge_function(x, y, distances): + return distances + + else: + edge_function = _weighted_abs_diff + + # Strategy: we are going to build the (i, j, data) arrays of a scipy + # sparse CSR matrix. + # - grab the raveled IDs of the foreground (mask == True) parts of the + # image **in the padded space**. + # - broadcast them together with the raveled offsets to their neighbors. + # This gives us for each foreground pixel a list of neighbors (that + # may or may not be selected by the mask). (We also track the *distance* + # to each neighbor.) + # - select "valid" entries in the neighbors and distance arrays by indexing + # into the mask, which we can do since these are raveled indices. + # - use np.repeat() to repeat each source index according to the number + # of neighbors selected by the mask it has. Each of these repeated + # indices will be lined up with its neighbor, i.e. **this is the row_ind + # array** of the CSR format matrix. + # - use the mask as a boolean index to get a 1D view of the selected + # neighbors. **This is the col_ind array.** + # - by default, the same boolean indexing can be applied to the distances + # to each neighbor, to give the **data array.** Optionally, a + # provided edge function can be computed on the pixel values and the + # distances to give a different value for the edges. + # Note, we use map_array to map the raveled coordinates in the padded + # image to the ones in the original image, and those are the returned + # nodes. + padded = np.pad(mask, 1, mode='constant', constant_values=False) + nodes_padded = np.flatnonzero(padded) + neighbor_offsets_padded, distances_padded = _raveled_offsets_and_distances( + padded.shape, connectivity=connectivity, spacing=spacing + ) + neighbors_padded = nodes_padded[:, np.newaxis] + neighbor_offsets_padded + neighbor_distances_full = np.broadcast_to(distances_padded, neighbors_padded.shape) + nodes = np.flatnonzero(mask) + nodes_sequential = np.arange(nodes.size) + # neighbors outside the mask get mapped to 0, which is a valid index, + # BUT, they will be masked out in the next step. + neighbors = map_array(neighbors_padded, nodes_padded, nodes) + neighbors_mask = padded.reshape(-1)[neighbors_padded] + num_neighbors = np.sum(neighbors_mask, axis=1) + indices = np.repeat(nodes, num_neighbors) + indices_sequential = np.repeat(nodes_sequential, num_neighbors) + neighbor_indices = neighbors[neighbors_mask] + neighbor_distances = neighbor_distances_full[neighbors_mask] + neighbor_indices_sequential = map_array(neighbor_indices, nodes, nodes_sequential) + + image_r = image.reshape(-1) + data = edge_function( + image_r[indices], image_r[neighbor_indices], neighbor_distances + ) + + m = nodes_sequential.size + graph = sparse.csr_array( + (data, (indices_sequential, neighbor_indices_sequential)), shape=(m, m) + ) + + if sparse_type == "matrix": + graph = sparse.csr_matrix(graph) + elif sparse_type != "array": + msg = f"`sparse_type` must be 'array' or 'matrix', got {sparse_type}" + raise ValueError(msg) + + return graph, nodes + + +def central_pixel(graph, nodes=None, shape=None, partition_size=100): + """Find the pixel with the highest closeness centrality. + + Closeness centrality is the inverse of the total sum of shortest distances + from a node to every other node. + + Parameters + ---------- + graph : scipy.sparse.csr_array or scipy.sparse.csr_matrix + The sparse representation of the graph. + nodes : array of int + The raveled index of each node in graph in the image. If not provided, + the returned value will be the index in the input graph. + shape : tuple of int + The shape of the image in which the nodes are embedded. If provided, + the returned coordinates are a NumPy multi-index of the same + dimensionality as the input shape. Otherwise, the returned coordinate + is the raveled index provided in `nodes`. + partition_size : int + This function computes the shortest path distance between every pair + of nodes in the graph. This can result in a very large (N*N) matrix. + As a simple performance tweak, the distance values are computed in + lots of `partition_size`, resulting in a memory requirement of only + partition_size*N. + + Returns + ------- + position : int or tuple of int + If shape is given, the coordinate of the central pixel in the image. + Otherwise, the raveled index of that pixel. + distances : array of float + The total sum of distances from each node to each other reachable + node. + """ + if nodes is None: + nodes = np.arange(graph.shape[0]) + if partition_size is None: + num_splits = 1 + else: + num_splits = max(2, graph.shape[0] // partition_size) + graph.indices, graph.indptr = _safe_downcast_indices( + graph, np.int32, 'index values too large for csgraph' + ) + idxs = np.arange(graph.shape[0]) + total_shortest_path_len_list = [] + for partition in np.array_split(idxs, num_splits): + shortest_paths = csgraph.shortest_path(graph, directed=False, indices=partition) + shortest_paths_no_inf = np.nan_to_num(shortest_paths) + total_shortest_path_len_list.append(np.sum(shortest_paths_no_inf, axis=1)) + total_shortest_path_len = np.concatenate(total_shortest_path_len_list) + nonzero = np.flatnonzero(total_shortest_path_len) + min_sp = np.argmin(total_shortest_path_len[nonzero]) + raveled_index = nodes[nonzero[min_sp]] + if shape is not None: + central = np.unravel_index(raveled_index, shape) + else: + central = raveled_index + return central, total_shortest_path_len diff --git a/python_embeded/Lib/site-packages/skimage/graph/_graph_cut.py b/python_embeded/Lib/site-packages/skimage/graph/_graph_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..6028f2004295764fd29a1e0738732dcb68e74e24 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/_graph_cut.py @@ -0,0 +1,314 @@ +import networkx as nx +import numpy as np +from scipy.sparse import linalg + +from . import _ncut, _ncut_cy + + +def cut_threshold(labels, rag, thresh, in_place=True): + """Combine regions separated by weight less than threshold. + + Given an image's labels and its RAG, output new labels by + combining regions whose nodes are separated by a weight less + than the given threshold. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The region adjacency graph. + thresh : float + The threshold. Regions connected by edges with smaller weights are + combined. + in_place : bool + If set, modifies `rag` in place. The function will remove the edges + with weights less that `thresh`. If set to `False` the function + makes a copy of `rag` before proceeding. + + Returns + ------- + out : ndarray + The new labelled array. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels) + >>> new_labels = graph.cut_threshold(labels, rag, 10) + + References + ---------- + .. [1] Alain Tremeau and Philippe Colantoni + "Regions Adjacency Graph Applied To Color Image Segmentation" + :DOI:`10.1109/83.841950` + + """ + if not in_place: + rag = rag.copy() + + # Because deleting edges while iterating through them produces an error. + to_remove = [(x, y) for x, y, d in rag.edges(data=True) if d['weight'] >= thresh] + rag.remove_edges_from(to_remove) + + comps = nx.connected_components(rag) + + # We construct an array which can map old labels to the new ones. + # All the labels within a connected component are assigned to a single + # label in the output. + map_array = np.arange(labels.max() + 1, dtype=labels.dtype) + for i, nodes in enumerate(comps): + for node in nodes: + for label in rag.nodes[node]['labels']: + map_array[label] = i + + return map_array[labels] + + +def cut_normalized( + labels, + rag, + thresh=0.001, + num_cuts=10, + in_place=True, + max_edge=1.0, + *, + rng=None, +): + """Perform Normalized Graph cut on the Region Adjacency Graph. + + Given an image's labels and its similarity RAG, recursively perform + a 2-way normalized cut on it. All nodes belonging to a subgraph + that cannot be cut further are assigned a unique label in the + output. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The region adjacency graph. + thresh : float + The threshold. A subgraph won't be further subdivided if the + value of the N-cut exceeds `thresh`. + num_cuts : int + The number or N-cuts to perform before determining the optimal one. + in_place : bool + If set, modifies `rag` in place. For each node `n` the function will + set a new attribute ``rag.nodes[n]['ncut label']``. + max_edge : float, optional + The maximum possible value of an edge in the RAG. This corresponds to + an edge between identical regions. This is used to put self + edges in the RAG. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The `rng` is used to determine the starting point + of `scipy.sparse.linalg.eigsh`. + + Returns + ------- + out : ndarray + The new labeled array. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels, mode='similarity') + >>> new_labels = graph.cut_normalized(labels, rag) + + References + ---------- + .. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation", + Pattern Analysis and Machine Intelligence, + IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000. + + """ + rng = np.random.default_rng(rng) + if not in_place: + rag = rag.copy() + + for node in rag.nodes(): + rag.add_edge(node, node, weight=max_edge) + + _ncut_relabel(rag, thresh, num_cuts, rng) + + map_array = np.zeros(labels.max() + 1, dtype=labels.dtype) + # Mapping from old labels to new + for n, d in rag.nodes(data=True): + map_array[d['labels']] = d['ncut label'] + + return map_array[labels] + + +def partition_by_cut(cut, rag): + """Compute resulting subgraphs from given bi-partition. + + Parameters + ---------- + cut : array + A array of booleans. Elements set to `True` belong to one + set. + rag : RAG + The Region Adjacency Graph. + + Returns + ------- + sub1, sub2 : RAG + The two resulting subgraphs from the bi-partition. + """ + # `cut` is derived from `D` and `W` matrices, which also follow the + # ordering returned by `rag.nodes()` because we use + # nx.to_scipy_sparse_array. + + # Example + # rag.nodes() = [3, 7, 9, 13] + # cut = [True, False, True, False] + # nodes1 = [3, 9] + # nodes2 = [7, 10] + + nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]] + nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]] + + sub1 = rag.subgraph(nodes1) + sub2 = rag.subgraph(nodes2) + + return sub1, sub2 + + +def get_min_ncut(ev, d, w, num_cuts): + """Threshold an eigenvector evenly, to determine minimum ncut. + + Parameters + ---------- + ev : array + The eigenvector to threshold. + d : ndarray + The diagonal matrix of the graph. + w : ndarray + The weight matrix of the graph. + num_cuts : int + The number of evenly spaced thresholds to check for. + + Returns + ------- + mask : array + The array of booleans which denotes the bi-partition. + mcut : float + The value of the minimum ncut. + """ + mcut = np.inf + mn = ev.min() + mx = ev.max() + + # If all values in `ev` are equal, it implies that the graph can't be + # further sub-divided. In this case the bi-partition is the the graph + # itself and an empty set. + min_mask = np.zeros_like(ev, dtype=bool) + if np.allclose(mn, mx): + return min_mask, mcut + + # Refer Shi & Malik 2001, Section 3.1.3, Page 892 + # Perform evenly spaced n-cuts and determine the optimal one. + for t in np.linspace(mn, mx, num_cuts, endpoint=False): + mask = ev > t + cost = _ncut.ncut_cost(mask, d, w) + if cost < mcut: + min_mask = mask + mcut = cost + + return min_mask, mcut + + +def _label_all(rag, attr_name): + """Assign a unique integer to the given attribute in the RAG. + + This function assumes that all labels in `rag` are unique. It + picks up a random label from them and assigns it to the `attr_name` + attribute of all the nodes. + + rag : RAG + The Region Adjacency Graph. + attr_name : string + The attribute to which a unique integer is assigned. + """ + node = min(rag.nodes()) + new_label = rag.nodes[node]['labels'][0] + for n, d in rag.nodes(data=True): + d[attr_name] = new_label + + +def _ncut_relabel(rag, thresh, num_cuts, random_generator): + """Perform Normalized Graph cut on the Region Adjacency Graph. + + Recursively partition the graph into 2, until further subdivision + yields a cut greater than `thresh` or such a cut cannot be computed. + For such a subgraph, indices to labels of all its nodes map to a single + unique value. + + Parameters + ---------- + rag : RAG + The region adjacency graph. + thresh : float + The threshold. A subgraph won't be further subdivided if the + value of the N-cut exceeds `thresh`. + num_cuts : int + The number or N-cuts to perform before determining the optimal one. + random_generator : `numpy.random.Generator` + Provides initial values for eigenvalue solver. + """ + d, w = _ncut.DW_matrices(rag) + m = w.shape[0] + + if (m > 2) and (d != w).nnz > 0: + # This avoids further segmenting a graph that is too small, + # and the degenerate case (d == w), which typically occurs + # when only three single pixels remain. + # + # We're not sure exactly why this latter case arises. For + # SciPy <= 0.14, SciPy continued to compute an eigenvector, + # but newer versions (correctly) won't. We refuse to guess, + # and stop further segmentation. + # + # It may make sense to a warning here; on the other hand segmentations + # are not a ground truth, so this level of "noise" should be acceptable. + + d2 = d.copy() + # Since d is diagonal, we can directly operate on its data + # the inverse of the square root + d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) + + # Refer Shi & Malik 2001, Equation 7, Page 891 + A = d2 @ (d - w) @ d2 + # Initialize the vector to ensure reproducibility. + v0 = random_generator.random(A.shape[0]) + vals, vectors = linalg.eigsh(A, which='SM', v0=v0, k=min(100, m - 2)) + + # Pick second smallest eigenvector. + # Refer Shi & Malik 2001, Section 3.2.3, Page 893 + vals, vectors = np.real(vals), np.real(vectors) + index2 = _ncut_cy.argmin2(vals) + ev = vectors[:, index2] + + cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts) + if mcut < thresh: + # Sub divide and perform N-cut again + # Refer Shi & Malik 2001, Section 3.2.5, Page 893 + sub1, sub2 = partition_by_cut(cut_mask, rag) + + _ncut_relabel(sub1, thresh, num_cuts, random_generator) + _ncut_relabel(sub2, thresh, num_cuts, random_generator) + return + + # The N-cut wasn't small enough, or could not be computed. + # The remaining graph is a region. + # Assign `ncut label` by picking any label from the existing nodes, since + # `labels` are unique, `new_label` is also unique. + _label_all(rag, 'ncut label') diff --git a/python_embeded/Lib/site-packages/skimage/graph/_graph_merge.py b/python_embeded/Lib/site-packages/skimage/graph/_graph_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..ee81ac50d68eaa9eaf9c8097c6e083044aff403c --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/_graph_merge.py @@ -0,0 +1,138 @@ +import numpy as np +import heapq + + +def _revalidate_node_edges(rag, node, heap_list): + """Handles validation and invalidation of edges incident to a node. + + This function invalidates all existing edges incident on `node` and inserts + new items in `heap_list` updated with the valid weights. + + rag : RAG + The Region Adjacency Graph. + node : int + The id of the node whose incident edges are to be validated/invalidated + . + heap_list : list + The list containing the existing heap of edges. + """ + # networkx updates data dictionary if edge exists + # this would mean we have to reposition these edges in + # heap if their weight is updated. + # instead we invalidate them + + for nbr in rag.neighbors(node): + data = rag[node][nbr] + try: + # invalidate edges incident on `dst`, they have new weights + data['heap item'][3] = False + _invalidate_edge(rag, node, nbr) + except KeyError: + # will handle the case where the edge did not exist in the existing + # graph + pass + + wt = data['weight'] + heap_item = [wt, node, nbr, True] + data['heap item'] = heap_item + heapq.heappush(heap_list, heap_item) + + +def _rename_node(graph, node_id, copy_id): + """Rename `node_id` in `graph` to `copy_id`.""" + + graph._add_node_silent(copy_id) + graph.nodes[copy_id].update(graph.nodes[node_id]) + + for nbr in graph.neighbors(node_id): + wt = graph[node_id][nbr]['weight'] + graph.add_edge(nbr, copy_id, {'weight': wt}) + + graph.remove_node(node_id) + + +def _invalidate_edge(graph, n1, n2): + """Invalidates the edge (n1, n2) in the heap.""" + graph[n1][n2]['heap item'][3] = False + + +def merge_hierarchical( + labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func +): + """Perform hierarchical merging of a RAG. + + Greedily merges the most similar pair of nodes until no edges lower than + `thresh` remain. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The Region Adjacency Graph. + thresh : float + Regions connected by an edge with weight smaller than `thresh` are + merged. + rag_copy : bool + If set, the RAG copied before modifying. + in_place_merge : bool + If set, the nodes are merged in place. Otherwise, a new node is + created for each merge.. + merge_func : callable + This function is called before merging two nodes. For the RAG `graph` + while merging `src` and `dst`, it is called as follows + ``merge_func(graph, src, dst)``. + weight_func : callable + The function to compute the new weights of the nodes adjacent to the + merged node. This is directly supplied as the argument `weight_func` + to `merge_nodes`. + + Returns + ------- + out : ndarray + The new labeled array. + + """ + if rag_copy: + rag = rag.copy() + + edge_heap = [] + for n1, n2, data in rag.edges(data=True): + # Push a valid edge in the heap + wt = data['weight'] + heap_item = [wt, n1, n2, True] + heapq.heappush(edge_heap, heap_item) + + # Reference to the heap item in the graph + data['heap item'] = heap_item + + while len(edge_heap) > 0 and edge_heap[0][0] < thresh: + _, n1, n2, valid = heapq.heappop(edge_heap) + + # Ensure popped edge is valid, if not, the edge is discarded + if valid: + # Invalidate all neighbors of `src` before its deleted + + for nbr in rag.neighbors(n1): + _invalidate_edge(rag, n1, nbr) + + for nbr in rag.neighbors(n2): + _invalidate_edge(rag, n2, nbr) + + if not in_place_merge: + next_id = rag.next_id() + _rename_node(rag, n2, next_id) + src, dst = n1, next_id + else: + src, dst = n1, n2 + + merge_func(rag, src, dst) + new_id = rag.merge_nodes(src, dst, weight_func) + _revalidate_node_edges(rag, new_id, edge_heap) + + label_map = np.arange(labels.max() + 1) + for ix, (n, d) in enumerate(rag.nodes(data=True)): + for label in d['labels']: + label_map[label] = ix + + return label_map[labels] diff --git a/python_embeded/Lib/site-packages/skimage/graph/_mcp.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/graph/_mcp.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..8e0a1c827adebd4a874c33ffce7817028bd23db4 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/graph/_mcp.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/graph/_ncut.py b/python_embeded/Lib/site-packages/skimage/graph/_ncut.py new file mode 100644 index 0000000000000000000000000000000000000000..792714279c3218427e31a490155a74cf61cb28c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/_ncut.py @@ -0,0 +1,64 @@ +import networkx as nx +import numpy as np +from scipy import sparse +from . import _ncut_cy + + +def DW_matrices(graph): + """Returns the diagonal and weight matrices of a graph. + + Parameters + ---------- + graph : RAG + A Region Adjacency Graph. + + Returns + ------- + D : csc_array + The diagonal matrix of the graph. ``D[i, i]`` is the sum of weights of + all edges incident on `i`. All other entries are `0`. + W : csc_array + The weight matrix of the graph. ``W[i, j]`` is the weight of the edge + joining `i` to `j`. + """ + # sparse.eighsh is most efficient with CSC-formatted input + W = nx.to_scipy_sparse_array(graph, format='csc') + entries = W.sum(axis=0) + D = sparse.dia_array((entries, 0), shape=W.shape).tocsc() + + return D, W + + +def ncut_cost(cut, D, W): + """Returns the N-cut cost of a bi-partition of a graph. + + Parameters + ---------- + cut : ndarray + The mask for the nodes in the graph. Nodes corresponding to a `True` + value are in one set. + D : csc_array + The diagonal matrix of the graph. + W : csc_array + The weight matrix of the graph. + + Returns + ------- + cost : float + The cost of performing the N-cut. + + References + ---------- + .. [1] Normalized Cuts and Image Segmentation, Jianbo Shi and + Jitendra Malik, IEEE Transactions on Pattern Analysis and Machine + Intelligence, Page 889, Equation 2. + """ + cut = np.array(cut) + cut_cost = _ncut_cy.cut_cost(cut, W.data, W.indices, W.indptr, num_cols=W.shape[0]) + + # D has elements only along the diagonal, one per node, so we can directly + # index the data attribute with cut. + assoc_a = D.data[cut].sum() + assoc_b = D.data[~cut].sum() + + return (cut_cost / assoc_a) + (cut_cost / assoc_b) diff --git a/python_embeded/Lib/site-packages/skimage/graph/_ncut_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/graph/_ncut_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..421090486bf256620ff9001bc54f36f9a4c7d391 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/graph/_ncut_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/graph/_rag.py b/python_embeded/Lib/site-packages/skimage/graph/_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..0491973f261e77e248089d0e185100ba151838ef --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/_rag.py @@ -0,0 +1,581 @@ +import networkx as nx +import numpy as np +from scipy import ndimage as ndi +from scipy import sparse +import math + +from .. import measure, segmentation, util, color +from .._shared.version_requirements import require + + +def _edge_generator_from_csr(csr_array): + """Yield weighted edge triples for use by NetworkX from a CSR matrix. + + This function is a straight rewrite of + `networkx.convert_matrix._csr_gen_triples`. Since that is a private + function, it is safer to include our own here. + + Parameters + ---------- + csr_array : scipy.sparse.csr_array + The input matrix. An edge (i, j, w) will be yielded if there is a + data value for coordinates (i, j) in the matrix, even if that value + is 0. + + Yields + ------ + i, j, w : (int, int, float) tuples + Each value `w` in the matrix along with its coordinates (i, j). + + Examples + -------- + + >>> dense = np.eye(2, dtype=float) + >>> csr = sparse.csr_array(dense) + >>> edges = _edge_generator_from_csr(csr) + >>> list(edges) + [(0, 0, 1.0), (1, 1, 1.0)] + """ + nrows = csr_array.shape[0] + values = csr_array.data + indptr = csr_array.indptr + col_indices = csr_array.indices + for i in range(nrows): + for j in range(indptr[i], indptr[i + 1]): + yield i, col_indices[j], values[j] + + +def min_weight(graph, src, dst, n): + """Callback to handle merging nodes by choosing minimum weight. + + Returns a dictionary with `"weight"` set as either the weight between + (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when + both exist. + + Parameters + ---------- + graph : RAG + The graph under consideration. + src, dst : int + The verices in `graph` to be merged. + n : int + A neighbor of `src` or `dst` or both. + + Returns + ------- + data : dict + A dict with the `"weight"` attribute set the weight between + (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when + both exist. + + """ + + # cover the cases where n only has edge to either `src` or `dst` + default = {'weight': np.inf} + w1 = graph[n].get(src, default)['weight'] + w2 = graph[n].get(dst, default)['weight'] + return {'weight': min(w1, w2)} + + +def _add_edge_filter(values, graph): + """Create edge in `graph` between central element of `values` and the rest. + + Add an edge between the middle element in `values` and + all other elements of `values` into `graph`. ``values[len(values) // 2]`` + is expected to be the central value of the footprint used. + + Parameters + ---------- + values : array + The array to process. + graph : RAG + The graph to add edges in. + + Returns + ------- + 0 : float + Always returns 0. The return value is required so that `generic_filter` + can put it in the output array, but it is ignored by this filter. + """ + values = values.astype(int) + center = values[len(values) // 2] + for value in values: + if value != center and not graph.has_edge(center, value): + graph.add_edge(center, value) + return 0.0 + + +class RAG(nx.Graph): + """The Region Adjacency Graph (RAG) of an image, subclasses :obj:`networkx.Graph`. + + Parameters + ---------- + label_image : array of int + An initial segmentation, with each region labeled as a different + integer. Every unique value in ``label_image`` will correspond to + a node in the graph. + connectivity : int in {1, ..., ``label_image.ndim``}, optional + The connectivity between pixels in ``label_image``. For a 2D image, + a connectivity of 1 corresponds to immediate neighbors up, down, + left, and right, while a connectivity of 2 also includes diagonal + neighbors. See :func:`scipy.ndimage.generate_binary_structure`. + data : :obj:`networkx.Graph` specification, optional + Initial or additional edges to pass to :obj:`networkx.Graph` + constructor. Valid edge specifications include edge list (list of tuples), + NumPy arrays, and SciPy sparse matrices. + **attr : keyword arguments, optional + Additional attributes to add to the graph. + """ + + def __init__(self, label_image=None, connectivity=1, data=None, **attr): + super().__init__(data, **attr) + if self.number_of_nodes() == 0: + self.max_id = 0 + else: + self.max_id = max(self.nodes()) + + if label_image is not None: + fp = ndi.generate_binary_structure(label_image.ndim, connectivity) + # In the next ``ndi.generic_filter`` function, the kwarg + # ``output`` is used to provide a strided array with a single + # 64-bit floating point number, to which the function repeatedly + # writes. This is done because even if we don't care about the + # output, without this, a float array of the same shape as the + # input image will be created and that could be expensive in + # memory consumption. + output = np.broadcast_to(1.0, label_image.shape) + output.setflags(write=True) + ndi.generic_filter( + label_image, + function=_add_edge_filter, + footprint=fp, + mode='nearest', + output=output, + extra_arguments=(self,), + ) + + def merge_nodes( + self, + src, + dst, + weight_func=min_weight, + in_place=True, + extra_arguments=None, + extra_keywords=None, + ): + """Merge node `src` and `dst`. + + The new combined node is adjacent to all the neighbors of `src` + and `dst`. `weight_func` is called to decide the weight of edges + incident on the new node. + + Parameters + ---------- + src, dst : int + Nodes to be merged. + weight_func : callable, optional + Function to decide the attributes of edges incident on the new + node. For each neighbor `n` for `src` and `dst`, `weight_func` will + be called as follows: `weight_func(src, dst, n, *extra_arguments, + **extra_keywords)`. `src`, `dst` and `n` are IDs of vertices in the + RAG object which is in turn a subclass of :obj:`networkx.Graph`. It is + expected to return a dict of attributes of the resulting edge. + in_place : bool, optional + If set to `True`, the merged node has the id `dst`, else merged + node has a new id which is returned. + extra_arguments : sequence, optional + The sequence of extra positional arguments passed to + `weight_func`. + extra_keywords : dictionary, optional + The dict of keyword arguments passed to the `weight_func`. + + Returns + ------- + id : int + The id of the new node. + + Notes + ----- + If `in_place` is `False` the resulting node has a new id, rather than + `dst`. + """ + if extra_arguments is None: + extra_arguments = [] + if extra_keywords is None: + extra_keywords = {} + + src_nbrs = set(self.neighbors(src)) + dst_nbrs = set(self.neighbors(dst)) + neighbors = (src_nbrs | dst_nbrs) - {src, dst} + + if in_place: + new = dst + else: + new = self.next_id() + self.add_node(new) + + for neighbor in neighbors: + data = weight_func( + self, src, dst, neighbor, *extra_arguments, **extra_keywords + ) + self.add_edge(neighbor, new, attr_dict=data) + + self.nodes[new]['labels'] = ( + self.nodes[src]['labels'] + self.nodes[dst]['labels'] + ) + self.remove_node(src) + + if not in_place: + self.remove_node(dst) + + return new + + def add_node(self, n, attr_dict=None, **attr): + """Add node `n` while updating the maximum node id. + + .. seealso:: :obj:`networkx.Graph.add_node`.""" + if attr_dict is None: # compatibility with old networkx + attr_dict = attr + else: + attr_dict.update(attr) + super().add_node(n, **attr_dict) + self.max_id = max(n, self.max_id) + + def add_edge(self, u, v, attr_dict=None, **attr): + """Add an edge between `u` and `v` while updating max node id. + + .. seealso:: :obj:`networkx.Graph.add_edge`.""" + if attr_dict is None: # compatibility with old networkx + attr_dict = attr + else: + attr_dict.update(attr) + super().add_edge(u, v, **attr_dict) + self.max_id = max(u, v, self.max_id) + + def copy(self): + """Copy the graph with its max node id. + + .. seealso:: :obj:`networkx.Graph.copy`.""" + g = super().copy() + g.max_id = self.max_id + return g + + def fresh_copy(self): + """Return a fresh copy graph with the same data structure. + + A fresh copy has no nodes, edges or graph attributes. It is + the same data structure as the current graph. This method is + typically used to create an empty version of the graph. + + This is required when subclassing Graph with networkx v2 and + does not cause problems for v1. Here is more detail from + the network migrating from 1.x to 2.x document:: + + With the new GraphViews (SubGraph, ReversedGraph, etc) + you can't assume that ``G.__class__()`` will create a new + instance of the same graph type as ``G``. In fact, the + call signature for ``__class__`` differs depending on + whether ``G`` is a view or a base class. For v2.x you + should use ``G.fresh_copy()`` to create a null graph of + the correct type---ready to fill with nodes and edges. + + """ + return RAG() + + def next_id(self): + """Returns the `id` for the new node to be inserted. + + The current implementation returns one more than the maximum `id`. + + Returns + ------- + id : int + The `id` of the new node to be inserted. + """ + return self.max_id + 1 + + def _add_node_silent(self, n): + """Add node `n` without updating the maximum node id. + + This is a convenience method used internally. + + .. seealso:: :obj:`networkx.Graph.add_node`.""" + super().add_node(n) + + +def rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0): + """Compute the Region Adjacency Graph using mean colors. + + Given an image and its initial segmentation, this method constructs the + corresponding Region Adjacency Graph (RAG). Each node in the RAG + represents a set of pixels within `image` with the same label in `labels`. + The weight between two adjacent regions represents how similar or + dissimilar two regions are depending on the `mode` parameter. + + Parameters + ---------- + image : ndarray, shape(M, N[, ..., P], 3) + Input image. + labels : ndarray, shape(M, N[, ..., P]) + The labelled image. This should have one dimension less than + `image`. If `image` has dimensions `(M, N, 3)` `labels` should have + dimensions `(M, N)`. + connectivity : int, optional + Pixels with a squared distance less than `connectivity` from each other + are considered adjacent. It can range from 1 to `labels.ndim`. Its + behavior is the same as `connectivity` parameter in + ``scipy.ndimage.generate_binary_structure``. + mode : {'distance', 'similarity'}, optional + The strategy to assign edge weights. + + 'distance' : The weight between two adjacent regions is the + :math:`|c_1 - c_2|`, where :math:`c_1` and :math:`c_2` are the mean + colors of the two regions. It represents the Euclidean distance in + their average color. + + 'similarity' : The weight between two adjacent is + :math:`e^{-d^2/sigma}` where :math:`d=|c_1 - c_2|`, where + :math:`c_1` and :math:`c_2` are the mean colors of the two regions. + It represents how similar two regions are. + sigma : float, optional + Used for computation when `mode` is "similarity". It governs how + close to each other two colors should be, for their corresponding edge + weight to be significant. A very large value of `sigma` could make + any two colors behave as though they were similar. + + Returns + ------- + out : RAG + The region adjacency graph. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels) + + References + ---------- + .. [1] Alain Tremeau and Philippe Colantoni + "Regions Adjacency Graph Applied To Color Image Segmentation" + :DOI:`10.1109/83.841950` + """ + graph = RAG(labels, connectivity=connectivity) + + for n in graph: + graph.nodes[n].update( + { + 'labels': [n], + 'pixel count': 0, + 'total color': np.array([0, 0, 0], dtype=np.float64), + } + ) + + for index in np.ndindex(labels.shape): + current = labels[index] + graph.nodes[current]['pixel count'] += 1 + graph.nodes[current]['total color'] += image[index] + + for n in graph: + graph.nodes[n]['mean color'] = ( + graph.nodes[n]['total color'] / graph.nodes[n]['pixel count'] + ) + + for x, y, d in graph.edges(data=True): + diff = graph.nodes[x]['mean color'] - graph.nodes[y]['mean color'] + diff = np.linalg.norm(diff) + if mode == 'similarity': + d['weight'] = math.e ** (-(diff**2) / sigma) + elif mode == 'distance': + d['weight'] = diff + else: + raise ValueError(f"The mode '{mode}' is not recognised") + + return graph + + +def rag_boundary(labels, edge_map, connectivity=2): + """Comouter RAG based on region boundaries + + Given an image's initial segmentation and its edge map this method + constructs the corresponding Region Adjacency Graph (RAG). Each node in the + RAG represents a set of pixels within the image with the same label in + `labels`. The weight between two adjacent regions is the average value + in `edge_map` along their boundary. + + labels : ndarray + The labelled image. + edge_map : ndarray + This should have the same shape as that of `labels`. For all pixels + along the boundary between 2 adjacent regions, the average value of the + corresponding pixels in `edge_map` is the edge weight between them. + connectivity : int, optional + Pixels with a squared distance less than `connectivity` from each other + are considered adjacent. It can range from 1 to `labels.ndim`. Its + behavior is the same as `connectivity` parameter in + `scipy.ndimage.generate_binary_structure`. + + Examples + -------- + >>> from skimage import data, segmentation, filters, color, graph + >>> img = data.chelsea() + >>> labels = segmentation.slic(img) + >>> edge_map = filters.sobel(color.rgb2gray(img)) + >>> rag = graph.rag_boundary(labels, edge_map) + + """ + + conn = ndi.generate_binary_structure(labels.ndim, connectivity) + eroded = ndi.grey_erosion(labels, footprint=conn) + dilated = ndi.grey_dilation(labels, footprint=conn) + boundaries0 = eroded != labels + boundaries1 = dilated != labels + labels_small = np.concatenate((eroded[boundaries0], labels[boundaries1])) + labels_large = np.concatenate((labels[boundaries0], dilated[boundaries1])) + n = np.max(labels_large) + 1 + + # use a dummy broadcast array as data for RAG + ones = np.broadcast_to(1.0, labels_small.shape) + count_matrix = sparse.csr_array( + (ones, (labels_small, labels_large)), dtype=int, shape=(n, n) + ) + data = np.concatenate((edge_map[boundaries0], edge_map[boundaries1])) + + graph_matrix = sparse.csr_array((data, (labels_small, labels_large))) + graph_matrix.data /= count_matrix.data + + rag = RAG() + rag.add_weighted_edges_from(_edge_generator_from_csr(graph_matrix), weight='weight') + rag.add_weighted_edges_from(_edge_generator_from_csr(count_matrix), weight='count') + + for n in rag.nodes(): + rag.nodes[n].update({'labels': [n]}) + + return rag + + +@require("matplotlib", ">=3.3") +def show_rag( + labels, + rag, + image, + border_color='black', + edge_width=1.5, + edge_cmap='magma', + img_cmap='bone', + in_place=True, + ax=None, +): + """Show a Region Adjacency Graph on an image. + + Given a labelled image and its corresponding RAG, show the nodes and edges + of the RAG on the image with the specified colors. Edges are displayed between + the centroid of the 2 adjacent regions in the image. + + Parameters + ---------- + labels : ndarray, shape (M, N) + The labelled image. + rag : RAG + The Region Adjacency Graph. + image : ndarray, shape (M, N[, 3]) + Input image. If `colormap` is `None`, the image should be in RGB + format. + border_color : color spec, optional + Color with which the borders between regions are drawn. + edge_width : float, optional + The thickness with which the RAG edges are drawn. + edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional + Any matplotlib colormap with which the edges are drawn. + img_cmap : :py:class:`matplotlib.colors.Colormap`, optional + Any matplotlib colormap with which the image is draw. If set to `None` + the image is drawn as it is. + in_place : bool, optional + If set, the RAG is modified in place. For each node `n` the function + will set a new attribute ``rag.nodes[n]['centroid']``. + ax : :py:class:`matplotlib.axes.Axes`, optional + The axes to draw on. If not specified, new axes are created and drawn + on. + + Returns + ------- + lc : :py:class:`matplotlib.collections.LineCollection` + A collection of lines that represent the edges of the graph. It can be + passed to the :meth:`matplotlib.figure.Figure.colorbar` function. + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('matplotlib') + + >>> from skimage import data, segmentation, graph + >>> import matplotlib.pyplot as plt + >>> + >>> img = data.coffee() + >>> labels = segmentation.slic(img) + >>> g = graph.rag_mean_color(img, labels) + >>> lc = graph.show_rag(labels, g, img) + >>> cbar = plt.colorbar(lc) + """ + from matplotlib import colors + from matplotlib import pyplot as plt + from matplotlib.collections import LineCollection + + if not in_place: + rag = rag.copy() + + if ax is None: + fig, ax = plt.subplots() + out = util.img_as_float(image, force_copy=True) + + if img_cmap is None: + if image.ndim < 3 or image.shape[2] not in [3, 4]: + msg = 'If colormap is `None`, an RGB or RGBA image should be given' + raise ValueError(msg) + # Ignore the alpha channel + out = image[:, :, :3] + else: + img_cmap = plt.get_cmap(img_cmap) + out = color.rgb2gray(image) + # Ignore the alpha channel + out = img_cmap(out)[:, :, :3] + + edge_cmap = plt.get_cmap(edge_cmap) + + # Handling the case where one node has multiple labels + # offset is 1 so that regionprops does not ignore 0 + offset = 1 + map_array = np.arange(labels.max() + 1) + for n, d in rag.nodes(data=True): + for label in d['labels']: + map_array[label] = offset + offset += 1 + + rag_labels = map_array[labels] + regions = measure.regionprops(rag_labels) + + for (n, data), region in zip(rag.nodes(data=True), regions): + data['centroid'] = tuple(map(int, region['centroid'])) + + cc = colors.ColorConverter() + if border_color is not None: + border_color = cc.to_rgb(border_color) + out = segmentation.mark_boundaries(out, rag_labels, color=border_color) + + ax.imshow(out) + + # Defining the end points of the edges + # The tuple[::-1] syntax reverses a tuple as matplotlib uses (x,y) + # convention while skimage uses (row, column) + lines = [ + [rag.nodes[n1]['centroid'][::-1], rag.nodes[n2]['centroid'][::-1]] + for (n1, n2) in rag.edges() + ] + + lc = LineCollection(lines, linewidths=edge_width, cmap=edge_cmap) + edge_weights = [d['weight'] for x, y, d in rag.edges(data=True)] + lc.set_array(np.array(edge_weights)) + ax.add_collection(lc) + + return lc diff --git a/python_embeded/Lib/site-packages/skimage/graph/_spath.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/graph/_spath.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..d0b2c7acf6d83241d0eab7cb518b1fc2b875ca82 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/graph/_spath.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/graph/heap.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/graph/heap.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..fd6d4381205391fd677178c7b4989fccf3872959 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/graph/heap.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/graph/mcp.py b/python_embeded/Lib/site-packages/skimage/graph/mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..72a7daa5170ebbe4b84fd37a09b5db24e8bf305c --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/mcp.py @@ -0,0 +1,88 @@ +from ._mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible # noqa: F401 + + +def route_through_array(array, start, end, fully_connected=True, geometric=True): + """Simple example of how to use the MCP and MCP_Geometric classes. + + See the MCP and MCP_Geometric class documentation for explanation of the + path-finding algorithm. + + Parameters + ---------- + array : ndarray + Array of costs. + start : iterable + n-d index into `array` defining the starting point + end : iterable + n-d index into `array` defining the end point + fully_connected : bool (optional) + If True, diagonal moves are permitted, if False, only axial moves. + geometric : bool (optional) + If True, the MCP_Geometric class is used to calculate costs, if False, + the MCP base class is used. See the class documentation for + an explanation of the differences between MCP and MCP_Geometric. + + Returns + ------- + path : list + List of n-d index tuples defining the path from `start` to `end`. + cost : float + Cost of the path. If `geometric` is False, the cost of the path is + the sum of the values of `array` along the path. If `geometric` is + True, a finer computation is made (see the documentation of the + MCP_Geometric class). + + See Also + -------- + MCP, MCP_Geometric + + Examples + -------- + >>> import numpy as np + >>> from skimage.graph import route_through_array + >>> + >>> image = np.array([[1, 3], [10, 12]]) + >>> image + array([[ 1, 3], + [10, 12]]) + >>> # Forbid diagonal steps + >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False) + ([(0, 0), (0, 1), (1, 1)], 9.5) + >>> # Now allow diagonal steps: the path goes directly from start to end + >>> route_through_array(image, [0, 0], [1, 1]) + ([(0, 0), (1, 1)], 9.19238815542512) + >>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12) + >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False, + ... geometric=False) + ([(0, 0), (0, 1), (1, 1)], 16.0) + >>> # Larger array where we display the path that is selected + >>> image = np.arange((36)).reshape((6, 6)) + >>> image + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 21, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> # Find the path with lowest cost + >>> indices, weight = route_through_array(image, (0, 0), (5, 5)) + >>> indices = np.stack(indices, axis=-1) + >>> path = np.zeros_like(image) + >>> path[indices[0], indices[1]] = 1 + >>> path + array([[1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 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]]) + + """ + start, end = tuple(start), tuple(end) + if geometric: + mcp_class = MCP_Geometric + else: + mcp_class = MCP + m = mcp_class(array, fully_connected=fully_connected) + costs, traceback_array = m.find_costs([start], [end]) + return m.traceback(end), costs[end] diff --git a/python_embeded/Lib/site-packages/skimage/graph/spath.py b/python_embeded/Lib/site-packages/skimage/graph/spath.py new file mode 100644 index 0000000000000000000000000000000000000000..a59397db94b09a0cd497a4386fccd39b22014f18 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/graph/spath.py @@ -0,0 +1,83 @@ +import numpy as np +from . import _spath + + +def shortest_path(arr, reach=1, axis=-1, output_indexlist=False): + """Find the shortest path through an n-d array from one side to another. + + Parameters + ---------- + arr : ndarray of float64 + reach : int, optional + By default (``reach = 1``), the shortest path can only move + one row up or down for every step it moves forward (i.e., + the path gradient is limited to 1). `reach` defines the + number of elements that can be skipped along each non-axis + dimension at each step. + axis : int, optional + The axis along which the path must always move forward (default -1) + output_indexlist : bool, optional + See return value `p` for explanation. + + Returns + ------- + p : iterable of int + For each step along `axis`, the coordinate of the shortest path. + If `output_indexlist` is True, then the path is returned as a list of + n-d tuples that index into `arr`. If False, then the path is returned + as an array listing the coordinates of the path along the non-axis + dimensions for each step along the axis dimension. That is, + `p.shape == (arr.shape[axis], arr.ndim-1)` except that p is squeezed + before returning so if `arr.ndim == 2`, then + `p.shape == (arr.shape[axis],)` + cost : float + Cost of path. This is the absolute sum of all the + differences along the path. + + """ + # First: calculate the valid moves from any given position. Basically, + # always move +1 along the given axis, and then can move anywhere within + # a grid defined by the reach. + if axis < 0: + axis += arr.ndim + offset_ind_shape = (2 * reach + 1,) * (arr.ndim - 1) + offset_indices = np.indices(offset_ind_shape) - reach + offset_indices = np.insert(offset_indices, axis, np.ones(offset_ind_shape), axis=0) + offset_size = np.multiply.reduce(offset_ind_shape) + offsets = np.reshape(offset_indices, (arr.ndim, offset_size), order='F').T + + # Valid starting positions are anywhere on the hyperplane defined by + # position 0 on the given axis. Ending positions are anywhere on the + # hyperplane at position -1 along the same. + non_axis_shape = arr.shape[:axis] + arr.shape[axis + 1 :] + non_axis_indices = np.indices(non_axis_shape) + non_axis_size = np.multiply.reduce(non_axis_shape) + start_indices = np.insert(non_axis_indices, axis, np.zeros(non_axis_shape), axis=0) + starts = np.reshape(start_indices, (arr.ndim, non_axis_size), order='F').T + end_indices = np.insert( + non_axis_indices, + axis, + np.full(non_axis_shape, -1, dtype=non_axis_indices.dtype), + axis=0, + ) + ends = np.reshape(end_indices, (arr.ndim, non_axis_size), order='F').T + + # Find the minimum-cost path to one of the end-points + m = _spath.MCP_Diff(arr, offsets=offsets) + costs, traceback = m.find_costs(starts, ends, find_all_ends=False) + + # Figure out which end-point was found + for end in ends: + cost = costs[tuple(end)] + if cost != np.inf: + break + traceback = m.traceback(end) + + if not output_indexlist: + traceback = np.array(traceback) + traceback = np.concatenate( + [traceback[:, :axis], traceback[:, axis + 1 :]], axis=1 + ) + traceback = np.squeeze(traceback) + + return traceback, cost diff --git a/python_embeded/Lib/site-packages/skimage/io/__init__.py b/python_embeded/Lib/site-packages/skimage/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b33a163851fd81149dc700e2b9d47287b0b1e9e --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/__init__.py @@ -0,0 +1,43 @@ +"""Reading and saving of images and videos.""" + +import warnings + +from .manage_plugins import * +from .manage_plugins import _hide_plugin_deprecation_warnings +from .sift import * +from .collection import * + +from ._io import * +from ._image_stack import * + + +with _hide_plugin_deprecation_warnings(): + reset_plugins() + + +__all__ = [ + "concatenate_images", + "imread", + "imread_collection", + "imread_collection_wrapper", + "imsave", + "load_sift", + "load_surf", + "pop", + "push", + "ImageCollection", + "MultiImage", +] + + +def __getattr__(name): + if name == "available_plugins": + warnings.warn( + "`available_plugins` is deprecated since version 0.25 and will " + "be removed in version 0.27. Instead, use `imageio` or other " + "I/O packages directly.", + category=FutureWarning, + stacklevel=2, + ) + return globals()["_available_plugins"] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/python_embeded/Lib/site-packages/skimage/io/_image_stack.py b/python_embeded/Lib/site-packages/skimage/io/_image_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..01fd34863935502052884eb602db7557c932899f --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/_image_stack.py @@ -0,0 +1,35 @@ +import numpy as np + + +__all__ = ['image_stack', 'push', 'pop'] + + +# Shared image queue +image_stack = [] + + +def push(img): + """Push an image onto the shared image stack. + + Parameters + ---------- + img : ndarray + Image to push. + + """ + if not isinstance(img, np.ndarray): + raise ValueError("Can only push ndarrays to the image stack.") + + image_stack.append(img) + + +def pop(): + """Pop an image from the shared image stack. + + Returns + ------- + img : ndarray + Image popped from the stack. + + """ + return image_stack.pop() diff --git a/python_embeded/Lib/site-packages/skimage/io/_io.py b/python_embeded/Lib/site-packages/skimage/io/_io.py new file mode 100644 index 0000000000000000000000000000000000000000..919d15d51cbfdbfe14c0126a6038ca0c352bda27 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/_io.py @@ -0,0 +1,289 @@ +import pathlib +import warnings + +import numpy as np + +from .._shared.utils import warn, deprecate_func, deprecate_parameter, DEPRECATED +from .._shared.version_requirements import require +from ..exposure import is_low_contrast +from ..color.colorconv import rgb2gray, rgba2rgb +from ..io.manage_plugins import call_plugin, _hide_plugin_deprecation_warnings +from .util import file_or_url_context + +__all__ = [ + 'imread', + 'imsave', + 'imshow', + 'show', + 'imread_collection', + 'imshow_collection', +] + + +_remove_plugin_param_template = ( + "The plugin infrastructure in `skimage.io` and the parameter " + "`{deprecated_name}` are deprecated since version {deprecated_version} and " + "will be removed in {changed_version} (or later). To avoid this warning, " + "please do not use the parameter `{deprecated_name}`. Instead, use `imageio` " + "or other I/O packages directly. See also `{func_name}`." +) + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imread(fname, as_gray=False, plugin=DEPRECATED, **plugin_args): + """Load an image from file. + + Parameters + ---------- + fname : str or pathlib.Path + Image file name, e.g. ``test.jpg`` or URL. + as_gray : bool, optional + If True, convert color images to gray-scale (64-bit floats). + Images that are already in gray-scale format are not converted. + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + + Returns + ------- + img_array : ndarray + The different color bands/channels are stored in the + third dimension, such that a gray-image is MxN, an + RGB-image MxNx3 and an RGBA-image MxNx4. + + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imread`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + + if isinstance(fname, pathlib.Path): + fname = str(fname.resolve()) + + if plugin is None and hasattr(fname, 'lower'): + if fname.lower().endswith(('.tiff', '.tif')): + plugin = 'tifffile' + + with file_or_url_context(fname) as fname, _hide_plugin_deprecation_warnings(): + img = call_plugin('imread', fname, plugin=plugin, **plugin_args) + + if not hasattr(img, 'ndim'): + return img + + if img.ndim > 2: + if img.shape[-1] not in (3, 4) and img.shape[-3] in (3, 4): + img = np.swapaxes(img, -1, -3) + img = np.swapaxes(img, -2, -3) + + if as_gray: + if img.shape[2] == 4: + img = rgba2rgb(img) + img = rgb2gray(img) + + return img + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imread_collection( + load_pattern, conserve_memory=True, plugin=DEPRECATED, **plugin_args +): + """ + Load a collection of images. + + Parameters + ---------- + load_pattern : str or list + List of objects to load. These are usually filenames, but may + vary depending on the currently active plugin. See :class:`ImageCollection` + for the default behaviour of this parameter. + conserve_memory : bool, optional + If True, never keep more than one in memory at a specific + time. Otherwise, images will be cached once they are loaded. + + Returns + ------- + ic : :class:`ImageCollection` + Collection of images. + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imread_collection`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + with _hide_plugin_deprecation_warnings(): + return call_plugin( + 'imread_collection', + load_pattern, + conserve_memory, + plugin=plugin, + **plugin_args, + ) + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imsave(fname, arr, plugin=DEPRECATED, *, check_contrast=True, **plugin_args): + """Save an image to file. + + Parameters + ---------- + fname : str or pathlib.Path + Target filename. + arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4) + Image data. + check_contrast : bool, optional + Check for low contrast and print warning (default: True). + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imsave`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + + if isinstance(fname, pathlib.Path): + fname = str(fname.resolve()) + if plugin is None and hasattr(fname, 'lower'): + if fname.lower().endswith(('.tiff', '.tif')): + plugin = 'tifffile' + if arr.dtype == bool: + warn( + f'{fname} is a boolean image: setting True to 255 and False to 0. ' + 'To silence this warning, please convert the image using ' + 'img_as_ubyte.', + stacklevel=3, + ) + arr = arr.astype('uint8') * 255 + if check_contrast and is_low_contrast(arr): + warn(f'{fname} is a low contrast image') + + with _hide_plugin_deprecation_warnings(): + return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def imshow(arr, plugin=None, **plugin_args): + """Display an image. + + Parameters + ---------- + arr : ndarray or str + Image data or name of image file. + plugin : str + Name of plugin to use. By default, the different plugins are + tried (starting with imageio) until a suitable candidate is found. + + Other Parameters + ---------------- + plugin_args : keywords + Passed to the given plugin. + + """ + if isinstance(arr, str): + arr = call_plugin('imread', arr, plugin=plugin) + with _hide_plugin_deprecation_warnings(): + return call_plugin('imshow', arr, plugin=plugin, **plugin_args) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def imshow_collection(ic, plugin=None, **plugin_args): + """Display a collection of images. + + Parameters + ---------- + ic : :class:`ImageCollection` + Collection to display. + + Other Parameters + ---------------- + plugin_args : keywords + Passed to the given plugin. + + """ + with _hide_plugin_deprecation_warnings(): + return call_plugin('imshow_collection', ic, plugin=plugin, **plugin_args) + + +@require("matplotlib", ">=3.3") +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def show(): + """Display pending images. + + Launch the event loop of the current GUI plugin, and display all + pending images, queued via `imshow`. This is required when using + `imshow` from non-interactive scripts. + + A call to `show` will block execution of code until all windows + have been closed. + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('matplotlib') + + >>> import skimage.io as io + >>> rng = np.random.default_rng() + >>> for i in range(4): + ... ax_im = io.imshow(rng.random((50, 50))) # doctest: +SKIP + >>> io.show() # doctest: +SKIP + + """ + with _hide_plugin_deprecation_warnings(): + return call_plugin('_app_show') diff --git a/python_embeded/Lib/site-packages/skimage/io/collection.py b/python_embeded/Lib/site-packages/skimage/io/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1d220e264cb91d34a4e996d4a68d3d16a6c0f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/collection.py @@ -0,0 +1,493 @@ +"""Data structures to hold collections of images, with optional caching.""" + +import os +from glob import glob +import re +from collections.abc import Sequence +from copy import copy + +import numpy as np +from PIL import Image + +from tifffile import TiffFile + + +__all__ = [ + 'MultiImage', + 'ImageCollection', + 'concatenate_images', + 'imread_collection_wrapper', +] + + +def concatenate_images(ic): + """Concatenate all images in the image collection into an array. + + Parameters + ---------- + ic : an iterable of images + The images to be concatenated. + + Returns + ------- + array_cat : ndarray + An array having one more dimension than the images in `ic`. + + See Also + -------- + ImageCollection.concatenate + MultiImage.concatenate + + Raises + ------ + ValueError + If images in `ic` don't have identical shapes. + + Notes + ----- + ``concatenate_images`` receives any iterable object containing images, + including ImageCollection and MultiImage, and returns a NumPy array. + """ + all_images = [image[np.newaxis, ...] for image in ic] + try: + array_cat = np.concatenate(all_images) + except ValueError: + raise ValueError('Image dimensions must agree.') + return array_cat + + +def alphanumeric_key(s): + """Convert string to list of strings and ints that gives intuitive sorting. + + Parameters + ---------- + s : string + + Returns + ------- + k : a list of strings and ints + + Examples + -------- + >>> alphanumeric_key('z23a') + ['z', 23, 'a'] + >>> filenames = ['f9.10.png', 'e10.png', 'f9.9.png', 'f10.10.png', + ... 'f10.9.png'] + >>> sorted(filenames) + ['e10.png', 'f10.10.png', 'f10.9.png', 'f9.10.png', 'f9.9.png'] + >>> sorted(filenames, key=alphanumeric_key) + ['e10.png', 'f9.9.png', 'f9.10.png', 'f10.9.png', 'f10.10.png'] + """ + k = [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', s)] + return k + + +def _is_multipattern(input_pattern): + """Helping function. Returns True if pattern contains a tuple, list, or a + string separated with os.pathsep.""" + # Conditions to be accepted by ImageCollection: + has_str_ospathsep = isinstance(input_pattern, str) and os.pathsep in input_pattern + not_a_string = not isinstance(input_pattern, str) + has_iterable = isinstance(input_pattern, Sequence) + has_strings = all(isinstance(pat, str) for pat in input_pattern) + + is_multipattern = has_str_ospathsep or ( + not_a_string and has_iterable and has_strings + ) + return is_multipattern + + +class ImageCollection: + """Load and manage a collection of image files. + + Parameters + ---------- + load_pattern : str or list of str + Pattern string or list of strings to load. The filename path can be + absolute or relative. + conserve_memory : bool, optional + If True, :class:`skimage.io.ImageCollection` does not keep more than one in + memory at a specific time. Otherwise, images will be cached once they are loaded. + + Other parameters + ---------------- + load_func : callable + ``imread`` by default. See Notes below. + **load_func_kwargs : dict + Any other keyword arguments are passed to `load_func`. + + Attributes + ---------- + files : list of str + If a pattern string is given for `load_pattern`, this attribute + stores the expanded file list. Otherwise, this is equal to + `load_pattern`. + + Notes + ----- + Note that files are always returned in alphanumerical order. Also note that slicing + returns a new :class:`skimage.io.ImageCollection`, *not* a view into the data. + + ImageCollection image loading can be customized through + `load_func`. For an ImageCollection ``ic``, ``ic[5]`` calls + ``load_func(load_pattern[5])`` to load that image. + + For example, here is an ImageCollection that, for each video provided, + loads every second frame:: + + import imageio.v3 as iio3 + import itertools + + def vidread_step(f, step): + vid = iio3.imiter(f) + return list(itertools.islice(vid, None, None, step) + + video_file = 'no_time_for_that_tiny.gif' + ic = ImageCollection(video_file, load_func=vidread_step, step=2) + + ic # is an ImageCollection object of length 1 because 1 video is provided + + x = ic[0] + x[5] # the 10th frame of the first video + + Alternatively, if `load_func` is provided and `load_pattern` is a + sequence, an :class:`skimage.io.ImageCollection` of corresponding length will + be created, and the individual images will be loaded by calling `load_func` with the + matching element of the `load_pattern` as its first argument. In this + case, the elements of the sequence do not need to be names of existing + files (or strings at all). For example, to create an :class:`skimage.io.ImageCollection` + containing 500 images from a video:: + + class FrameReader: + def __init__ (self, f): + self.f = f + def __call__ (self, index): + return iio3.imread(self.f, index=index) + + ic = ImageCollection(range(500), load_func=FrameReader('movie.mp4')) + + ic # is an ImageCollection object of length 500 + + Another use of `load_func` would be to convert all images to ``uint8``:: + + def imread_convert(f): + return imread(f).astype(np.uint8) + + ic = ImageCollection('/tmp/*.png', load_func=imread_convert) + + Examples + -------- + >>> import imageio.v3 as iio3 + >>> import skimage.io as io + + # Where your images are located + >>> data_dir = os.path.join(os.path.dirname(__file__), '../data') + + >>> coll = io.ImageCollection(data_dir + '/chess*.png') + >>> len(coll) + 2 + >>> coll[0].shape + (200, 200) + + >>> image_col = io.ImageCollection([f'{data_dir}/*.png', '{data_dir}/*.jpg']) + + >>> class MultiReader: + ... def __init__ (self, f): + ... self.f = f + ... def __call__ (self, index): + ... return iio3.imread(self.f, index=index) + ... + >>> filename = data_dir + '/no_time_for_that_tiny.gif' + >>> ic = io.ImageCollection(range(24), load_func=MultiReader(filename)) + >>> len(image_col) + 23 + >>> isinstance(ic[0], np.ndarray) + True + """ + + def __init__( + self, load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs + ): + """Load and manage a collection of images.""" + self._files = [] + if _is_multipattern(load_pattern): + if isinstance(load_pattern, str): + load_pattern = load_pattern.split(os.pathsep) + for pattern in load_pattern: + self._files.extend(glob(pattern)) + self._files = sorted(self._files, key=alphanumeric_key) + elif isinstance(load_pattern, str): + self._files.extend(glob(load_pattern)) + self._files = sorted(self._files, key=alphanumeric_key) + elif isinstance(load_pattern, Sequence) and load_func is not None: + self._files = list(load_pattern) + else: + raise TypeError('Invalid pattern as input.') + + if load_func is None: + from ._io import imread + + self.load_func = imread + self._numframes = self._find_images() + else: + self.load_func = load_func + self._numframes = len(self._files) + self._frame_index = None + + if conserve_memory: + memory_slots = 1 + else: + memory_slots = self._numframes + + self._conserve_memory = conserve_memory + self._cached = None + + self.load_func_kwargs = load_func_kwargs + self.data = np.empty(memory_slots, dtype=object) + + @property + def files(self): + return self._files + + @property + def conserve_memory(self): + return self._conserve_memory + + def _find_images(self): + index = [] + for fname in self._files: + if fname.lower().endswith(('.tiff', '.tif')): + with open(fname, 'rb') as f: + img = TiffFile(f) + index += [(fname, i) for i in range(len(img.pages))] + else: + try: + im = Image.open(fname) + im.seek(0) + except OSError: + continue + i = 0 + while True: + try: + im.seek(i) + except EOFError: + break + index.append((fname, i)) + i += 1 + if hasattr(im, 'fp') and im.fp: + im.fp.close() + self._frame_index = index + return len(index) + + def __getitem__(self, n): + """Return selected image(s) in the collection. + + Loading is done on demand. + + Parameters + ---------- + n : int or slice + The image number to be returned, or a slice selecting the images + and ordering to be returned in a new ImageCollection. + + Returns + ------- + img : ndarray or :class:`skimage.io.ImageCollection` + The `n`-th image in the collection, or a new ImageCollection with + the selected images. + """ + if hasattr(n, '__index__'): + n = n.__index__() + + if not isinstance(n, (int, slice)): + raise TypeError('slicing must be with an int or slice object') + + if isinstance(n, int): + n = self._check_imgnum(n) + idx = n % len(self.data) + + if (self.conserve_memory and n != self._cached) or (self.data[idx] is None): + kwargs = self.load_func_kwargs + if self._frame_index: + fname, img_num = self._frame_index[n] + if img_num is not None: + kwargs['img_num'] = img_num + try: + self.data[idx] = self.load_func(fname, **kwargs) + # Account for functions that do not accept an img_num kwarg + except TypeError as e: + if "unexpected keyword argument 'img_num'" in str(e): + del kwargs['img_num'] + self.data[idx] = self.load_func(fname, **kwargs) + else: + raise + else: + self.data[idx] = self.load_func(self.files[n], **kwargs) + self._cached = n + + return self.data[idx] + else: + # A slice object was provided, so create a new ImageCollection + # object. Any loaded image data in the original ImageCollection + # will be copied by reference to the new object. Image data + # loaded after this creation is not linked. + fidx = range(self._numframes)[n] + new_ic = copy(self) + + if self._frame_index: + new_ic._files = [self._frame_index[i][0] for i in fidx] + new_ic._frame_index = [self._frame_index[i] for i in fidx] + else: + new_ic._files = [self._files[i] for i in fidx] + + new_ic._numframes = len(fidx) + + if self.conserve_memory: + if self._cached in fidx: + new_ic._cached = fidx.index(self._cached) + new_ic.data = np.copy(self.data) + else: + new_ic.data = np.empty(1, dtype=object) + else: + new_ic.data = self.data[fidx] + return new_ic + + def _check_imgnum(self, n): + """Check that the given image number is valid.""" + num = self._numframes + if -num <= n < num: + n = n % num + else: + raise IndexError(f"There are only {num} images in the collection") + return n + + def __iter__(self): + """Iterate over the images.""" + for i in range(len(self)): + yield self[i] + + def __len__(self): + """Number of images in collection.""" + return self._numframes + + def __str__(self): + return str(self.files) + + def reload(self, n=None): + """Clear the image cache. + + Parameters + ---------- + n : None or int + Clear the cache for this image only. By default, the + entire cache is erased. + + """ + self.data = np.empty_like(self.data) + + def concatenate(self): + """Concatenate all images in the collection into an array. + + Returns + ------- + ar : np.ndarray + An array having one more dimension than the images in `self`. + + See Also + -------- + skimage.io.concatenate_images + + Raises + ------ + ValueError + If images in the :class:`skimage.io.ImageCollection` do not have identical + shapes. + """ + return concatenate_images(self) + + +def imread_collection_wrapper(imread): + def imread_collection(load_pattern, conserve_memory=True): + """Return an `ImageCollection` from files matching the given pattern. + + Note that files are always stored in alphabetical order. Also note that + slicing returns a new ImageCollection, *not* a view into the data. + + See `skimage.io.ImageCollection` for details. + + Parameters + ---------- + load_pattern : str or list + Pattern glob or filenames to load. The path can be absolute or + relative. Multiple patterns should be separated by a colon, + e.g. ``/tmp/work/*.png:/tmp/other/*.jpg``. Also see + implementation notes below. + conserve_memory : bool, optional + If True, never keep more than one in memory at a specific + time. Otherwise, images will be cached once they are loaded. + + """ + return ImageCollection( + load_pattern, conserve_memory=conserve_memory, load_func=imread + ) + + return imread_collection + + +class MultiImage(ImageCollection): + """A class containing all frames from multi-frame TIFF images. + + Parameters + ---------- + load_pattern : str or list of str + Pattern glob or filenames to load. The path can be absolute or + relative. + conserve_memory : bool, optional + Whether to conserve memory by only caching the frames of a single + image. Default is True. + + Notes + ----- + `MultiImage` returns a list of image-data arrays. In this + regard, it is very similar to `ImageCollection`, but the two differ in + their treatment of multi-frame images. + + For a TIFF image containing N frames of size WxH, `MultiImage` stores + all frames of that image as a single element of shape `(N, W, H)` in the + list. `ImageCollection` instead creates N elements of shape `(W, H)`. + + For an animated GIF image, `MultiImage` reads only the first frame, while + `ImageCollection` reads all frames by default. + + Examples + -------- + # Where your images are located + >>> data_dir = os.path.join(os.path.dirname(__file__), '../data') + + >>> multipage_tiff = data_dir + '/multipage.tif' + >>> multi_img = MultiImage(multipage_tiff) + >>> len(multi_img) # multi_img contains one element + 1 + >>> multi_img[0].shape # this element is a two-frame image of shape: + (2, 15, 10) + + >>> image_col = ImageCollection(multipage_tiff) + >>> len(image_col) # image_col contains two elements + 2 + >>> for frame in image_col: + ... print(frame.shape) # each element is a frame of shape (15, 10) + ... + (15, 10) + (15, 10) + """ + + def __init__(self, filename, conserve_memory=True, dtype=None, **imread_kwargs): + """Load a multi-img.""" + from ._io import imread + + self._filename = filename + super().__init__(filename, conserve_memory, load_func=imread, **imread_kwargs) + + @property + def filename(self): + return self._filename diff --git a/python_embeded/Lib/site-packages/skimage/io/manage_plugins.py b/python_embeded/Lib/site-packages/skimage/io/manage_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..f8fb3e558488980fb333db8cbd8b8f0a348bba8a --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/manage_plugins.py @@ -0,0 +1,405 @@ +"""Handle image reading, writing and plotting plugins. + +To improve performance, plugins are only loaded as needed. As a result, there +can be multiple states for a given plugin: + + available: Defined in an *ini file located in ``skimage.io._plugins``. + See also :func:`skimage.io.available_plugins`. + partial definition: Specified in an *ini file, but not defined in the + corresponding plugin module. This will raise an error when loaded. + available but not on this system: Defined in ``skimage.io._plugins``, but + a dependent library (e.g. Qt, PIL) is not available on your system. + This will raise an error when loaded. + loaded: The real availability is determined when it's explicitly loaded, + either because it's one of the default plugins, or because it's + loaded explicitly by the user. + +""" + +import os.path +import warnings +from configparser import ConfigParser +from glob import glob +from contextlib import contextmanager + +from .._shared.utils import deprecate_func +from .collection import imread_collection_wrapper + +__all__ = [ + 'use_plugin', + 'call_plugin', + 'plugin_info', + 'plugin_order', + 'reset_plugins', + 'find_available_plugins', + '_available_plugins', +] + +# The plugin store will save a list of *loaded* io functions for each io type +# (e.g. 'imread', 'imsave', etc.). Plugins are loaded as requested. +plugin_store = None +# Dictionary mapping plugin names to a list of functions they provide. +plugin_provides = {} +# The module names for the plugins in `skimage.io._plugins`. +plugin_module_name = {} +# Meta-data about plugins provided by *.ini files. +plugin_meta_data = {} +# For each plugin type, default to the first available plugin as defined by +# the following preferences. +preferred_plugins = { + # Default plugins for all types (overridden by specific types below). + 'all': ['imageio', 'pil', 'matplotlib'], + 'imshow': ['matplotlib'], + 'imshow_collection': ['matplotlib'], +} + + +@contextmanager +def _hide_plugin_deprecation_warnings(): + """Ignore warnings related to plugin infrastructure deprecation.""" + with warnings.catch_warnings(): + warnings.filterwarnings( + action="ignore", + message=".*use `imageio` or other I/O packages directly.*", + category=FutureWarning, + module="skimage", + ) + yield + + +def _clear_plugins(): + """Clear the plugin state to the default, i.e., where no plugins are loaded""" + global plugin_store + plugin_store = { + 'imread': [], + 'imsave': [], + 'imshow': [], + 'imread_collection': [], + 'imshow_collection': [], + '_app_show': [], + } + + +with _hide_plugin_deprecation_warnings(): + _clear_plugins() + + +def _load_preferred_plugins(): + # Load preferred plugin for each io function. + io_types = ['imsave', 'imshow', 'imread_collection', 'imshow_collection', 'imread'] + for p_type in io_types: + _set_plugin(p_type, preferred_plugins['all']) + + plugin_types = (p for p in preferred_plugins.keys() if p != 'all') + for p_type in plugin_types: + _set_plugin(p_type, preferred_plugins[p_type]) + + +def _set_plugin(plugin_type, plugin_list): + for plugin in plugin_list: + if plugin not in _available_plugins: + continue + try: + use_plugin(plugin, kind=plugin_type) + break + except (ImportError, RuntimeError, OSError): + pass + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def reset_plugins(): + with _hide_plugin_deprecation_warnings(): + _clear_plugins() + _load_preferred_plugins() + + +def _parse_config_file(filename): + """Return plugin name and meta-data dict from plugin config file.""" + parser = ConfigParser() + parser.read(filename) + name = parser.sections()[0] + + meta_data = {} + for opt in parser.options(name): + meta_data[opt] = parser.get(name, opt) + + return name, meta_data + + +def _scan_plugins(): + """Scan the plugins directory for .ini files and parse them + to gather plugin meta-data. + """ + pd = os.path.dirname(__file__) + config_files = glob(os.path.join(pd, '_plugins', '*.ini')) + + for filename in config_files: + name, meta_data = _parse_config_file(filename) + if 'provides' not in meta_data: + warnings.warn( + f'file {filename} not recognized as a scikit-image io plugin, skipping.' + ) + continue + plugin_meta_data[name] = meta_data + provides = [s.strip() for s in meta_data['provides'].split(',')] + valid_provides = [p for p in provides if p in plugin_store] + + for p in provides: + if p not in plugin_store: + print(f"Plugin `{name}` wants to provide non-existent `{p}`. Ignoring.") + + # Add plugins that provide 'imread' as provider of 'imread_collection'. + need_to_add_collection = ( + 'imread_collection' not in valid_provides and 'imread' in valid_provides + ) + if need_to_add_collection: + valid_provides.append('imread_collection') + + plugin_provides[name] = valid_provides + + plugin_module_name[name] = os.path.basename(filename)[:-4] + + +with _hide_plugin_deprecation_warnings(): + _scan_plugins() + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def find_available_plugins(loaded=False): + """List available plugins. + + Parameters + ---------- + loaded : bool + If True, show only those plugins currently loaded. By default, + all plugins are shown. + + Returns + ------- + p : dict + Dictionary with plugin names as keys and exposed functions as + values. + + """ + active_plugins = set() + for plugin_func in plugin_store.values(): + for plugin, func in plugin_func: + active_plugins.add(plugin) + + d = {} + for plugin in plugin_provides: + if not loaded or plugin in active_plugins: + d[plugin] = [f for f in plugin_provides[plugin] if not f.startswith('_')] + + return d + + +with _hide_plugin_deprecation_warnings(): + _available_plugins = find_available_plugins() + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def call_plugin(kind, *args, **kwargs): + """Find the appropriate plugin of 'kind' and execute it. + + Parameters + ---------- + kind : {'imshow', 'imsave', 'imread', 'imread_collection'} + Function to look up. + plugin : str, optional + Plugin to load. Defaults to None, in which case the first + matching plugin is used. + *args, **kwargs : arguments and keyword arguments + Passed to the plugin function. + + """ + if kind not in plugin_store: + raise ValueError(f'Invalid function ({kind}) requested.') + + plugin_funcs = plugin_store[kind] + if len(plugin_funcs) == 0: + msg = ( + f"No suitable plugin registered for {kind}.\n\n" + "You may load I/O plugins with the `skimage.io.use_plugin` " + "command. A list of all available plugins are shown in the " + "`skimage.io` docstring." + ) + raise RuntimeError(msg) + + plugin = kwargs.pop('plugin', None) + if plugin is None: + _, func = plugin_funcs[0] + else: + _load(plugin) + try: + func = [f for (p, f) in plugin_funcs if p == plugin][0] + except IndexError: + raise RuntimeError(f'Could not find the plugin "{plugin}" for {kind}.') + + return func(*args, **kwargs) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def use_plugin(name, kind=None): + """Set the default plugin for a specified operation. The plugin + will be loaded if it hasn't been already. + + Parameters + ---------- + name : str + Name of plugin. See ``skimage.io.available_plugins`` for a list of available + plugins. + kind : {'imsave', 'imread', 'imshow', 'imread_collection', 'imshow_collection'}, optional + Set the plugin for this function. By default, + the plugin is set for all functions. + + Examples + -------- + To use Matplotlib as the default image reader, you would write: + + >>> from skimage import io + >>> io.use_plugin('matplotlib', 'imread') + + To see a list of available plugins run ``skimage.io.available_plugins``. Note + that this lists plugins that are defined, but the full list may not be usable + if your system does not have the required libraries installed. + + """ + if kind is None: + kind = plugin_store.keys() + else: + if kind not in plugin_provides[name]: + raise RuntimeError(f"Plugin {name} does not support `{kind}`.") + + if kind == 'imshow': + kind = [kind, '_app_show'] + else: + kind = [kind] + + _load(name) + + for k in kind: + if k not in plugin_store: + raise RuntimeError(f"'{k}' is not a known plugin function.") + + funcs = plugin_store[k] + + # Shuffle the plugins so that the requested plugin stands first + # in line + funcs = [(n, f) for (n, f) in funcs if n == name] + [ + (n, f) for (n, f) in funcs if n != name + ] + + plugin_store[k] = funcs + + +def _inject_imread_collection_if_needed(module): + """Add `imread_collection` to module if not already present.""" + if not hasattr(module, 'imread_collection') and hasattr(module, 'imread'): + imread = getattr(module, 'imread') + func = imread_collection_wrapper(imread) + setattr(module, 'imread_collection', func) + + +@_hide_plugin_deprecation_warnings() +def _load(plugin): + """Load the given plugin. + + Parameters + ---------- + plugin : str + Name of plugin to load. + + See Also + -------- + plugins : List of available plugins + + """ + if plugin in find_available_plugins(loaded=True): + return + if plugin not in plugin_module_name: + raise ValueError(f"Plugin {plugin} not found.") + else: + modname = plugin_module_name[plugin] + plugin_module = __import__('skimage.io._plugins.' + modname, fromlist=[modname]) + + provides = plugin_provides[plugin] + for p in provides: + if p == 'imread_collection': + _inject_imread_collection_if_needed(plugin_module) + elif not hasattr(plugin_module, p): + print(f"Plugin {plugin} does not provide {p} as advertised. Ignoring.") + continue + + store = plugin_store[p] + func = getattr(plugin_module, p) + if (plugin, func) not in store: + store.append((plugin, func)) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def plugin_info(plugin): + """Return plugin meta-data. + + Parameters + ---------- + plugin : str + Name of plugin. + + Returns + ------- + m : dict + Meta data as specified in plugin ``.ini``. + + """ + try: + return plugin_meta_data[plugin] + except KeyError: + raise ValueError(f'No information on plugin "{plugin}"') + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def plugin_order(): + """Return the currently preferred plugin order. + + Returns + ------- + p : dict + Dictionary of preferred plugin order, with function name as key and + plugins (in order of preference) as value. + + """ + p = {} + for func in plugin_store: + p[func] = [plugin_name for (plugin_name, f) in plugin_store[func]] + return p diff --git a/python_embeded/Lib/site-packages/skimage/io/sift.py b/python_embeded/Lib/site-packages/skimage/io/sift.py new file mode 100644 index 0000000000000000000000000000000000000000..a7452e1ec779275ddb03d03b8a884ee2ce96bcfe --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/sift.py @@ -0,0 +1,93 @@ +import numpy as np + +__all__ = ['load_sift', 'load_surf'] + + +def _sift_read(filelike, mode='SIFT'): + """Read SIFT or SURF features from externally generated file. + + This routine reads SIFT or SURF files generated by binary utilities from + http://people.cs.ubc.ca/~lowe/keypoints/ and + http://www.vision.ee.ethz.ch/~surf/. + + This routine *does not* generate SIFT/SURF features from an image. These + algorithms are patent encumbered. Please use :obj:`skimage.feature.CENSURE` + instead. + + Parameters + ---------- + filelike : string or open file + Input file generated by the feature detectors from + http://people.cs.ubc.ca/~lowe/keypoints/ or + http://www.vision.ee.ethz.ch/~surf/ . + mode : {'SIFT', 'SURF'}, optional + Kind of descriptor used to generate `filelike`. + + Returns + ------- + data : record array with fields + - row: int + row position of feature + - column: int + column position of feature + - scale: float + feature scale + - orientation: float + feature orientation + - data: array + feature values + + """ + if isinstance(filelike, str): + f = open(filelike) + filelike_is_str = True + else: + f = filelike + filelike_is_str = False + + if mode == 'SIFT': + nr_features, feature_len = map(int, f.readline().split()) + datatype = np.dtype( + [ + ('row', float), + ('column', float), + ('scale', float), + ('orientation', float), + ('data', (float, feature_len)), + ] + ) + else: + mode = 'SURF' + feature_len = int(f.readline()) - 1 + nr_features = int(f.readline()) + datatype = np.dtype( + [ + ('column', float), + ('row', float), + ('second_moment', (float, 3)), + ('sign', float), + ('data', (float, feature_len)), + ] + ) + + data = np.fromfile(f, sep=' ') + if data.size != nr_features * datatype.itemsize / np.dtype(float).itemsize: + raise OSError(f'Invalid {mode} feature file.') + + # If `filelike` is passed to the function as filename - close the file + if filelike_is_str: + f.close() + + return data.view(datatype) + + +def load_sift(f): + return _sift_read(f, mode='SIFT') + + +def load_surf(f): + return _sift_read(f, mode='SURF') + + +load_sift.__doc__ = _sift_read.__doc__ +load_surf.__doc__ = _sift_read.__doc__ diff --git a/python_embeded/Lib/site-packages/skimage/io/util.py b/python_embeded/Lib/site-packages/skimage/io/util.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e49916561ad7afc3e92a881de76becb9a1438f --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/io/util.py @@ -0,0 +1,41 @@ +import urllib.parse +import urllib.request +from urllib.error import URLError, HTTPError + +import os +import re +import tempfile +from contextlib import contextmanager + + +URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') + + +def is_url(filename): + """Return True if string is an http or ftp path.""" + return isinstance(filename, str) and URL_REGEX.match(filename) is not None + + +@contextmanager +def file_or_url_context(resource_name): + """Yield name of file from the given resource (i.e. file or url).""" + if is_url(resource_name): + url_components = urllib.parse.urlparse(resource_name) + _, ext = os.path.splitext(url_components.path) + try: + with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: + with urllib.request.urlopen(resource_name) as u: + f.write(u.read()) + # f must be closed before yielding + yield f.name + except (URLError, HTTPError): + # could not open URL + os.remove(f.name) + raise + except (FileNotFoundError, FileExistsError, PermissionError, BaseException): + # could not create temporary file + raise + else: + os.remove(f.name) + else: + yield resource_name diff --git a/python_embeded/Lib/site-packages/skimage/measure/__init__.py b/python_embeded/Lib/site-packages/skimage/measure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f43b70583162e0f47c814c3753eae344a2c3463b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/__init__.py @@ -0,0 +1,5 @@ +"""Measurement of image properties, e.g., region properties, contours.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/measure/__init__.pyi b/python_embeded/Lib/site-packages/skimage/measure/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fbd0375d8754347bb8b233d44d937079116afb01 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/__init__.pyi @@ -0,0 +1,75 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'find_contours', + 'regionprops', + 'regionprops_table', + 'perimeter', + 'perimeter_crofton', + 'euler_number', + 'approximate_polygon', + 'subdivide_polygon', + 'LineModelND', + 'CircleModel', + 'EllipseModel', + 'ransac', + 'block_reduce', + 'moments', + 'moments_central', + 'moments_coords', + 'moments_coords_central', + 'moments_normalized', + 'moments_hu', + 'inertia_tensor', + 'inertia_tensor_eigvals', + 'marching_cubes', + 'mesh_surface_area', + 'profile_line', + 'label', + 'points_in_poly', + 'grid_points_in_poly', + 'shannon_entropy', + 'blur_effect', + 'pearson_corr_coeff', + 'manders_coloc_coeff', + 'manders_overlap_coeff', + 'intersection_coeff', + 'centroid', +] + +from ._find_contours import find_contours +from ._marching_cubes_lewiner import marching_cubes, mesh_surface_area +from ._regionprops import ( + regionprops, + perimeter, + perimeter_crofton, + euler_number, + regionprops_table, +) +from ._polygon import approximate_polygon, subdivide_polygon +from .pnpoly import points_in_poly, grid_points_in_poly +from ._moments import ( + moments, + moments_central, + moments_coords, + moments_coords_central, + moments_normalized, + centroid, + moments_hu, + inertia_tensor, + inertia_tensor_eigvals, +) +from .profile import profile_line +from .fit import LineModelND, CircleModel, EllipseModel, ransac +from .block import block_reduce +from ._label import label +from .entropy import shannon_entropy +from ._blur_effect import blur_effect +from ._colocalization import ( + pearson_corr_coeff, + manders_coloc_coeff, + manders_overlap_coeff, + intersection_coeff, +) diff --git a/python_embeded/Lib/site-packages/skimage/measure/_blur_effect.py b/python_embeded/Lib/site-packages/skimage/measure/_blur_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b41da3dda2be94d60ef5fb8db96046ba186da5 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_blur_effect.py @@ -0,0 +1,98 @@ +import numpy as np +import scipy.ndimage as ndi + +from ..color import rgb2gray +from ..util import img_as_float + +# TODO: when minimum numpy dependency is 1.25 use: +# np..exceptions.AxisError instead of AxisError +# and remove this try-except +try: + from numpy import AxisError +except ImportError: + from numpy.exceptions import AxisError + + +__all__ = ['blur_effect'] + + +_EPSILON = np.spacing(np.float64(1)) + + +def blur_effect(image, h_size=11, channel_axis=None, reduce_func=np.max): + """Compute a metric that indicates the strength of blur in an image + (0 for no blur, 1 for maximal blur). + + Parameters + ---------- + image : ndarray + RGB or grayscale nD image. The input image is converted to grayscale + before computing the blur metric. + h_size : int, optional + Size of the re-blurring filter. + channel_axis : int or None, optional + If None, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array + corresponds to color channels. + reduce_func : callable, optional + Function used to calculate the aggregation of blur metrics along all + axes. If set to None, the entire list is returned, where the i-th + element is the blur metric along the i-th axis. + + Returns + ------- + blur : float (0 to 1) or list of floats + Blur metric: by default, the maximum of blur metrics along all axes. + + Notes + ----- + `h_size` must keep the same value in order to compare results between + images. Most of the time, the default size (11) is enough. This means that + the metric can clearly discriminate blur up to an average 11x11 filter; if + blur is higher, the metric still gives good results but its values tend + towards an asymptote. + + References + ---------- + .. [1] Frederique Crete, Thierry Dolmiere, Patricia Ladret, and Marina + Nicolas "The blur effect: perception and estimation with a new + no-reference perceptual blur metric" Proc. SPIE 6492, Human Vision and + Electronic Imaging XII, 64920I (2007) + https://hal.archives-ouvertes.fr/hal-00232709 + :DOI:`10.1117/12.702790` + """ + + if channel_axis is not None: + try: + # ensure color channels are in the final dimension + image = np.moveaxis(image, channel_axis, -1) + except AxisError: + print('channel_axis must be one of the image array dimensions') + raise + except TypeError: + print('channel_axis must be an integer') + raise + image = rgb2gray(image) + n_axes = image.ndim + image = img_as_float(image) + shape = image.shape + B = [] + + from ..filters import sobel + + slices = tuple([slice(2, s - 1) for s in shape]) + for ax in range(n_axes): + filt_im = ndi.uniform_filter1d(image, h_size, axis=ax) + im_sharp = np.abs(sobel(image, axis=ax)) + im_blur = np.abs(sobel(filt_im, axis=ax)) + + # avoid numerical instabilities + im_sharp = np.maximum(_EPSILON, im_sharp) + im_blur = np.maximum(_EPSILON, im_blur) + + T = np.maximum(0, im_sharp - im_blur) + M1 = np.sum(im_sharp[slices]) + M2 = np.sum(T[slices]) + B.append(np.abs(M1 - M2) / M1) + + return B if reduce_func is None else reduce_func(B) diff --git a/python_embeded/Lib/site-packages/skimage/measure/_ccomp.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/measure/_ccomp.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..95de249adb9342babb522d1667b8ce1a792f11ff Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/measure/_ccomp.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/measure/_colocalization.py b/python_embeded/Lib/site-packages/skimage/measure/_colocalization.py new file mode 100644 index 0000000000000000000000000000000000000000..30a2ea56708fd7f2540b157eeaadc4a9c08983a8 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_colocalization.py @@ -0,0 +1,304 @@ +import numpy as np +from scipy.stats import pearsonr + +from .._shared.utils import check_shape_equality, as_binary_ndarray + +__all__ = [ + 'pearson_corr_coeff', + 'manders_coloc_coeff', + 'manders_overlap_coeff', + 'intersection_coeff', +] + + +def pearson_corr_coeff(image0, image1, mask=None): + r"""Calculate Pearson's Correlation Coefficient between pixel intensities + in channels. + + Parameters + ---------- + image0 : (M, N) ndarray + Image of channel A. + image1 : (M, N) ndarray + Image of channel 2 to be correlated with channel B. + Must have same dimensions as `image0`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0` and `image1` pixels within this region of interest mask + are included in the calculation. Must have same dimensions as `image0`. + + Returns + ------- + pcc : float + Pearson's correlation coefficient of the pixel intensities between + the two images, within the mask if provided. + p-value : float + Two-tailed p-value. + + Notes + ----- + Pearson's Correlation Coefficient (PCC) measures the linear correlation + between the pixel intensities of the two images. Its value ranges from -1 + for perfect linear anti-correlation to +1 for perfect linear correlation. + The calculation of the p-value assumes that the intensities of pixels in + each input image are normally distributed. + + Scipy's implementation of Pearson's correlation coefficient is used. Please + refer to it for further information and caveats [1]_. + + .. math:: + r = \frac{\sum (A_i - m_A_i) (B_i - m_B_i)} + {\sqrt{\sum (A_i - m_A_i)^2 \sum (B_i - m_B_i)^2}} + + where + :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0` + :math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`, + :math:`m_A_i` is the mean of the pixel values in `image0` + :math:`m_B_i` is the mean of the pixel values in `image1` + + A low PCC value does not necessarily mean that there is no correlation + between the two channel intensities, just that there is no linear + correlation. You may wish to plot the pixel intensities of each of the two + channels in a 2D scatterplot and use Spearman's rank correlation if a + non-linear correlation is visually identified [2]_. Also consider if you + are interested in correlation or co-occurence, in which case a method + involving segmentation masks (e.g. MCC or intersection coefficient) may be + more suitable [3]_ [4]_. + + Providing the mask of only relevant sections of the image (e.g., cells, or + particular cellular compartments) and removing noise is important as the + PCC is sensitive to these measures [3]_ [4]_. + + References + ---------- + .. [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html + .. [2] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html + .. [3] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + .. [4] Bolte, S. and Cordelières, F.P. (2006), A guided tour into + subcellular colocalization analysis in light microscopy. Journal of + Microscopy, 224: 213-232. + https://doi.org/10.1111/j.1365-2818.2006.01706.x + """ + image0 = np.asarray(image0) + image1 = np.asarray(image1) + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1, mask) + image0 = image0[mask] + image1 = image1[mask] + else: + check_shape_equality(image0, image1) + # scipy pearsonr function only takes flattened arrays + image0 = image0.reshape(-1) + image1 = image1.reshape(-1) + + return tuple(float(v) for v in pearsonr(image0, image1)) + + +def manders_coloc_coeff(image0, image1_mask, mask=None): + r"""Manders' colocalization coefficient between two channels. + + Parameters + ---------- + image0 : (M, N) ndarray + Image of channel A. All pixel values should be non-negative. + image1_mask : (M, N) ndarray of dtype bool + Binary mask with segmented regions of interest in channel B. + Must have same dimensions as `image0`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0` pixel values within this region of interest mask are + included in the calculation. + Must have same dimensions as `image0`. + + Returns + ------- + mcc : float + Manders' colocalization coefficient. + + Notes + ----- + Manders' Colocalization Coefficient (MCC) is the fraction of total + intensity of a certain channel (channel A) that is within the segmented + region of a second channel (channel B) [1]_. It ranges from 0 for no + colocalisation to 1 for complete colocalization. It is also referred to + as M1 and M2. + + MCC is commonly used to measure the colocalization of a particular protein + in a subceullar compartment. Typically a segmentation mask for channel B + is generated by setting a threshold that the pixel values must be above + to be included in the MCC calculation. In this implementation, + the channel B mask is provided as the argument `image1_mask`, allowing + the exact segmentation method to be decided by the user beforehand. + + The implemented equation is: + + .. math:: + r = \frac{\sum A_{i,coloc}}{\sum A_i} + + where + :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0` + :math:`A_{i,coloc} = A_i` if :math:`Bmask_i > 0` + :math:`Bmask_i` is the value of the :math:`i^{th}` pixel in + `mask` + + MCC is sensitive to noise, with diffuse signal in the first channel + inflating its value. Images should be processed to remove out of focus and + background light before the MCC is calculated [2]_. + + References + ---------- + .. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of + co-localization of objects in dual-colour confocal images. Journal + of Microscopy, 169: 375-382. + https://doi.org/10.1111/j.1365-2818.1993.tb03313.x + https://imagej.net/media/manders.pdf + .. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + + """ + image0 = np.asarray(image0) + image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask") + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1_mask, mask) + image0 = image0[mask] + image1_mask = image1_mask[mask] + else: + check_shape_equality(image0, image1_mask) + # check non-negative image + if image0.min() < 0: + raise ValueError("image contains negative values") + + sum = np.sum(image0) + if sum == 0: + return 0 + return np.sum(image0 * image1_mask) / sum + + +def manders_overlap_coeff(image0, image1, mask=None): + r"""Manders' overlap coefficient + + Parameters + ---------- + image0 : (M, N) ndarray + Image of channel A. All pixel values should be non-negative. + image1 : (M, N) ndarray + Image of channel B. All pixel values should be non-negative. + Must have same dimensions as `image0` + mask : (M, N) ndarray of dtype bool, optional + Only `image0` and `image1` pixel values within this region of interest + mask are included in the calculation. + Must have ♣same dimensions as `image0`. + + Returns + ------- + moc: float + Manders' Overlap Coefficient of pixel intensities between the two + images. + + Notes + ----- + Manders' Overlap Coefficient (MOC) is given by the equation [1]_: + + .. math:: + r = \frac{\sum A_i B_i}{\sqrt{\sum A_i^2 \sum B_i^2}} + + where + :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0` + :math:`B_i` is the value of the :math:`i^{th}` pixel in `image1` + + It ranges between 0 for no colocalization and 1 for complete colocalization + of all pixels. + + MOC does not take into account pixel intensities, just the fraction of + pixels that have positive values for both channels[2]_ [3]_. Its usefulness + has been criticized as it changes in response to differences in both + co-occurence and correlation and so a particular MOC value could indicate + a wide range of colocalization patterns [4]_ [5]_. + + References + ---------- + .. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of + co-localization of objects in dual-colour confocal images. Journal + of Microscopy, 169: 375-382. + https://doi.org/10.1111/j.1365-2818.1993.tb03313.x + https://imagej.net/media/manders.pdf + .. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + .. [3] Bolte, S. and Cordelières, F.P. (2006), A guided tour into + subcellular colocalization analysis in light microscopy. Journal of + Microscopy, 224: 213-232. + https://doi.org/10.1111/j.1365-2818.2006.01 + .. [4] Adler J, Parmryd I. (2010), Quantifying colocalization by + correlation: the Pearson correlation coefficient is + superior to the Mander's overlap coefficient. Cytometry A. + Aug;77(8):733-42.https://doi.org/10.1002/cyto.a.20896 + .. [5] Adler, J, Parmryd, I. Quantifying colocalization: The case for + discarding the Manders overlap coefficient. Cytometry. 2021; 99: + 910– 920. https://doi.org/10.1002/cyto.a.24336 + + """ + image0 = np.asarray(image0) + image1 = np.asarray(image1) + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1, mask) + image0 = image0[mask] + image1 = image1[mask] + else: + check_shape_equality(image0, image1) + + # check non-negative image + if image0.min() < 0: + raise ValueError("image0 contains negative values") + if image1.min() < 0: + raise ValueError("image1 contains negative values") + + denom = (np.sum(np.square(image0)) * (np.sum(np.square(image1)))) ** 0.5 + return np.sum(np.multiply(image0, image1)) / denom + + +def intersection_coeff(image0_mask, image1_mask, mask=None): + r"""Fraction of a channel's segmented binary mask that overlaps with a + second channel's segmented binary mask. + + Parameters + ---------- + image0_mask : (M, N) ndarray of dtype bool + Image mask of channel A. + image1_mask : (M, N) ndarray of dtype bool + Image mask of channel B. + Must have same dimensions as `image0_mask`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0_mask` and `image1_mask` pixels within this region of + interest + mask are included in the calculation. + Must have same dimensions as `image0_mask`. + + Returns + ------- + Intersection coefficient, float + Fraction of `image0_mask` that overlaps with `image1_mask`. + + """ + image0_mask = as_binary_ndarray(image0_mask, variable_name="image0_mask") + image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask") + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0_mask, image1_mask, mask) + image0_mask = image0_mask[mask] + image1_mask = image1_mask[mask] + else: + check_shape_equality(image0_mask, image1_mask) + + nonzero_image0 = np.count_nonzero(image0_mask) + if nonzero_image0 == 0: + return 0 + nonzero_joint = np.count_nonzero(np.logical_and(image0_mask, image1_mask)) + return nonzero_joint / nonzero_image0 diff --git a/python_embeded/Lib/site-packages/skimage/measure/_find_contours.py b/python_embeded/Lib/site-packages/skimage/measure/_find_contours.py new file mode 100644 index 0000000000000000000000000000000000000000..9e28a017f1220609f71ec9d9cb1c38e6bc582970 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_find_contours.py @@ -0,0 +1,218 @@ +import numpy as np + +from ._find_contours_cy import _get_contour_segments + +from collections import deque + +_param_options = ('high', 'low') + + +def find_contours( + image, level=None, fully_connected='low', positive_orientation='low', *, mask=None +): + """Find iso-valued contours in a 2D array for a given level value. + + Uses the "marching squares" method to compute the iso-valued contours of + the input 2D array for a particular level value. Array values are linearly + interpolated to provide better precision for the output contours. + + Parameters + ---------- + image : (M, N) ndarray of double + Input image in which to find contours. + level : float, optional + Value along which to find contours in the array. By default, the level + is set to (max(image) + min(image)) / 2 + + .. versionchanged:: 0.18 + This parameter is now optional. + fully_connected : str, {'low', 'high'} + Indicates whether array elements below the given level value are to be + considered fully-connected (and hence elements above the value will + only be face connected), or vice-versa. (See notes below for details.) + positive_orientation : str, {'low', 'high'} + Indicates whether the output contours will produce positively-oriented + polygons around islands of low- or high-valued elements. If 'low' then + contours will wind counter-clockwise around elements below the + iso-value. Alternately, this means that low-valued elements are always + on the left of the contour. (See below for details.) + mask : (M, N) ndarray of bool or None + A boolean mask, True where we want to draw contours. + Note that NaN values are always excluded from the considered region + (``mask`` is set to ``False`` wherever ``array`` is ``NaN``). + + Returns + ------- + contours : list of (K, 2) ndarrays + Each contour is a ndarray of ``(row, column)`` coordinates along the contour. + + See Also + -------- + skimage.measure.marching_cubes + + Notes + ----- + The marching squares algorithm is a special case of the marching cubes + algorithm [1]_. A simple explanation is available here: + + https://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html + + There is a single ambiguous case in the marching squares algorithm: when + a given ``2 x 2``-element square has two high-valued and two low-valued + elements, each pair diagonally adjacent. (Where high- and low-valued is + with respect to the contour value sought.) In this case, either the + high-valued elements can be 'connected together' via a thin isthmus that + separates the low-valued elements, or vice-versa. When elements are + connected together across a diagonal, they are considered 'fully + connected' (also known as 'face+vertex-connected' or '8-connected'). Only + high-valued or low-valued elements can be fully-connected, the other set + will be considered as 'face-connected' or '4-connected'. By default, + low-valued elements are considered fully-connected; this can be altered + with the 'fully_connected' parameter. + + Output contours are not guaranteed to be closed: contours which intersect + the array edge or a masked-off region (either where mask is False or where + array is NaN) will be left open. All other contours will be closed. (The + closed-ness of a contours can be tested by checking whether the beginning + point is the same as the end point.) + + Contours are oriented. By default, array values lower than the contour + value are to the left of the contour and values greater than the contour + value are to the right. This means that contours will wind + counter-clockwise (i.e. in 'positive orientation') around islands of + low-valued pixels. This behavior can be altered with the + 'positive_orientation' parameter. + + The order of the contours in the output list is determined by the position + of the smallest ``x,y`` (in lexicographical order) coordinate in the + contour. This is a side effect of how the input array is traversed, but + can be relied upon. + + .. warning:: + + Array coordinates/values are assumed to refer to the *center* of the + array element. Take a simple example input: ``[0, 1]``. The interpolated + position of 0.5 in this array is midway between the 0-element (at + ``x=0``) and the 1-element (at ``x=1``), and thus would fall at + ``x=0.5``. + + This means that to find reasonable contours, it is best to find contours + midway between the expected "light" and "dark" values. In particular, + given a binarized array, *do not* choose to find contours at the low or + high value of the array. This will often yield degenerate contours, + especially around structures that are a single array element wide. Instead, + choose a middle value, as above. + + References + ---------- + .. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High + Resolution 3D Surface Construction Algorithm. Computer Graphics + (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). + :DOI:`10.1145/37401.37422` + + Examples + -------- + >>> a = np.zeros((3, 3)) + >>> a[0, 0] = 1 + >>> a + array([[1., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> find_contours(a, 0.5) + [array([[0. , 0.5], + [0.5, 0. ]])] + """ + if fully_connected not in _param_options: + raise ValueError( + 'Parameters "fully_connected" must be either ' '"high" or "low".' + ) + if positive_orientation not in _param_options: + raise ValueError( + 'Parameters "positive_orientation" must be either ' '"high" or "low".' + ) + if image.shape[0] < 2 or image.shape[1] < 2: + raise ValueError("Input array must be at least 2x2.") + if image.ndim != 2: + raise ValueError('Only 2D arrays are supported.') + if mask is not None: + if mask.shape != image.shape: + raise ValueError('Parameters "array" and "mask"' ' must have same shape.') + if not np.can_cast(mask.dtype, bool, casting='safe'): + raise TypeError('Parameter "mask" must be a binary array.') + mask = mask.astype(np.uint8, copy=False) + if level is None: + level = (np.nanmin(image) + np.nanmax(image)) / 2.0 + + segments = _get_contour_segments( + image.astype(np.float64), float(level), fully_connected == 'high', mask=mask + ) + contours = _assemble_contours(segments) + if positive_orientation == 'high': + contours = [c[::-1] for c in contours] + return contours + + +def _assemble_contours(segments): + current_index = 0 + contours = {} + starts = {} + ends = {} + for from_point, to_point in segments: + # Ignore degenerate segments. + # This happens when (and only when) one vertex of the square is + # exactly the contour level, and the rest are above or below. + # This degenerate vertex will be picked up later by neighboring + # squares. + if from_point == to_point: + continue + + tail, tail_num = starts.pop(to_point, (None, None)) + head, head_num = ends.pop(from_point, (None, None)) + + if tail is not None and head is not None: + # We need to connect these two contours. + if tail is head: + # We need to closed a contour: add the end point + head.append(to_point) + else: # tail is not head + # We need to join two distinct contours. + # We want to keep the first contour segment created, so that + # the final contours are ordered left->right, top->bottom. + if tail_num > head_num: + # tail was created second. Append tail to head. + head.extend(tail) + # Remove tail from the detected contours + contours.pop(tail_num, None) + # Update starts and ends + starts[head[0]] = (head, head_num) + ends[head[-1]] = (head, head_num) + else: # tail_num <= head_num + # head was created second. Prepend head to tail. + tail.extendleft(reversed(head)) + # Remove head from the detected contours + starts.pop(head[0], None) # head[0] can be == to_point! + contours.pop(head_num, None) + # Update starts and ends + starts[tail[0]] = (tail, tail_num) + ends[tail[-1]] = (tail, tail_num) + elif tail is None and head is None: + # We need to add a new contour + new_contour = deque((from_point, to_point)) + contours[current_index] = new_contour + starts[from_point] = (new_contour, current_index) + ends[to_point] = (new_contour, current_index) + current_index += 1 + elif head is None: # tail is not None + # tail first element is to_point: the new segment should be + # prepended. + tail.appendleft(from_point) + # Update starts + starts[from_point] = (tail, tail_num) + else: # tail is None and head is not None: + # head last element is from_point: the new segment should be + # appended + head.append(to_point) + # Update ends + ends[to_point] = (head, head_num) + + return [np.array(contour) for _, contour in sorted(contours.items())] diff --git a/python_embeded/Lib/site-packages/skimage/measure/_find_contours_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/measure/_find_contours_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..9cdcb8fd4f98c88de5a56bb6712f82785e979121 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/measure/_find_contours_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/measure/_label.py b/python_embeded/Lib/site-packages/skimage/measure/_label.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa104128ef859da8a4071c947c3b0967518fc70 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_label.py @@ -0,0 +1,125 @@ +from scipy import ndimage +from ._ccomp import label_cython as clabel + + +def _label_bool(image, background=None, return_num=False, connectivity=None): + """Faster implementation of clabel for boolean input. + + See context: https://github.com/scikit-image/scikit-image/issues/4833 + """ + from ..morphology._util import _resolve_neighborhood + + if background == 1: + image = ~image + + if connectivity is None: + connectivity = image.ndim + + if not 1 <= connectivity <= image.ndim: + raise ValueError( + f'Connectivity for {image.ndim}D image should ' + f'be in [1, ..., {image.ndim}]. Got {connectivity}.' + ) + + footprint = _resolve_neighborhood(None, connectivity, image.ndim) + result = ndimage.label(image, structure=footprint) + + if return_num: + return result + else: + return result[0] + + +def label(label_image, background=None, return_num=False, connectivity=None): + r"""Label connected regions of an integer array. + + Two pixels are connected when they are neighbors and have the same value. + In 2D, they can be neighbors either in a 1- or 2-connected sense. + The value refers to the maximum number of orthogonal hops to consider a + pixel/voxel a neighbor:: + + 1-connectivity 2-connectivity diagonal connection close-up + + [ ] [ ] [ ] [ ] [ ] + | \ | / | <- hop 2 + [ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ] + | / | \ hop 1 + [ ] [ ] [ ] [ ] + + Parameters + ---------- + label_image : ndarray of dtype int + Image to label. + background : int, optional + Consider all pixels with this value as background pixels, and label + them as 0. By default, 0-valued pixels are considered as background + pixels. + return_num : bool, optional + Whether to return the number of assigned labels. + connectivity : int, optional + Maximum number of orthogonal hops to consider a pixel/voxel + as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. + + Returns + ------- + labels : ndarray of dtype int + Labeled array, where all connected regions are assigned the + same integer value. + num : int, optional + Number of labels, which equals the maximum label index and is only + returned if return_num is `True`. + + See Also + -------- + skimage.measure.regionprops + skimage.measure.regionprops_table + + References + ---------- + .. [1] Christophe Fiorio and Jens Gustedt, "Two linear time Union-Find + strategies for image processing", Theoretical Computer Science + 154 (1996), pp. 165-181. + .. [2] Kensheng Wu, Ekow Otoo and Arie Shoshani, "Optimizing connected + component labeling algorithms", Paper LBNL-56864, 2005, + Lawrence Berkeley National Laboratory (University of California), + http://repositories.cdlib.org/lbnl/LBNL-56864 + + Examples + -------- + >>> import numpy as np + >>> x = np.eye(3).astype(int) + >>> print(x) + [[1 0 0] + [0 1 0] + [0 0 1]] + >>> print(label(x, connectivity=1)) + [[1 0 0] + [0 2 0] + [0 0 3]] + >>> print(label(x, connectivity=2)) + [[1 0 0] + [0 1 0] + [0 0 1]] + >>> print(label(x, background=-1)) + [[1 2 2] + [2 1 2] + [2 2 1]] + >>> x = np.array([[1, 0, 0], + ... [1, 1, 5], + ... [0, 0, 0]]) + >>> print(label(x)) + [[1 0 0] + [1 1 2] + [0 0 0]] + """ + if label_image.dtype == bool: + return _label_bool( + label_image, + background=background, + return_num=return_num, + connectivity=connectivity, + ) + else: + return clabel(label_image, background, return_num, connectivity) diff --git a/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner.py b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b86fd942f582559bed50affe4d535e1d85d767 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner.py @@ -0,0 +1,352 @@ +import base64 + +import numpy as np + +from . import _marching_cubes_lewiner_luts as mcluts +from . import _marching_cubes_lewiner_cy + + +def marching_cubes( + volume, + level=None, + *, + spacing=(1.0, 1.0, 1.0), + gradient_direction='descent', + step_size=1, + allow_degenerate=True, + method='lewiner', + mask=None, +): + """Marching cubes algorithm to find surfaces in 3d volumetric data. + + In contrast with Lorensen et al. approach [2]_, Lewiner et + al. algorithm is faster, resolves ambiguities, and guarantees + topologically correct results. Therefore, this algorithm generally + a better choice. + + Parameters + ---------- + volume : (M, N, P) ndarray + Input data volume to find isosurfaces. Will internally be + converted to float32 if necessary. + level : float, optional + Contour value to search for isosurfaces in `volume`. If not + given or None, the average of the min and max of vol is used. + spacing : length-3 tuple of floats, optional + Voxel spacing in spatial dimensions corresponding to numpy array + indexing dimensions (M, N, P) as in `volume`. + gradient_direction : string, optional + Controls if the mesh was generated from an isosurface with gradient + descent toward objects of interest (the default), or the opposite, + considering the *left-hand* rule. + The two options are: + * descent : Object was greater than exterior + * ascent : Exterior was greater than object + step_size : int, optional + Step size in voxels. Default 1. Larger steps yield faster but + coarser results. The result will always be topologically correct + though. + allow_degenerate : bool, optional + Whether to allow degenerate (i.e. zero-area) triangles in the + end-result. Default True. If False, degenerate triangles are + removed, at the cost of making the algorithm slower. + method: {'lewiner', 'lorensen'}, optional + Whether the method of Lewiner et al. or Lorensen et al. will be used. + mask : (M, N, P) array, optional + Boolean array. The marching cube algorithm will be computed only on + True elements. This will save computational time when interfaces + are located within certain region of the volume M, N, P-e.g. the top + half of the cube-and also allow to compute finite surfaces-i.e. open + surfaces that do not end at the border of the cube. + + Returns + ------- + verts : (V, 3) array + Spatial coordinates for V unique mesh vertices. Coordinate order + matches input `volume` (M, N, P). If ``allow_degenerate`` is set to + True, then the presence of degenerate triangles in the mesh can make + this array have duplicate vertices. + faces : (F, 3) array + Define triangular faces via referencing vertex indices from ``verts``. + This algorithm specifically outputs triangles, so each face has + exactly three indices. + normals : (V, 3) array + The normal direction at each vertex, as calculated from the + data. + values : (V,) array + Gives a measure for the maximum value of the data in the local region + near each vertex. This can be used by visualization tools to apply + a colormap to the mesh. + + See Also + -------- + skimage.measure.mesh_surface_area + skimage.measure.find_contours + + Notes + ----- + The algorithm [1]_ is an improved version of Chernyaev's Marching + Cubes 33 algorithm. It is an efficient algorithm that relies on + heavy use of lookup tables to handle the many different cases, + keeping the algorithm relatively easy. This implementation is + written in Cython, ported from Lewiner's C++ implementation. + + To quantify the area of an isosurface generated by this algorithm, pass + verts and faces to `skimage.measure.mesh_surface_area`. + + Regarding visualization of algorithm output, to contour a volume + named `myvolume` about the level 0.0, using the ``mayavi`` package:: + + >>> + >> from mayavi import mlab + >> verts, faces, _, _ = marching_cubes(myvolume, 0.0) + >> mlab.triangular_mesh([vert[0] for vert in verts], + [vert[1] for vert in verts], + [vert[2] for vert in verts], + faces) + >> mlab.show() + + Similarly using the ``visvis`` package:: + + >>> + >> import visvis as vv + >> verts, faces, normals, values = marching_cubes(myvolume, 0.0) + >> vv.mesh(np.fliplr(verts), faces, normals, values) + >> vv.use().Run() + + To reduce the number of triangles in the mesh for better performance, + see this `example + `_ + using the ``mayavi`` package. + + References + ---------- + .. [1] Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan + Tavares. Efficient implementation of Marching Cubes' cases with + topological guarantees. Journal of Graphics Tools 8(2) + pp. 1-15 (december 2003). + :DOI:`10.1080/10867651.2003.10487582` + .. [2] Lorensen, William and Harvey E. Cline. Marching Cubes: A High + Resolution 3D Surface Construction Algorithm. Computer Graphics + (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). + :DOI:`10.1145/37401.37422` + """ + use_classic = False + if method == 'lorensen': + use_classic = True + elif method != 'lewiner': + raise ValueError("method should be either 'lewiner' or 'lorensen'") + return _marching_cubes_lewiner( + volume, + level, + spacing, + gradient_direction, + step_size, + allow_degenerate, + use_classic=use_classic, + mask=mask, + ) + + +def _marching_cubes_lewiner( + volume, + level, + spacing, + gradient_direction, + step_size, + allow_degenerate, + use_classic, + mask, +): + """Lewiner et al. algorithm for marching cubes. See + marching_cubes_lewiner for documentation. + + """ + + # Check volume and ensure its in the format that the alg needs + if not isinstance(volume, np.ndarray) or (volume.ndim != 3): + raise ValueError('Input volume should be a 3D numpy array.') + if volume.shape[0] < 2 or volume.shape[1] < 2 or volume.shape[2] < 2: + raise ValueError("Input array must be at least 2x2x2.") + volume = np.ascontiguousarray(volume, np.float32) # no copy if not necessary + + # Check/convert other inputs: + # level + if level is None: + level = 0.5 * (volume.min() + volume.max()) + else: + level = float(level) + if level < volume.min() or level > volume.max(): + raise ValueError("Surface level must be within volume data range.") + # spacing + if len(spacing) != 3: + raise ValueError("`spacing` must consist of three floats.") + # step_size + step_size = int(step_size) + if step_size < 1: + raise ValueError('step_size must be at least one.') + # use_classic + use_classic = bool(use_classic) + + # Get LutProvider class (reuse if possible) + L = _get_mc_luts() + + # Check if a mask array is passed + if mask is not None: + if not mask.shape == volume.shape: + raise ValueError('volume and mask must have the same shape.') + + # Apply algorithm + func = _marching_cubes_lewiner_cy.marching_cubes + vertices, faces, normals, values = func( + volume, level, L, step_size, use_classic, mask + ) + + if not len(vertices): + raise RuntimeError('No surface found at the given iso value.') + + # Output in z-y-x order, as is common in skimage + vertices = np.fliplr(vertices) + normals = np.fliplr(normals) + + # Finishing touches to output + faces.shape = -1, 3 + if gradient_direction == 'descent': + # MC implementation is right-handed, but gradient_direction is + # left-handed + faces = np.fliplr(faces) + elif not gradient_direction == 'ascent': + raise ValueError( + f"Incorrect input {gradient_direction} in `gradient_direction`, " + "see docstring." + ) + if not np.array_equal(spacing, (1, 1, 1)): + vertices = vertices * np.r_[spacing] + + if allow_degenerate: + return vertices, faces, normals, values + else: + fun = _marching_cubes_lewiner_cy.remove_degenerate_faces + return fun(vertices.astype(np.float32), faces, normals, values) + + +def _to_array(args): + shape, text = args + byts = base64.decodebytes(text.encode('utf-8')) + ar = np.frombuffer(byts, dtype='int8') + ar.shape = shape + return ar + + +# Map an edge-index to two relative pixel positions. The edge index +# represents a point that lies somewhere in between these pixels. +# Linear interpolation should be used to determine where it is exactly. +# 0 +# 3 1 -> 0x +# 2 xx + +# fmt: off +EDGETORELATIVEPOSX = np.array([ [0,1],[1,1],[1,0],[0,0], [0,1],[1,1],[1,0],[0,0], [0,0],[1,1],[1,1],[0,0] ], 'int8') +EDGETORELATIVEPOSY = np.array([ [0,0],[0,1],[1,1],[1,0], [0,0],[0,1],[1,1],[1,0], [0,0],[0,0],[1,1],[1,1] ], 'int8') +EDGETORELATIVEPOSZ = np.array([ [0,0],[0,0],[0,0],[0,0], [1,1],[1,1],[1,1],[1,1], [0,1],[0,1],[0,1],[0,1] ], 'int8') +# fmt: on + + +def _get_mc_luts(): + """Kind of lazy obtaining of the luts.""" + if not hasattr(mcluts, 'THE_LUTS'): + mcluts.THE_LUTS = _marching_cubes_lewiner_cy.LutProvider( + EDGETORELATIVEPOSX, + EDGETORELATIVEPOSY, + EDGETORELATIVEPOSZ, + _to_array(mcluts.CASESCLASSIC), + _to_array(mcluts.CASES), + _to_array(mcluts.TILING1), + _to_array(mcluts.TILING2), + _to_array(mcluts.TILING3_1), + _to_array(mcluts.TILING3_2), + _to_array(mcluts.TILING4_1), + _to_array(mcluts.TILING4_2), + _to_array(mcluts.TILING5), + _to_array(mcluts.TILING6_1_1), + _to_array(mcluts.TILING6_1_2), + _to_array(mcluts.TILING6_2), + _to_array(mcluts.TILING7_1), + _to_array(mcluts.TILING7_2), + _to_array(mcluts.TILING7_3), + _to_array(mcluts.TILING7_4_1), + _to_array(mcluts.TILING7_4_2), + _to_array(mcluts.TILING8), + _to_array(mcluts.TILING9), + _to_array(mcluts.TILING10_1_1), + _to_array(mcluts.TILING10_1_1_), + _to_array(mcluts.TILING10_1_2), + _to_array(mcluts.TILING10_2), + _to_array(mcluts.TILING10_2_), + _to_array(mcluts.TILING11), + _to_array(mcluts.TILING12_1_1), + _to_array(mcluts.TILING12_1_1_), + _to_array(mcluts.TILING12_1_2), + _to_array(mcluts.TILING12_2), + _to_array(mcluts.TILING12_2_), + _to_array(mcluts.TILING13_1), + _to_array(mcluts.TILING13_1_), + _to_array(mcluts.TILING13_2), + _to_array(mcluts.TILING13_2_), + _to_array(mcluts.TILING13_3), + _to_array(mcluts.TILING13_3_), + _to_array(mcluts.TILING13_4), + _to_array(mcluts.TILING13_5_1), + _to_array(mcluts.TILING13_5_2), + _to_array(mcluts.TILING14), + _to_array(mcluts.TEST3), + _to_array(mcluts.TEST4), + _to_array(mcluts.TEST6), + _to_array(mcluts.TEST7), + _to_array(mcluts.TEST10), + _to_array(mcluts.TEST12), + _to_array(mcluts.TEST13), + _to_array(mcluts.SUBCONFIG13), + ) + + return mcluts.THE_LUTS + + +def mesh_surface_area(verts, faces): + """Compute surface area, given vertices and triangular faces. + + Parameters + ---------- + verts : (V, 3) array of floats + Array containing coordinates for V unique mesh vertices. + faces : (F, 3) array of ints + List of length-3 lists of integers, referencing vertex coordinates as + provided in `verts`. + + Returns + ------- + area : float + Surface area of mesh. Units now [coordinate units] ** 2. + + Notes + ----- + The arguments expected by this function are the first two outputs from + `skimage.measure.marching_cubes`. For unit correct output, ensure correct + `spacing` was passed to `skimage.measure.marching_cubes`. + + This algorithm works properly only if the ``faces`` provided are all + triangles. + + See Also + -------- + skimage.measure.marching_cubes + + """ + # Fancy indexing to define two vector arrays from triangle vertices + actual_verts = verts[faces] + a = actual_verts[:, 0, :] - actual_verts[:, 1, :] + b = actual_verts[:, 0, :] - actual_verts[:, 2, :] + del actual_verts + + # Area of triangle in 3D = 1/2 * Euclidean norm of cross product + return ((np.cross(a, b) ** 2).sum(axis=1) ** 0.5).sum() / 2.0 diff --git a/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..5874c83297328e4cc5dcbc37c147ea1c16b6383b Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_luts.py b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_luts.py new file mode 100644 index 0000000000000000000000000000000000000000..4583783f271694a31b25fef51c590640219286b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_marching_cubes_lewiner_luts.py @@ -0,0 +1,672 @@ +# This file was auto-generated from `mc_meta/LookUpTable.h` by +# `mc_meta/createluts.py`. The `mc_meta` scripts are not +# distributed with scikit-image, but are available in the +# repository under tools/precompute/mc_meta. + +# static const char casesClassic[256][16] +CASESCLASSIC = ( + (256, 16), + """ +/////////////////////wAIA/////////////////8AAQn/////////////////AQgDCQgB//// +/////////wECCv////////////////8ACAMBAgr/////////////CQIKAAIJ/////////////wII +AwIKCAoJCP////////8DCwL/////////////////AAsCCAsA/////////////wEJAAIDC/////// +//////8BCwIBCQsJCAv/////////AwoBCwoD/////////////wAKAQAICggLCv////////8DCQAD +CwkLCgn/////////CQgKCggL/////////////wQHCP////////////////8EAwAHAwT///////// +////AAEJCAQH/////////////wQBCQQHAQcDAf////////8BAgoIBAf/////////////AwQHAwAE +AQIK/////////wkCCgkAAggEB/////////8CCgkCCQcCBwMHCQT/////CAQHAwsC//////////// +/wsEBwsCBAIABP////////8JAAEIBAcCAwv/////////BAcLCQQLCQsCCQIB/////wMKAQMLCgcI +BP////////8BCwoBBAsBAAQHCwT/////BAcICQALCQsKCwAD/////wQHCwQLCQkLCv////////8J +BQT/////////////////CQUEAAgD/////////////wAFBAEFAP////////////8IBQQIAwUDAQX/ +////////AQIKCQUE/////////////wMACAECCgQJBf////////8FAgoFBAIEAAL/////////AgoF +AwIFAwUEAwQI/////wkFBAIDC/////////////8ACwIACAsECQX/////////AAUEAAEFAgML//// +/////wIBBQIFCAIICwQIBf////8KAwsKAQMJBQT/////////BAkFAAgBCAoBCAsK/////wUEAAUA +CwULCgsAA/////8FBAgFCAoKCAv/////////CQcIBQcJ/////////////wkDAAkFAwUHA/////// +//8ABwgAAQcBBQf/////////AQUDAwUH/////////////wkHCAkFBwoBAv////////8KAQIJBQAF +AwAFBwP/////CAACCAIFCAUHCgUC/////wIKBQIFAwMFB/////////8HCQUHCAkDCwL///////// +CQUHCQcCCQIAAgcL/////wIDCwABCAEHCAEFB/////8LAgELAQcHAQX/////////CQUICAUHCgED +CgML/////wUHAAUACQcLAAEACgsKAP8LCgALAAMKBQAIAAcFBwD/CwoFBwsF/////////////woG +Bf////////////////8ACAMFCgb/////////////CQABBQoG/////////////wEIAwEJCAUKBv// +//////8BBgUCBgH/////////////AQYFAQIGAwAI/////////wkGBQkABgACBv////////8FCQgF +CAIFAgYDAgj/////AgMLCgYF/////////////wsACAsCAAoGBf////////8AAQkCAwsFCgb///// +////BQoGAQkCCQsCCQgL/////wYDCwYFAwUBA/////////8ACAsACwUABQEFCwb/////AwsGAAMG +AAYFAAUJ/////wYFCQYJCwsJCP////////8FCgYEBwj/////////////BAMABAcDBgUK//////// +/wEJAAUKBggEB/////////8KBgUBCQcBBwMHCQT/////BgECBgUBBAcI/////////wECBQUCBgMA +BAMEB/////8IBAcJAAUABgUAAgb/////BwMJBwkEAwIJBQkGAgYJ/wMLAgcIBAoGBf////////8F +CgYEBwIEAgACBwv/////AAEJBAcIAgMLBQoG/////wkCAQkLAgkECwcLBAUKBv8IBAcDCwUDBQEF +Cwb/////BQELBQsGAQALBwsEAAQL/wAFCQAGBQADBgsGAwgEB/8GBQkGCQsEBwkHCwn/////CgQJ +BgQK/////////////wQKBgQJCgAIA/////////8KAAEKBgAGBAD/////////CAMBCAEGCAYEBgEK +/////wEECQECBAIGBP////////8DAAgBAgkCBAkCBgT/////AAIEBAIG/////////////wgDAggC +BAQCBv////////8KBAkKBgQLAgP/////////AAgCAggLBAkKBAoG/////wMLAgABBgAGBAYBCv// +//8GBAEGAQoECAECAQsICwH/CQYECQMGCQEDCwYD/////wgLAQgBAAsGAQkBBAYEAf8DCwYDBgAA +BgT/////////BgQICwYI/////////////wcKBgcICggJCv////////8ABwMACgcACQoGBwr///// +CgYHAQoHAQcIAQgA/////woGBwoHAQEHA/////////8BAgYBBggBCAkIBgf/////AgYJAgkBBgcJ +AAkDBwMJ/wcIAAcABgYAAv////////8HAwIGBwL/////////////AgMLCgYICggJCAYH/////wIA +BwIHCwAJBwYHCgkKB/8BCAABBwgBCgcGBwoCAwv/CwIBCwEHCgYBBgcB/////wgJBggGBwkBBgsG +AwEDBv8ACQELBgf/////////////BwgABwAGAwsACwYA/////wcLBv////////////////8HBgv/ +////////////////AwAICwcG/////////////wABCQsHBv////////////8IAQkIAwELBwb///// +////CgECBgsH/////////////wECCgMACAYLB/////////8CCQACCgkGCwf/////////BgsHAgoD +CggDCgkI/////wcCAwYCB/////////////8HAAgHBgAGAgD/////////AgcGAgMHAAEJ//////// +/wEGAgEIBgEJCAgHBv////8KBwYKAQcBAwf/////////CgcGAQcKAQgHAQAI/////wADBwAHCgAK +CQYKB/////8HBgoHCggICgn/////////BggECwgG/////////////wMGCwMABgAEBv////////8I +BgsIBAYJAAH/////////CQQGCQYDCQMBCwMG/////wYIBAYLCAIKAf////////8BAgoDAAsABgsA +BAb/////BAsIBAYLAAIJAgoJ/////woJAwoDAgkEAwsDBgQGA/8IAgMIBAIEBgL/////////AAQC +BAYC/////////////wEJAAIDBAIEBgQDCP////8BCQQBBAICBAb/////////CAEDCAYBCAQGBgoB +/////woBAAoABgYABP////////8EBgMEAwgGCgMAAwkKCQP/CgkEBgoE/////////////wQJBQcG +C/////////////8ACAMECQULBwb/////////BQABBQQABwYL/////////wsHBggDBAMFBAMBBf// +//8JBQQKAQIHBgv/////////BgsHAQIKAAgDBAkF/////wcGCwUECgQCCgQAAv////8DBAgDBQQD +AgUKBQILBwb/BwIDBwYCBQQJ/////////wkFBAAIBgAGAgYIB/////8DBgIDBwYBBQAFBAD///// +BgIIBggHAgEIBAgFAQUI/wkFBAoBBgEHBgEDB/////8BBgoBBwYBAAcIBwAJBQT/BAAKBAoFAAMK +BgoHAwcK/wcGCgcKCAUECgQICv////8GCQUGCwkLCAn/////////AwYLAAYDAAUGAAkF/////wAL +CAAFCwABBQUGC/////8GCwMGAwUFAwH/////////AQIKCQULCQsICwUG/////wALAwAGCwAJBgUG +CQECCv8LCAULBQYIAAUKBQIAAgX/BgsDBgMFAgoDCgUD/////wUICQUCCAUGAgMIAv////8JBQYJ +BgAABgL/////////AQUIAQgABQYIAwgCBgII/wEFBgIBBv////////////8BAwYBBgoDCAYFBgkI +CQb/CgEACgAGCQUABQYA/////wADCAUGCv////////////8KBQb/////////////////CwUKBwUL +/////////////wsFCgsHBQgDAP////////8FCwcFCgsBCQD/////////CgcFCgsHCQgBCAMB//// +/wsBAgsHAQcFAf////////8ACAMBAgcBBwUHAgv/////CQcFCQIHCQACAgsH/////wcFAgcCCwUJ +AgMCCAkIAv8CBQoCAwUDBwX/////////CAIACAUCCAcFCgIF/////wkAAQUKAwUDBwMKAv////8J +CAIJAgEIBwIKAgUHBQL/AQMFAwcF/////////////wAIBwAHAQEHBf////////8JAAMJAwUFAwf/ +////////CQgHBQkH/////////////wUIBAUKCAoLCP////////8FAAQFCwAFCgsLAwD/////AAEJ +CAQKCAoLCgQF/////woLBAoEBQsDBAkEAQMBBP8CBQECCAUCCwgEBQj/////AAQLAAsDBAULAgsB +BQEL/wACBQAFCQILBQQFCAsIBf8JBAUCCwP/////////////AgUKAwUCAwQFAwgE/////wUKAgUC +BAQCAP////////8DCgIDBQoDCAUEBQgAAQn/BQoCBQIEAQkCCQQC/////wgEBQgFAwMFAf////// +//8ABAUBAAX/////////////CAQFCAUDCQAFAAMF/////wkEBf////////////////8ECwcECQsJ +Cgv/////////AAgDBAkHCQsHCQoL/////wEKCwELBAEEAAcEC/////8DAQQDBAgBCgQHBAsKCwT/ +BAsHCQsECQILCQEC/////wkHBAkLBwkBCwILAQAIA/8LBwQLBAICBAD/////////CwcECwQCCAME +AwIE/////wIJCgIHCQIDBwcECf////8JCgcJBwQKAgcIBwACAAf/AwcKAwoCBwQKAQoABAAK/wEK +AggHBP////////////8ECQEEAQcHAQP/////////BAkBBAEHAAgBCAcB/////wQAAwcEA/////// +//////8ECAf/////////////////CQoICgsI/////////////wMACQMJCwsJCv////////8AAQoA +CggICgv/////////AwEKCwMK/////////////wECCwELCQkLCP////////8DAAkDCQsBAgkCCwn/ +////AAILCAAL/////////////wMCC/////////////////8CAwgCCAoKCAn/////////CQoCAAkC +/////////////wIDCAIICgABCAEKCP////8BCgL/////////////////AQMICQEI//////////// +/wAJAf////////////////8AAwj//////////////////////////////////////w== +""", +) + +# static const char cases[256][2] +CASES = ( + (256, 2), + """ +AP8BAAEBAgABAgMAAgMFAAEDAgEDAwUBAgUFBAUJCAABBAICAwQFAgQCBgIGCQsAAwgFBQcDCQEG +EA4DDAwFGAEFAwECBAUDAwYHAAUKCQAEAwYEBgsOAQYRDAQLBgUZAggFBwUMCAEGEgwFDgcFHAYV +CwQMDwUeCgUGIAYnAgwBBgQAAwUGAAIGBgMFCw4AAwkGBQcEDAEFDgsDCQQFGgMKBgYHBQwCBhMK +AQwNBhgHBwwJDQEHCQwUBiEHDQMMAgoGBwUNCwIFEAwHCAMFHQYWCgIMEQYbDgkGIgUnAg4FFA4F +CQUFIAsKBiMFKQIQDBcGJQcOAxAGLgQGAxUBCAEHAwIEAQYBAwcHAQYKDAACBwUGBgwLAQUPCQIO +BgUbAgkFCAYNDgIGFAwGCgMGGQUSCAIMEAUfCwkFIgYoAg0DCwcCBg4MAwcGDQAMDgcIBhcMCgoE +BhwMFQcKBikDDQUVCQMLCAUhDBYHCwYqAw4OCwUkBiwCEQYvAxIEBwEJAgsGCAYPCgAFEQwICwcG +GgUTDgQMEgYdCAQFIwUoAg8FFgsFDBMGHg4KBiQGKwQECQcFJQcPAxEFLAITAxYBCgUXDAsOCAYf +CQYHDAUqAw8LCwYmBi0EBQUtAxMCFQELCAUFJgUrAhIFLgMUAhYBDAUvAhQDFwENAhcBDgEPAP8= +""", +) + +# static const char tiling1[16][3] +TILING1 = ( + (16, 3), + """ +AAgDAAEJAQIKAwsCBAcICQUECgYFBwYLBwsGCgUGCQQFBAgHAwILAQoCAAkBAAMI +""", +) + +# static const char tiling2[24][6] +TILING2 = ( + (24, 6), + """ +AQgDCQgBAAsCCAsABAMABwMECQIKAAIJAAUEAQUAAwoBCwoDAQYFAgYBBwIDBgIHCQcIBQcJBggE +CwgGCgQJBgQKCwUKBwULCwoFBwsFCgkEBgoEBgQICwYICQgHBQkHBwMCBgcCAQUGAgEGAwEKCwMK +AAQFAQAFCQoCAAkCBAADBwQDAAILCAALAQMICQEI +""", +) + +# static const char tiling3_1[24][6] +TILING3_1 = ( + (24, 6), + """ +AAgDAQIKCQUEAAgDAwAICwcGAQkAAgMLAAEJCAQHCQABBQoGAQIKCQUECgECBgsHCAQHAwsCAgML +CgYFBQoGBAcIBAkFBwYLBQkECwYHBgoFCAcECwMCBQYKBwQIAgsDAgEKBwsGCgIBBAUJAQAJBgoF +CQEABwQIAAkBCwMCCAADBgcLBAUJAwgAAwgACgIB +""", +) + +# static const char tiling3_2[24][12] +TILING3_2 = ( + (24, 12), + """ +CgMCCggDCgEACAoAAwQIAwUEAwAJBQMJBggHBgAIBgsDAAYDCwADCwkACwIBCQsBBwkEBwEJBwgA +AQcABgEKBgABCQAGCQYFBAoFBAIKBAkBAgQBBwILBwECBwYKAQcKAgcLAgQHAgMIBAIIBQsGBQML +BQoCAwUCCAYHCAoGCAQFCggFCwUGCwkFCwcECQsEBgULBQkLBAcLBAsJBwYIBgoIBQQIBQgKBgsF +CwMFAgoFAgUDCwcCBwQCCAMCCAIECwIHAgEHCgYHCgcBBQoECgIEAQkEAQQCCgEGAQAGBgAJBQYJ +BAkHCQEHAAgHAAcBAwALAAkLAQILAQsJBwgGCAAGAwsGAwYACAQDBAUDCQADCQMFAgMKAwgKAAEK +AAoI +""", +) + +# static const char tiling4_1[8][6] +TILING4_1 = ( + (8, 6), + """ +AAgDBQoGAAEJCwcGAQIKCAQHCQUEAgMLBAUJCwMCCgIBBwQICQEABgcLAwgABgoF +""", +) + +# static const char tiling4_2[8][18] +TILING4_2 = ( + (8, 18), + """ +CAUABQgGAwYIBgMKAAoDCgAFCQYBBgkHAAcJBwALAQsACwEGCgcCBwoEAQQKBAEIAggBCAIHCwQD +BAsFAgULBQIJAwkCCQMEAwQLBQsECwUCCQIFAgkDBAMJAgcKBAoHCgQBCAEEAQgCBwIIAQYJBwkG +CQcACwAHAAsBBgELAAUIBggFCAYDCgMGAwoABQAK +""", +) + +# static const char tiling5[48][9] +TILING5 = ( + (48, 9), + """ +AggDAgoICgkIAQsCAQkLCQgLBAEJBAcBBwMBCAUECAMFAwEFAAoBAAgKCAsKCwQHCwIEAgAEBwAI +BwYABgIACQMACQUDBQcDAwYLAwAGAAQGAwkAAwsJCwoJBQIKBQQCBAACCQYFCQAGAAIGAAcIAAEH +AQUHCgABCgYABgQABgMLBgUDBQEDCgcGCgEHAQMHAQQJAQIEAgYECwECCwcBBwUBCAIDCAQCBAYC +AgUKAgMFAwcFBwoGBwgKCAkKBgkFBgsJCwgJBQgEBQoICgsIBAsHBAkLCQoLBAcLBAsJCQsKBQQI +BQgKCggLBgUJBgkLCwkIBwYKBwoICAoJAgoFAgUDAwUHCAMCCAIEBAIGCwIBCwEHBwEFAQkEAQQC +AgQGCgYHCgcBAQcDBgsDBgMFBQMBCgEACgAGBgAEAAgHAAcBAQcFCQUGCQYAAAYCBQoCBQIEBAIA +AwAJAwkLCwkKAwsGAwYAAAYECQADCQMFBQMHBwgABwAGBgACCwcECwQCAgQAAAEKAAoICAoLCAQF +CAUDAwUBBAkBBAEHBwEDAQILAQsJCQsIAgMIAggKCggJ +""", +) + +# static const char tiling6_1_1[48][9] +TILING6_1_1 = ( + (48, 9), + """ +BgUKAwEICQgBCwcGCQMBAwkIAQIKBwAEAAcDAwAIBQIGAgUBBQQJAgALCAsACgYFCAIAAggLCgYF +AAQDBwMEAwAIBgQKCQoECAMACgcFBwoLCAQHCgACAAoJBwYLAAIJCgkCAgMLBAEFAQQAAAEJBgMH +AwYCCQABCwQGBAsICwcGAQUABAAFAAEJBwULCgsFBAcIAQMKCwoDCQUECwEDAQsKCgECCAUHBQgJ +CAQHAgYBBQEGAQIKBAYICwgGAgMLBQcJCAkHCwIDCQYEBgkKCQUEAwcCBgIHBAUJAgcDBwIGAwIL +BAYJCgkGCwMCCQcFBwkICgIBCAYEBggLBwQIAQYCBgEFAgEKBwUICQgFBAUJAwELCgsBCAcECgMB +AwoLCQEACwUHBQsKBgcLAAUBBQAEAQAJBgQLCAsECQEABwMGAgYDCwMCBQEEAAQBCwYHCQIAAgkK +BwQIAgAKCQoAAAMIBQcKCwoHCAADCgQGBAoJBQYKAwQABAMHBQYKAAIICwgCCQQFCwACAAsICAAD +BgIFAQUCCgIBBAAHAwcABgcLAQMJCAkDCgUGCAEDAQgJ +""", +) + +# static const char tiling6_1_2[48][27] +TILING6_1_2 = ( + (48, 27), + """ +AQwDDAoDBgMKAwYIBQgGCAUMDAkIAQkMDAUKAQwDAQsMCwEGCQYBBgkHDAcJCQgMDAgDCwcMBAwA +BAEMAQQKBwoECgcCDAIHBwMMDAMAAQIMBgwCBgMMAwYIBQgGCAUADAAFBQEMDAECAwAMAAwCDAkC +BQIJAgULBAsFCwQMDAgLAAgMDAQJAAwCAAoMCgAFCAUABQgGDAYICAsMDAsCCgYMBAwADAUACgAF +AAoDBgMKAwYMDAcDBAcMDAYFBAwGDAgGAwYIBgMKAAoDCgAMDAkKBAkMDAAIBQwHBQgMCAUACgAF +AAoDDAMKCgsMDAsHCAMMAgwAAggMCAIHCgcCBwoEDAQKCgkMDAkACAQMAgwADAsABwALAAcJBgkH +CQYMDAoJAgoMDAYLBQwBBQIMAgULBAsFCwQDDAMEBAAMDAABAgMMBwwDBwAMAAcJBgkHCQYBDAEG +BgIMDAIDAAEMBgwEBgkMCQYBCwEGAQsADAALCwgMDAgECQAMBQwBDAYBCwEGAQsABwALAAcMDAQA +BQQMDAcGBQwHDAkHAAcJBwALAQsACwEMDAoLBQoMDAEJAwwBDAgBBAEIAQQKBwoECgcMDAsKAwsM +DAcIAwwBAwkMCQMECwQDBAsFDAULCwoMDAoBCQUMBwwFBwoMCgcCCAIHAggBDAEICAkMDAkFCgEM +BgwCDAcCCAIHAggBBAEIAQQMDAUBBgUMDAQHBgwEDAoEAQQKBAEIAggBCAIMDAsIBgsMDAIKBwwF +DAsFAgULBQIJAwkCCQMMDAgJBwgMDAMLBAwGBAsMCwQDCQMEAwkCDAIJCQoMDAoGCwIMBwwDDAQD +CQMEAwkCBQIJAgUMDAYCBwYMDAUEAwwHAwQMBAMJAgkDCQIFDAUCAgYMDAYHBAUMBgwEDAsEAwQL +BAMJAgkDCQIMDAoJBgoMDAILBQwHBQsMCwUCCQIFAgkDDAMJCQgMDAgHCwMMBAwGBAoMCgQBCAEE +AQgCDAIICAsMDAsGCgIMAgwGAgcMBwIIAQgCCAEEDAQBAQUMDAUGBwQMBQwHDAoHAgcKBwIIAQgC +CAEMDAkIBQkMDAEKAQwDDAkDBAMJAwQLBQsECwUMDAoLAQoMDAUJAQwDAQgMCAEECgQBBAoHDAcK +CgsMDAsDCAcMBwwFBwkMCQcACwAHAAsBDAELCwoMDAoFCQEMAQwFAQYMBgELAAsBCwAHDAcAAAQM +DAQFBgcMBAwGDAkGAQYJBgELAAsBCwAMDAgLBAgMDAAJAwwHDAAHCQcABwkGAQYJBgEMDAIGAwIM +DAEAAQwFDAIFCwUCBQsEAwQLBAMMDAAEAQAMDAMCAAwCAAsMCwAHCQcABwkGDAYJCQoMDAoCCwYM +AAwCDAgCBwIIAgcKBAoHCgQMDAkKAAkMDAQIBwwFDAgFAAUIBQAKAwoACgMMDAsKBwsMDAMIBgwE +BggMCAYDCgMGAwoADAAKCgkMDAkECAAMAAwEAAUMBQAKAwoACgMGDAYDAwcMDAcEBQYMAgwADAoA +BQAKAAUIBggFCAYMDAsIAgsMDAYKAgwAAgkMCQIFCwUCBQsEDAQLCwgMDAgACQQMAgwGDAMGCAYD +BggFAAUIBQAMDAEFAgEMDAADAAwEDAEECgQBBAoHAgcKBwIMDAMHAAMMDAIBAwwBDAsBBgELAQYJ +BwkGCQcMDAgJAwgMDAcLAwwBAwoMCgMGCAYDBggFDAUICAkMDAkBCgUM +""", +) + +# static const char tiling6_2[48][15] +TILING6_2 = ( + (48, 15), + """ +AQoDBgMKAwYIBQgGCAUJAQsDCwEGCQYBBgkHCAcJBAEAAQQKBwoECgcCAwIHBgMCAwYIBQgGCAUA +AQAFAAkCBQIJAgULBAsFCwQIAAoCCgAFCAUABQgGCwYIBAUACgAFAAoDBgMKAwYHBAgGAwYIBgMK +AAoDCgAJBQgHCAUACgAFAAoDCwMKAggACAIHCgcCBwoECQQKAgsABwALAAcJBgkHCQYKBQIBAgUL +BAsFCwQDAAMEBwADAAcJBgkHCQYBAgEGBgkECQYBCwEGAQsACAALBQYBCwEGAQsABwALAAcEBQkH +AAcJBwALAQsACwEKAwgBBAEIAQQKBwoECgcLAwkBCQMECwQDBAsFCgULBwoFCgcCCAIHAggBCQEI +BgcCCAIHAggBBAEIAQQFBgoEAQQKBAEIAggBCAILBwsFAgULBQIJAwkCCQMIBAsGCwQDCQMEAwkC +CgIJBwQDCQMEAwkCBQIJAgUGAwQHBAMJAgkDCQIFBgUCBgsEAwQLBAMJAgkDCQIKBQsHCwUCCQIF +AgkDCAMJBAoGCgQBCAEEAQgCCwIIAgcGBwIIAQgCCAEEBQQBBQoHAgcKBwIIAQgCCAEJAQkDBAMJ +AwQLBQsECwUKAQgDCAEECgQBBAoHCwcKBwkFCQcACwAHAAsBCgELAQYFBgELAAsBCwAHBAcABAkG +AQYJBgELAAsBCwAIAwAHCQcABwkGAQYJBgECAQIFCwUCBQsEAwQLBAMAAAsCCwAHCQcABwkGCgYJ +AAgCBwIIAgcKBAoHCgQJBwgFAAUIBQAKAwoACgMLBggECAYDCgMGAwoACQAKAAUEBQAKAwoACgMG +BwYDAgoABQAKAAUIBggFCAYLAgkACQIFCwUCBQsECAQLAgMGCAYDBggFAAUIBQABAAEECgQBBAoH +AgcKBwIDAwsBBgELAQYJBwkGCQcIAwoBCgMGCAYDBggFCQUI +""", +) + +# static const char tiling7_1[16][9] +TILING7_1 = ( + (16, 9), + """ +CQUECgECCAMACwcGCAMACgECAwAIBQQJBwYLCAQHCQABCwIDCgYFCwIDCQABAAEJBgUKBAcIAQIK +BwYLBQQJAgMLBAcIBgUKCwMCCAcECgUGCgIBCwYHCQQFCQEACgUGCAcEBQYKAwILAQAJBwQIAQAJ +AwILCAADCQQFCwYHBgcLAAMIAgEKBAUJAgEKAAMI +""", +) + +# static const char tiling7_2[16][3][15] +TILING7_2 = ( + (16, 3, 15), + """ +AQIKAwQIBAMFAAUDBQAJAwAICQEEAgQBBAIFCgUCCQUEAAoBCgAICggCAwIIAwAIAQYKBgEHAgcB +BwILAQIKCwMGAAYDBgAHCAcACwcGAggDCAIKCAoAAQAKCQUECwMGAAYDBgAHCAcACwcGAwQIBAMF +AAUDBQAJAwAIBAkHCwcJBQsJCwUGAAEJAgcLBwIEAwQCBAMIAgMLCAAHAQcABwEECQQBCAQHAwkA +CQMLCQsBAgELAgMLAAUJBQAGAQYABgEKAAEJCgIFAwUCBQMGCwYDBgUKAQsCCwEJCwkDAAMJBgUK +CAAHAQcABwEECQQBCAQHAAUJBQAGAQYABgEKAAEJBQoECAQKBggKCAYHCwcGCQEEAgQBBAIFCgUC +CQUEAQYKBgEHAgcBBwILAQIKBgsFCQULBwkLCQcECAQHCgIFAwUCBQMGCwYDBgUKAgcLBwIEAwQC +BAMIAgMLBwgGCgYIBAoICgQFBwQIBQIKAgUDBgMFAwYLCgUGCwcCBAIHAgQDCAMECwMCBggHCAYK +CAoEBQQKBgcLBAEJAQQCBQIEAgUKBAUJCgYBBwEGAQcCCwIHCgIBBQsGCwUJCwkHBAcJCgUGBwAI +AAcBBAEHAQQJBwQICQUABgAFAAYBCgEGCQEABAoFCgQICggGBwYICwMCCQUABgAFAAYBCgEGCQEA +BQIKAgUDBgMFAwYLCgUGAgsBCQELAwkLCQMACQEACwcCBAIHAgQDCAMECwMCBwAIAAcBBAEHAQQJ +BwQIAAkDCwMJAQsJCwECBAUJBgMLAwYABwAGAAcIBgcLCAQDBQMEAwUACQAFCAADBwkECQcLCQsF +BgULCAADCgYBBwEGAQcCCwIHCgIBBgMLAwYABwAGAAcIBgcLAwgCCgIIAAoICgABCgIBCAQDBQME +AwUACQAFCAADBAEJAQQCBQIEAgUKBAUJAQoACAAKAggKCAID +""", +) + +# static const char tiling7_3[16][3][27] +TILING7_3 = ( + (16, 3, 27), + """ +DAIKDAoFDAUEDAQIDAgDDAMADAAJDAkBDAECDAUEDAQIDAgDDAMCDAIKDAoBDAEADAAJDAkFBQQM +CgUMAgoMAwIMCAMMAAgMAQAMCQEMBAkMDAAIDAgHDAcGDAYKDAoBDAECDAILDAsDDAMADAcGDAYK +DAoBDAEADAAIDAgDDAMCDAILDAsHBwYMCAcMAAgMAQAMCgEMAgoMAwIMCwMMBgsMCQUMAAkMAwAM +CwMMBgsMBwYMCAcMBAgMBQQMAwAMCwMMBgsMBQYMCQUMBAkMBwQMCAcMAAgMDAMADAAJDAkFDAUG +DAYLDAsHDAcEDAQIDAgDDAEJDAkEDAQHDAcLDAsCDAIDDAMIDAgADAABDAQHDAcLDAsCDAIBDAEJ +DAkADAADDAMIDAgEBAcMCQQMAQkMAgEMCwIMAwsMAAMMCAAMBwgMDAMLDAsGDAYFDAUJDAkADAAB +DAEKDAoCDAIDDAYFDAUJDAkADAADDAMLDAsCDAIBDAEKDAoGBgUMCwYMAwsMAAMMCQAMAQkMAgEM +CgIMBQoMCgYMAQoMAAEMCAAMBwgMBAcMCQQMBQkMBgUMAAEMCAAMBwgMBgcMCgYMBQoMBAUMCQQM +AQkMDAABDAEKDAoGDAYHDAcIDAgEDAQFDAUJDAkACwcMAgsMAQIMCQEMBAkMBQQMCgUMBgoMBwYM +AQIMCQEMBAkMBwQMCwcMBgsMBQYMCgUMAgoMDAECDAILDAsHDAcEDAQJDAkFDAUGDAYKDAoBCAQM +AwgMAgMMCgIMBQoMBgUMCwYMBwsMBAcMAgMMCgIMBQoMBAUMCAQMBwgMBgcMCwYMAwsMDAIDDAMI +DAgEDAQFDAUKDAoGDAYHDAcLDAsCDAQIDAgDDAMCDAIKDAoFDAUGDAYLDAsHDAcEDAMCDAIKDAoF +DAUEDAQIDAgHDAcGDAYLDAsDAwIMCAMMBAgMBQQMCgUMBgoMBwYMCwcMAgsMDAcLDAsCDAIBDAEJ +DAkEDAQFDAUKDAoGDAYHDAIBDAEJDAkEDAQHDAcLDAsGDAYFDAUKDAoCAgEMCwIMBwsMBAcMCQQM +BQkMBgUMCgYMAQoMDAYKDAoBDAEADAAIDAgHDAcEDAQJDAkFDAUGDAEADAAIDAgHDAcGDAYKDAoF +DAUEDAQJDAkBAQAMCgEMBgoMBwYMCAcMBAgMBQQMCQUMAAkMCwMMBgsMBQYMCQUMAAkMAQAMCgEM +AgoMAwIMBQYMCQUMAAkMAwAMCwMMAgsMAQIMCgEMBgoMDAUGDAYLDAsDDAMADAAJDAkBDAECDAIK +DAoFCQEMBAkMBwQMCwcMAgsMAwIMCAMMAAgMAQAMBwQMCwcMAgsMAQIMCQEMAAkMAwAMCAMMBAgM +DAcEDAQJDAkBDAECDAILDAsDDAMADAAIDAgHDAUJDAkADAADDAMLDAsGDAYHDAcIDAgEDAQFDAAD +DAMLDAsGDAYFDAUJDAkEDAQHDAcIDAgAAAMMCQAMBQkMBgUMCwYMBwsMBAcMCAQMAwgMCAAMBwgM +BgcMCgYMAQoMAgEMCwIMAwsMAAMMBgcMCgYMAQoMAAEMCAAMAwgMAgMMCwIMBwsMDAYHDAcIDAgA +DAABDAEKDAoCDAIDDAMLDAsGCgIMBQoMBAUMCAQMAwgMAAMMCQAMAQkMAgEMBAUMCAQMAwgMAgMM +CgIMAQoMAAEMCQAMBQkMDAQFDAUKDAoCDAIDDAMIDAgADAABDAEJDAkE +""", +) + +# static const char tiling7_4_1[16][15] +TILING7_4_1 = ( + (16, 15), + """ +AwQIBAMKAgoDBAoFCQEAAQYKBgEIAAgBBggHCwMCCwMGCQYDBgkFAAkDBwQIAgcLBwIJAQkCBwkE +CAADAAUJBQALAwsABQsGCgIBCAAHCgcABwoGAQoABAUJCQEECwQBBAsHAgsBBQYKCgIFCAUCBQgE +AwgCBgcLBQIKAgUIBAgFAggDCwcGBAEJAQQLBwsEAQsCCgYFBwAIAAcKBgoHAAoBCQUECQUACwAF +AAsDBgsFAQIKCwcCCQIHAgkBBAkHAwAIBgMLAwYJBQkGAwkACAQHCgYBCAEGAQgABwgGAgMLCAQD +CgMEAwoCBQoEAAEJ +""", +) + +# static const char tiling7_4_2[16][27] +TILING7_4_2 = ( + (16, 27), + """ +CQQIBAkFCgUJAQoJCgECAAIBAgADCAMACQgACwYKBgsHCAcLAwgLCAMAAgADAAIBCgECCwoCCwMI +AAgDCAAJCAkEBQQJBAUHBgcFBwYLBwsICAcLBwgECQQIAAkICQABAwEAAQMCCwIDCAsDCgUJBQoG +CwYKAgsKCwIDAQMCAwEACQABCgkBCAAJAQkACQEKCQoFBgUKBQYEBwQGBAcIBAgJCQEKAgoBCgIL +CgsGBwYLBgcFBAUHBQQJBQkKCgILAwsCCwMICwgHBAcIBwQGBQYEBgUKBgoLCwIKAgsDCAMLBwgL +CAcEBgQHBAYFCgUGCwoGCgEJAQoCCwIKBgsKCwYHBQcGBwUECQQFCgkFCQAIAAkBCgEJBQoJCgUG +BAYFBgQHCAcECQgECQUKBgoFCgYLCgsCAwILAgMBAAEDAQAJAQkKCwcIBAgHCAQJCAkAAQAJAAED +AgMBAwILAwsICAMLAwgACQAIBAkICQQFBwUEBQcGCwYHCAsHCgYLBwsGCwcICwgDAAMIAwACAQIA +AgEKAgoLCAQJBQkECQUKCQoBAgEKAQIAAwACAAMIAAgJ +""", +) + +# static const char tiling8[6][6] +TILING8 = ( + (6, 6), + """ +CQgKCggLAQUDAwUHAAQCBAYCAAIEBAIGAQMFAwcFCQoICgsI +""", +) + +# static const char tiling9[8][12] +TILING9 = ( + (8, 12), + """ +AgoFAwIFAwUEAwQIBAcLCQQLCQsCCQIBCgcGAQcKAQgHAQAIAwYLAAYDAAUGAAkFAwsGAAMGAAYF +AAUJCgYHAQoHAQcIAQgABAsHCQsECQILCQECAgUKAwUCAwQFAwgE +""", +) + +# static const char tiling10_1_1[6][12] +TILING10_1_1 = ( + (6, 12), + """ +BQoHCwcKCAEJAQgDAQIFBgUCBAMAAwQHCwAIAAsCBAkGCgYJCQAKAgoABggECAYLBwIDAgcGAAEE +BQQBBwkFCQcICgELAwsB +""", +) + +# static const char tiling10_1_1_[6][12] +TILING10_1_1_ = ( + (6, 12), + """ +BQkHCAcJCwEKAQsDAwIHBgcCBAEAAQQFCgAJAAoCBAgGCwYICAALAgsABgkECQYKBQIBAgUGAAME +BwQDBwoFCgcLCQEIAwgB +""", +) + +# static const char tiling10_1_2[6][24] +TILING10_1_2 = ( + (6, 24), + """ +AwsHAwcICQgHBQkHCQUKCQoBAwEKCwMKBwYFBwUEAAQFAQAFAAECAAIDBwMCBgcCCwIKBgsKCwYE +CwQIAAgECQAEAAkKAAoCCwIKCwoGBAYKCQQKBAkABAAICwgAAgsABwYFBAcFBwQABwADAgMAAQIA +AgEFAgUGBwgDCwcDBwsKBwoFCQUKAQkKCQEDCQMI +""", +) + +# static const char tiling10_2[6][24] +TILING10_2 = ( + (6, 24), + """ +DAUJDAkIDAgDDAMBDAEKDAoLDAsHDAcFDAEADAAEDAQHDAcDDAMCDAIGDAYFDAUBBAgMBgQMCgYM +CQoMAAkMAgAMCwIMCAsMDAkEDAQGDAYLDAsIDAgADAACDAIKDAoJAAMMBAAMBQQMAQUMAgEMBgIM +BwYMAwcMCgUMCwoMAwsMAQMMCQEMCAkMBwgMBQcM +""", +) + +# static const char tiling10_2_[6][24] +TILING10_2_ = ( + (6, 24), + """ +CAcMCQgMAQkMAwEMCwMMCgsMBQoMBwUMBAUMAAQMAwAMBwMMBgcMAgYMAQIMBQEMDAsGDAYEDAQJ +DAkKDAoCDAIADAAIDAgLBgoMBAYMCAQMCwgMAgsMAAIMCQAMCgkMDAcEDAQADAABDAEFDAUGDAYC +DAIDDAMHDAcLDAsKDAoBDAEDDAMIDAgJDAkFDAUH +""", +) + +# static const char tiling11[12][12] +TILING11 = ( + (12, 12), + """ +AgoJAgkHAgcDBwkEAQYCAQgGAQkICAcGCAMBCAEGCAYEBgEKAAgLAAsFAAUBBQsGCQUHCQcCCQIA +AgcLBQAEBQsABQoLCwMABQQABQALBQsKCwADCQcFCQIHCQACAgsHAAsIAAULAAEFBQYLCAEDCAYB +CAQGBgoBAQIGAQYIAQgJCAYHAgkKAgcJAgMHBwQJ +""", +) + +# static const char tiling12_1_1[24][12] +TILING12_1_1 = ( + (24, 12), + """ +BwYLCgMCAwoICQgKBgUKCQIBAgkLCAsJCgYFBwkECQcBAwEHBwYLBAgFAwUIBQMBBQQJCAEAAQgK +CwoIAQIKAAkDBQMJAwUHCgECAAsDCwAGBAYACAMAAgkBCQIEBgQCAwAIAgsBBwELAQcFBgUKBwsE +AgQLBAIACQUEBggHCAYAAgAGCAMABwQLCQsECwkKBAcICwADAAsJCgkLBAcIBQkGAAYJBgACCwcG +BAoFCgQCAAIECwIDAQgACAEHBQcBAAEJAwgCBAIIAgQGAgMLAQoABgAKAAYECQABAwoCCgMFBwUD +CQABBAUICggFCAoLCAQHBQsGCwUDAQMFBQQJBgoHAQcKBwEDCgECBQYJCwkGCQsICwIDBgcKCAoH +CggJ +""", +) + +# static const char tiling12_1_1_[24][12] +TILING12_1_1_ = ( + (24, 12), + """ +AwILCgcGBwoICQgKAgEKCQYFBgkLCAsJCQQFBwoGCgcBAwEHBwQIBgsFAwULBQMBAQAJCAUEBQgK +CwoIAQAJAgoDBQMKAwUHCwMCAAoBCgAGBAYACQEAAggDCAIEBgQCAwILAAgBBwEIAQcFBgcLBQoE +AgQKBAIACAcEBgkFCQYAAgAGCAcEAwALCQsACwkKAAMICwQHBAsJCgkLBAUJBwgGAAYIBgACCgUG +BAsHCwQCAAIECAADAQsCCwEHBQcBAAMIAQkCBAIJAgQGAgEKAwsABgALAAYECgIBAwkACQMFBwUD +CQQFAAEICggBCAoLCwYHBQgECAUDAQMFBQYKBAkHAQcJBwEDCgUGAQIJCwkCCQsICwYHAgMKCAoD +CggJ +""", +) + +# static const char tiling12_1_2[24][24] +TILING12_1_2 = ( + (24, 24), + """ +BwMLAwcICQgHBgkHCQYKAgoGCwIGAgsDBgIKAgYLCAsGBQgGCAUJAQkFCgEFAQoCCgkFCQoBAwEK +BgMKAwYHBAcGBQQGBAUJBwgLAwsICwMBCwEGBQYBBgUEBgQHCAcEBQEJAQUKCwoFBAsFCwQIAAgE +CQAEAAkBAQkKBQoJCgUHCgcCAwIHAgMAAgABCQEACgsCCwoGBAYKAQQKBAEAAwABAgMBAwILCAkA +CQgEBgQIAwYIBgMCAQIDAAEDAQAJAwsIBwgLCAcFCAUAAQAFAAECAAIDCwMCBgsKAgoLCgIACgAF +BAUABQQHBQcGCwYHCQgECAkAAgAJBQIJAgUGBwYFBAcFBwQICAQACQAEAAkKAAoDCwMKAwsHAwcI +BAgHBAAIAAQJCgkEBwoECgcLAwsHCAMHAwgABAkIAAgJCAACCAIHBgcCBwYFBwUECQQFCwoGCgsC +AAILBwALAAcEBQQHBgUHBQYKCwgDCAsHBQcLAgULBQIBAAECAwACAAMIAAgJBAkICQQGCQYBAgEG +AQIDAQMACAADAgoLBgsKCwYECwQDAAMEAwABAwECCgIBCQoBCgkFBwUJAAcJBwADAgMAAQIAAgEK +CQUBCgEFAQoLAQsACAALAAgEAAQJBQkECAsHCwgDAQMIBAEIAQQFBgUEBwYEBgcLBQoJAQkKCQED +CQMEBwQDBAcGBAYFCgUGCgYCCwIGAgsIAggBCQEIAQkFAQUKBgoFCwcDCAMHAwgJAwkCCgIJAgoG +AgYLBwsG +""", +) + +# static const char tiling12_2[24][24] +TILING12_2 = ( + (24, 24), + """ +CQgMCgkMAgoMAwIMCwMMBgsMBwYMCAcMCAsMCQgMAQkMAgEMCgIMBQoMBgUMCwYMAwEMBwMMBAcM +CQQMBQkMBgUMCgYMAQoMDAMBDAEFDAUGDAYLDAsHDAcEDAQIDAgDCwoMCAsMAAgMAQAMCQEMBAkM +BQQMCgUMDAUHDAcDDAMCDAIKDAoBDAEADAAJDAkFBAYMAAQMAQAMCgEMAgoMAwIMCwMMBgsMBgQM +AgYMAwIMCAMMAAgMAQAMCQEMBAkMDAcFDAUBDAEADAAIDAgDDAMCDAILDAsHDAIADAAEDAQFDAUK +DAoGDAYHDAcLDAsCAgAMBgIMBwYMCAcMBAgMBQQMCQUMAAkMDAkKDAoLDAsHDAcEDAQIDAgDDAMA +DAAJCgkMCwoMBwsMBAcMCAQMAwgMAAMMCQAMDAACDAIGDAYHDAcIDAgEDAQFDAUJDAkAAAIMBAAM +BQQMCgUMBgoMBwYMCwcMAgsMBQcMAQUMAAEMCAAMAwgMAgMMCwIMBwsMDAQGDAYCDAIDDAMIDAgA +DAABDAEJDAkEDAYEDAQADAABDAEKDAoCDAIDDAMLDAsGBwUMAwcMAgMMCgIMAQoMAAEMCQAMBQkM +DAoLDAsIDAgADAABDAEJDAkEDAQFDAUKAQMMBQEMBgUMCwYMBwsMBAcMCAQMAwgMDAEDDAMHDAcE +DAQJDAkFDAUGDAYKDAoBDAsIDAgJDAkBDAECDAIKDAoFDAUGDAYLDAgJDAkKDAoCDAIDDAMLDAsG +DAYHDAcI +""", +) + +# static const char tiling12_2_[24][24] +TILING12_2_ = ( + (24, 24), + """ +DAILDAsHDAcGDAYKDAoJDAkIDAgDDAMCDAEKDAoGDAYFDAUJDAkIDAgLDAsCDAIBDAQFDAUKDAoG +DAYHDAcDDAMBDAEJDAkEBwYMCAcMBAgMBQQMAQUMAwEMCwMMBgsMDAAJDAkFDAUEDAQIDAgLDAsK +DAoBDAEAAQIMCQEMAAkMAwAMBwMMBQcMCgUMAgoMDAECDAILDAsDDAMADAAEDAQGDAYKDAoBDAMA +DAAJDAkBDAECDAIGDAYEDAQIDAgDAwAMCwMMAgsMAQIMBQEMBwUMCAcMAAgMBgUMCwYMBwsMBAcM +AAQMAgAMCgIMBQoMDAcEDAQJDAkFDAUGDAYCDAIADAAIDAgHCAcMAAgMAwAMCwMMCgsMCQoMBAkM +BwQMDAcIDAgADAADDAMLDAsKDAoJDAkEDAQHBAcMCQQMBQkMBgUMAgYMAAIMCAAMBwgMDAUGDAYL +DAsHDAcEDAQADAACDAIKDAoFDAADDAMLDAsCDAIBDAEFDAUHDAcIDAgAAAMMCQAMAQkMAgEMBgIM +BAYMCAQMAwgMAgEMCwIMAwsMAAMMBAAMBgQMCgYMAQoMDAIBDAEJDAkADAADDAMHDAcFDAUKDAoC +CQAMBQkMBAUMCAQMCwgMCgsMAQoMAAEMDAYHDAcIDAgEDAQFDAUBDAEDDAMLDAsGBQQMCgUMBgoM +BwYMAwcMAQMMCQEMBAkMCgEMBgoMBQYMCQUMCAkMCwgMAgsMAQIMCwIMBwsMBgcMCgYMCQoMCAkM +AwgMAgMM +""", +) + +# static const char tiling13_1[2][12] +TILING13_1 = ( + (2, 12), + """ +CwcGAQIKCAMACQUECAQHAgMLCQABCgYF +""", +) + +# static const char tiling13_1_[2][12] +TILING13_1_ = ( + (2, 12), + """ +BwQICwMCAQAJBQYKBgcLCgIBAAMIBAUJ +""", +) + +# static const char tiling13_2[2][6][18] +TILING13_2 = ( + (2, 6, 18), + """ +AQIKCwcGAwQIBAMFAAUDBQAJCAMACwcGCQEEAgQBBAIFCgUCCQUECAMAAQYKBgEHAgcBBwILCQUE +AQIKCwMGAAYDBgAHCAcACQUECwcGAAoBCgAICggCAwIIAQIKAwAIBAkHCwcJBQsJCwUGAgMLCAQH +AAUJBQAGAQYABgEKCQABCAQHCgIFAwUCBQMGCwYDBgUKCQABAgcLBwIEAwQCBAMIBgUKAgMLCAAH +AQcABwEECQQBBgUKCAQHAQsCCwEJCwkDAAMJAgMLAAEJBQoECAQKBggKCAYH +""", +) + +# static const char tiling13_2_[2][6][18] +TILING13_2_ = ( + (2, 6, 18), + """ +CgUGCwMCBwAIAAcBBAEHAQQJCwMCBwQICQUABgAFAAYBCgEGAQAJBwQIBQIKAgUDBgMFAwYLCgUG +AQAJCwcCBAIHAgQDCAMECgUGBwQIAgsBCQELAwkLCQMACwMCCQEABAoFCgQICggGBwYIBgcLCAAD +BAEJAQQCBQIEAgUKCAADBAUJCgYBBwEGAQcCCwIHAgEKBAUJBgMLAwYABwAGAAcIBgcLAgEKCAQD +BQMEAwUACQAFBgcLBAUJAwgCCgIIAAoICgABCAADCgIBBQsGCwUJCwkHBAcJ +""", +) + +# static const char tiling13_3[2][12][30] +TILING13_3 = ( + (2, 12, 30), + """ +CwcGDAIKDAoFDAUEDAQIDAgDDAMADAAJDAkBDAECAQIKCQUMAAkMAwAMCwMMBgsMBwYMCAcMBAgM +BQQMCwcGDAUEDAQIDAgDDAMCDAIKDAoBDAEADAAJDAkFAQIKDAMADAAJDAkFDAUGDAYLDAsHDAcE +DAQIDAgDCAMACwcMAgsMAQIMCQEMBAkMBQQMCgUMBgoMBwYMCwcGBQQMCgUMAgoMAwIMCAMMAAgM +AQAMCQEMBAkMCAMAAQIMCQEMBAkMBwQMCwcMBgsMBQYMCgUMAgoMCQUEDAAIDAgHDAcGDAYKDAoB +DAECDAILDAsDDAMACQUEDAcGDAYKDAoBDAEADAAIDAgDDAMCDAILDAsHCAMADAECDAILDAsHDAcE +DAQJDAkFDAUGDAYKDAoBCQUEBwYMCAcMAAgMAQAMCgEMAgoMAwIMCwMMBgsMAQIKAwAMCwMMBgsM +BQYMCQUMBAkMBwQMCAcMAAgMCAQHDAMLDAsGDAYFDAUJDAkADAABDAEKDAoCDAIDAgMLCgYMAQoM +AAEMCAAMBwgMBAcMCQQMBQkMBgUMCAQHDAYFDAUJDAkADAADDAMLDAsCDAIBDAEKDAoGAgMLDAAB +DAEKDAoGDAYHDAcIDAgEDAQFDAUJDAkAAAEJCAQMAwgMAgMMCgIMBQoMBgUMCwYMBwsMBAcMCAQH +BgUMCwYMAwsMAAMMCQAMAQkMAgEMCgIMBQoMCQABAgMMCgIMBQoMBAUMCAQMBwgMBgcMCwYMAwsM +BgUKDAEJDAkEDAQHDAcLDAsCDAIDDAMIDAgADAABBgUKDAQHDAcLDAsCDAIBDAEJDAkADAADDAMI +DAgECQABDAIDDAMIDAgEDAQFDAUKDAoGDAYHDAcLDAsCBgUKBAcMCQQMAQkMAgEMCwIMAwsMAAMM +CAAMBwgMAgMLAAEMCAAMBwgMBgcMCgYMBQoMBAUMCQQMAQkM +""", +) + +# static const char tiling13_3_[2][12][30] +TILING13_3_ = ( + (2, 12, 30), + """ +AwILCAcMAAgMAQAMCgEMBgoMBQYMCQUMBAkMBwQMBQYKDAILDAsHDAcEDAQJDAkBDAEADAAIDAgD +DAMCCgUGDAcEDAQJDAkBDAECDAILDAsDDAMADAAIDAgHCwMCDAEADAAIDAgHDAcGDAYKDAoFDAUE +DAQJDAkBBwQICwMMBgsMBQYMCQUMAAkMAQAMCgEMAgoMAwIMBwQIBQYMCQUMAAkMAwAMCwMMAgsM +AQIMCgEMBgoMCwMCAQAMCgEMBgoMBwYMCAcMBAgMBQQMCQUMAAkMAQAJDAQIDAgDDAMCDAIKDAoF +DAUGDAYLDAsHDAcEBwQIDAUGDAYLDAsDDAMADAAJDAkBDAECDAIKDAoFAQAJDAMCDAIKDAoFDAUE +DAQIDAgHDAcGDAYLDAsDCgUGBwQMCwcMAgsMAQIMCQEMAAkMAwAMCAMMBAgMCQEAAwIMCAMMBAgM +BQQMCgUMBgoMBwYMCwcMAgsMAAMICQQMAQkMAgEMCwIMBwsMBgcMCgYMBQoMBAUMCwYHDAMIDAgE +DAQFDAUKDAoCDAIBDAEJDAkADAADBgcLDAQFDAUKDAoCDAIDDAMIDAgADAABDAEJDAkECAADDAIB +DAEJDAkEDAQHDAcLDAsGDAYFDAUKDAoCBAUJCAAMBwgMBgcMCgYMAQoMAgEMCwIMAwsMAAMMBAUJ +BgcMCgYMAQoMAAEMCAAMAwgMAgMMCwIMBwsMCAADAgEMCwIMBwsMBAcMCQQMBQkMBgUMCgYMAQoM +AgEKDAUJDAkADAADDAMLDAsGDAYHDAcIDAgEDAQFBAUJDAYHDAcIDAgADAABDAEKDAoCDAIDDAML +DAsGAgEKDAADDAMLDAsGDAYFDAUJDAkEDAQHDAcIDAgABgcLBAUMCAQMAwgMAgMMCgIMAQoMAAEM +CQAMBQkMCgIBAAMMCQAMBQkMBgUMCwYMBwsMBAcMCAQMAwgM +""", +) + +# static const char tiling13_4[2][4][36] +TILING13_4 = ( + (2, 4, 36), + """ +DAIKDAoFDAUGDAYLDAsHDAcEDAQIDAgDDAMADAAJDAkBDAECCwMMBgsMBwYMCAcMBAgMBQQMCQUM +AAkMAQAMCgEMAgoMAwIMCQEMBAkMBQQMCgUMBgoMBwYMCwcMAgsMAwIMCAMMAAgMAQAMDAAIDAgH +DAcEDAQJDAkFDAUGDAYKDAoBDAECDAILDAsDDAMADAMLDAsGDAYHDAcIDAgEDAQFDAUJDAkADAAB +DAEKDAoCDAIDCAAMBwgMBAcMCQQMBQkMBgUMCgYMAQoMAgEMCwIMAwsMAAMMCgIMBQoMBgUMCwYM +BwsMBAcMCAQMAwgMAAMMCQAMAQkMAgEMDAEJDAkEDAQFDAUKDAoGDAYHDAcLDAsCDAIDDAMIDAgA +DAAB +""", +) + +# static const char tiling13_5_1[2][4][18] +TILING13_5_1 = ( + (2, 4, 18), + """ +BwYLAQAJCgMCAwoFAwUIBAgFAQIKBwQIAwALBgsACQYABgkFAwAIBQYKAQIJBAkCCwQCBAsHBQQJ +AwILCAEAAQgHAQcKBgoHBAcIAgEKCwADAAsGAAYJBQkGAgMLBAUJAAEIBwgBCgcBBwoGAAEJBgcL +AgMKBQoDCAUDBQgEBgUKAAMICQIBAgkEAgQLBwsE +""", +) + +# static const char tiling13_5_2[2][4][30] +TILING13_5_2 = ( + (2, 4, 30), + """ +AQAJBwQIBwgDBwMLAgsDCwIKCwoGBQYKBgUHBAcFBwQICwMCBgsCCgYCBgoFCQUKAQkKCQEAAgAB +AAIDBQYKCQEABAkACAQABAgHCwcIAwsICwMCAAIDAgABAwILBQYKBQoBBQEJAAkBCQAICQgEBAgH +BAcFBgUHAgEKBAUJBAkABAAIAwgACAMLCAsHBgcLBwYEBQQGBAUJCAADBwgDCwcDBwsGCgYLAgoL +CgIBAwECAQMABgcLCgIBBQoBCQUBBQkECAQJAAgJCAADAQMAAwECAAMIBgcLBgsCBgIKAQoCCgEJ +CgkFBQkEBQQGBwYE +""", +) + +# static const char tiling14[12][12] +TILING14 = ( + (12, 12), + """ +BQkIBQgCBQIGAwIIAgEFAgUIAggLBAgFCQQGCQYDCQMBCwMGAQsKAQQLAQAEBwsECAIACAUCCAcF +CgIFAAcDAAoHAAkKBgcKAAMHAAcKAAoJBgoHCAACCAIFCAUHCgUCAQoLAQsEAQQABwQLCQYECQMG +CQEDCwYDAgUBAggFAgsIBAUIBQgJBQIIBQYCAwgC +""", +) + +# static const char test3[24] +TEST3 = ( + (24,), + """ +BQEEBQECAgMEAwYG+vr9/P3+/v/7/P/7 +""", +) + +# static const char test4[8] +TEST4 = ( + (8,), + """ +BwcHB/n5+fk= +""", +) + +# static const char test6[48][3] +TEST6 = ( + (48, 3), + """ +AgcKBAcLBQcBBQcDAQcJAwcKBgcFAQcIBAcIAQcIAwcLBQcCBQcAAQcJBgcGAgcJBAcIAgcJAgcK +BgcHAwcKBAcLAwcLBgcE+vkE/fkL/PkL/fkK+vkH/vkK/vkJ/PkI/vkJ+vkG//kJ+/kA+/kC/fkL +//kI/PkI//kI+vkF/fkK//kJ+/kD+/kB/PkL/vkK +""", +) + +# static const char test7[16][5] +TEST7 = ( + (16, 5), + """ +AQIFBwEDBAUHAwQBBgcEBAEFBwACAwUHAgECBgcFAgMGBwYDBAYHB/38+vkH/v36+Qb//vr5Bf79 ++/kC/P/7+QD8//r5BP38+/kD//77+QE= +""", +) + +# static const char test10[6][3] +TEST10 = ( + (6, 3), + """ +AgQHBQYHAQMHAQMHBQYHAgQH +""", +) + +# static const char test12[24][4] +TEST12 = ( + (24, 4), + """ +BAMHCwMCBwoCBgcFBgQHBwIBBwkFAgcBBQMHAgUBBwAFBAcDBgMHBgEGBwQBBAcIBAEHCAYBBwQD +BgcGBAUHAwEFBwADBQcCAgUHAQECBwkEBgcHBgIHBQIDBwoDBAcL +""", +) + +# static const char test13[2][7] +TEST13 = ( + (2, 7), + """ +AQIDBAUGBwIDBAEFBgc= +""", +) + +# static const char subconfig13[64] +SUBCONFIG13 = ( + (64,), + """ +AAECBwP/C/8ECP//Dv///wUJDBcP/xUmERT/JBohHiwGCg0TEP8ZJRIY/yMWIB0r////Iv//HCr/ +H/8pGygnLQ== +""", +) diff --git a/python_embeded/Lib/site-packages/skimage/measure/_moments.py b/python_embeded/Lib/site-packages/skimage/measure/_moments.py new file mode 100644 index 0000000000000000000000000000000000000000..114af741023ef6cfdaa5d2a90fc53360b5e00acf --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_moments.py @@ -0,0 +1,504 @@ +import itertools + +import numpy as np + +from .._shared.utils import _supported_float_type, check_nD +from . import _moments_cy +from ._moments_analytical import moments_raw_to_central + + +def moments_coords(coords, order=3): + """Calculate all raw image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale, nor rotation + invariant. + + Parameters + ---------- + coords : (N, D) double or uint8 array + Array of N points that describe an image of D dimensionality in + Cartesian space. + order : int, optional + Maximum order of moments. Default is 3. + + Returns + ------- + M : (``order + 1``, ``order + 1``, ...) array + Raw image moments. (D dimensions) + + References + ---------- + .. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham + University, version 0.2, Durham, 2001. + + Examples + -------- + >>> coords = np.array([[row, col] + ... for row in range(13, 17) + ... for col in range(14, 18)], dtype=np.float64) + >>> M = moments_coords(coords) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> centroid + (14.5, 15.5) + """ + return moments_coords_central(coords, 0, order=order) + + +def moments_coords_central(coords, center=None, order=3): + """Calculate all central image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale nor rotation + invariant. + + Parameters + ---------- + coords : (N, D) double or uint8 array + Array of N points that describe an image of D dimensionality in + Cartesian space. A tuple of coordinates as returned by + ``np.nonzero`` is also accepted as input. + center : tuple of float, optional + Coordinates of the image centroid. This will be computed if it + is not provided. + order : int, optional + Maximum order of moments. Default is 3. + + Returns + ------- + Mc : (``order + 1``, ``order + 1``, ...) array + Central image moments. (D dimensions) + + References + ---------- + .. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham + University, version 0.2, Durham, 2001. + + Examples + -------- + >>> coords = np.array([[row, col] + ... for row in range(13, 17) + ... for col in range(14, 18)]) + >>> moments_coords_central(coords) + array([[16., 0., 20., 0.], + [ 0., 0., 0., 0.], + [20., 0., 25., 0.], + [ 0., 0., 0., 0.]]) + + As seen above, for symmetric objects, odd-order moments (columns 1 and 3, + rows 1 and 3) are zero when centered on the centroid, or center of mass, + of the object (the default). If we break the symmetry by adding a new + point, this no longer holds: + + >>> coords2 = np.concatenate((coords, [[17, 17]]), axis=0) + >>> np.round(moments_coords_central(coords2), + ... decimals=2) # doctest: +NORMALIZE_WHITESPACE + array([[17. , 0. , 22.12, -2.49], + [ 0. , 3.53, 1.73, 7.4 ], + [25.88, 6.02, 36.63, 8.83], + [ 4.15, 19.17, 14.8 , 39.6 ]]) + + Image moments and central image moments are equivalent (by definition) + when the center is (0, 0): + + >>> np.allclose(moments_coords(coords), + ... moments_coords_central(coords, (0, 0))) + True + """ + if isinstance(coords, tuple): + # This format corresponds to coordinate tuples as returned by + # e.g. np.nonzero: (row_coords, column_coords). + # We represent them as an npoints x ndim array. + coords = np.stack(coords, axis=-1) + check_nD(coords, 2) + ndim = coords.shape[1] + + float_type = _supported_float_type(coords.dtype) + if center is None: + center = np.mean(coords, axis=0, dtype=float) + + # center the coordinates + coords = coords.astype(float_type, copy=False) - center + + # generate all possible exponents for each axis in the given set of points + # produces a matrix of shape (N, D, order + 1) + coords = np.stack([coords**c for c in range(order + 1)], axis=-1) + + # add extra dimensions for proper broadcasting + coords = coords.reshape(coords.shape + (1,) * (ndim - 1)) + + calc = 1 + + for axis in range(ndim): + # isolate each point's axis + isolated_axis = coords[:, axis] + + # rotate orientation of matrix for proper broadcasting + isolated_axis = np.moveaxis(isolated_axis, 1, 1 + axis) + + # calculate the moments for each point, one axis at a time + calc = calc * isolated_axis + + # sum all individual point moments to get our final answer + Mc = np.sum(calc, axis=0) + + return Mc + + +def moments(image, order=3, *, spacing=None): + """Calculate all raw image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale nor rotation + invariant. + + Parameters + ---------- + image : (N[, ...]) double or uint8 array + Rasterized shape as image. + order : int, optional + Maximum order of moments. Default is 3. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + m : (``order + 1``, ``order + 1``) array + Raw image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> M = moments(image) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> centroid + (14.5, 14.5) + """ + return moments_central(image, (0,) * image.ndim, order=order, spacing=spacing) + + +def moments_central(image, center=None, order=3, *, spacing=None, **kwargs): + """Calculate all central image moments up to a certain order. + + The center coordinates (cr, cc) can be calculated from the raw moments as: + {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that central moments are translation invariant but not scale and + rotation invariant. + + Parameters + ---------- + image : (N[, ...]) double or uint8 array + Rasterized shape as image. + center : tuple of float, optional + Coordinates of the image centroid. This will be computed if it + is not provided. + order : int, optional + The maximum order of moments computed. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + mu : (``order + 1``, ``order + 1``) array + Central image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> M = moments(image) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> moments_central(image, centroid) + array([[16., 0., 20., 0.], + [ 0., 0., 0., 0.], + [20., 0., 25., 0.], + [ 0., 0., 0., 0.]]) + """ + if center is None: + # Note: No need for an explicit call to centroid. + # The centroid will be obtained from the raw moments. + moments_raw = moments(image, order=order, spacing=spacing) + return moments_raw_to_central(moments_raw) + float_dtype = _supported_float_type(image.dtype) + if spacing is None: + spacing = np.ones(image.ndim, dtype=float_dtype) + calc = image.astype(float_dtype, copy=False) + for dim, dim_length in enumerate(image.shape): + delta = np.arange(dim_length, dtype=float_dtype) * spacing[dim] - center[dim] + powers_of_delta = delta[:, np.newaxis] ** np.arange( + order + 1, dtype=float_dtype + ) + calc = np.rollaxis(calc, dim, image.ndim) + calc = np.dot(calc, powers_of_delta) + calc = np.rollaxis(calc, -1, dim) + return calc + + +def moments_normalized(mu, order=3, spacing=None): + """Calculate all normalized central image moments up to a certain order. + + Note that normalized central moments are translation and scale invariant + but not rotation invariant. + + Parameters + ---------- + mu : (M[, ...], M) array + Central image moments, where M must be greater than or equal + to ``order``. + order : int, optional + Maximum order of moments. Default is 3. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + nu : (``order + 1``[, ...], ``order + 1``) array + Normalized central image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> m = moments(image) + >>> centroid = (m[0, 1] / m[0, 0], m[1, 0] / m[0, 0]) + >>> mu = moments_central(image, centroid) + >>> moments_normalized(mu) + array([[ nan, nan, 0.078125 , 0. ], + [ nan, 0. , 0. , 0. ], + [0.078125 , 0. , 0.00610352, 0. ], + [0. , 0. , 0. , 0. ]]) + """ + if np.any(np.array(mu.shape) <= order): + raise ValueError("Shape of image moments must be >= `order`") + if spacing is None: + spacing = np.ones(mu.ndim) + nu = np.zeros_like(mu) + mu0 = mu.ravel()[0] + scale = min(spacing) + for powers in itertools.product(range(order + 1), repeat=mu.ndim): + if sum(powers) < 2: + nu[powers] = np.nan + else: + nu[powers] = (mu[powers] / scale ** sum(powers)) / ( + mu0 ** (sum(powers) / nu.ndim + 1) + ) + return nu + + +def moments_hu(nu): + """Calculate Hu's set of image moments (2D-only). + + Note that this set of moments is proved to be translation, scale and + rotation invariant. + + Parameters + ---------- + nu : (M, M) array + Normalized central image moments, where M must be >= 4. + + Returns + ------- + nu : (7,) array + Hu's set of image moments. + + References + ---------- + .. [1] M. K. Hu, "Visual Pattern Recognition by Moment Invariants", + IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962 + .. [2] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [3] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [4] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [5] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 0.5 + >>> image[10:12, 10:12] = 1 + >>> mu = moments_central(image) + >>> nu = moments_normalized(mu) + >>> moments_hu(nu) + array([0.74537037, 0.35116598, 0.10404918, 0.04064421, 0.00264312, + 0.02408546, 0. ]) + """ + dtype = np.float32 if nu.dtype == 'float32' else np.float64 + return _moments_cy.moments_hu(nu.astype(dtype, copy=False)) + + +def centroid(image, *, spacing=None): + """Return the (weighted) centroid of an image. + + Parameters + ---------- + image : array + The input image. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + center : tuple of float, length ``image.ndim`` + The centroid of the (nonzero) pixels in ``image``. + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 0.5 + >>> image[10:12, 10:12] = 1 + >>> centroid(image) + array([13.16666667, 13.16666667]) + """ + M = moments_central(image, center=(0,) * image.ndim, order=1, spacing=spacing) + center = ( + M[tuple(np.eye(image.ndim, dtype=int))] # array of weighted sums + # for each axis + / M[(0,) * image.ndim] + ) # weighted sum of all points + return center + + +def inertia_tensor(image, mu=None, *, spacing=None): + """Compute the inertia tensor of the input image. + + Parameters + ---------- + image : array + The input image. + mu : array, optional + The pre-computed central moments of ``image``. The inertia tensor + computation requires the central moments of the image. If an + application requires both the central moments and the inertia tensor + (for example, `skimage.measure.regionprops`), then it is more + efficient to pre-compute them and pass them to the inertia tensor + call. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + T : array, shape ``(image.ndim, image.ndim)`` + The inertia tensor of the input image. :math:`T_{i, j}` contains + the covariance of image intensity along axes :math:`i` and :math:`j`. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor + .. [2] Bernd Jähne. Spatio-Temporal Image Processing: Theory and + Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993. + """ + if mu is None: + mu = moments_central( + image, order=2, spacing=spacing + ) # don't need higher-order moments + mu0 = mu[(0,) * image.ndim] + result = np.zeros((image.ndim, image.ndim), dtype=mu.dtype) + + # nD expression to get coordinates ([2, 0], [0, 2]) (2D), + # ([2, 0, 0], [0, 2, 0], [0, 0, 2]) (3D), etc. + corners2 = tuple(2 * np.eye(image.ndim, dtype=int)) + d = np.diag(result) + d.flags.writeable = True + # See https://ocw.mit.edu/courses/aeronautics-and-astronautics/ + # 16-07-dynamics-fall-2009/lecture-notes/MIT16_07F09_Lec26.pdf + # Iii is the sum of second-order moments of every axis *except* i, not the + # second order moment of axis i. + # See also https://github.com/scikit-image/scikit-image/issues/3229 + d[:] = (np.sum(mu[corners2]) - mu[corners2]) / mu0 + + for dims in itertools.combinations(range(image.ndim), 2): + mu_index = np.zeros(image.ndim, dtype=int) + mu_index[list(dims)] = 1 + result[dims] = -mu[tuple(mu_index)] / mu0 + result.T[dims] = -mu[tuple(mu_index)] / mu0 + return result + + +def inertia_tensor_eigvals(image, mu=None, T=None, *, spacing=None): + """Compute the eigenvalues of the inertia tensor of the image. + + The inertia tensor measures covariance of the image intensity along + the image axes. (See `inertia_tensor`.) The relative magnitude of the + eigenvalues of the tensor is thus a measure of the elongation of a + (bright) object in the image. + + Parameters + ---------- + image : array + The input image. + mu : array, optional + The pre-computed central moments of ``image``. + T : array, shape ``(image.ndim, image.ndim)`` + The pre-computed inertia tensor. If ``T`` is given, ``mu`` and + ``image`` are ignored. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + eigvals : list of float, length ``image.ndim`` + The eigenvalues of the inertia tensor of ``image``, in descending + order. + + Notes + ----- + Computing the eigenvalues requires the inertia tensor of the input image. + This is much faster if the central moments (``mu``) are provided, or, + alternatively, one can provide the inertia tensor (``T``) directly. + """ + if T is None: + T = inertia_tensor(image, mu, spacing=spacing) + eigvals = np.linalg.eigvalsh(T) + # Floating point precision problems could make a positive + # semidefinite matrix have an eigenvalue that is very slightly + # negative. This can cause problems down the line, so set values + # very near zero to zero. + eigvals = np.clip(eigvals, 0, None, out=eigvals) + return sorted(eigvals, reverse=True) diff --git a/python_embeded/Lib/site-packages/skimage/measure/_moments_analytical.py b/python_embeded/Lib/site-packages/skimage/measure/_moments_analytical.py new file mode 100644 index 0000000000000000000000000000000000000000..c6915fe10b7da428549bd4d7c60eee5d01b16544 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_moments_analytical.py @@ -0,0 +1,171 @@ +"""Analytical transformations from raw image moments to central moments. + +The expressions for the 2D central moments of order <=2 are often given in +textbooks. Expressions for higher orders and dimensions were generated in SymPy +using ``tools/precompute/moments_sympy.py`` in the GitHub repository. + +""" + +import itertools +import math + +import numpy as np + + +def _moments_raw_to_central_fast(moments_raw): + """Analytical formulae for 2D and 3D central moments of order < 4. + + `moments_raw_to_central` will automatically call this function when + ndim < 4 and order < 4. + + Parameters + ---------- + moments_raw : ndarray + The raw moments. + + Returns + ------- + moments_central : ndarray + The central moments. + """ + ndim = moments_raw.ndim + order = moments_raw.shape[0] - 1 + float_dtype = moments_raw.dtype + # convert to float64 during the computation for better accuracy + moments_raw = moments_raw.astype(np.float64, copy=False) + moments_central = np.zeros_like(moments_raw) + if order >= 4 or ndim not in [2, 3]: + raise ValueError("This function only supports 2D or 3D moments of order < 4.") + m = moments_raw + if ndim == 2: + cx = m[1, 0] / m[0, 0] + cy = m[0, 1] / m[0, 0] + moments_central[0, 0] = m[0, 0] + # Note: 1st order moments are both 0 + if order > 1: + # 2nd order moments + moments_central[1, 1] = m[1, 1] - cx * m[0, 1] + moments_central[2, 0] = m[2, 0] - cx * m[1, 0] + moments_central[0, 2] = m[0, 2] - cy * m[0, 1] + if order > 2: + # 3rd order moments + moments_central[2, 1] = ( + m[2, 1] + - 2 * cx * m[1, 1] + - cy * m[2, 0] + + cx**2 * m[0, 1] + + cy * cx * m[1, 0] + ) + moments_central[1, 2] = ( + m[1, 2] - 2 * cy * m[1, 1] - cx * m[0, 2] + 2 * cy * cx * m[0, 1] + ) + moments_central[3, 0] = m[3, 0] - 3 * cx * m[2, 0] + 2 * cx**2 * m[1, 0] + moments_central[0, 3] = m[0, 3] - 3 * cy * m[0, 2] + 2 * cy**2 * m[0, 1] + else: + # 3D case + cx = m[1, 0, 0] / m[0, 0, 0] + cy = m[0, 1, 0] / m[0, 0, 0] + cz = m[0, 0, 1] / m[0, 0, 0] + moments_central[0, 0, 0] = m[0, 0, 0] + # Note: all first order moments are 0 + if order > 1: + # 2nd order moments + moments_central[0, 0, 2] = -cz * m[0, 0, 1] + m[0, 0, 2] + moments_central[0, 1, 1] = -cy * m[0, 0, 1] + m[0, 1, 1] + moments_central[0, 2, 0] = -cy * m[0, 1, 0] + m[0, 2, 0] + moments_central[1, 0, 1] = -cx * m[0, 0, 1] + m[1, 0, 1] + moments_central[1, 1, 0] = -cx * m[0, 1, 0] + m[1, 1, 0] + moments_central[2, 0, 0] = -cx * m[1, 0, 0] + m[2, 0, 0] + if order > 2: + # 3rd order moments + moments_central[0, 0, 3] = ( + 2 * cz**2 * m[0, 0, 1] - 3 * cz * m[0, 0, 2] + m[0, 0, 3] + ) + moments_central[0, 1, 2] = ( + -cy * m[0, 0, 2] + 2 * cz * (cy * m[0, 0, 1] - m[0, 1, 1]) + m[0, 1, 2] + ) + moments_central[0, 2, 1] = ( + cy**2 * m[0, 0, 1] + - 2 * cy * m[0, 1, 1] + + cz * (cy * m[0, 1, 0] - m[0, 2, 0]) + + m[0, 2, 1] + ) + moments_central[0, 3, 0] = ( + 2 * cy**2 * m[0, 1, 0] - 3 * cy * m[0, 2, 0] + m[0, 3, 0] + ) + moments_central[1, 0, 2] = ( + -cx * m[0, 0, 2] + 2 * cz * (cx * m[0, 0, 1] - m[1, 0, 1]) + m[1, 0, 2] + ) + moments_central[1, 1, 1] = ( + -cx * m[0, 1, 1] + + cy * (cx * m[0, 0, 1] - m[1, 0, 1]) + + cz * (cx * m[0, 1, 0] - m[1, 1, 0]) + + m[1, 1, 1] + ) + moments_central[1, 2, 0] = ( + -cx * m[0, 2, 0] - 2 * cy * (-cx * m[0, 1, 0] + m[1, 1, 0]) + m[1, 2, 0] + ) + moments_central[2, 0, 1] = ( + cx**2 * m[0, 0, 1] + - 2 * cx * m[1, 0, 1] + + cz * (cx * m[1, 0, 0] - m[2, 0, 0]) + + m[2, 0, 1] + ) + moments_central[2, 1, 0] = ( + cx**2 * m[0, 1, 0] + - 2 * cx * m[1, 1, 0] + + cy * (cx * m[1, 0, 0] - m[2, 0, 0]) + + m[2, 1, 0] + ) + moments_central[3, 0, 0] = ( + 2 * cx**2 * m[1, 0, 0] - 3 * cx * m[2, 0, 0] + m[3, 0, 0] + ) + + return moments_central.astype(float_dtype, copy=False) + + +def moments_raw_to_central(moments_raw): + ndim = moments_raw.ndim + order = moments_raw.shape[0] - 1 + if ndim in [2, 3] and order < 4: + return _moments_raw_to_central_fast(moments_raw) + + moments_central = np.zeros_like(moments_raw) + m = moments_raw + # centers as computed in centroid above + centers = tuple(m[tuple(np.eye(ndim, dtype=int))] / m[(0,) * ndim]) + + if ndim == 2: + # This is the general 2D formula from + # https://en.wikipedia.org/wiki/Image_moment#Central_moments + for p in range(order + 1): + for q in range(order + 1): + if p + q > order: + continue + for i in range(p + 1): + term1 = math.comb(p, i) + term1 *= (-centers[0]) ** (p - i) + for j in range(q + 1): + term2 = math.comb(q, j) + term2 *= (-centers[1]) ** (q - j) + moments_central[p, q] += term1 * term2 * m[i, j] + return moments_central + + # The nested loops below are an n-dimensional extension of the 2D formula + # given at https://en.wikipedia.org/wiki/Image_moment#Central_moments + + # iterate over all [0, order] (inclusive) on each axis + for orders in itertools.product(*((range(order + 1),) * ndim)): + # `orders` here is the index into the `moments_central` output array + if sum(orders) > order: + # skip any moment that is higher than the requested order + continue + # loop over terms from `m` contributing to `moments_central[orders]` + for idxs in itertools.product(*[range(o + 1) for o in orders]): + val = m[idxs] + for i_order, c, idx in zip(orders, centers, idxs): + val *= math.comb(i_order, idx) + val *= (-c) ** (i_order - idx) + moments_central[orders] += val + + return moments_central diff --git a/python_embeded/Lib/site-packages/skimage/measure/_moments_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/measure/_moments_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..bd6bf03bcfb5f85f7c147d67a2ea45d12ccf531e Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/measure/_moments_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/measure/_pnpoly.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/measure/_pnpoly.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..caafa2d6f940d553dc81c60d43bbd10b81c1aba9 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/measure/_pnpoly.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/measure/_polygon.py b/python_embeded/Lib/site-packages/skimage/measure/_polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..0c9057f4dfd23469cac4ac5346a33b077a5d6a0b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_polygon.py @@ -0,0 +1,168 @@ +import numpy as np +from scipy import signal + + +def approximate_polygon(coords, tolerance): + """Approximate a polygonal chain with the specified tolerance. + + It is based on the Douglas-Peucker algorithm. + + Note that the approximated polygon is always within the convex hull of the + original polygon. + + Parameters + ---------- + coords : (K, 2) array + Coordinate array. + tolerance : float + Maximum distance from original points of polygon to approximated + polygonal chain. If tolerance is 0, the original coordinate array + is returned. + + Returns + ------- + coords : (L, 2) array + Approximated polygonal chain where L <= K. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm + """ + if tolerance <= 0: + return coords + + chain = np.zeros(coords.shape[0], 'bool') + # pre-allocate distance array for all points + dists = np.zeros(coords.shape[0]) + chain[0] = True + chain[-1] = True + pos_stack = [(0, chain.shape[0] - 1)] + end_of_chain = False + + while not end_of_chain: + start, end = pos_stack.pop() + # determine properties of current line segment + r0, c0 = coords[start, :] + r1, c1 = coords[end, :] + dr = r1 - r0 + dc = c1 - c0 + segment_angle = -np.arctan2(dr, dc) + segment_dist = c0 * np.sin(segment_angle) + r0 * np.cos(segment_angle) + + # select points in-between line segment + segment_coords = coords[start + 1 : end, :] + segment_dists = dists[start + 1 : end] + + # check whether to take perpendicular or euclidean distance with + # inner product of vectors + + # vectors from points -> start and end + dr0 = segment_coords[:, 0] - r0 + dc0 = segment_coords[:, 1] - c0 + dr1 = segment_coords[:, 0] - r1 + dc1 = segment_coords[:, 1] - c1 + # vectors points -> start and end projected on start -> end vector + projected_lengths0 = dr0 * dr + dc0 * dc + projected_lengths1 = -dr1 * dr - dc1 * dc + perp = np.logical_and(projected_lengths0 > 0, projected_lengths1 > 0) + eucl = np.logical_not(perp) + segment_dists[perp] = np.abs( + segment_coords[perp, 0] * np.cos(segment_angle) + + segment_coords[perp, 1] * np.sin(segment_angle) + - segment_dist + ) + segment_dists[eucl] = np.minimum( + # distance to start point + np.sqrt(dc0[eucl] ** 2 + dr0[eucl] ** 2), + # distance to end point + np.sqrt(dc1[eucl] ** 2 + dr1[eucl] ** 2), + ) + + if np.any(segment_dists > tolerance): + # select point with maximum distance to line + new_end = start + np.argmax(segment_dists) + 1 + pos_stack.append((new_end, end)) + pos_stack.append((start, new_end)) + chain[new_end] = True + + if len(pos_stack) == 0: + end_of_chain = True + + return coords[chain, :] + + +# B-Spline subdivision +_SUBDIVISION_MASKS = { + # degree: (mask_even, mask_odd) + # extracted from (degree + 2)th row of Pascal's triangle + 1: ([1, 1], [1, 1]), + 2: ([3, 1], [1, 3]), + 3: ([1, 6, 1], [0, 4, 4]), + 4: ([5, 10, 1], [1, 10, 5]), + 5: ([1, 15, 15, 1], [0, 6, 20, 6]), + 6: ([7, 35, 21, 1], [1, 21, 35, 7]), + 7: ([1, 28, 70, 28, 1], [0, 8, 56, 56, 8]), +} + + +def subdivide_polygon(coords, degree=2, preserve_ends=False): + """Subdivision of polygonal curves using B-Splines. + + Note that the resulting curve is always within the convex hull of the + original polygon. Circular polygons stay closed after subdivision. + + Parameters + ---------- + coords : (K, 2) array + Coordinate array. + degree : {1, 2, 3, 4, 5, 6, 7}, optional + Degree of B-Spline. Default is 2. + preserve_ends : bool, optional + Preserve first and last coordinate of non-circular polygon. Default is + False. + + Returns + ------- + coords : (L, 2) array + Subdivided coordinate array. + + References + ---------- + .. [1] http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf + """ + if degree not in _SUBDIVISION_MASKS: + raise ValueError("Invalid B-Spline degree. Only degree 1 - 7 is " "supported.") + + circular = np.all(coords[0, :] == coords[-1, :]) + + method = 'valid' + if circular: + # remove last coordinate because of wrapping + coords = coords[:-1, :] + # circular convolution by wrapping boundaries + method = 'same' + + mask_even, mask_odd = _SUBDIVISION_MASKS[degree] + # divide by total weight + mask_even = np.array(mask_even, float) / (2**degree) + mask_odd = np.array(mask_odd, float) / (2**degree) + + even = signal.convolve2d( + coords.T, np.atleast_2d(mask_even), mode=method, boundary='wrap' + ) + odd = signal.convolve2d( + coords.T, np.atleast_2d(mask_odd), mode=method, boundary='wrap' + ) + + out = np.zeros((even.shape[1] + odd.shape[1], 2)) + out[1::2] = even.T + out[::2] = odd.T + + if circular: + # close polygon + out = np.vstack([out, out[0, :]]) + + if preserve_ends and not circular: + out = np.vstack([coords[0, :], out, coords[-1, :]]) + + return out diff --git a/python_embeded/Lib/site-packages/skimage/measure/_regionprops.py b/python_embeded/Lib/site-packages/skimage/measure/_regionprops.py new file mode 100644 index 0000000000000000000000000000000000000000..31a378f15792b4e8f482b008f8083a451964ff18 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_regionprops.py @@ -0,0 +1,1437 @@ +import inspect +import sys +from functools import wraps +from math import atan2 +from math import pi as PI +from math import sqrt +from warnings import warn + +import numpy as np +from scipy import ndimage as ndi +from scipy.spatial.distance import pdist + +from . import _moments +from ._find_contours import find_contours +from ._marching_cubes_lewiner import marching_cubes +from ._regionprops_utils import ( + euler_number, + perimeter, + perimeter_crofton, + _normalize_spacing, +) + +__all__ = ['regionprops', 'euler_number', 'perimeter', 'perimeter_crofton'] + + +# All values in this PROPS dict correspond to current scikit-image property +# names. The keys in this PROPS dict correspond to older names used in prior +# releases. For backwards compatibility, these older names will continue to +# work, but will not be documented. +PROPS = { + 'Area': 'area', + 'BoundingBox': 'bbox', + 'BoundingBoxArea': 'area_bbox', + 'bbox_area': 'area_bbox', + 'CentralMoments': 'moments_central', + 'Centroid': 'centroid', + 'ConvexArea': 'area_convex', + 'convex_area': 'area_convex', + # 'ConvexHull', + 'ConvexImage': 'image_convex', + 'convex_image': 'image_convex', + 'Coordinates': 'coords', + 'Eccentricity': 'eccentricity', + 'EquivDiameter': 'equivalent_diameter_area', + 'equivalent_diameter': 'equivalent_diameter_area', + 'EulerNumber': 'euler_number', + 'Extent': 'extent', + # 'Extrema', + 'FeretDiameter': 'feret_diameter_max', + 'FeretDiameterMax': 'feret_diameter_max', + 'FilledArea': 'area_filled', + 'filled_area': 'area_filled', + 'FilledImage': 'image_filled', + 'filled_image': 'image_filled', + 'HuMoments': 'moments_hu', + 'Image': 'image', + 'InertiaTensor': 'inertia_tensor', + 'InertiaTensorEigvals': 'inertia_tensor_eigvals', + 'IntensityImage': 'image_intensity', + 'intensity_image': 'image_intensity', + 'Label': 'label', + 'LocalCentroid': 'centroid_local', + 'local_centroid': 'centroid_local', + 'MajorAxisLength': 'axis_major_length', + 'major_axis_length': 'axis_major_length', + 'MaxIntensity': 'intensity_max', + 'max_intensity': 'intensity_max', + 'MeanIntensity': 'intensity_mean', + 'mean_intensity': 'intensity_mean', + 'MinIntensity': 'intensity_min', + 'min_intensity': 'intensity_min', + 'std_intensity': 'intensity_std', + 'MinorAxisLength': 'axis_minor_length', + 'minor_axis_length': 'axis_minor_length', + 'Moments': 'moments', + 'NormalizedMoments': 'moments_normalized', + 'Orientation': 'orientation', + 'Perimeter': 'perimeter', + 'CroftonPerimeter': 'perimeter_crofton', + # 'PixelIdxList', + # 'PixelList', + 'Slice': 'slice', + 'Solidity': 'solidity', + # 'SubarrayIdx' + 'WeightedCentralMoments': 'moments_weighted_central', + 'weighted_moments_central': 'moments_weighted_central', + 'WeightedCentroid': 'centroid_weighted', + 'weighted_centroid': 'centroid_weighted', + 'WeightedHuMoments': 'moments_weighted_hu', + 'weighted_moments_hu': 'moments_weighted_hu', + 'WeightedLocalCentroid': 'centroid_weighted_local', + 'weighted_local_centroid': 'centroid_weighted_local', + 'WeightedMoments': 'moments_weighted', + 'weighted_moments': 'moments_weighted', + 'WeightedNormalizedMoments': 'moments_weighted_normalized', + 'weighted_moments_normalized': 'moments_weighted_normalized', +} + +COL_DTYPES = { + 'area': float, + 'area_bbox': float, + 'area_convex': float, + 'area_filled': float, + 'axis_major_length': float, + 'axis_minor_length': float, + 'bbox': int, + 'centroid': float, + 'centroid_local': float, + 'centroid_weighted': float, + 'centroid_weighted_local': float, + 'coords': object, + 'coords_scaled': object, + 'eccentricity': float, + 'equivalent_diameter_area': float, + 'euler_number': int, + 'extent': float, + 'feret_diameter_max': float, + 'image': object, + 'image_convex': object, + 'image_filled': object, + 'image_intensity': object, + 'inertia_tensor': float, + 'inertia_tensor_eigvals': float, + 'intensity_max': float, + 'intensity_mean': float, + 'intensity_min': float, + 'intensity_std': float, + 'label': int, + 'moments': float, + 'moments_central': float, + 'moments_hu': float, + 'moments_normalized': float, + 'moments_weighted': float, + 'moments_weighted_central': float, + 'moments_weighted_hu': float, + 'moments_weighted_normalized': float, + 'num_pixels': int, + 'orientation': float, + 'perimeter': float, + 'perimeter_crofton': float, + 'slice': object, + 'solidity': float, +} + +OBJECT_COLUMNS = [col for col, dtype in COL_DTYPES.items() if dtype == object] + +PROP_VALS = set(PROPS.values()) + +_require_intensity_image = ( + 'image_intensity', + 'intensity_max', + 'intensity_mean', + 'intensity_min', + 'intensity_std', + 'moments_weighted', + 'moments_weighted_central', + 'centroid_weighted', + 'centroid_weighted_local', + 'moments_weighted_hu', + 'moments_weighted_normalized', +) + + +def _infer_number_of_required_args(func): + """Infer the number of required arguments for a function + + Parameters + ---------- + func : callable + The function that is being inspected. + + Returns + ------- + n_args : int + The number of required arguments of func. + """ + argspec = inspect.getfullargspec(func) + n_args = len(argspec.args) + if argspec.defaults is not None: + n_args -= len(argspec.defaults) + return n_args + + +def _infer_regionprop_dtype(func, *, intensity, ndim): + """Infer the dtype of a region property calculated by func. + + If a region property function always returns the same shape and type of + output regardless of input size, then the dtype is the dtype of the + returned array. Otherwise, the property has object dtype. + + Parameters + ---------- + func : callable + Function to be tested. The signature should be array[bool] -> Any if + intensity is False, or *(array[bool], array[float]) -> Any otherwise. + intensity : bool + Whether the regionprop is calculated on an intensity image. + ndim : int + The number of dimensions for which to check func. + + Returns + ------- + dtype : NumPy data type + The data type of the returned property. + """ + mask_1 = np.ones((1,) * ndim, dtype=bool) + mask_1 = np.pad(mask_1, (0, 1), constant_values=False) + mask_2 = np.ones((2,) * ndim, dtype=bool) + mask_2 = np.pad(mask_2, (1, 0), constant_values=False) + propmasks = [mask_1, mask_2] + + rng = np.random.default_rng() + + if intensity and _infer_number_of_required_args(func) == 2: + + def _func(mask): + return func(mask, rng.random(mask.shape)) + + else: + _func = func + props1, props2 = map(_func, propmasks) + if ( + np.isscalar(props1) + and np.isscalar(props2) + or np.array(props1).shape == np.array(props2).shape + ): + dtype = np.array(props1).dtype.type + else: + dtype = np.object_ + return dtype + + +def _cached(f): + @wraps(f) + def wrapper(obj): + cache = obj._cache + prop = f.__name__ + + if not obj._cache_active: + return f(obj) + + if prop not in cache: + cache[prop] = f(obj) + + return cache[prop] + + return wrapper + + +def only2d(method): + @wraps(method) + def func2d(self, *args, **kwargs): + if self._ndim > 2: + raise NotImplementedError( + f"Property {method.__name__} is not implemented for 3D images" + ) + return method(self, *args, **kwargs) + + return func2d + + +def _inertia_eigvals_to_axes_lengths_3D(inertia_tensor_eigvals): + """Compute ellipsoid axis lengths from inertia tensor eigenvalues. + + Parameters + --------- + inertia_tensor_eigvals : sequence of float + A sequence of 3 floating point eigenvalues, sorted in descending order. + + Returns + ------- + axis_lengths : list of float + The ellipsoid axis lengths sorted in descending order. + + Notes + ----- + Let a >= b >= c be the ellipsoid semi-axes and s1 >= s2 >= s3 be the + inertia tensor eigenvalues. + + The inertia tensor eigenvalues are given for a solid ellipsoid in [1]_. + s1 = 1 / 5 * (a**2 + b**2) + s2 = 1 / 5 * (a**2 + c**2) + s3 = 1 / 5 * (b**2 + c**2) + + Rearranging to solve for a, b, c in terms of s1, s2, s3 gives + a = math.sqrt(5 / 2 * ( s1 + s2 - s3)) + b = math.sqrt(5 / 2 * ( s1 - s2 + s3)) + c = math.sqrt(5 / 2 * (-s1 + s2 + s3)) + + We can then simply replace sqrt(5/2) by sqrt(10) to get the full axes + lengths rather than the semi-axes lengths. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors + """ + axis_lengths = [] + for ax in range(2, -1, -1): + w = sum(v * -1 if i == ax else v for i, v in enumerate(inertia_tensor_eigvals)) + axis_lengths.append(sqrt(10 * w)) + return axis_lengths + + +class RegionProperties: + """Please refer to `skimage.measure.regionprops` for more information + on the available region properties. + """ + + def __init__( + self, + slice, + label, + label_image, + intensity_image, + cache_active, + *, + extra_properties=None, + spacing=None, + offset=None, + ): + if intensity_image is not None: + ndim = label_image.ndim + if not ( + intensity_image.shape[:ndim] == label_image.shape + and intensity_image.ndim in [ndim, ndim + 1] + ): + raise ValueError( + 'Label and intensity image shapes must match,' + ' except for channel (last) axis.' + ) + multichannel = label_image.shape < intensity_image.shape + else: + multichannel = False + + self.label = label + if offset is None: + offset = np.zeros((label_image.ndim,), dtype=int) + self._offset = np.array(offset) + + self._slice = slice + self.slice = slice + self._label_image = label_image + self._intensity_image = intensity_image + + self._cache_active = cache_active + self._cache = {} + self._ndim = label_image.ndim + self._multichannel = multichannel + self._spatial_axes = tuple(range(self._ndim)) + if spacing is None: + spacing = np.full(self._ndim, 1.0) + self._spacing = _normalize_spacing(spacing, self._ndim) + self._pixel_area = np.prod(self._spacing) + + self._extra_properties = {} + if extra_properties is not None: + for func in extra_properties: + name = func.__name__ + if hasattr(self, name): + msg = ( + f"Extra property '{name}' is shadowed by existing " + f"property and will be inaccessible. Consider " + f"renaming it." + ) + warn(msg) + self._extra_properties = {func.__name__: func for func in extra_properties} + + def __getattr__(self, attr): + if attr == "__setstate__": + # When deserializing this object with pickle, `__setstate__` + # is accessed before any other attributes like `self._intensity_image` + # are available which leads to a RecursionError when trying to + # access them later on in this function. So guard against this by + # provoking the default AttributeError (gh-6465). + return self.__getattribute__(attr) + + if self._intensity_image is None and attr in _require_intensity_image: + raise AttributeError( + f"Attribute '{attr}' unavailable when `intensity_image` " + f"has not been specified." + ) + if attr in self._extra_properties: + func = self._extra_properties[attr] + n_args = _infer_number_of_required_args(func) + # determine whether func requires intensity image + if n_args == 2: + if self._intensity_image is not None: + if self._multichannel: + multichannel_list = [ + func(self.image, self.image_intensity[..., i]) + for i in range(self.image_intensity.shape[-1]) + ] + return np.stack(multichannel_list, axis=-1) + else: + return func(self.image, self.image_intensity) + else: + raise AttributeError( + f'intensity image required to calculate {attr}' + ) + elif n_args == 1: + return func(self.image) + else: + raise AttributeError( + f'Custom regionprop function\'s number of arguments must ' + f'be 1 or 2, but {attr} takes {n_args} arguments.' + ) + elif attr in PROPS and attr.lower() == attr: + if ( + self._intensity_image is None + and PROPS[attr] in _require_intensity_image + ): + raise AttributeError( + f"Attribute '{attr}' unavailable when `intensity_image` " + f"has not been specified." + ) + # retrieve deprecated property (excluding old CamelCase ones) + return getattr(self, PROPS[attr]) + else: + raise AttributeError(f"'{type(self)}' object has no attribute '{attr}'") + + def __setattr__(self, name, value): + if name in PROPS: + super().__setattr__(PROPS[name], value) + else: + super().__setattr__(name, value) + + @property + @_cached + def num_pixels(self): + return np.sum(self.image) + + @property + @_cached + def area(self): + return np.sum(self.image) * self._pixel_area + + @property + def bbox(self): + """ + Returns + ------- + A tuple of the bounding box's start coordinates for each dimension, + followed by the end coordinates for each dimension + """ + return tuple( + [self.slice[i].start for i in range(self._ndim)] + + [self.slice[i].stop for i in range(self._ndim)] + ) + + @property + def area_bbox(self): + return self.image.size * self._pixel_area + + @property + def centroid(self): + return tuple(self.coords_scaled.mean(axis=0)) + + @property + @_cached + def area_convex(self): + return np.sum(self.image_convex) * self._pixel_area + + @property + @_cached + def image_convex(self): + from ..morphology.convex_hull import convex_hull_image + + return convex_hull_image(self.image) + + @property + def coords_scaled(self): + indices = np.argwhere(self.image) + object_offset = np.array([self.slice[i].start for i in range(self._ndim)]) + return (object_offset + indices) * self._spacing + self._offset + + @property + def coords(self): + indices = np.argwhere(self.image) + object_offset = np.array([self.slice[i].start for i in range(self._ndim)]) + return object_offset + indices + self._offset + + @property + @only2d + def eccentricity(self): + l1, l2 = self.inertia_tensor_eigvals + if l1 == 0: + return 0 + return sqrt(1 - l2 / l1) + + @property + def equivalent_diameter_area(self): + return (2 * self._ndim * self.area / PI) ** (1 / self._ndim) + + @property + def euler_number(self): + if self._ndim not in [2, 3]: + raise NotImplementedError( + 'Euler number is implemented for ' '2D or 3D images only' + ) + return euler_number(self.image, self._ndim) + + @property + def extent(self): + return self.area / self.area_bbox + + @property + def feret_diameter_max(self): + identity_convex_hull = np.pad( + self.image_convex, 2, mode='constant', constant_values=0 + ) + if self._ndim == 2: + coordinates = np.vstack( + find_contours(identity_convex_hull, 0.5, fully_connected='high') + ) + elif self._ndim == 3: + coordinates, _, _, _ = marching_cubes(identity_convex_hull, level=0.5) + distances = pdist(coordinates * self._spacing, 'sqeuclidean') + return sqrt(np.max(distances)) + + @property + def area_filled(self): + return np.sum(self.image_filled) * self._pixel_area + + @property + @_cached + def image_filled(self): + structure = np.ones((3,) * self._ndim) + return ndi.binary_fill_holes(self.image, structure) + + @property + @_cached + def image(self): + return self._label_image[self.slice] == self.label + + @property + @_cached + def inertia_tensor(self): + mu = self.moments_central + return _moments.inertia_tensor(self.image, mu, spacing=self._spacing) + + @property + @_cached + def inertia_tensor_eigvals(self): + return _moments.inertia_tensor_eigvals(self.image, T=self.inertia_tensor) + + @property + @_cached + def image_intensity(self): + if self._intensity_image is None: + raise AttributeError('No intensity image specified.') + image = ( + self.image + if not self._multichannel + else np.expand_dims(self.image, self._ndim) + ) + return self._intensity_image[self.slice] * image + + def _image_intensity_double(self): + return self.image_intensity.astype(np.float64, copy=False) + + @property + def centroid_local(self): + M = self.moments + M0 = M[(0,) * self._ndim] + + def _get_element(axis): + return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis) + + return np.asarray( + tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim)) + ) + + @property + def intensity_max(self): + vals = self.image_intensity[self.image] + return np.max(vals, axis=0).astype(np.float64, copy=False) + + @property + def intensity_mean(self): + return np.mean(self.image_intensity[self.image], axis=0) + + @property + def intensity_min(self): + vals = self.image_intensity[self.image] + return np.min(vals, axis=0).astype(np.float64, copy=False) + + @property + def intensity_std(self): + vals = self.image_intensity[self.image] + return np.std(vals, axis=0) + + @property + def axis_major_length(self): + if self._ndim == 2: + l1 = self.inertia_tensor_eigvals[0] + return 4 * sqrt(l1) + elif self._ndim == 3: + # equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[0] + ev = self.inertia_tensor_eigvals + return sqrt(10 * (ev[0] + ev[1] - ev[2])) + else: + raise ValueError("axis_major_length only available in 2D and 3D") + + @property + def axis_minor_length(self): + if self._ndim == 2: + l2 = self.inertia_tensor_eigvals[-1] + return 4 * sqrt(l2) + elif self._ndim == 3: + # equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[-1] + ev = self.inertia_tensor_eigvals + return sqrt(10 * (-ev[0] + ev[1] + ev[2])) + else: + raise ValueError("axis_minor_length only available in 2D and 3D") + + @property + @_cached + def moments(self): + M = _moments.moments(self.image.astype(np.uint8), 3, spacing=self._spacing) + return M + + @property + @_cached + def moments_central(self): + mu = _moments.moments_central( + self.image.astype(np.uint8), + self.centroid_local, + order=3, + spacing=self._spacing, + ) + return mu + + @property + @only2d + def moments_hu(self): + if any(s != 1.0 for s in self._spacing): + raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only') + return _moments.moments_hu(self.moments_normalized) + + @property + @_cached + def moments_normalized(self): + return _moments.moments_normalized( + self.moments_central, 3, spacing=self._spacing + ) + + @property + @only2d + def orientation(self): + a, b, b, c = self.inertia_tensor.flat + if a - c == 0: + if b < 0: + return PI / 4.0 + else: + return -PI / 4.0 + else: + return 0.5 * atan2(-2 * b, c - a) + + @property + @only2d + def perimeter(self): + if len(np.unique(self._spacing)) != 1: + raise NotImplementedError('`perimeter` supports isotropic spacings only') + return perimeter(self.image, 4) * self._spacing[0] + + @property + @only2d + def perimeter_crofton(self): + if len(np.unique(self._spacing)) != 1: + raise NotImplementedError('`perimeter` supports isotropic spacings only') + return perimeter_crofton(self.image, 4) * self._spacing[0] + + @property + def solidity(self): + return self.area / self.area_convex + + @property + def centroid_weighted(self): + ctr = self.centroid_weighted_local + return tuple( + idx + slc.start * spc + for idx, slc, spc in zip(ctr, self.slice, self._spacing) + ) + + @property + def centroid_weighted_local(self): + M = self.moments_weighted + M0 = M[(0,) * self._ndim] + + def _get_element(axis): + return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis) + + return np.asarray( + tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim)) + ) + + @property + @_cached + def moments_weighted(self): + image = self._image_intensity_double() + if self._multichannel: + moments = np.stack( + [ + _moments.moments(image[..., i], order=3, spacing=self._spacing) + for i in range(image.shape[-1]) + ], + axis=-1, + ) + else: + moments = _moments.moments(image, order=3, spacing=self._spacing) + return moments + + @property + @_cached + def moments_weighted_central(self): + ctr = self.centroid_weighted_local + image = self._image_intensity_double() + if self._multichannel: + moments_list = [ + _moments.moments_central( + image[..., i], center=ctr[..., i], order=3, spacing=self._spacing + ) + for i in range(image.shape[-1]) + ] + moments = np.stack(moments_list, axis=-1) + else: + moments = _moments.moments_central( + image, ctr, order=3, spacing=self._spacing + ) + return moments + + @property + @only2d + def moments_weighted_hu(self): + if not (np.array(self._spacing) == np.array([1, 1])).all(): + raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only') + nu = self.moments_weighted_normalized + if self._multichannel: + nchannels = self._intensity_image.shape[-1] + return np.stack( + [_moments.moments_hu(nu[..., i]) for i in range(nchannels)], + axis=-1, + ) + else: + return _moments.moments_hu(nu) + + @property + @_cached + def moments_weighted_normalized(self): + mu = self.moments_weighted_central + if self._multichannel: + nchannels = self._intensity_image.shape[-1] + return np.stack( + [ + _moments.moments_normalized( + mu[..., i], order=3, spacing=self._spacing + ) + for i in range(nchannels) + ], + axis=-1, + ) + else: + return _moments.moments_normalized(mu, order=3, spacing=self._spacing) + + def __iter__(self): + props = PROP_VALS + + if self._intensity_image is None: + unavailable_props = _require_intensity_image + props = props.difference(unavailable_props) + + return iter(sorted(props)) + + def __getitem__(self, key): + value = getattr(self, key, None) + if value is not None: + return value + else: # backwards compatibility + return getattr(self, PROPS[key]) + + def __eq__(self, other): + if not isinstance(other, RegionProperties): + return False + + for key in PROP_VALS: + try: + # so that NaNs are equal + np.testing.assert_equal( + getattr(self, key, None), getattr(other, key, None) + ) + except AssertionError: + return False + + return True + + +# For compatibility with code written prior to 0.16 +_RegionProperties = RegionProperties + + +def _props_to_dict(regions, properties=('label', 'bbox'), separator='-'): + """Convert image region properties list into a column dictionary. + + Parameters + ---------- + regions : (K,) list + List of RegionProperties objects as returned by :func:`regionprops`. + properties : tuple or list of str, optional + Properties that will be included in the resulting dictionary + For a list of available properties, please see :func:`regionprops`. + Users should remember to add "label" to keep track of region + identities. + separator : str, optional + For non-scalar properties not listed in OBJECT_COLUMNS, each element + will appear in its own column, with the index of that element separated + from the property name by this separator. For example, the inertia + tensor of a 2D region will appear in four columns: + ``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``, + and ``inertia_tensor-1-1`` (where the separator is ``-``). + + Object columns are those that cannot be split in this way because the + number of columns would change depending on the object. For example, + ``image`` and ``coords``. + + Returns + ------- + out_dict : dict + Dictionary mapping property names to an array of values of that + property, one value per region. This dictionary can be used as input to + pandas ``DataFrame`` to map property names to columns in the frame and + regions to rows. + + Notes + ----- + Each column contains either a scalar property, an object property, or an + element in a multidimensional array. + + Properties with scalar values for each region, such as "eccentricity", will + appear as a float or int array with that property name as key. + + Multidimensional properties *of fixed size* for a given image dimension, + such as "centroid" (every centroid will have three elements in a 3D image, + no matter the region size), will be split into that many columns, with the + name {property_name}{separator}{element_num} (for 1D properties), + {property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D + properties), and so on. + + For multidimensional properties that don't have a fixed size, such as + "image" (the image of a region varies in size depending on the region + size), an object array will be used, with the corresponding property name + as the key. + + Examples + -------- + >>> from skimage import data, util, measure + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> proplist = regionprops(label_image, image) + >>> props = _props_to_dict(proplist, properties=['label', 'inertia_tensor', + ... 'inertia_tensor_eigvals']) + >>> props # doctest: +ELLIPSIS +SKIP + {'label': array([ 1, 2, ...]), ... + 'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ... + ..., + 'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])} + + The resulting dictionary can be directly passed to pandas, if installed, to + obtain a clean DataFrame: + + >>> import pandas as pd # doctest: +SKIP + >>> data = pd.DataFrame(props) # doctest: +SKIP + >>> data.head() # doctest: +SKIP + label inertia_tensor-0-0 ... inertia_tensor_eigvals-1 + 0 1 4012.909888 ... 267.065503 + 1 2 8.514739 ... 2.834806 + 2 3 0.666667 ... 0.000000 + 3 4 0.000000 ... 0.000000 + 4 5 0.222222 ... 0.111111 + + """ + + out = {} + n = len(regions) + for prop in properties: + r = regions[0] + # Copy the original property name so the output will have the + # user-provided property name in the case of deprecated names. + orig_prop = prop + # determine the current property name for any deprecated property. + prop = PROPS.get(prop, prop) + rp = getattr(r, prop) + if prop in COL_DTYPES: + dtype = COL_DTYPES[prop] + else: + func = r._extra_properties[prop] + dtype = _infer_regionprop_dtype( + func, + intensity=r._intensity_image is not None, + ndim=r.image.ndim, + ) + + # scalars and objects are dedicated one column per prop + # array properties are raveled into multiple columns + # for more info, refer to notes 1 + if np.isscalar(rp) or prop in OBJECT_COLUMNS or dtype is np.object_: + column_buffer = np.empty(n, dtype=dtype) + for i in range(n): + column_buffer[i] = regions[i][prop] + out[orig_prop] = np.copy(column_buffer) + else: + # precompute property column names and locations + modified_props = [] + locs = [] + for ind in np.ndindex(np.shape(rp)): + modified_props.append(separator.join(map(str, (orig_prop,) + ind))) + locs.append(ind if len(ind) > 1 else ind[0]) + + # fill temporary column data_array + n_columns = len(locs) + column_data = np.empty((n, n_columns), dtype=dtype) + for k in range(n): + # we coerce to a numpy array to ensure structures like + # tuple-of-arrays expand correctly into columns + rp = np.asarray(regions[k][prop]) + for i, loc in enumerate(locs): + column_data[k, i] = rp[loc] + + # add the columns to the output dictionary + for i, modified_prop in enumerate(modified_props): + out[modified_prop] = column_data[:, i] + return out + + +def regionprops_table( + label_image, + intensity_image=None, + properties=('label', 'bbox'), + *, + cache=True, + separator='-', + extra_properties=None, + spacing=None, +): + """Compute image properties and return them as a pandas-compatible table. + + The table is a dictionary mapping column names to value arrays. See Notes + section below for details. + + .. versionadded:: 0.16 + + Parameters + ---------- + label_image : (M, N[, P]) ndarray + Labeled input image. Labels with value 0 are ignored. + intensity_image : (M, N[, P][, C]) ndarray, optional + Intensity (i.e., input) image with same size as labeled image, plus + optionally an extra dimension for multichannel data. The channel dimension, + if present, must be the last axis. Default is None. + + .. versionchanged:: 0.18.0 + The ability to provide an extra dimension for channels was added. + properties : tuple or list of str, optional + Properties that will be included in the resulting dictionary + For a list of available properties, please see :func:`regionprops`. + Users should remember to add "label" to keep track of region + identities. + cache : bool, optional + Determine whether to cache calculated properties. The computation is + much faster for cached properties, whereas the memory consumption + increases. + separator : str, optional + For non-scalar properties not listed in OBJECT_COLUMNS, each element + will appear in its own column, with the index of that element separated + from the property name by this separator. For example, the inertia + tensor of a 2D region will appear in four columns: + ``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``, + and ``inertia_tensor-1-1`` (where the separator is ``-``). + + Object columns are those that cannot be split in this way because the + number of columns would change depending on the object. For example, + ``image`` and ``coords``. + extra_properties : Iterable of callables + Add extra property computation functions that are not included with + skimage. The name of the property is derived from the function name, + the dtype is inferred by calling the function on a small sample. + If the name of an extra property clashes with the name of an existing + property the extra property will not be visible and a UserWarning is + issued. A property computation function must take a region mask as its + first argument. If the property requires an intensity image, it must + accept the intensity image as the second argument. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + out_dict : dict + Dictionary mapping property names to an array of values of that + property, one value per region. This dictionary can be used as input to + pandas ``DataFrame`` to map property names to columns in the frame and + regions to rows. If the image has no regions, + the arrays will have length 0, but the correct type. + + Notes + ----- + Each column contains either a scalar property, an object property, or an + element in a multidimensional array. + + Properties with scalar values for each region, such as "eccentricity", will + appear as a float or int array with that property name as key. + + Multidimensional properties *of fixed size* for a given image dimension, + such as "centroid" (every centroid will have three elements in a 3D image, + no matter the region size), will be split into that many columns, with the + name {property_name}{separator}{element_num} (for 1D properties), + {property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D + properties), and so on. + + For multidimensional properties that don't have a fixed size, such as + "image" (the image of a region varies in size depending on the region + size), an object array will be used, with the corresponding property name + as the key. + + Examples + -------- + >>> from skimage import data, util, measure + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> props = measure.regionprops_table(label_image, image, + ... properties=['label', 'inertia_tensor', + ... 'inertia_tensor_eigvals']) + >>> props # doctest: +ELLIPSIS +SKIP + {'label': array([ 1, 2, ...]), ... + 'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ... + ..., + 'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])} + + The resulting dictionary can be directly passed to pandas, if installed, to + obtain a clean DataFrame: + + >>> import pandas as pd # doctest: +SKIP + >>> data = pd.DataFrame(props) # doctest: +SKIP + >>> data.head() # doctest: +SKIP + label inertia_tensor-0-0 ... inertia_tensor_eigvals-1 + 0 1 4012.909888 ... 267.065503 + 1 2 8.514739 ... 2.834806 + 2 3 0.666667 ... 0.000000 + 3 4 0.000000 ... 0.000000 + 4 5 0.222222 ... 0.111111 + + [5 rows x 7 columns] + + If we want to measure a feature that does not come as a built-in + property, we can define custom functions and pass them as + ``extra_properties``. For example, we can create a custom function + that measures the intensity quartiles in a region: + + >>> from skimage import data, util, measure + >>> import numpy as np + >>> def quartiles(regionmask, intensity): + ... return np.percentile(intensity[regionmask], q=(25, 50, 75)) + >>> + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> props = measure.regionprops_table(label_image, intensity_image=image, + ... properties=('label',), + ... extra_properties=(quartiles,)) + >>> import pandas as pd # doctest: +SKIP + >>> pd.DataFrame(props).head() # doctest: +SKIP + label quartiles-0 quartiles-1 quartiles-2 + 0 1 117.00 123.0 130.0 + 1 2 111.25 112.0 114.0 + 2 3 111.00 111.0 111.0 + 3 4 111.00 111.5 112.5 + 4 5 112.50 113.0 114.0 + + """ + regions = regionprops( + label_image, + intensity_image=intensity_image, + cache=cache, + extra_properties=extra_properties, + spacing=spacing, + ) + if extra_properties is not None: + properties = list(properties) + [prop.__name__ for prop in extra_properties] + if len(regions) == 0: + ndim = label_image.ndim + label_image = np.zeros((3,) * ndim, dtype=int) + label_image[(1,) * ndim] = 1 + if intensity_image is not None: + intensity_image = np.zeros( + label_image.shape + intensity_image.shape[ndim:], + dtype=intensity_image.dtype, + ) + regions = regionprops( + label_image, + intensity_image=intensity_image, + cache=cache, + extra_properties=extra_properties, + spacing=spacing, + ) + + out_d = _props_to_dict(regions, properties=properties, separator=separator) + return {k: v[:0] for k, v in out_d.items()} + + return _props_to_dict(regions, properties=properties, separator=separator) + + +def regionprops( + label_image, + intensity_image=None, + cache=True, + *, + extra_properties=None, + spacing=None, + offset=None, +): + r"""Measure properties of labeled image regions. + + Parameters + ---------- + label_image : (M, N[, P]) ndarray + Labeled input image. Labels with value 0 are ignored. + + .. versionchanged:: 0.14.1 + Previously, ``label_image`` was processed by ``numpy.squeeze`` and + so any number of singleton dimensions was allowed. This resulted in + inconsistent handling of images with singleton dimensions. To + recover the old behaviour, use + ``regionprops(np.squeeze(label_image), ...)``. + intensity_image : (M, N[, P][, C]) ndarray, optional + Intensity (i.e., input) image with same size as labeled image, plus + optionally an extra dimension for multichannel data. Currently, + this extra channel dimension, if present, must be the last axis. + Default is None. + + .. versionchanged:: 0.18.0 + The ability to provide an extra dimension for channels was added. + cache : bool, optional + Determine whether to cache calculated properties. The computation is + much faster for cached properties, whereas the memory consumption + increases. + extra_properties : Iterable of callables + Add extra property computation functions that are not included with + skimage. The name of the property is derived from the function name, + the dtype is inferred by calling the function on a small sample. + If the name of an extra property clashes with the name of an existing + property the extra property will not be visible and a UserWarning is + issued. A property computation function must take a region mask as its + first argument. If the property requires an intensity image, it must + accept the intensity image as the second argument. + spacing: tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + offset : array-like of int, shape `(label_image.ndim,)`, optional + Coordinates of the origin ("top-left" corner) of the label image. + Normally this is ([0, ]0, 0), but it might be different if one wants + to obtain regionprops of subvolumes within a larger volume. + + Returns + ------- + properties : list of RegionProperties + Each item describes one labeled region, and can be accessed using the + attributes listed below. + + Notes + ----- + The following properties can be accessed as attributes or keys: + + **area** : float + Area of the region i.e. number of pixels of the region scaled by pixel-area. + **area_bbox** : float + Area of the bounding box i.e. number of pixels of bounding box scaled by pixel-area. + **area_convex** : float + Area of the convex hull image, which is the smallest convex + polygon that encloses the region. + **area_filled** : float + Area of the region with all the holes filled in. + **axis_major_length** : float + The length of the major axis of the ellipse that has the same + normalized second central moments as the region. + **axis_minor_length** : float + The length of the minor axis of the ellipse that has the same + normalized second central moments as the region. + **bbox** : tuple + Bounding box ``(min_row, min_col, max_row, max_col)``. + Pixels belonging to the bounding box are in the half-open interval + ``[min_row; max_row)`` and ``[min_col; max_col)``. + **centroid** : array + Centroid coordinate tuple ``(row, col)``. + **centroid_local** : array + Centroid coordinate tuple ``(row, col)``, relative to region bounding + box. + **centroid_weighted** : array + Centroid coordinate tuple ``(row, col)`` weighted with intensity + image. + **centroid_weighted_local** : array + Centroid coordinate tuple ``(row, col)``, relative to region bounding + box, weighted with intensity image. + **coords_scaled** : (K, 2) ndarray + Coordinate list ``(row, col)`` of the region scaled by ``spacing``. + **coords** : (K, 2) ndarray + Coordinate list ``(row, col)`` of the region. + **eccentricity** : float + Eccentricity of the ellipse that has the same second-moments as the + region. The eccentricity is the ratio of the focal distance + (distance between focal points) over the major axis length. + The value is in the interval [0, 1). + When it is 0, the ellipse becomes a circle. + **equivalent_diameter_area** : float + The diameter of a circle with the same area as the region. + **euler_number** : int + Euler characteristic of the set of non-zero pixels. + Computed as number of connected components subtracted by number of + holes (input.ndim connectivity). In 3D, number of connected + components plus number of holes subtracted by number of tunnels. + **extent** : float + Ratio of pixels in the region to pixels in the total bounding box. + Computed as ``area / (rows * cols)`` + **feret_diameter_max** : float + Maximum Feret's diameter computed as the longest distance between + points around a region's convex hull contour as determined by + ``find_contours``. [5]_ + **image** : (H, J) ndarray + Sliced binary region image which has the same size as bounding box. + **image_convex** : (H, J) ndarray + Binary convex hull image which has the same size as bounding box. + **image_filled** : (H, J) ndarray + Binary region image with filled holes which has the same size as + bounding box. + **image_intensity** : ndarray + Image inside region bounding box. + **inertia_tensor** : ndarray + Inertia tensor of the region for the rotation around its mass. + **inertia_tensor_eigvals** : tuple + The eigenvalues of the inertia tensor in decreasing order. + **intensity_max** : float + Value with the greatest intensity in the region. + **intensity_mean** : float + Value with the mean intensity in the region. + **intensity_min** : float + Value with the least intensity in the region. + **intensity_std** : float + Standard deviation of the intensity in the region. + **label** : int + The label in the labeled input image. + **moments** : (3, 3) ndarray + Spatial moments up to 3rd order:: + + m_ij = sum{ array(row, col) * row^i * col^j } + + where the sum is over the `row`, `col` coordinates of the region. + **moments_central** : (3, 3) ndarray + Central moments (translation invariant) up to 3rd order:: + + mu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } + + where the sum is over the `row`, `col` coordinates of the region, + and `row_c` and `col_c` are the coordinates of the region's centroid. + **moments_hu** : tuple + Hu moments (translation, scale and rotation invariant). + **moments_normalized** : (3, 3) ndarray + Normalized moments (translation and scale invariant) up to 3rd order:: + + nu_ij = mu_ij / m_00^[(i+j)/2 + 1] + + where `m_00` is the zeroth spatial moment. + **moments_weighted** : (3, 3) ndarray + Spatial moments of intensity image up to 3rd order:: + + wm_ij = sum{ array(row, col) * row^i * col^j } + + where the sum is over the `row`, `col` coordinates of the region. + **moments_weighted_central** : (3, 3) ndarray + Central moments (translation invariant) of intensity image up to + 3rd order:: + + wmu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } + + where the sum is over the `row`, `col` coordinates of the region, + and `row_c` and `col_c` are the coordinates of the region's weighted + centroid. + **moments_weighted_hu** : tuple + Hu moments (translation, scale and rotation invariant) of intensity + image. + **moments_weighted_normalized** : (3, 3) ndarray + Normalized moments (translation and scale invariant) of intensity + image up to 3rd order:: + + wnu_ij = wmu_ij / wm_00^[(i+j)/2 + 1] + + where ``wm_00`` is the zeroth spatial moment (intensity-weighted area). + **num_pixels** : int + Number of foreground pixels. + **orientation** : float + Angle between the 0th axis (rows) and the major + axis of the ellipse that has the same second moments as the region, + ranging from `-pi/2` to `pi/2` counter-clockwise. + **perimeter** : float + Perimeter of object which approximates the contour as a line + through the centers of border pixels using a 4-connectivity. + **perimeter_crofton** : float + Perimeter of object approximated by the Crofton formula in 4 + directions. + **slice** : tuple of slices + A slice to extract the object from the source image. + **solidity** : float + Ratio of pixels in the region to pixels of the convex hull image. + + Each region also supports iteration, so that you can do:: + + for prop in region: + print(prop, region[prop]) + + See Also + -------- + label + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + .. [5] W. Pabst, E. Gregorová. Characterization of particles and particle + systems, pp. 27-28. ICT Prague, 2007. + https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf + + Examples + -------- + >>> from skimage import data, util + >>> from skimage.measure import label, regionprops + >>> img = util.img_as_ubyte(data.coins()) > 110 + >>> label_img = label(img, connectivity=img.ndim) + >>> props = regionprops(label_img) + >>> # centroid of first labeled object + >>> props[0].centroid + (22.72987986048314, 81.91228523446583) + >>> # centroid of first labeled object + >>> props[0]['centroid'] + (22.72987986048314, 81.91228523446583) + + Add custom measurements by passing functions as ``extra_properties`` + + >>> from skimage import data, util + >>> from skimage.measure import label, regionprops + >>> import numpy as np + >>> img = util.img_as_ubyte(data.coins()) > 110 + >>> label_img = label(img, connectivity=img.ndim) + >>> def pixelcount(regionmask): + ... return np.sum(regionmask) + >>> props = regionprops(label_img, extra_properties=(pixelcount,)) + >>> props[0].pixelcount + 7741 + >>> props[1]['pixelcount'] + 42 + + """ + + if label_image.ndim not in (2, 3): + raise TypeError('Only 2-D and 3-D images supported.') + + if not np.issubdtype(label_image.dtype, np.integer): + if np.issubdtype(label_image.dtype, bool): + raise TypeError( + 'Non-integer image types are ambiguous: ' + 'use skimage.measure.label to label the connected ' + 'components of label_image, ' + 'or label_image.astype(np.uint8) to interpret ' + 'the True values as a single label.' + ) + else: + raise TypeError('Non-integer label_image types are ambiguous') + + if offset is None: + offset_arr = np.zeros((label_image.ndim,), dtype=int) + else: + offset_arr = np.asarray(offset) + if offset_arr.ndim != 1 or offset_arr.size != label_image.ndim: + raise ValueError( + 'Offset should be an array-like of integers ' + 'of shape (label_image.ndim,); ' + f'{offset} was provided.' + ) + + regions = [] + + objects = ndi.find_objects(label_image) + for i, sl in enumerate(objects): + if sl is None: + continue + + label = i + 1 + + props = RegionProperties( + sl, + label, + label_image, + intensity_image, + cache, + spacing=spacing, + extra_properties=extra_properties, + offset=offset_arr, + ) + regions.append(props) + + return regions + + +def _parse_docs(): + import re + import textwrap + + doc = regionprops.__doc__ or '' + arg_regex = r'\*\*(\w+)\*\* \:.*?\n(.*?)(?=\n [\*\S]+)' + if sys.version_info >= (3, 13): + arg_regex = r'\*\*(\w+)\*\* \:.*?\n(.*?)(?=\n[\*\S]+)' + + matches = re.finditer(arg_regex, doc, flags=re.DOTALL) + prop_doc = {m.group(1): textwrap.dedent(m.group(2)) for m in matches} + + return prop_doc + + +def _install_properties_docs(): + prop_doc = _parse_docs() + + for p in [member for member in dir(RegionProperties) if not member.startswith('_')]: + getattr(RegionProperties, p).__doc__ = prop_doc[p] + + +if __debug__: + # don't install docstrings when in optimized/non-debug mode + _install_properties_docs() diff --git a/python_embeded/Lib/site-packages/skimage/measure/_regionprops_utils.py b/python_embeded/Lib/site-packages/skimage/measure/_regionprops_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9aa82fae0d6a6d20176180b3e0e30126a5b78c --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/_regionprops_utils.py @@ -0,0 +1,630 @@ +from math import sqrt +from numbers import Real +import numpy as np +from scipy import ndimage as ndi + + +STREL_4 = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8) +STREL_8 = np.ones((3, 3), dtype=np.uint8) + + +# Coefficients from +# Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of Discretized Sets +# - On the Choice of Adjacency in Homogeneous Lattices. +# In: Mecke K., Stoyan D. (eds) Morphology of Condensed Matter. Lecture Notes +# in Physics, vol 600. Springer, Berlin, Heidelberg. +# The value of coefficients correspond to the contributions to the Euler number +# of specific voxel configurations, which are themselves encoded thanks to a +# LUT. Computing the Euler number from the addition of the contributions of +# local configurations is possible thanks to an integral geometry formula +# (see the paper by Ohser et al. for more details). +EULER_COEFS2D_4 = [0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0] +EULER_COEFS2D_8 = [0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0] +EULER_COEFS3D_26 = np.array( + [ + 0, + 1, + 1, + 0, + 1, + 0, + -2, + -1, + 1, + -2, + 0, + -1, + 0, + -1, + -1, + 0, + 1, + 0, + -2, + -1, + -2, + -1, + -1, + -2, + -6, + -3, + -3, + -2, + -3, + -2, + 0, + -1, + 1, + -2, + 0, + -1, + -6, + -3, + -3, + -2, + -2, + -1, + -1, + -2, + -3, + 0, + -2, + -1, + 0, + -1, + -1, + 0, + -3, + -2, + 0, + -1, + -3, + 0, + -2, + -1, + 0, + 1, + 1, + 0, + 1, + -2, + -6, + -3, + 0, + -1, + -3, + -2, + -2, + -1, + -3, + 0, + -1, + -2, + -2, + -1, + 0, + -1, + -3, + -2, + -1, + 0, + 0, + -1, + -3, + 0, + 0, + 1, + -2, + -1, + 1, + 0, + -2, + -1, + -3, + 0, + -3, + 0, + 0, + 1, + -1, + 4, + 0, + 3, + 0, + 3, + 1, + 2, + -1, + -2, + -2, + -1, + -2, + -1, + 1, + 0, + 0, + 3, + 1, + 2, + 1, + 2, + 2, + 1, + 1, + -6, + -2, + -3, + -2, + -3, + -1, + 0, + 0, + -3, + -1, + -2, + -1, + -2, + -2, + -1, + -2, + -3, + -1, + 0, + -1, + 0, + 4, + 3, + -3, + 0, + 0, + 1, + 0, + 1, + 3, + 2, + 0, + -3, + -1, + -2, + -3, + 0, + 0, + 1, + -1, + 0, + 0, + -1, + -2, + 1, + -1, + 0, + -1, + -2, + -2, + -1, + 0, + 1, + 3, + 2, + -2, + 1, + -1, + 0, + 1, + 2, + 2, + 1, + 0, + -3, + -3, + 0, + -1, + -2, + 0, + 1, + -1, + 0, + -2, + 1, + 0, + -1, + -1, + 0, + -1, + -2, + 0, + 1, + -2, + -1, + 3, + 2, + -2, + 1, + 1, + 2, + -1, + 0, + 2, + 1, + -1, + 0, + -2, + 1, + -2, + 1, + 1, + 2, + -2, + 3, + -1, + 2, + -1, + 2, + 0, + 1, + 0, + -1, + -1, + 0, + -1, + 0, + 2, + 1, + -1, + 2, + 0, + 1, + 0, + 1, + 1, + 0, + ] +) + + +def euler_number(image, connectivity=None): + """Calculate the Euler characteristic in binary image. + + For 2D objects, the Euler number is the number of objects minus the number + of holes. For 3D objects, the Euler number is obtained as the number of + objects plus the number of holes, minus the number of tunnels, or loops. + + Parameters + ---------- + image: (M, N[, P]) ndarray + Input image. If image is not binary, all values greater than zero + are considered as the object. + connectivity : int, optional + Maximum number of orthogonal hops to consider a pixel/voxel + as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. + 4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2, + respectively). + 6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3, + respectively). Connectivity 2 is not defined. + + Returns + ------- + euler_number : int + Euler characteristic of the set of all objects in the image. + + Notes + ----- + The Euler characteristic is an integer number that describes the + topology of the set of all objects in the input image. If object is + 4-connected, then background is 8-connected, and conversely. + + The computation of the Euler characteristic is based on an integral + geometry formula in discretized space. In practice, a neighborhood + configuration is constructed, and a LUT is applied for each + configuration. The coefficients used are the ones of Ohser et al. + + It can be useful to compute the Euler characteristic for several + connectivities. A large relative difference between results + for different connectivities suggests that the image resolution + (with respect to the size of objects and holes) is too low. + + References + ---------- + .. [1] S. Rivollier. Analyse d’image geometrique et morphometrique par + diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, + 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. + https://tel.archives-ouvertes.fr/tel-00560838 + .. [2] Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of + Discretized Sets - On the Choice of Adjacency in Homogeneous + Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed + Matter. Lecture Notes in Physics, vol 600. Springer, Berlin, + Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> SAMPLE = np.zeros((100,100,100)); + >>> SAMPLE[40:60, 40:60, 40:60]=1 + >>> euler_number(SAMPLE) # doctest: +ELLIPSIS + 1... + >>> SAMPLE[45:55,45:55,45:55] = 0; + >>> euler_number(SAMPLE) # doctest: +ELLIPSIS + 2... + >>> SAMPLE = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 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, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + ... [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0], + ... [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], + ... [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]) + >>> euler_number(SAMPLE) # doctest: + 0 + >>> euler_number(SAMPLE, connectivity=1) # doctest: + 2 + """ + + # as image can be a label image, transform it to binary + image = (image > 0).astype(int) + image = np.pad(image, pad_width=1, mode='constant') + + # check connectivity + if connectivity is None: + connectivity = image.ndim + + # config variable is an adjacency configuration. A coefficient given by + # variable coefs is attributed to each configuration in order to get + # the Euler characteristic. + if image.ndim == 2: + config = np.array([[0, 0, 0], [0, 1, 4], [0, 2, 8]]) + if connectivity == 1: + coefs = EULER_COEFS2D_4 + else: + coefs = EULER_COEFS2D_8 + bins = 16 + else: # 3D images + if connectivity == 2: + raise NotImplementedError( + 'For 3D images, Euler number is implemented ' + 'for connectivities 1 and 3 only' + ) + + config = np.array( + [ + [[0, 0, 0], [0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 1, 4], [0, 2, 8]], + [[0, 0, 0], [0, 16, 64], [0, 32, 128]], + ] + ) + if connectivity == 1: + coefs = EULER_COEFS3D_26[::-1] + else: + coefs = EULER_COEFS3D_26 + bins = 256 + + # XF has values in the 0-255 range in 3D, and in the 0-15 range in 2D, + # with one unique value for each binary configuration of the + # 27-voxel cube in 3D / 8-pixel square in 2D, up to symmetries + XF = ndi.convolve(image, config, mode='constant', cval=0) + h = np.bincount(XF.ravel(), minlength=bins) + + if image.ndim == 2: + return coefs @ h + else: + return int(0.125 * coefs @ h) + + +def perimeter(image, neighborhood=4): + """Calculate total perimeter of all objects in binary image. + + Parameters + ---------- + image : (M, N) ndarray + Binary input image. + neighborhood : 4 or 8, optional + Neighborhood connectivity for border pixel determination. It is used to + compute the contour. A higher neighborhood widens the border on which + the perimeter is computed. + + Returns + ------- + perimeter : float + Total perimeter of all objects in binary image. + + References + ---------- + .. [1] K. Benkrid, D. Crookes. Design and FPGA Implementation of + a Perimeter Estimator. The Queen's University of Belfast. + http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc + + Examples + -------- + >>> from skimage import data, util + >>> from skimage.measure import label + >>> # coins image (binary) + >>> img_coins = data.coins() > 110 + >>> # total perimeter of all objects in the image + >>> perimeter(img_coins, neighborhood=4) # doctest: +ELLIPSIS + 7796.867... + >>> perimeter(img_coins, neighborhood=8) # doctest: +ELLIPSIS + 8806.268... + + """ + if image.ndim != 2: + raise NotImplementedError('`perimeter` supports 2D images only') + + if neighborhood == 4: + strel = STREL_4 + else: + strel = STREL_8 + image = image.astype(np.uint8) + eroded_image = ndi.binary_erosion(image, strel, border_value=0) + border_image = image - eroded_image + + perimeter_weights = np.zeros(50, dtype=np.float64) + perimeter_weights[[5, 7, 15, 17, 25, 27]] = 1 + perimeter_weights[[21, 33]] = sqrt(2) + perimeter_weights[[13, 23]] = (1 + sqrt(2)) / 2 + + perimeter_image = ndi.convolve( + border_image, + np.array([[10, 2, 10], [2, 1, 2], [10, 2, 10]]), + mode='constant', + cval=0, + ) + + # You can also write + # return perimeter_weights[perimeter_image].sum() + # but that was measured as taking much longer than bincount + np.dot (5x + # as much time) + perimeter_histogram = np.bincount(perimeter_image.ravel(), minlength=50) + total_perimeter = perimeter_histogram @ perimeter_weights + return total_perimeter + + +def perimeter_crofton(image, directions=4): + """Calculate total Crofton perimeter of all objects in binary image. + + Parameters + ---------- + image : (M, N) ndarray + Input image. If image is not binary, all values greater than zero + are considered as the object. + directions : 2 or 4, optional + Number of directions used to approximate the Crofton perimeter. By + default, 4 is used: it should be more accurate than 2. + Computation time is the same in both cases. + + Returns + ------- + perimeter : float + Total perimeter of all objects in binary image. + + Notes + ----- + This measure is based on Crofton formula [1], which is a measure from + integral geometry. It is defined for general curve length evaluation via + a double integral along all directions. In a discrete + space, 2 or 4 directions give a quite good approximation, 4 being more + accurate than 2 for more complex shapes. + + Similar to :func:`~.measure.perimeter`, this function returns an + approximation of the perimeter in continuous space. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Crofton_formula + .. [2] S. Rivollier. Analyse d’image geometrique et morphometrique par + diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, + 2010. + Ecole Nationale Superieure des Mines de Saint-Etienne. + https://tel.archives-ouvertes.fr/tel-00560838 + + Examples + -------- + >>> from skimage import data, util + >>> from skimage.measure import label + >>> # coins image (binary) + >>> img_coins = data.coins() > 110 + >>> # total perimeter of all objects in the image + >>> perimeter_crofton(img_coins, directions=2) # doctest: +ELLIPSIS + 8144.578... + >>> perimeter_crofton(img_coins, directions=4) # doctest: +ELLIPSIS + 7837.077... + """ + if image.ndim != 2: + raise NotImplementedError('`perimeter_crofton` supports 2D images only') + + # as image could be a label image, transform it to binary image + image = (image > 0).astype(np.uint8) + image = np.pad(image, pad_width=1, mode='constant') + XF = ndi.convolve( + image, np.array([[0, 0, 0], [0, 1, 4], [0, 2, 8]]), mode='constant', cval=0 + ) + + h = np.bincount(XF.ravel(), minlength=16) + + # definition of the LUT + if directions == 2: + coefs = [ + 0, + np.pi / 2, + 0, + 0, + 0, + np.pi / 2, + 0, + 0, + np.pi / 2, + np.pi, + 0, + 0, + np.pi / 2, + np.pi, + 0, + 0, + ] + else: + coefs = [ + 0, + np.pi / 4 * (1 + 1 / (np.sqrt(2))), + np.pi / (4 * np.sqrt(2)), + np.pi / (2 * np.sqrt(2)), + 0, + np.pi / 4 * (1 + 1 / (np.sqrt(2))), + 0, + np.pi / (4 * np.sqrt(2)), + np.pi / 4, + np.pi / 2, + np.pi / (4 * np.sqrt(2)), + np.pi / (4 * np.sqrt(2)), + np.pi / 4, + np.pi / 2, + 0, + 0, + ] + + total_perimeter = coefs @ h + return total_perimeter + + +def _normalize_spacing(spacing, ndims): + """Normalize spacing parameter. + + The `spacing` parameter should be a sequence of numbers matching + the image dimensions. If `spacing` is a scalar, assume equal + spacing along all dimensions. + + Parameters + --------- + spacing : Any + User-provided `spacing` keyword. + ndims : int + Number of image dimensions. + + Returns + ------- + spacing : array + Corrected spacing. + + Raises + ------ + ValueError + If `spacing` is invalid. + + """ + spacing = np.array(spacing) + if spacing.shape == (): + spacing = np.broadcast_to(spacing, shape=(ndims,)) + elif spacing.shape != (ndims,): + raise ValueError( + f"spacing isn't a scalar nor a sequence of shape {(ndims,)}, got {spacing}." + ) + if not all(isinstance(s, Real) for s in spacing): + raise TypeError( + f"Element of spacing isn't float or integer type, got {spacing}." + ) + if not all(np.isfinite(spacing)): + raise ValueError( + f"Invalid spacing parameter. All elements must be finite, got {spacing}." + ) + return spacing diff --git a/python_embeded/Lib/site-packages/skimage/measure/block.py b/python_embeded/Lib/site-packages/skimage/measure/block.py new file mode 100644 index 0000000000000000000000000000000000000000..0806b8fb75058fad5a3c021fc57fec4b62713bc9 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/block.py @@ -0,0 +1,94 @@ +import numpy as np +from ..util import view_as_blocks + + +def block_reduce(image, block_size=2, func=np.sum, cval=0, func_kwargs=None): + """Downsample image by applying function `func` to local blocks. + + This function is useful for max and mean pooling, for example. + + Parameters + ---------- + image : (M[, ...]) ndarray + N-dimensional input image. + block_size : array_like or int + Array containing down-sampling integer factor along each axis. + Default block_size is 2. + func : callable + Function object which is used to calculate the return value for each + local block. This function must implement an ``axis`` parameter. + Primary functions are ``numpy.sum``, ``numpy.min``, ``numpy.max``, + ``numpy.mean`` and ``numpy.median``. See also `func_kwargs`. + cval : float + Constant padding value if image is not perfectly divisible by the + block size. + func_kwargs : dict + Keyword arguments passed to `func`. Notably useful for passing dtype + argument to ``np.mean``. Takes dictionary of inputs, e.g.: + ``func_kwargs={'dtype': np.float16})``. + + Returns + ------- + image : ndarray + Down-sampled image with same number of dimensions as input image. + + Examples + -------- + >>> from skimage.measure import block_reduce + >>> image = np.arange(3*3*4).reshape(3, 3, 4) + >>> image # doctest: +NORMALIZE_WHITESPACE + array([[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]], + [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]], + [[24, 25, 26, 27], + [28, 29, 30, 31], + [32, 33, 34, 35]]]) + >>> block_reduce(image, block_size=(3, 3, 1), func=np.mean) + array([[[16., 17., 18., 19.]]]) + >>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=np.max) + >>> image_max1 # doctest: +NORMALIZE_WHITESPACE + array([[[11]], + [[23]], + [[35]]]) + >>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max) + >>> image_max2 # doctest: +NORMALIZE_WHITESPACE + array([[[27], + [31], + [35]]]) + """ + + if np.isscalar(block_size): + block_size = (block_size,) * image.ndim + elif len(block_size) != image.ndim: + raise ValueError( + "`block_size` must be a scalar or have " "the same length as `image.shape`" + ) + + if func_kwargs is None: + func_kwargs = {} + + pad_width = [] + for i in range(len(block_size)): + if block_size[i] < 1: + raise ValueError( + "Down-sampling factors must be >= 1. Use " + "`skimage.transform.resize` to up-sample an " + "image." + ) + if image.shape[i] % block_size[i] != 0: + after_width = block_size[i] - (image.shape[i] % block_size[i]) + else: + after_width = 0 + pad_width.append((0, after_width)) + + if np.any(np.asarray(pad_width)): + image = np.pad( + image, pad_width=pad_width, mode='constant', constant_values=cval + ) + + blocked = view_as_blocks(image, block_size) + + return func(blocked, axis=tuple(range(image.ndim, blocked.ndim)), **func_kwargs) diff --git a/python_embeded/Lib/site-packages/skimage/measure/entropy.py b/python_embeded/Lib/site-packages/skimage/measure/entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..a77c6035205964e0f647f89a44e246fd66e3562b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/entropy.py @@ -0,0 +1,41 @@ +from numpy import unique +from scipy.stats import entropy as scipy_entropy + + +def shannon_entropy(image, base=2): + """Calculate the Shannon entropy of an image. + + The Shannon entropy is defined as S = -sum(pk * log(pk)), + where pk are frequency/probability of pixels of value k. + + Parameters + ---------- + image : (M, N) ndarray + Grayscale input image. + base : float, optional + The logarithmic base to use. + + Returns + ------- + entropy : float + + Notes + ----- + The returned value is measured in bits or shannon (Sh) for base=2, natural + unit (nat) for base=np.e and hartley (Hart) for base=10. + + References + ---------- + .. [1] `https://en.wikipedia.org/wiki/Entropy_(information_theory) `_ + .. [2] https://en.wiktionary.org/wiki/Shannon_entropy + + Examples + -------- + >>> from skimage import data + >>> from skimage.measure import shannon_entropy + >>> shannon_entropy(data.camera()) + 7.231695011055706 + """ + + _, counts = unique(image, return_counts=True) + return scipy_entropy(counts, base=base) diff --git a/python_embeded/Lib/site-packages/skimage/measure/fit.py b/python_embeded/Lib/site-packages/skimage/measure/fit.py new file mode 100644 index 0000000000000000000000000000000000000000..6b21eeaa1674d9f0bb238fc900fbe611a350dc1c --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/fit.py @@ -0,0 +1,977 @@ +import math +from warnings import warn + +import numpy as np +from numpy.linalg import inv +from scipy import optimize, spatial + + +_EPSILON = np.spacing(1) + + +def _check_data_dim(data, dim): + if data.ndim != 2 or data.shape[1] != dim: + raise ValueError(f"Input data must have shape (N, {dim}).") + + +def _check_data_atleast_2D(data): + if data.ndim < 2 or data.shape[1] < 2: + raise ValueError('Input data must be at least 2D.') + + +class BaseModel: + def __init__(self): + self.params = None + + +class LineModelND(BaseModel): + """Total least squares estimator for N-dimensional lines. + + In contrast to ordinary least squares line estimation, this estimator + minimizes the orthogonal distances of points to the estimated line. + + Lines are defined by a point (origin) and a unit vector (direction) + according to the following vector equation:: + + X = origin + lambda * direction + + Attributes + ---------- + params : tuple + Line model parameters in the following order `origin`, `direction`. + + Examples + -------- + >>> x = np.linspace(1, 2, 25) + >>> y = 1.5 * x + 3 + >>> lm = LineModelND() + >>> lm.estimate(np.stack([x, y], axis=-1)) + True + >>> tuple(np.round(lm.params, 5)) + (array([1.5 , 5.25]), array([0.5547 , 0.83205])) + >>> res = lm.residuals(np.stack([x, y], axis=-1)) + >>> np.abs(np.round(res, 9)) + 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.]) + >>> np.round(lm.predict_y(x[:5]), 3) + array([4.5 , 4.562, 4.625, 4.688, 4.75 ]) + >>> np.round(lm.predict_x(y[:5]), 3) + array([1. , 1.042, 1.083, 1.125, 1.167]) + + """ + + def estimate(self, data): + """Estimate line model from data. + + This minimizes the sum of shortest (orthogonal) distances + from the given data points to the estimated line. + + Parameters + ---------- + data : (N, dim) array + N points in a space of dimensionality dim >= 2. + + Returns + ------- + success : bool + True, if model estimation succeeds. + """ + _check_data_atleast_2D(data) + + origin = data.mean(axis=0) + data = data - origin + + if data.shape[0] == 2: # well determined + direction = data[1] - data[0] + norm = np.linalg.norm(direction) + if norm != 0: # this should not happen to be norm 0 + direction /= norm + elif data.shape[0] > 2: # over-determined + # Note: with full_matrices=1 Python dies with joblib parallel_for. + _, _, v = np.linalg.svd(data, full_matrices=False) + direction = v[0] + else: # under-determined + return False + + self.params = (origin, direction) + + return True + + def residuals(self, data, params=None): + """Determine residuals of data to model. + + For each point, the shortest (orthogonal) distance to the line is + returned. It is obtained by projecting the data onto the line. + + Parameters + ---------- + data : (N, dim) array + N points in a space of dimension dim. + params : (2,) array, optional + Optional custom parameter set in the form (`origin`, `direction`). + + Returns + ------- + residuals : (N,) array + Residual for each data point. + """ + _check_data_atleast_2D(data) + if params is None: + if self.params is None: + raise ValueError('Parameters cannot be None') + params = self.params + if len(params) != 2: + raise ValueError('Parameters are defined by 2 sets.') + + origin, direction = params + res = (data - origin) - ((data - origin) @ direction)[ + ..., np.newaxis + ] * direction + return np.linalg.norm(res, axis=1) + + def predict(self, x, axis=0, params=None): + """Predict intersection of the estimated line model with a hyperplane + orthogonal to a given axis. + + Parameters + ---------- + x : (n, 1) array + Coordinates along an axis. + axis : int + Axis orthogonal to the hyperplane intersecting the line. + params : (2,) array, optional + Optional custom parameter set in the form (`origin`, `direction`). + + Returns + ------- + data : (n, m) array + Predicted coordinates. + + Raises + ------ + ValueError + If the line is parallel to the given axis. + """ + if params is None: + if self.params is None: + raise ValueError('Parameters cannot be None') + params = self.params + if len(params) != 2: + raise ValueError('Parameters are defined by 2 sets.') + + origin, direction = params + + if direction[axis] == 0: + # line parallel to axis + raise ValueError(f'Line parallel to axis {axis}') + + l = (x - origin[axis]) / direction[axis] + data = origin + l[..., np.newaxis] * direction + return data + + def predict_x(self, y, params=None): + """Predict x-coordinates for 2D lines using the estimated model. + + Alias for:: + + predict(y, axis=1)[:, 0] + + Parameters + ---------- + y : array + y-coordinates. + params : (2,) array, optional + Optional custom parameter set in the form (`origin`, `direction`). + + Returns + ------- + x : array + Predicted x-coordinates. + + """ + x = self.predict(y, axis=1, params=params)[:, 0] + return x + + def predict_y(self, x, params=None): + """Predict y-coordinates for 2D lines using the estimated model. + + Alias for:: + + predict(x, axis=0)[:, 1] + + Parameters + ---------- + x : array + x-coordinates. + params : (2,) array, optional + Optional custom parameter set in the form (`origin`, `direction`). + + Returns + ------- + y : array + Predicted y-coordinates. + + """ + y = self.predict(x, axis=0, params=params)[:, 1] + return y + + +class CircleModel(BaseModel): + """Total least squares estimator for 2D circles. + + The functional model of the circle is:: + + r**2 = (x - xc)**2 + (y - yc)**2 + + This estimator minimizes the squared distances from all points to the + circle:: + + min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } + + A minimum number of 3 points is required to solve for the parameters. + + Attributes + ---------- + params : tuple + Circle model parameters in the following order `xc`, `yc`, `r`. + + Notes + ----- + The estimation is carried out using a 2D version of the spherical + estimation given in [1]_. + + References + ---------- + .. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models + for pvc-coated polyester via inverse bubble inflation. + Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87. + https://hdl.handle.net/10019.1/98627 + + Examples + -------- + >>> t = np.linspace(0, 2 * np.pi, 25) + >>> xy = CircleModel().predict_xy(t, params=(2, 3, 4)) + >>> model = CircleModel() + >>> model.estimate(xy) + True + >>> tuple(np.round(model.params, 5)) + (2.0, 3.0, 4.0) + >>> res = model.residuals(xy) + >>> np.abs(np.round(res, 9)) + 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.]) + """ + + def estimate(self, data): + """Estimate circle model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + + _check_data_dim(data, dim=2) + + # to prevent integer overflow, cast data to float, if it isn't already + float_type = np.promote_types(data.dtype, np.float32) + data = data.astype(float_type, copy=False) + # normalize value range to avoid misfitting due to numeric errors if + # the relative distanceses are small compared to absolute distances + origin = data.mean(axis=0) + data = data - origin + scale = data.std() + if scale < np.finfo(float_type).tiny: + warn( + "Standard deviation of data is too small to estimate " + "circle with meaningful precision.", + category=RuntimeWarning, + stacklevel=2, + ) + return False + data /= scale + + # Adapted from a spherical estimator covered in a blog post by Charles + # Jeckel (see also reference 1 above): + # https://jekel.me/2015/Least-Squares-Sphere-Fit/ + A = np.append(data * 2, np.ones((data.shape[0], 1), dtype=float_type), axis=1) + f = np.sum(data**2, axis=1) + C, _, rank, _ = np.linalg.lstsq(A, f, rcond=None) + + if rank != 3: + warn("Input does not contain enough significant data points.") + return False + + center = C[0:2] + distances = spatial.minkowski_distance(center, data) + r = np.sqrt(np.mean(distances**2)) + + # revert normalization and set params + center *= scale + r *= scale + center += origin + self.params = tuple(center) + (r,) + + return True + + def residuals(self, data): + """Determine residuals of data to model. + + For each point the shortest distance to the circle is returned. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + residuals : (N,) array + Residual for each data point. + + """ + + _check_data_dim(data, dim=2) + + xc, yc, r = self.params + + x = data[:, 0] + y = data[:, 1] + + return r - np.sqrt((x - xc) ** 2 + (y - yc) ** 2) + + def predict_xy(self, t, params=None): + """Predict x- and y-coordinates using the estimated model. + + Parameters + ---------- + t : array + Angles in circle in radians. Angles start to count from positive + x-axis to positive y-axis in a right-handed system. + params : (3,) array, optional + Optional custom parameter set. + + Returns + ------- + xy : (..., 2) array + Predicted x- and y-coordinates. + + """ + if params is None: + params = self.params + xc, yc, r = params + + x = xc + r * np.cos(t) + y = yc + r * np.sin(t) + + return np.concatenate((x[..., None], y[..., None]), axis=t.ndim) + + +class EllipseModel(BaseModel): + """Total least squares estimator for 2D ellipses. + + The functional model of the ellipse is:: + + xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t) + yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t) + d = sqrt((x - xt)**2 + (y - yt)**2) + + where ``(xt, yt)`` is the closest point on the ellipse to ``(x, y)``. Thus + d is the shortest distance from the point to the ellipse. + + The estimator is based on a least squares minimization. The optimal + solution is computed directly, no iterations are required. This leads + to a simple, stable and robust fitting method. + + The ``params`` attribute contains the parameters in the following order:: + + xc, yc, a, b, theta + + Attributes + ---------- + params : tuple + Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`, + `theta`. + + Examples + -------- + + >>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25), + ... params=(10, 15, 8, 4, np.deg2rad(30))) + >>> ellipse = EllipseModel() + >>> ellipse.estimate(xy) + True + >>> np.round(ellipse.params, 2) + array([10. , 15. , 8. , 4. , 0.52]) + >>> np.round(abs(ellipse.residuals(xy)), 5) + 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.]) + """ + + def estimate(self, data): + """Estimate ellipse model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + + References + ---------- + .. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares + fitting of ellipses". In Proc. 6th International Conference in + Central Europe on Computer Graphics and Visualization. + WSCG (Vol. 98, pp. 125-132). + + """ + # Original Implementation: Ben Hammel, Nick Sullivan-Molina + # another REFERENCE: [2] http://mathworld.wolfram.com/Ellipse.html + _check_data_dim(data, dim=2) + + if len(data) < 5: + warn( + "Need at least 5 data points to estimate an ellipse.", + category=RuntimeWarning, + stacklevel=2, + ) + return False + + # to prevent integer overflow, cast data to float, if it isn't already + float_type = np.promote_types(data.dtype, np.float32) + data = data.astype(float_type, copy=False) + + # normalize value range to avoid misfitting due to numeric errors if + # the relative distances are small compared to absolute distances + origin = data.mean(axis=0) + data = data - origin + scale = data.std() + if scale < np.finfo(float_type).tiny: + warn( + "Standard deviation of data is too small to estimate " + "ellipse with meaningful precision.", + category=RuntimeWarning, + stacklevel=2, + ) + return False + data /= scale + + x = data[:, 0] + y = data[:, 1] + + # Quadratic part of design matrix [eqn. 15] from [1] + D1 = np.vstack([x**2, x * y, y**2]).T + # Linear part of design matrix [eqn. 16] from [1] + D2 = np.vstack([x, y, np.ones_like(x)]).T + + # forming scatter matrix [eqn. 17] from [1] + S1 = D1.T @ D1 + S2 = D1.T @ D2 + S3 = D2.T @ D2 + + # Constraint matrix [eqn. 18] + C1 = np.array([[0.0, 0.0, 2.0], [0.0, -1.0, 0.0], [2.0, 0.0, 0.0]]) + + try: + # Reduced scatter matrix [eqn. 29] + M = inv(C1) @ (S1 - S2 @ inv(S3) @ S2.T) + except np.linalg.LinAlgError: # LinAlgError: Singular matrix + return False + + # M*|a b c >=l|a b c >. Find eigenvalues and eigenvectors + # from this equation [eqn. 28] + eig_vals, eig_vecs = np.linalg.eig(M) + + # eigenvector must meet constraint 4ac - b^2 to be valid. + cond = 4 * np.multiply(eig_vecs[0, :], eig_vecs[2, :]) - np.power( + eig_vecs[1, :], 2 + ) + a1 = eig_vecs[:, (cond > 0)] + # seeks for empty matrix + if 0 in a1.shape or len(a1.ravel()) != 3: + return False + a, b, c = a1.ravel() + + # |d f g> = -S3^(-1)*S2^(T)*|a b c> [eqn. 24] + a2 = -inv(S3) @ S2.T @ a1 + d, f, g = a2.ravel() + + # eigenvectors are the coefficients of an ellipse in general form + # a*x^2 + 2*b*x*y + c*y^2 + 2*d*x + 2*f*y + g = 0 (eqn. 15) from [2] + b /= 2.0 + d /= 2.0 + f /= 2.0 + + # finding center of ellipse [eqn.19 and 20] from [2] + x0 = (c * d - b * f) / (b**2.0 - a * c) + y0 = (a * f - b * d) / (b**2.0 - a * c) + + # Find the semi-axes lengths [eqn. 21 and 22] from [2] + numerator = a * f**2 + c * d**2 + g * b**2 - 2 * b * d * f - a * c * g + term = np.sqrt((a - c) ** 2 + 4 * b**2) + denominator1 = (b**2 - a * c) * (term - (a + c)) + denominator2 = (b**2 - a * c) * (-term - (a + c)) + width = np.sqrt(2 * numerator / denominator1) + height = np.sqrt(2 * numerator / denominator2) + + # angle of counterclockwise rotation of major-axis of ellipse + # to x-axis [eqn. 23] from [2]. + phi = 0.5 * np.arctan((2.0 * b) / (a - c)) + if a > c: + phi += 0.5 * np.pi + + # stabilize parameters: + # sometimes small fluctuations in data can cause + # height and width to swap + if width < height: + width, height = height, width + phi += np.pi / 2 + + phi %= np.pi + + # revert normalization and set params + params = np.nan_to_num([x0, y0, width, height, phi]).real + params[:4] *= scale + params[:2] += origin + + self.params = tuple(float(p) for p in params) + + return True + + def residuals(self, data): + """Determine residuals of data to model. + + For each point the shortest distance to the ellipse is returned. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + residuals : (N,) array + Residual for each data point. + + """ + + _check_data_dim(data, dim=2) + + xc, yc, a, b, theta = self.params + + ctheta = math.cos(theta) + stheta = math.sin(theta) + + x = data[:, 0] + y = data[:, 1] + + N = data.shape[0] + + def fun(t, xi, yi): + ct = math.cos(np.squeeze(t)) + st = math.sin(np.squeeze(t)) + xt = xc + a * ctheta * ct - b * stheta * st + yt = yc + a * stheta * ct + b * ctheta * st + return (xi - xt) ** 2 + (yi - yt) ** 2 + + # def Dfun(t, xi, yi): + # ct = math.cos(t) + # st = math.sin(t) + # xt = xc + a * ctheta * ct - b * stheta * st + # yt = yc + a * stheta * ct + b * ctheta * st + # dfx_t = - 2 * (xi - xt) * (- a * ctheta * st + # - b * stheta * ct) + # dfy_t = - 2 * (yi - yt) * (- a * stheta * st + # + b * ctheta * ct) + # return [dfx_t + dfy_t] + + residuals = np.empty((N,), dtype=np.float64) + + # initial guess for parameter t of closest point on ellipse + t0 = np.arctan2(y - yc, x - xc) - theta + + # determine shortest distance to ellipse for each point + for i in range(N): + xi = x[i] + yi = y[i] + # faster without Dfun, because of the python overhead + t, _ = optimize.leastsq(fun, t0[i], args=(xi, yi)) + residuals[i] = np.sqrt(fun(t, xi, yi)) + + return residuals + + def predict_xy(self, t, params=None): + """Predict x- and y-coordinates using the estimated model. + + Parameters + ---------- + t : array + Angles in circle in radians. Angles start to count from positive + x-axis to positive y-axis in a right-handed system. + params : (5,) array, optional + Optional custom parameter set. + + Returns + ------- + xy : (..., 2) array + Predicted x- and y-coordinates. + + """ + + if params is None: + params = self.params + + xc, yc, a, b, theta = params + + ct = np.cos(t) + st = np.sin(t) + ctheta = math.cos(theta) + stheta = math.sin(theta) + + x = xc + a * ctheta * ct - b * stheta * st + y = yc + a * stheta * ct + b * ctheta * st + + return np.concatenate((x[..., None], y[..., None]), axis=t.ndim) + + +def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability): + """Determine number trials such that at least one outlier-free subset is + sampled for the given inlier/outlier ratio. + + Parameters + ---------- + n_inliers : int + Number of inliers in the data. + n_samples : int + Total number of samples in the data. + min_samples : int + Minimum number of samples chosen randomly from original data. + probability : float + Probability (confidence) that one outlier-free sample is generated. + + Returns + ------- + trials : int + Number of trials. + """ + if probability == 0: + return 0 + if n_inliers == 0: + return np.inf + inlier_ratio = n_inliers / n_samples + nom = 1 - probability + denom = 1 - inlier_ratio**min_samples + # Keep (de-)nominator in the range of [_EPSILON, 1 - _EPSILON] so that + # it is always guaranteed that the logarithm is negative and we return + # a positive number of trials. + nom = np.clip(nom, a_min=_EPSILON, a_max=1 - _EPSILON) + denom = np.clip(denom, a_min=_EPSILON, a_max=1 - _EPSILON) + return np.ceil(np.log(nom) / np.log(denom)) + + +def ransac( + data, + model_class, + min_samples, + residual_threshold, + is_data_valid=None, + is_model_valid=None, + max_trials=100, + stop_sample_num=np.inf, + stop_residuals_sum=0, + stop_probability=1, + rng=None, + initial_inliers=None, +): + """Fit a model to data with the RANSAC (random sample consensus) algorithm. + + RANSAC is an iterative algorithm for the robust estimation of parameters + from a subset of inliers from the complete data set. Each iteration + performs the following tasks: + + 1. Select `min_samples` random samples from the original data and check + whether the set of data is valid (see `is_data_valid`). + 2. Estimate a model to the random subset + (`model_cls.estimate(*data[random_subset]`) and check whether the + estimated model is valid (see `is_model_valid`). + 3. Classify all data as inliers or outliers by calculating the residuals + to the estimated model (`model_cls.residuals(*data)`) - all data samples + with residuals smaller than the `residual_threshold` are considered as + inliers. + 4. Save estimated model as best model if number of inlier samples is + maximal. In case the current estimated model has the same number of + inliers, it is only considered as the best model if it has less sum of + residuals. + + These steps are performed either a maximum number of times or until one of + the special stop criteria are met. The final model is estimated using all + inlier samples of the previously determined best model. + + Parameters + ---------- + data : [list, tuple of] (N, ...) array + Data set to which the model is fitted, where N is the number of data + points and the remaining dimension are depending on model requirements. + If the model class requires multiple input data arrays (e.g. source and + destination coordinates of ``skimage.transform.AffineTransform``), + they can be optionally passed as tuple or list. Note, that in this case + the functions ``estimate(*data)``, ``residuals(*data)``, + ``is_model_valid(model, *random_data)`` and + ``is_data_valid(*random_data)`` must all take each data array as + separate arguments. + model_class : object + Object with the following object methods: + + * ``success = estimate(*data)`` + * ``residuals(*data)`` + + where `success` indicates whether the model estimation succeeded + (`True` or `None` for success, `False` for failure). + min_samples : int in range (0, N) + The minimum number of data points to fit a model to. + residual_threshold : float larger than 0 + Maximum distance for a data point to be classified as an inlier. + is_data_valid : function, optional + This function is called with the randomly selected data before the + model is fitted to it: `is_data_valid(*random_data)`. + is_model_valid : function, optional + This function is called with the estimated model and the randomly + selected data: `is_model_valid(model, *random_data)`, . + max_trials : int, optional + Maximum number of iterations for random sample selection. + stop_sample_num : int, optional + Stop iteration if at least this number of inliers are found. + stop_residuals_sum : float, optional + Stop iteration if sum of residuals is less than or equal to this + threshold. + stop_probability : float in range [0, 1], optional + RANSAC iteration stops if at least one outlier-free set of the + training data is sampled with ``probability >= stop_probability``, + depending on the current best model's inlier ratio and the number + of trials. This requires to generate at least N samples (trials): + + N >= log(1 - probability) / log(1 - e**m) + + where the probability (confidence) is typically set to a high value + such as 0.99, e is the current fraction of inliers w.r.t. the + total number of samples, and m is the min_samples value. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + initial_inliers : array-like of bool, shape (N,), optional + Initial samples selection for model estimation + + + Returns + ------- + model : object + Best model with largest consensus set. + inliers : (N,) array + Boolean mask of inliers classified as ``True``. + + References + ---------- + .. [1] "RANSAC", Wikipedia, https://en.wikipedia.org/wiki/RANSAC + + Examples + -------- + + Generate ellipse data without tilt and add noise: + + >>> t = np.linspace(0, 2 * np.pi, 50) + >>> xc, yc = 20, 30 + >>> a, b = 5, 10 + >>> x = xc + a * np.cos(t) + >>> y = yc + b * np.sin(t) + >>> data = np.column_stack([x, y]) + >>> rng = np.random.default_rng(203560) # do not copy this value + >>> data += rng.normal(size=data.shape) + + Add some faulty data: + + >>> data[0] = (100, 100) + >>> data[1] = (110, 120) + >>> data[2] = (120, 130) + >>> data[3] = (140, 130) + + Estimate ellipse model using all available data: + + >>> model = EllipseModel() + >>> model.estimate(data) + True + >>> np.round(model.params) # doctest: +SKIP + array([ 72., 75., 77., 14., 1.]) + + Estimate ellipse model using RANSAC: + + >>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50) + >>> abs(np.round(ransac_model.params)) # doctest: +SKIP + array([20., 30., 10., 6., 2.]) + >>> inliers # doctest: +SKIP + array([False, False, False, False, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True], dtype=bool) + >>> sum(inliers) > 40 + True + + RANSAC can be used to robustly estimate a geometric + transformation. In this section, we also show how to use a + proportion of the total samples, rather than an absolute number. + + >>> from skimage.transform import SimilarityTransform + >>> rng = np.random.default_rng() + >>> src = 100 * rng.random((50, 2)) + >>> model0 = SimilarityTransform(scale=0.5, rotation=1, + ... translation=(10, 20)) + >>> dst = model0(src) + >>> dst[0] = (10000, 10000) + >>> dst[1] = (-100, 100) + >>> dst[2] = (50, 50) + >>> ratio = 0.5 # use half of the samples + >>> min_samples = int(ratio * len(src)) + >>> model, inliers = ransac( + ... (src, dst), + ... SimilarityTransform, + ... min_samples, + ... 10, + ... initial_inliers=np.ones(len(src), dtype=bool), + ... ) # doctest: +SKIP + >>> inliers # doctest: +SKIP + array([False, False, False, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True]) + + """ + + best_inlier_num = 0 + best_inlier_residuals_sum = np.inf + best_inliers = [] + validate_model = is_model_valid is not None + validate_data = is_data_valid is not None + + rng = np.random.default_rng(rng) + + # in case data is not pair of input and output, male it like it + if not isinstance(data, (tuple, list)): + data = (data,) + num_samples = len(data[0]) + + if not (0 < min_samples <= num_samples): + raise ValueError(f"`min_samples` must be in range (0, {num_samples}]") + + if residual_threshold < 0: + raise ValueError("`residual_threshold` must be greater than zero") + + if max_trials < 0: + raise ValueError("`max_trials` must be greater than zero") + + if not (0 <= stop_probability <= 1): + raise ValueError("`stop_probability` must be in range [0, 1]") + + if initial_inliers is not None and len(initial_inliers) != num_samples: + raise ValueError( + f"RANSAC received a vector of initial inliers (length " + f"{len(initial_inliers)}) that didn't match the number of " + f"samples ({num_samples}). The vector of initial inliers should " + f"have the same length as the number of samples and contain only " + f"True (this sample is an initial inlier) and False (this one " + f"isn't) values." + ) + + # for the first run use initial guess of inliers + spl_idxs = ( + initial_inliers + if initial_inliers is not None + else rng.choice(num_samples, min_samples, replace=False) + ) + + # estimate model for current random sample set + model = model_class() + + num_trials = 0 + # max_trials can be updated inside the loop, so this cannot be a for-loop + while num_trials < max_trials: + num_trials += 1 + + # do sample selection according data pairs + samples = [d[spl_idxs] for d in data] + + # for next iteration choose random sample set and be sure that + # no samples repeat + spl_idxs = rng.choice(num_samples, min_samples, replace=False) + + # optional check if random sample set is valid + if validate_data and not is_data_valid(*samples): + continue + + success = model.estimate(*samples) + # backwards compatibility + if success is not None and not success: + continue + + # optional check if estimated model is valid + if validate_model and not is_model_valid(model, *samples): + continue + + residuals = np.abs(model.residuals(*data)) + # consensus set / inliers + inliers = residuals < residual_threshold + residuals_sum = residuals.dot(residuals) + + # choose as new best model if number of inliers is maximal + inliers_count = np.count_nonzero(inliers) + if ( + # more inliers + inliers_count > best_inlier_num + # same number of inliers but less "error" in terms of residuals + or ( + inliers_count == best_inlier_num + and residuals_sum < best_inlier_residuals_sum + ) + ): + best_inlier_num = inliers_count + best_inlier_residuals_sum = residuals_sum + best_inliers = inliers + max_trials = min( + max_trials, + _dynamic_max_trials( + best_inlier_num, num_samples, min_samples, stop_probability + ), + ) + if ( + best_inlier_num >= stop_sample_num + or best_inlier_residuals_sum <= stop_residuals_sum + ): + break + + # estimate final model using all inliers + if any(best_inliers): + # select inliers for each data array + data_inliers = [d[best_inliers] for d in data] + model.estimate(*data_inliers) + if validate_model and not is_model_valid(model, *data_inliers): + warn("Estimated model is not valid. Try increasing max_trials.") + else: + model = None + best_inliers = None + warn("No inliers found. Model not fitted") + + return model, best_inliers diff --git a/python_embeded/Lib/site-packages/skimage/measure/pnpoly.py b/python_embeded/Lib/site-packages/skimage/measure/pnpoly.py new file mode 100644 index 0000000000000000000000000000000000000000..69b74fec107e50cba5e2ea1125e7f7c49d4a46cc --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/pnpoly.py @@ -0,0 +1,67 @@ +from ._pnpoly import _grid_points_in_poly, _points_in_poly + + +def grid_points_in_poly(shape, verts, binarize=True): + """Test whether points on a specified grid are inside a polygon. + + For each ``(r, c)`` coordinate on a grid, i.e. ``(0, 0)``, ``(0, 1)`` etc., + test whether that point lies inside a polygon. + + You can control the output type with the `binarize` flag. Please refer to its + documentation for further details. + + Parameters + ---------- + shape : tuple (M, N) + Shape of the grid. + verts : (V, 2) array + Specify the V vertices of the polygon, sorted either clockwise + or anti-clockwise. The first point may (but does not need to be) + duplicated. + binarize: bool + If `True`, the output of the function is a boolean mask. + Otherwise, it is a labeled array. The labels are: + O - outside, 1 - inside, 2 - vertex, 3 - edge. + + See Also + -------- + points_in_poly + + Returns + ------- + mask : (M, N) ndarray + If `binarize` is True, the output is a boolean mask. True means the + corresponding pixel falls inside the polygon. + If `binarize` is False, the output is a labeled array, with pixels + having a label between 0 and 3. The meaning of the values is: + O - outside, 1 - inside, 2 - vertex, 3 - edge. + + """ + output = _grid_points_in_poly(shape, verts) + if binarize: + output = output.astype(bool) + return output + + +def points_in_poly(points, verts): + """Test whether points lie inside a polygon. + + Parameters + ---------- + points : (K, 2) array + Input points, ``(x, y)``. + verts : (L, 2) array + Vertices of the polygon, sorted either clockwise or anti-clockwise. + The first point may (but does not need to be) duplicated. + + See Also + -------- + grid_points_in_poly + + Returns + ------- + mask : (K,) array of bool + True if corresponding point is inside the polygon. + + """ + return _points_in_poly(points, verts) diff --git a/python_embeded/Lib/site-packages/skimage/measure/profile.py b/python_embeded/Lib/site-packages/skimage/measure/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..591b8b89624f28507dc88cd8fd17531fa49c09db --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/measure/profile.py @@ -0,0 +1,190 @@ +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _validate_interpolation_order, _fix_ndimage_mode + + +def profile_line( + image, + src, + dst, + linewidth=1, + order=None, + mode='reflect', + cval=0.0, + *, + reduce_func=np.mean, +): + """Return the intensity profile of an image measured along a scan line. + + Parameters + ---------- + image : ndarray, shape (M, N[, C]) + The image, either grayscale (2D array) or multichannel + (3D array, where the final axis contains the channel + information). + src : array_like, shape (2,) + The coordinates of the start point of the scan line. + dst : array_like, shape (2,) + The coordinates of the end point of the scan + line. The destination point is *included* in the profile, in + contrast to standard numpy indexing. + linewidth : int, optional + Width of the scan, perpendicular to the line + order : int in {0, 1, 2, 3, 4, 5}, optional + The order of the spline interpolation, default is 0 if + image.dtype is bool and 1 otherwise. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + mode : {'constant', 'nearest', 'reflect', 'mirror', 'wrap'}, optional + How to compute any values falling outside of the image. + cval : float, optional + If `mode` is 'constant', what constant value to use outside the image. + reduce_func : callable, optional + Function used to calculate the aggregation of pixel values + perpendicular to the profile_line direction when `linewidth` > 1. + If set to None the unreduced array will be returned. + + Returns + ------- + return_value : array + The intensity profile along the scan line. The length of the profile + is the ceil of the computed length of the scan line. + + Examples + -------- + >>> x = np.array([[1, 1, 1, 2, 2, 2]]) + >>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)]) + >>> img + array([[0, 0, 0, 0, 0, 0], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [0, 0, 0, 0, 0, 0]]) + >>> profile_line(img, (2, 1), (2, 4)) + array([1., 1., 2., 2.]) + >>> profile_line(img, (1, 0), (1, 6), cval=4) + array([1., 1., 1., 2., 2., 2., 2.]) + + The destination point is included in the profile, in contrast to + standard numpy indexing. + For example: + + >>> profile_line(img, (1, 0), (1, 6)) # The final point is out of bounds + array([1., 1., 1., 2., 2., 2., 2.]) + >>> profile_line(img, (1, 0), (1, 5)) # This accesses the full first row + array([1., 1., 1., 2., 2., 2.]) + + For different reduce_func inputs: + + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.mean) + array([0.66666667, 0.66666667, 0.66666667, 1.33333333]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.max) + array([1, 1, 1, 2]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sum) + array([2, 2, 2, 4]) + + The unreduced array will be returned when `reduce_func` is None or when + `reduce_func` acts on each pixel value individually. + + >>> profile_line(img, (1, 2), (4, 2), linewidth=3, order=0, + ... reduce_func=None) + array([[1, 1, 2], + [1, 1, 2], + [1, 1, 2], + [0, 0, 0]]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sqrt) + array([[1. , 1. , 0. ], + [1. , 1. , 0. ], + [1. , 1. , 0. ], + [1.41421356, 1.41421356, 0. ]]) + """ + + order = _validate_interpolation_order(image.dtype, order) + mode = _fix_ndimage_mode(mode) + + perp_lines = _line_profile_coordinates(src, dst, linewidth=linewidth) + if image.ndim == 3: + pixels = [ + ndi.map_coordinates( + image[..., i], + perp_lines, + prefilter=order > 1, + order=order, + mode=mode, + cval=cval, + ) + for i in range(image.shape[2]) + ] + pixels = np.transpose(np.asarray(pixels), (1, 2, 0)) + else: + pixels = ndi.map_coordinates( + image, perp_lines, prefilter=order > 1, order=order, mode=mode, cval=cval + ) + # The outputted array with reduce_func=None gives an array where the + # row values (axis=1) are flipped. Here, we make this consistent. + pixels = np.flip(pixels, axis=1) + + if reduce_func is None: + intensities = pixels + else: + try: + intensities = reduce_func(pixels, axis=1) + except TypeError: # function doesn't allow axis kwarg + intensities = np.apply_along_axis(reduce_func, arr=pixels, axis=1) + + return intensities + + +def _line_profile_coordinates(src, dst, linewidth=1): + """Return the coordinates of the profile of an image along a scan line. + + Parameters + ---------- + src : 2-tuple of numeric scalar (float or int) + The start point of the scan line. + dst : 2-tuple of numeric scalar (float or int) + The end point of the scan line. + linewidth : int, optional + Width of the scan, perpendicular to the line + + Returns + ------- + coords : array, shape (2, N, C), float + The coordinates of the profile along the scan line. The length of the + profile is the ceil of the computed length of the scan line. + + Notes + ----- + This is a utility method meant to be used internally by skimage functions. + The destination point is included in the profile, in contrast to + standard numpy indexing. + """ + src_row, src_col = src = np.asarray(src, dtype=float) + dst_row, dst_col = dst = np.asarray(dst, dtype=float) + d_row, d_col = dst - src + theta = np.arctan2(d_row, d_col) + + length = int(np.ceil(np.hypot(d_row, d_col) + 1)) + # we add one above because we include the last point in the profile + # (in contrast to standard numpy indexing) + line_col = np.linspace(src_col, dst_col, length) + line_row = np.linspace(src_row, dst_row, length) + + # we subtract 1 from linewidth to change from pixel-counting + # (make this line 3 pixels wide) to point distances (the + # distance between pixel centers) + col_width = (linewidth - 1) * np.sin(-theta) / 2 + row_width = (linewidth - 1) * np.cos(theta) / 2 + perp_rows = np.stack( + [ + np.linspace(row_i - row_width, row_i + row_width, linewidth) + for row_i in line_row + ] + ) + perp_cols = np.stack( + [ + np.linspace(col_i - col_width, col_i + col_width, linewidth) + for col_i in line_col + ] + ) + return np.stack([perp_rows, perp_cols]) diff --git a/python_embeded/Lib/site-packages/skimage/metrics/__init__.py b/python_embeded/Lib/site-packages/skimage/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47d118ec8d87faa058e61bfbdc7704e32ce92e4a --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/__init__.py @@ -0,0 +1,5 @@ +"""Metrics corresponding to images, e.g., distance metrics, similarity, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/metrics/__init__.pyi b/python_embeded/Lib/site-packages/skimage/metrics/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..73199d59cfce8a1357ee8cdf6ac29bd087f1f986 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/__init__.pyi @@ -0,0 +1,28 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + "adapted_rand_error", + "variation_of_information", + "contingency_table", + "mean_squared_error", + "normalized_mutual_information", + "normalized_root_mse", + "peak_signal_noise_ratio", + "structural_similarity", + "hausdorff_distance", + "hausdorff_pair", +] + +from ._adapted_rand_error import adapted_rand_error +from ._contingency_table import contingency_table +from ._structural_similarity import structural_similarity +from ._variation_of_information import variation_of_information +from .set_metrics import hausdorff_distance, hausdorff_pair +from .simple_metrics import ( + mean_squared_error, + normalized_mutual_information, + normalized_root_mse, + peak_signal_noise_ratio, +) diff --git a/python_embeded/Lib/site-packages/skimage/metrics/_adapted_rand_error.py b/python_embeded/Lib/site-packages/skimage/metrics/_adapted_rand_error.py new file mode 100644 index 0000000000000000000000000000000000000000..28f07255b56f43a317bd3efd8f486cff231435a4 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/_adapted_rand_error.py @@ -0,0 +1,103 @@ +from .._shared.utils import check_shape_equality +from ._contingency_table import contingency_table + +__all__ = ['adapted_rand_error'] + + +def adapted_rand_error( + image_true=None, image_test=None, *, table=None, ignore_labels=(0,), alpha=0.5 +): + r"""Compute Adapted Rand error as defined by the SNEMI3D contest. [1]_ + + Parameters + ---------- + image_true : ndarray of int + Ground-truth label image, same shape as im_test. + image_test : ndarray of int + Test image. + table : scipy.sparse array in crs format, optional + A contingency table built with skimage.evaluate.contingency_table. + If None, it will be computed on the fly. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + alpha : float, optional + Relative weight given to precision and recall in the adapted Rand error + calculation. + + Returns + ------- + are : float + The adapted Rand error. + prec : float + The adapted Rand precision: this is the number of pairs of pixels that + have the same label in the test label image *and* in the true image, + divided by the number in the test image. + rec : float + The adapted Rand recall: this is the number of pairs of pixels that + have the same label in the test label image *and* in the true image, + divided by the number in the true image. + + Notes + ----- + Pixels with label 0 in the true segmentation are ignored in the score. + + The adapted Rand error is calculated as follows: + + :math:`1 - \frac{\sum_{ij} p_{ij}^{2}}{\alpha \sum_{k} s_{k}^{2} + + (1-\alpha)\sum_{k} t_{k}^{2}}`, + where :math:`p_{ij}` is the probability that a pixel has the same label + in the test image *and* in the true image, :math:`t_{k}` is the + probability that a pixel has label :math:`k` in the true image, + and :math:`s_{k}` is the probability that a pixel has label :math:`k` + in the test image. + + Default behavior is to weight precision and recall equally in the + adapted Rand error calculation. + When alpha = 0, adapted Rand error = recall. + When alpha = 1, adapted Rand error = precision. + + + References + ---------- + .. [1] Arganda-Carreras I, Turaga SC, Berger DR, et al. (2015) + Crowdsourcing the creation of image segmentation algorithms + for connectomics. Front. Neuroanat. 9:142. + :DOI:`10.3389/fnana.2015.00142` + """ + if image_test is not None and image_true is not None: + check_shape_equality(image_true, image_test) + + if table is None: + p_ij = contingency_table( + image_true, + image_test, + ignore_labels=ignore_labels, + normalize=False, + sparse_type="array", + ) + else: + p_ij = table + + if alpha < 0.0 or alpha > 1.0: + raise ValueError('alpha must be between 0 and 1') + + # Sum of the joint distribution squared + sum_p_ij2 = p_ij.data @ p_ij.data - p_ij.sum() + + a_i = p_ij.sum(axis=1).ravel() + b_i = p_ij.sum(axis=0).ravel() + + # Sum of squares of the test segment sizes (this is 2x the number of pairs + # of pixels with the same label in im_test) + sum_a2 = a_i @ a_i - a_i.sum() + # Same for im_true + sum_b2 = b_i @ b_i - b_i.sum() + + precision = sum_p_ij2 / sum_a2 + recall = sum_p_ij2 / sum_b2 + + fscore = sum_p_ij2 / (alpha * sum_a2 + (1 - alpha) * sum_b2) + are = 1.0 - fscore + + return are, precision, recall diff --git a/python_embeded/Lib/site-packages/skimage/metrics/_contingency_table.py b/python_embeded/Lib/site-packages/skimage/metrics/_contingency_table.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c297b8d5f47965d22334ed1d74091a56b59582 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/_contingency_table.py @@ -0,0 +1,51 @@ +import scipy.sparse as sparse +import numpy as np + +__all__ = ['contingency_table'] + + +def contingency_table( + im_true, im_test, *, ignore_labels=None, normalize=False, sparse_type="matrix" +): + """ + Return the contingency table for all regions in matched segmentations. + + Parameters + ---------- + im_true : ndarray of int + Ground-truth label image, same shape as im_test. + im_test : ndarray of int + Test image. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + normalize : bool + Determines if the contingency table is normalized by pixel count. + sparse_type : {"matrix", "array"}, optional + The return type of `cont`, either `scipy.sparse.csr_array` or + `scipy.sparse.csr_matrix` (default). + + Returns + ------- + cont : scipy.sparse.csr_matrix or scipy.sparse.csr_array + A contingency table. `cont[i, j]` will equal the number of voxels + labeled `i` in `im_true` and `j` in `im_test`. Depending on `sparse_type`, + this can be returned as a `scipy.sparse.csr_array`. + """ + + if ignore_labels is None: + ignore_labels = [] + im_test_r = im_test.reshape(-1) + im_true_r = im_true.reshape(-1) + data = np.isin(im_true_r, ignore_labels, invert=True).astype(float) + if normalize: + data /= np.count_nonzero(data) + cont = sparse.csr_array((data, (im_true_r, im_test_r))) + + if sparse_type == "matrix": + cont = sparse.csr_matrix(cont) + elif sparse_type != "array": + msg = f"`sparse_type` must be 'array' or 'matrix', got {sparse_type}" + raise ValueError(msg) + + return cont diff --git a/python_embeded/Lib/site-packages/skimage/metrics/_structural_similarity.py b/python_embeded/Lib/site-packages/skimage/metrics/_structural_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..6c351abf45405cd4839546396bfc642310b92f19 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/_structural_similarity.py @@ -0,0 +1,292 @@ +import functools + +import numpy as np +from scipy.ndimage import uniform_filter + +from .._shared import utils +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_shape_equality, warn +from ..util.arraycrop import crop +from ..util.dtype import dtype_range + +__all__ = ['structural_similarity'] + + +def structural_similarity( + im1, + im2, + *, + win_size=None, + gradient=False, + data_range=None, + channel_axis=None, + gaussian_weights=False, + full=False, + **kwargs, +): + """ + Compute the mean structural similarity index between two images. + Please pay attention to the `data_range` parameter with floating-point images. + + Parameters + ---------- + im1, im2 : ndarray + Images. Any dimensionality with same shape. + win_size : int or None, optional + The side-length of the sliding window used in comparison. Must be an + odd value. If `gaussian_weights` is True, this is ignored and the + window size will depend on `sigma`. + gradient : bool, optional + If True, also return the gradient with respect to im2. + data_range : float, optional + The data range of the input image (difference between maximum and + minimum possible values). By default, this is estimated from the image + data type. This estimate may be wrong for floating-point image data. + Therefore it is recommended to always pass this scalar value explicitly + (see note below). + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + gaussian_weights : bool, optional + If True, each patch has its mean and variance spatially weighted by a + normalized Gaussian kernel of width sigma=1.5. + full : bool, optional + If True, also return the full structural similarity image. + + Other Parameters + ---------------- + use_sample_covariance : bool + If True, normalize covariances by N-1 rather than, N where N is the + number of pixels within the sliding window. + K1 : float + Algorithm parameter, K1 (small constant, see [1]_). + K2 : float + Algorithm parameter, K2 (small constant, see [1]_). + sigma : float + Standard deviation for the Gaussian when `gaussian_weights` is True. + + Returns + ------- + mssim : float + The mean structural similarity index over the image. + grad : ndarray + The gradient of the structural similarity between im1 and im2 [2]_. + This is only returned if `gradient` is set to True. + S : ndarray + The full SSIM image. This is only returned if `full` is set to True. + + Notes + ----- + If `data_range` is not specified, the range is automatically guessed + based on the image data type. However for floating-point image data, this + estimate yields a result double the value of the desired range, as the + `dtype_range` in `skimage.util.dtype.py` has defined intervals from -1 to + +1. This yields an estimate of 2, instead of 1, which is most often + required when working with image data (as negative light intensities are + nonsensical). In case of working with YCbCr-like color data, note that + these ranges are different per channel (Cb and Cr have double the range + of Y), so one cannot calculate a channel-averaged SSIM with a single call + to this function, as identical ranges are assumed for each channel. + + To match the implementation of Wang et al. [1]_, set `gaussian_weights` + to True, `sigma` to 1.5, `use_sample_covariance` to False, and + specify the `data_range` argument. + + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_ssim`` to + ``skimage.metrics.structural_similarity``. + + References + ---------- + .. [1] Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. + (2004). Image quality assessment: From error visibility to + structural similarity. IEEE Transactions on Image Processing, + 13, 600-612. + https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf, + :DOI:`10.1109/TIP.2003.819861` + + .. [2] Avanaki, A. N. (2009). Exact global histogram specification + optimized for structural similarity. Optical Review, 16, 613-621. + :arxiv:`0901.0065` + :DOI:`10.1007/s10043-009-0119-z` + + """ + check_shape_equality(im1, im2) + float_type = _supported_float_type(im1.dtype) + + if channel_axis is not None: + # loop over channels + args = dict( + win_size=win_size, + gradient=gradient, + data_range=data_range, + channel_axis=None, + gaussian_weights=gaussian_weights, + full=full, + ) + args.update(kwargs) + nch = im1.shape[channel_axis] + mssim = np.empty(nch, dtype=float_type) + + if gradient: + G = np.empty(im1.shape, dtype=float_type) + if full: + S = np.empty(im1.shape, dtype=float_type) + channel_axis = channel_axis % im1.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + for ch in range(nch): + ch_result = structural_similarity(im1[_at(ch)], im2[_at(ch)], **args) + if gradient and full: + mssim[ch], G[_at(ch)], S[_at(ch)] = ch_result + elif gradient: + mssim[ch], G[_at(ch)] = ch_result + elif full: + mssim[ch], S[_at(ch)] = ch_result + else: + mssim[ch] = ch_result + mssim = mssim.mean() + if gradient and full: + return mssim, G, S + elif gradient: + return mssim, G + elif full: + return mssim, S + else: + return mssim + + K1 = kwargs.pop('K1', 0.01) + K2 = kwargs.pop('K2', 0.03) + sigma = kwargs.pop('sigma', 1.5) + if K1 < 0: + raise ValueError("K1 must be positive") + if K2 < 0: + raise ValueError("K2 must be positive") + if sigma < 0: + raise ValueError("sigma must be positive") + use_sample_covariance = kwargs.pop('use_sample_covariance', True) + + if gaussian_weights: + # Set to give an 11-tap filter with the default sigma of 1.5 to match + # Wang et. al. 2004. + truncate = 3.5 + + if win_size is None: + if gaussian_weights: + # set win_size used by crop to match the filter size + r = int(truncate * sigma + 0.5) # radius as in ndimage + win_size = 2 * r + 1 + else: + win_size = 7 # backwards compatibility + + if np.any((np.asarray(im1.shape) - win_size) < 0): + raise ValueError( + 'win_size exceeds image extent. ' + 'Either ensure that your images are ' + 'at least 7x7; or pass win_size explicitly ' + 'in the function call, with an odd value ' + 'less than or equal to the smaller side of your ' + 'images. If your images are multichannel ' + '(with color channels), set channel_axis to ' + 'the axis number corresponding to the channels.' + ) + + if not (win_size % 2 == 1): + raise ValueError('Window size must be odd.') + + if data_range is None: + if np.issubdtype(im1.dtype, np.floating) or np.issubdtype( + im2.dtype, np.floating + ): + raise ValueError( + 'Since image dtype is floating point, you must specify ' + 'the data_range parameter. Please read the documentation ' + 'carefully (including the note). It is recommended that ' + 'you always specify the data_range anyway.' + ) + if im1.dtype != im2.dtype: + warn( + "Inputs have mismatched dtypes. Setting data_range based on im1.dtype.", + stacklevel=2, + ) + dmin, dmax = dtype_range[im1.dtype.type] + data_range = dmax - dmin + if np.issubdtype(im1.dtype, np.integer) and (im1.dtype != np.uint8): + warn( + "Setting data_range based on im1.dtype. " + + f"data_range = {data_range:.0f}. " + + "Please specify data_range explicitly to avoid mistakes.", + stacklevel=2, + ) + + ndim = im1.ndim + + if gaussian_weights: + filter_func = gaussian + filter_args = {'sigma': sigma, 'truncate': truncate, 'mode': 'reflect'} + else: + filter_func = uniform_filter + filter_args = {'size': win_size} + + # ndimage filters need floating point data + im1 = im1.astype(float_type, copy=False) + im2 = im2.astype(float_type, copy=False) + + NP = win_size**ndim + + # filter has already normalized by NP + if use_sample_covariance: + cov_norm = NP / (NP - 1) # sample covariance + else: + cov_norm = 1.0 # population covariance to match Wang et. al. 2004 + + # compute (weighted) means + ux = filter_func(im1, **filter_args) + uy = filter_func(im2, **filter_args) + + # compute (weighted) variances and covariances + uxx = filter_func(im1 * im1, **filter_args) + uyy = filter_func(im2 * im2, **filter_args) + uxy = filter_func(im1 * im2, **filter_args) + vx = cov_norm * (uxx - ux * ux) + vy = cov_norm * (uyy - uy * uy) + vxy = cov_norm * (uxy - ux * uy) + + R = data_range + C1 = (K1 * R) ** 2 + C2 = (K2 * R) ** 2 + + A1, A2, B1, B2 = ( + 2 * ux * uy + C1, + 2 * vxy + C2, + ux**2 + uy**2 + C1, + vx + vy + C2, + ) + D = B1 * B2 + S = (A1 * A2) / D + + # to avoid edge effects will ignore filter radius strip around edges + pad = (win_size - 1) // 2 + + # compute (weighted) mean of ssim. Use float64 for accuracy. + mssim = crop(S, pad).mean(dtype=np.float64) + + if gradient: + # The following is Eqs. 7-8 of Avanaki 2009. + grad = filter_func(A1 / D, **filter_args) * im1 + grad += filter_func(-S / B2, **filter_args) * im2 + grad += filter_func((ux * (A2 - A1) - uy * (B2 - B1) * S) / D, **filter_args) + grad *= 2 / im1.size + + if full: + return mssim, grad, S + else: + return mssim, grad + else: + if full: + return mssim, S + else: + return mssim diff --git a/python_embeded/Lib/site-packages/skimage/metrics/_variation_of_information.py b/python_embeded/Lib/site-packages/skimage/metrics/_variation_of_information.py new file mode 100644 index 0000000000000000000000000000000000000000..198563fab716405d9a5cfe2b75d0d2ecca47d025 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/_variation_of_information.py @@ -0,0 +1,133 @@ +import numpy as np +import scipy.sparse as sparse +from ._contingency_table import contingency_table +from .._shared.utils import check_shape_equality + +__all__ = ['variation_of_information'] + + +def variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=()): + """Return symmetric conditional entropies associated with the VI. [1]_ + + The variation of information is defined as VI(X,Y) = H(X|Y) + H(Y|X). + If X is the ground-truth segmentation, then H(X|Y) can be interpreted + as the amount of under-segmentation and H(Y|X) as the amount + of over-segmentation. In other words, a perfect over-segmentation + will have H(X|Y)=0 and a perfect under-segmentation will have H(Y|X)=0. + + Parameters + ---------- + image0, image1 : ndarray of int + Label images / segmentations, must have same shape. + table : scipy.sparse array in csr format, optional + A contingency table built with skimage.evaluate.contingency_table. + If None, it will be computed with skimage.evaluate.contingency_table. + If given, the entropies will be computed from this table and any images + will be ignored. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + + Returns + ------- + vi : ndarray of float, shape (2,) + The conditional entropies of image1|image0 and image0|image1. + + References + ---------- + .. [1] Marina Meilă (2007), Comparing clusterings—an information based + distance, Journal of Multivariate Analysis, Volume 98, Issue 5, + Pages 873-895, ISSN 0047-259X, :DOI:`10.1016/j.jmva.2006.11.013`. + """ + h0g1, h1g0 = _vi_tables(image0, image1, table=table, ignore_labels=ignore_labels) + # false splits, false merges + return np.array([h1g0.sum(), h0g1.sum()]) + + +def _xlogx(x): + """Compute x * log_2(x). + + We define 0 * log_2(0) = 0 + + Parameters + ---------- + x : ndarray or scipy.sparse.csc_array or scipy.sparse.csr_array + The input array. + + Returns + ------- + y : same type as x + Result of x * log_2(x). + """ + y = x.copy() + if sparse.issparse(y) and y.format in ('csc', 'csr'): + z = y.data + else: + z = np.asarray(y) # ensure np.matrix converted to np.array + nz = z.nonzero() + z[nz] *= np.log2(z[nz]) + return y + + +def _vi_tables(im_true, im_test, table=None, ignore_labels=()): + """Compute probability tables used for calculating VI. + + Parameters + ---------- + im_true, im_test : ndarray of int + Input label images, any dimensionality. + table : csr_array, optional + Pre-computed contingency table. + ignore_labels : sequence of int, optional + Labels to ignore when computing scores. + + Returns + ------- + hxgy, hygx : ndarray of float + Per-segment conditional entropies of ``im_true`` given ``im_test`` and + vice-versa. + """ + check_shape_equality(im_true, im_test) + + if table is None: + # normalize, since it is an identity op if already done + pxy = contingency_table( + im_true, im_test, ignore_labels=ignore_labels, normalize=True + ) + + else: + pxy = table + + # compute marginal probabilities, converting to 1D array + px = np.ravel(pxy.sum(axis=1)) + py = np.ravel(pxy.sum(axis=0)) + + # use sparse matrix linear algebra to compute VI + # first, compute the inverse diagonal matrices + px_inv = sparse.dia_array((_invert_nonzero(px), 0), shape=(px.size, px.size)) + py_inv = sparse.dia_array((_invert_nonzero(py), 0), shape=(py.size, py.size)) + + # then, compute the entropies + hygx = -px @ _xlogx(px_inv @ pxy).sum(axis=1) + hxgy = -_xlogx(pxy @ py_inv).sum(axis=0) @ py + + return list(map(np.asarray, [hxgy, hygx])) + + +def _invert_nonzero(arr): + """Compute the inverse of the non-zero elements of arr, not changing 0. + + Parameters + ---------- + arr : ndarray + + Returns + ------- + arr_inv : ndarray + Array containing the inverse of the non-zero elements of arr, and + zero elsewhere. + """ + arr_inv = arr.copy() + nz = np.nonzero(arr) + arr_inv[nz] = 1 / arr[nz] + return arr_inv diff --git a/python_embeded/Lib/site-packages/skimage/metrics/set_metrics.py b/python_embeded/Lib/site-packages/skimage/metrics/set_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..6828be5ccaa238d1ab57a063d17c56cb804b560f --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/set_metrics.py @@ -0,0 +1,147 @@ +import warnings + +import numpy as np +from scipy.spatial import cKDTree + + +def hausdorff_distance(image0, image1, method="standard"): + """Calculate the Hausdorff distance between nonzero elements of given images. + + Parameters + ---------- + image0, image1 : ndarray + Arrays where ``True`` represents a point that is included in a + set of points. Both arrays must have the same shape. + method : {'standard', 'modified'}, optional, default = 'standard' + The method to use for calculating the Hausdorff distance. + ``standard`` is the standard Hausdorff distance, while ``modified`` + is the modified Hausdorff distance. + + Returns + ------- + distance : float + The Hausdorff distance between coordinates of nonzero pixels in + ``image0`` and ``image1``, using the Euclidean distance. + + Notes + ----- + The Hausdorff distance [1]_ is the maximum distance between any point on + ``image0`` and its nearest point on ``image1``, and vice-versa. + The Modified Hausdorff Distance (MHD) has been shown to perform better + than the directed Hausdorff Distance (HD) in the following work by + Dubuisson et al. [2]_. The function calculates forward and backward + mean distances and returns the largest of the two. + + References + ---------- + .. [1] http://en.wikipedia.org/wiki/Hausdorff_distance + .. [2] M. P. Dubuisson and A. K. Jain. A Modified Hausdorff distance for object + matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994. + :DOI:`10.1109/ICPR.1994.576361` + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.1.8155 + + Examples + -------- + >>> points_a = (3, 0) + >>> points_b = (6, 0) + >>> shape = (7, 1) + >>> image_a = np.zeros(shape, dtype=bool) + >>> image_b = np.zeros(shape, dtype=bool) + >>> image_a[points_a] = True + >>> image_b[points_b] = True + >>> hausdorff_distance(image_a, image_b) + 3.0 + + """ + + if method not in ('standard', 'modified'): + raise ValueError(f'unrecognized method {method}') + + a_points = np.transpose(np.nonzero(image0)) + b_points = np.transpose(np.nonzero(image1)) + + # Handle empty sets properly: + # - if both sets are empty, return zero + # - if only one set is empty, return infinity + if len(a_points) == 0: + return 0 if len(b_points) == 0 else np.inf + elif len(b_points) == 0: + return np.inf + + fwd, bwd = ( + cKDTree(a_points).query(b_points, k=1)[0], + cKDTree(b_points).query(a_points, k=1)[0], + ) + + if method == 'standard': # standard Hausdorff distance + return max(max(fwd), max(bwd)) + elif method == 'modified': # modified Hausdorff distance + return max(np.mean(fwd), np.mean(bwd)) + + +def hausdorff_pair(image0, image1): + """Returns pair of points that are Hausdorff distance apart between nonzero + elements of given images. + + The Hausdorff distance [1]_ is the maximum distance between any point on + ``image0`` and its nearest point on ``image1``, and vice-versa. + + Parameters + ---------- + image0, image1 : ndarray + Arrays where ``True`` represents a point that is included in a + set of points. Both arrays must have the same shape. + + Returns + ------- + point_a, point_b : array + A pair of points that have Hausdorff distance between them. + + References + ---------- + .. [1] http://en.wikipedia.org/wiki/Hausdorff_distance + + Examples + -------- + >>> points_a = (3, 0) + >>> points_b = (6, 0) + >>> shape = (7, 1) + >>> image_a = np.zeros(shape, dtype=bool) + >>> image_b = np.zeros(shape, dtype=bool) + >>> image_a[points_a] = True + >>> image_b[points_b] = True + >>> hausdorff_pair(image_a, image_b) + (array([3, 0]), array([6, 0])) + + """ + a_points = np.transpose(np.nonzero(image0)) + b_points = np.transpose(np.nonzero(image1)) + + # If either of the sets are empty, there is no corresponding pair of points + if len(a_points) == 0 or len(b_points) == 0: + warnings.warn("One or both of the images is empty.", stacklevel=2) + return (), () + + nearest_dists_from_b, nearest_a_point_indices_from_b = cKDTree(a_points).query( + b_points + ) + nearest_dists_from_a, nearest_b_point_indices_from_a = cKDTree(b_points).query( + a_points + ) + + max_index_from_a = nearest_dists_from_b.argmax() + max_index_from_b = nearest_dists_from_a.argmax() + + max_dist_from_a = nearest_dists_from_b[max_index_from_a] + max_dist_from_b = nearest_dists_from_a[max_index_from_b] + + if max_dist_from_b > max_dist_from_a: + return ( + a_points[max_index_from_b], + b_points[nearest_b_point_indices_from_a[max_index_from_b]], + ) + else: + return ( + a_points[nearest_a_point_indices_from_b[max_index_from_a]], + b_points[max_index_from_a], + ) diff --git a/python_embeded/Lib/site-packages/skimage/metrics/simple_metrics.py b/python_embeded/Lib/site-packages/skimage/metrics/simple_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce175867f3eea144106ff7bf1af7abc49709c73 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/metrics/simple_metrics.py @@ -0,0 +1,270 @@ +import numpy as np +from scipy.stats import entropy + +from ..util.dtype import dtype_range +from .._shared.utils import _supported_float_type, check_shape_equality, warn + +__all__ = [ + 'mean_squared_error', + 'normalized_root_mse', + 'peak_signal_noise_ratio', + 'normalized_mutual_information', +] + + +def _as_floats(image0, image1): + """ + Promote im1, im2 to nearest appropriate floating point precision. + """ + float_type = _supported_float_type((image0.dtype, image1.dtype)) + image0 = np.asarray(image0, dtype=float_type) + image1 = np.asarray(image1, dtype=float_type) + return image0, image1 + + +def mean_squared_error(image0, image1): + """ + Compute the mean-squared error between two images. + + Parameters + ---------- + image0, image1 : ndarray + Images. Any dimensionality, must have same shape. + + Returns + ------- + mse : float + The mean-squared error (MSE) metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_mse`` to + ``skimage.metrics.mean_squared_error``. + + """ + check_shape_equality(image0, image1) + image0, image1 = _as_floats(image0, image1) + return np.mean((image0 - image1) ** 2, dtype=np.float64) + + +def normalized_root_mse(image_true, image_test, *, normalization='euclidean'): + """ + Compute the normalized root mean-squared error (NRMSE) between two + images. + + Parameters + ---------- + image_true : ndarray + Ground-truth image, same shape as im_test. + image_test : ndarray + Test image. + normalization : {'euclidean', 'min-max', 'mean'}, optional + Controls the normalization method to use in the denominator of the + NRMSE. There is no standard method of normalization across the + literature [1]_. The methods available here are as follows: + + - 'euclidean' : normalize by the averaged Euclidean norm of + ``im_true``:: + + NRMSE = RMSE * sqrt(N) / || im_true || + + where || . || denotes the Frobenius norm and ``N = im_true.size``. + This result is equivalent to:: + + NRMSE = || im_true - im_test || / || im_true ||. + + - 'min-max' : normalize by the intensity range of ``im_true``. + - 'mean' : normalize by the mean of ``im_true`` + + Returns + ------- + nrmse : float + The NRMSE metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_nrmse`` to + ``skimage.metrics.normalized_root_mse``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Root-mean-square_deviation + + """ + check_shape_equality(image_true, image_test) + image_true, image_test = _as_floats(image_true, image_test) + + # Ensure that both 'Euclidean' and 'euclidean' match + normalization = normalization.lower() + if normalization == 'euclidean': + denom = np.sqrt(np.mean((image_true * image_true), dtype=np.float64)) + elif normalization == 'min-max': + denom = image_true.max() - image_true.min() + elif normalization == 'mean': + denom = image_true.mean() + else: + raise ValueError("Unsupported norm_type") + return np.sqrt(mean_squared_error(image_true, image_test)) / denom + + +def peak_signal_noise_ratio(image_true, image_test, *, data_range=None): + """ + Compute the peak signal to noise ratio (PSNR) for an image. + + Parameters + ---------- + image_true : ndarray + Ground-truth image, same shape as im_test. + image_test : ndarray + Test image. + data_range : int, optional + The data range of the input image (distance between minimum and + maximum possible values). By default, this is estimated from the image + data-type. + + Returns + ------- + psnr : float + The PSNR metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_psnr`` to + ``skimage.metrics.peak_signal_noise_ratio``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio + + """ + check_shape_equality(image_true, image_test) + + if data_range is None: + if image_true.dtype != image_test.dtype: + warn( + "Inputs have mismatched dtype. Setting data_range based on " + "image_true." + ) + dmin, dmax = dtype_range[image_true.dtype.type] + true_min, true_max = np.min(image_true), np.max(image_true) + if true_max > dmax or true_min < dmin: + raise ValueError( + "image_true has intensity values outside the range expected " + "for its data type. Please manually specify the data_range." + ) + if true_min >= 0: + # most common case (255 for uint8, 1 for float) + data_range = dmax + else: + data_range = dmax - dmin + + image_true, image_test = _as_floats(image_true, image_test) + + err = mean_squared_error(image_true, image_test) + data_range = float(data_range) # prevent overflow for small integer types + return 10 * np.log10((data_range**2) / err) + + +def _pad_to(arr, shape): + """Pad an array with trailing zeros to a given target shape. + + Parameters + ---------- + arr : ndarray + The input array. + shape : tuple + The target shape. + + Returns + ------- + padded : ndarray + The padded array. + + Examples + -------- + >>> _pad_to(np.ones((1, 1), dtype=int), (1, 3)) + array([[1, 0, 0]]) + """ + if not all(s >= i for s, i in zip(shape, arr.shape)): + raise ValueError( + f'Target shape {shape} cannot be smaller than input' + f'shape {arr.shape} along any axis.' + ) + padding = [(0, s - i) for s, i in zip(shape, arr.shape)] + return np.pad(arr, pad_width=padding, mode='constant', constant_values=0) + + +def normalized_mutual_information(image0, image1, *, bins=100): + r"""Compute the normalized mutual information (NMI). + + The normalized mutual information of :math:`A` and :math:`B` is given by:: + + .. math:: + + Y(A, B) = \frac{H(A) + H(B)}{H(A, B)} + + where :math:`H(X) := - \sum_{x \in X}{x \log x}` is the entropy. + + It was proposed to be useful in registering images by Colin Studholme and + colleagues [1]_. It ranges from 1 (perfectly uncorrelated image values) + to 2 (perfectly correlated image values, whether positively or negatively). + + Parameters + ---------- + image0, image1 : ndarray + Images to be compared. The two input images must have the same number + of dimensions. + bins : int or sequence of int, optional + The number of bins along each axis of the joint histogram. + + Returns + ------- + nmi : float + The normalized mutual information between the two arrays, computed at + the granularity given by ``bins``. Higher NMI implies more similar + input images. + + Raises + ------ + ValueError + If the images don't have the same number of dimensions. + + Notes + ----- + If the two input images are not the same shape, the smaller image is padded + with zeros. + + References + ---------- + .. [1] C. Studholme, D.L.G. Hill, & D.J. Hawkes (1999). An overlap + invariant entropy measure of 3D medical image alignment. + Pattern Recognition 32(1):71-86 + :DOI:`10.1016/S0031-3203(98)00091-0` + """ + if image0.ndim != image1.ndim: + raise ValueError( + f'NMI requires images of same number of dimensions. ' + f'Got {image0.ndim}D for `image0` and ' + f'{image1.ndim}D for `image1`.' + ) + if image0.shape != image1.shape: + max_shape = np.maximum(image0.shape, image1.shape) + padded0 = _pad_to(image0, max_shape) + padded1 = _pad_to(image1, max_shape) + else: + padded0, padded1 = image0, image1 + + hist, bin_edges = np.histogramdd( + [np.reshape(padded0, -1), np.reshape(padded1, -1)], + bins=bins, + density=True, + ) + + H0 = entropy(np.sum(hist, axis=0)) + H1 = entropy(np.sum(hist, axis=1)) + H01 = entropy(np.reshape(hist, -1)) + + return (H0 + H1) / H01 diff --git a/python_embeded/Lib/site-packages/skimage/morphology/__init__.py b/python_embeded/Lib/site-packages/skimage/morphology/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa300a691d2e7cf2993de12793c2c1388c2517ea --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/__init__.py @@ -0,0 +1,91 @@ +"""Morphological algorithms, e.g., closing, opening, skeletonization.""" + +from .binary import binary_closing, binary_dilation, binary_erosion, binary_opening +from .gray import black_tophat, closing, dilation, erosion, opening, white_tophat +from .isotropic import ( + isotropic_erosion, + isotropic_dilation, + isotropic_opening, + isotropic_closing, +) +from .footprints import ( + ball, + cube, + diamond, + disk, + ellipse, + footprint_from_sequence, + footprint_rectangle, + mirror_footprint, + octagon, + octahedron, + pad_footprint, + rectangle, + square, + star, +) +from ..measure._label import label +from ._skeletonize import medial_axis, skeletonize, thin +from .convex_hull import convex_hull_image, convex_hull_object +from .grayreconstruct import reconstruction +from .misc import remove_small_holes, remove_small_objects, remove_objects_by_distance +from .extrema import h_maxima, h_minima, local_minima, local_maxima +from ._flood_fill import flood, flood_fill +from .max_tree import ( + area_opening, + area_closing, + diameter_closing, + diameter_opening, + max_tree, + max_tree_local_maxima, +) + +__all__ = [ + 'area_closing', + 'area_opening', + 'ball', + 'binary_closing', + 'binary_dilation', + 'binary_erosion', + 'binary_opening', + 'black_tophat', + 'closing', + 'convex_hull_image', + 'convex_hull_object', + 'diameter_closing', + 'diameter_opening', + 'diamond', + 'dilation', + 'disk', + 'ellipse', + 'erosion', + 'flood', + 'flood_fill', + 'footprint_from_sequence', + 'footprint_rectangle', + 'h_maxima', + 'h_minima', + 'isotropic_closing', + 'isotropic_dilation', + 'isotropic_erosion', + 'isotropic_opening', + 'label', + 'local_maxima', + 'local_minima', + 'max_tree', + 'max_tree_local_maxima', + 'medial_axis', + 'mirror_footprint', + 'octagon', + 'octahedron', + 'opening', + 'pad_footprint', + 'reconstruction', + 'remove_small_holes', + 'remove_small_objects', + 'remove_objects_by_distance', + 'skeletonize', + 'star', + 'thin', + 'white_tophat', +] diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_convex_hull.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_convex_hull.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..65ae3a8f4989d1d4e55abc6cfd0778e865da5115 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_convex_hull.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_extrema_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_extrema_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..39660bdd43b9e0420fab590d27ceaef9e7d688c2 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_extrema_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill.py b/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b1dc26273931c82bdbbd1db5f66bced3ba26e2 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill.py @@ -0,0 +1,310 @@ +"""flood_fill.py - in place flood fill algorithm + +This module provides a function to fill all equal (or within tolerance) values +connected to a given seed point with a different value. +""" + +import numpy as np + +from ..util import crop +from ._flood_fill_cy import _flood_fill_equal, _flood_fill_tolerance +from ._util import ( + _offsets_to_raveled_neighbors, + _resolve_neighborhood, + _set_border_values, +) +from .._shared.dtype import numeric_dtype_min_max + + +def flood_fill( + image, + seed_point, + new_value, + *, + footprint=None, + connectivity=None, + tolerance=None, + in_place=False, +): + """Perform flood filling on an image. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found, then set to `new_value`. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + new_value : `image` type + New value to set the entire fill. This must be chosen in agreement + with the dtype of `image`. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + value of `image` at `seed_point` to be filled. This is fastest. + If a tolerance is provided, adjacent points with values within plus or + minus tolerance from the seed point are filled (inclusive). + in_place : bool, optional + If True, flood filling is applied to `image` in place. If False, the + flood filled result is returned without modifying the input `image` + (default). + + Returns + ------- + filled : ndarray + An array with the same shape as `image` is returned, with values in + areas connected to and equal (or within tolerance of) the seed point + replaced with `new_value`. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. + + Examples + -------- + >>> from skimage.morphology import flood_fill + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> flood_fill(image, (1, 1), 5) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> flood_fill(image, (1, 1), 5, connectivity=1) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> flood_fill(image, (0, 0), 5, tolerance=1) + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + mask = flood( + image, + seed_point, + footprint=footprint, + connectivity=connectivity, + tolerance=tolerance, + ) + + if not in_place: + image = image.copy() + + image[mask] = new_value + return image + + +def flood(image, seed_point, *, footprint=None, connectivity=None, tolerance=None): + """Mask corresponding to a flood fill. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + initial value of `image` at `seed_point`. This is fastest. If a value + is given, a comparison will be done at every point and if within + tolerance of the initial value will also be filled (inclusive). + + Returns + ------- + mask : ndarray + A Boolean array with the same shape as `image` is returned, with True + values for areas connected to and equal (or within tolerance of) the + seed point. All other values are False. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. This function returns just the mask + representing the fill. + + If indices are desired rather than masks for memory reasons, the user can + simply run `numpy.nonzero` on the result, save the indices, and discard + this mask. + + Examples + -------- + >>> from skimage.morphology import flood + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> mask = flood(image, (1, 1)) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> mask = flood(image, (1, 1), connectivity=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> mask = flood(image, (0, 0), tolerance=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + # Correct start point in ravelled image - only copy if non-contiguous + image = np.asarray(image) + if image.flags.f_contiguous is True: + order = 'F' + elif image.flags.c_contiguous is True: + order = 'C' + else: + image = np.ascontiguousarray(image) + order = 'C' + + # Shortcut for rank zero + if 0 in image.shape: + return np.zeros(image.shape, dtype=bool) + + # Convenience for 1d input + try: + iter(seed_point) + except TypeError: + seed_point = (seed_point,) + + seed_value = image[seed_point] + seed_point = tuple(np.asarray(seed_point) % image.shape) + + footprint = _resolve_neighborhood( + footprint, connectivity, image.ndim, enforce_adjacency=False + ) + center = tuple(s // 2 for s in footprint.shape) + # Compute padding width as the maximum offset to neighbors on each axis. + # Generates a 2-tuple of (pad_start, pad_end) for each axis. + pad_width = [ + (np.max(np.abs(idx - c)),) * 2 for idx, c in zip(np.nonzero(footprint), center) + ] + + # Must annotate borders + working_image = np.pad( + image, pad_width, mode='constant', constant_values=image.min() + ) + # Stride-aware neighbors - works for both C- and Fortran-contiguity + ravelled_seed_idx = np.ravel_multi_index( + [i + pad_start for i, (pad_start, pad_end) in zip(seed_point, pad_width)], + working_image.shape, + order=order, + ) + neighbor_offsets = _offsets_to_raveled_neighbors( + working_image.shape, footprint, center=center, order=order + ) + + # Use a set of flags; see _flood_fill_cy.pyx for meanings + flags = np.zeros(working_image.shape, dtype=np.uint8, order=order) + _set_border_values(flags, value=2, border_width=pad_width) + + try: + if tolerance is not None: + tolerance = abs(tolerance) + # Account for over- & underflow problems with seed_value ± tolerance + # in a way that works with NumPy 1 & 2 + min_value, max_value = numeric_dtype_min_max(seed_value.dtype) + low_tol = max(min_value.item(), seed_value.item() - tolerance) + high_tol = min(max_value.item(), seed_value.item() + tolerance) + + _flood_fill_tolerance( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + low_tol, + high_tol, + ) + else: + _flood_fill_equal( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + ) + except TypeError: + if working_image.dtype == np.float16: + # Provide the user with clearer error message + raise TypeError( + "dtype of `image` is float16 which is not " + "supported, try upcasting to float32" + ) + else: + raise + + # Output what the user requested; view does not create a new copy. + return crop(flags, pad_width, copy=False).view(bool) diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..162716d3f9dde7ba3fd4b2e15c28e5a0ed5c75c7 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_flood_fill_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_grayreconstruct.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_grayreconstruct.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..1df01530bbe8c13002f77270c87e265b92c0784a Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_grayreconstruct.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_max_tree.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_max_tree.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..e2cb43c368f63a91aa6d92b2d4dabdebfc69351d Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_max_tree.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_misc_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_misc_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..295267c94a3642440467616be9ed82006aa5fbff Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_misc_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize.py b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize.py new file mode 100644 index 0000000000000000000000000000000000000000..5a10ceed319a4881ce01d5a5a7e3fe250c77fef3 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize.py @@ -0,0 +1,655 @@ +""" +Algorithms for computing the skeleton of a binary image +""" + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD +from ..util import crop +from ._skeletonize_lee_cy import _compute_thin_image +from ._skeletonize_various_cy import ( + _fast_skeletonize, + _skeletonize_loop, + _table_lookup_index, +) + + +def skeletonize(image, *, method=None): + """Compute the skeleton of the input image via thinning. + + Parameters + ---------- + image : (M, N[, P]) ndarray of bool or int + The image containing the objects to be skeletonized. Each connected component + in the image is reduced to a single-pixel wide skeleton. The image is binarized + prior to thinning; thus, adjacent objects of different intensities are + considered as one. Zero or ``False`` values represent the background, nonzero + or ``True`` values -- foreground. + method : {'zhang', 'lee'}, optional + Which algorithm to use. Zhang's algorithm [Zha84]_ only works for + 2D images, and is the default for 2D. Lee's algorithm [Lee94]_ + works for 2D or 3D images and is the default for 3D. + + Returns + ------- + skeleton : (M, N[, P]) ndarray of bool + The thinned image. + + See Also + -------- + medial_axis + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[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, 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, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + 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, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 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]], dtype=uint8) + + """ + image = image.astype(bool, order="C", copy=False) + + if method not in {'zhang', 'lee', None}: + raise ValueError( + f'skeletonize method should be either "lee" or "zhang", ' f'got {method}.' + ) + if image.ndim == 2 and (method is None or method == 'zhang'): + skeleton = _skeletonize_zhang(image) + elif image.ndim == 3 and method == 'zhang': + raise ValueError('skeletonize method "zhang" only works for 2D ' 'images.') + elif image.ndim == 3 or (image.ndim == 2 and method == 'lee'): + skeleton = _skeletonize_lee(image) + else: + raise ValueError( + f'skeletonize requires a 2D or 3D image as input, ' f'got {image.ndim}D.' + ) + return skeleton + + +def _skeletonize_zhang(image): + """Return the skeleton of a 2D binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : numpy.ndarray + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray + A matrix containing the thinned image. + + See Also + -------- + medial_axis, skeletonize, thin + + Notes + ----- + The algorithm [Zha84]_ works by making successive passes of the image, + removing pixels on object borders. This continues until no + more pixels can be removed. The image is correlated with a + mask that assigns each pixel a number in the range [0...255] + corresponding to each possible pattern of its 8 neighboring + pixels. A look up table is then used to assign the pixels a + value of 0, 1, 2 or 3, which are selectively removed during + the iterations. + + Note that this algorithm will give different results than a + medial axis transform, which is also often referred to as + "skeletonization". + + References + ---------- + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[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, 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, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + 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, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 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]], dtype=uint8) + + """ + if image.ndim != 2: + raise ValueError("Zhang's skeletonize method requires a 2D array") + return _fast_skeletonize(image) + + +# --------- Skeletonization and thinning based on Guo and Hall 1989 --------- + + +def _generate_thin_luts(): + """generate LUTs for thinning algorithm (for reference)""" + + def nabe(n): + return np.array([n >> i & 1 for i in range(0, 9)]).astype(bool) + + def G1(n): + s = 0 + bits = nabe(n) + for i in (0, 2, 4, 6): + if not (bits[i]) and (bits[i + 1] or bits[(i + 2) % 8]): + s += 1 + return s == 1 + + g1_lut = np.array([G1(n) for n in range(256)]) + + def G2(n): + n1, n2 = 0, 0 + bits = nabe(n) + for k in (1, 3, 5, 7): + if bits[k] or bits[k - 1]: + n1 += 1 + if bits[k] or bits[(k + 1) % 8]: + n2 += 1 + return min(n1, n2) in [2, 3] + + g2_lut = np.array([G2(n) for n in range(256)]) + + g12_lut = g1_lut & g2_lut + + def G3(n): + bits = nabe(n) + return not ((bits[1] or bits[2] or not (bits[7])) and bits[0]) + + def G3p(n): + bits = nabe(n) + return not ((bits[5] or bits[6] or not (bits[3])) and bits[4]) + + g3_lut = np.array([G3(n) for n in range(256)]) + g3p_lut = np.array([G3p(n) for n in range(256)]) + + g123_lut = g12_lut & g3_lut + g123p_lut = g12_lut & g3p_lut + + return g123_lut, g123p_lut + + +# fmt: off +G123_LUT = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 1, 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, 1, 0, 1, 0, 0, 0, 1, 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, 1, 0, 1, 0, 0, 0, 1, 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, 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, 1, + 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=bool) + +G123P_LUT = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 1, 0, 1, 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, 1, 0, + 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 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, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, + 0, 1, 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], dtype=bool) +# fmt: on + + +def thin(image, max_num_iter=None): + """ + Perform morphological thinning of a binary image. + + Parameters + ---------- + image : binary (M, N) ndarray + The image to thin. If this input isn't already a binary image, + it gets converted into one: In this case, zero values are considered + background (False), nonzero values are considered foreground (True). + max_num_iter : int, number of iterations, optional + Regardless of the value of this parameter, the thinned image + is returned immediately if an iteration produces no change. + If this parameter is specified it thus sets an upper bound on + the number of iterations performed. + + Returns + ------- + out : ndarray of bool + Thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + This algorithm [1]_ works by making multiple passes over the image, + removing pixels matching a set of criteria designed to thin + connected regions while preserving eight-connected components and + 2 x 2 squares [2]_. In each of the two sub-iterations the algorithm + correlates the intermediate skeleton image with a neighborhood mask, + then looks up each neighborhood in a lookup table indicating whether + the central pixel should be deleted in that sub-iteration. + + References + ---------- + .. [1] Z. Guo and R. W. Hall, "Parallel thinning with + two-subiteration algorithms," Comm. ACM, vol. 32, no. 3, + pp. 359-373, 1989. :DOI:`10.1145/62065.62074` + .. [2] Lam, L., Seong-Whan Lee, and Ching Y. Suen, "Thinning + Methodologies-A Comprehensive Survey," IEEE Transactions on + Pattern Analysis and Machine Intelligence, Vol 14, No. 9, + p. 879, 1992. :DOI:`10.1109/34.161346` + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square[0, 1] = 1 + >>> square.view(np.uint8) + array([[0, 1, 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]], dtype=uint8) + >>> skel = thin(square) + >>> skel.view(np.uint8) + array([[0, 1, 0, 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, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + # check that image is 2d + check_nD(image, 2) + + # convert image to uint8 with values in {0, 1} + skel = np.asanyarray(image, dtype=bool).copy().view(np.uint8) + + # neighborhood mask + mask = np.array([[8, 4, 2], [16, 0, 1], [32, 64, 128]], dtype=np.uint8) + + # iterate until convergence, up to the iteration limit + max_num_iter = max_num_iter or np.inf + num_iter = 0 + n_pts_old, n_pts_new = np.inf, np.sum(skel) + while n_pts_old != n_pts_new and num_iter < max_num_iter: + n_pts_old = n_pts_new + + # perform the two "subiterations" described in the paper + for lut in [G123_LUT, G123P_LUT]: + # correlate image with neighborhood mask + N = ndi.correlate(skel, mask, mode='constant') + # take deletion decision from this subiteration's LUT + D = np.take(lut, N) + # perform deletion + skel[D] = 0 + + n_pts_new = np.sum(skel) # count points after thinning + num_iter += 1 + + return skel.astype(bool) + + +# --------- Skeletonization by medial axis transform -------- + +_eight_connect = ndi.generate_binary_structure(2, 2) + + +def medial_axis(image, mask=None, return_distance=False, *, rng=None): + """Compute the medial axis transform of a binary image. + + Parameters + ---------- + image : binary ndarray, shape (M, N) + The image of the shape to skeletonize. If this input isn't already a + binary image, it gets converted into one: In this case, zero values are + considered background (False), nonzero values are considered + foreground (True). + mask : binary ndarray, shape (M, N), optional + If a mask is given, only those elements in `image` with a true + value in `mask` are used for computing the medial axis. + return_distance : bool, optional + If true, the distance transform is returned as well as the skeleton. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG determines the order in which pixels are processed for + tiebreaking. + + .. versionadded:: 0.19 + + Returns + ------- + out : ndarray of bools + Medial axis transform of the image + dist : ndarray of ints, optional + Distance transform of the image (only returned if `return_distance` + is True) + + See Also + -------- + skeletonize, thin + + Notes + ----- + This algorithm computes the medial axis transform of an image + as the ridges of its distance transform. + + The different steps of the algorithm are as follows + * A lookup table is used, that assigns 0 or 1 to each configuration of + the 3x3 binary square, whether the central pixel should be removed + or kept. We want a point to be removed if it has more than one neighbor + and if removing it does not change the number of connected components. + + * The distance transform to the background is computed, as well as + the cornerness of the pixel. + + * The foreground (value of 1) points are ordered by + the distance transform, then the cornerness. + + * A cython function is called to reduce the image to its skeleton. It + processes pixels in the order determined at the previous step, and + removes or maintains a pixel according to the lookup table. Because + of the ordering, it is possible to process all pixels in only one + pass. + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square.view(np.uint8) + 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]], dtype=uint8) + >>> medial_axis(square).view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 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, 1, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + global _eight_connect + if mask is None: + masked_image = image.astype(bool) + else: + masked_image = image.astype(bool).copy() + masked_image[~mask] = False + # + # Build lookup table - three conditions + # 1. Keep only positive pixels (center_is_foreground array). + # AND + # 2. Keep if removing the pixel results in a different connectivity + # (if the number of connected components is different with and + # without the central pixel) + # OR + # 3. Keep if # pixels in neighborhood is 2 or less + # Note that table is independent of image + center_is_foreground = (np.arange(512) & 2**4).astype(bool) + table = ( + center_is_foreground # condition 1. + & ( + np.array( + [ + ndi.label(_pattern_of(index), _eight_connect)[1] + != ndi.label(_pattern_of(index & ~(2**4)), _eight_connect)[1] + for index in range(512) + ] + ) # condition 2 + | np.array([np.sum(_pattern_of(index)) < 3 for index in range(512)]) + ) + # condition 3 + ) + + # Build distance transform + distance = ndi.distance_transform_edt(masked_image) + if return_distance: + store_distance = distance.copy() + + # Corners + # The processing order along the edge is critical to the shape of the + # resulting skeleton: if you process a corner first, that corner will + # be eroded and the skeleton will miss the arm from that corner. Pixels + # with fewer neighbors are more "cornery" and should be processed last. + # We use a cornerness_table lookup table where the score of a + # configuration is the number of background (0-value) pixels in the + # 3x3 neighborhood + cornerness_table = np.array( + [9 - np.sum(_pattern_of(index)) for index in range(512)] + ) + corner_score = _table_lookup(masked_image, cornerness_table) + + # Define arrays for inner loop + i, j = np.mgrid[0 : image.shape[0], 0 : image.shape[1]] + result = masked_image.copy() + distance = distance[result] + i = np.ascontiguousarray(i[result], dtype=np.intp) + j = np.ascontiguousarray(j[result], dtype=np.intp) + result = np.ascontiguousarray(result, np.uint8) + + # Determine the order in which pixels are processed. + # We use a random # for tiebreaking. Assign each pixel in the image a + # predictable, random # so that masking doesn't affect arbitrary choices + # of skeletons + # + generator = np.random.default_rng(rng) + tiebreaker = generator.permutation(np.arange(masked_image.sum())) + order = np.lexsort((tiebreaker, corner_score[masked_image], distance)) + order = np.ascontiguousarray(order, dtype=np.int32) + + table = np.ascontiguousarray(table, dtype=np.uint8) + # Remove pixels not belonging to the medial axis + _skeletonize_loop(result, i, j, order, table) + + result = result.astype(bool) + if mask is not None: + result[~mask] = image[~mask] + if return_distance: + return result, store_distance + else: + return result + + +def _pattern_of(index): + """ + Return the pattern represented by an index value + Byte decomposition of index + """ + return np.array( + [ + [index & 2**0, index & 2**1, index & 2**2], + [index & 2**3, index & 2**4, index & 2**5], + [index & 2**6, index & 2**7, index & 2**8], + ], + bool, + ) + + +def _table_lookup(image, table): + """ + Perform a morphological transform on an image, directed by its + neighbors + + Parameters + ---------- + image : ndarray + A binary image + table : ndarray + A 512-element table giving the transform of each pixel given + the values of that pixel and its 8-connected neighbors. + + Returns + ------- + result : ndarray of same shape as `image` + Transformed image + + Notes + ----- + The pixels are numbered like this:: + + 0 1 2 + 3 4 5 + 6 7 8 + + The index at a pixel is the sum of 2** for pixels + that evaluate to true. + """ + # + # We accumulate into the indexer to get the index into the table + # at each point in the image + # + if image.shape[0] < 3 or image.shape[1] < 3: + image = image.astype(bool) + indexer = np.zeros(image.shape, int) + indexer[1:, 1:] += image[:-1, :-1] * 2**0 + indexer[1:, :] += image[:-1, :] * 2**1 + indexer[1:, :-1] += image[:-1, 1:] * 2**2 + + indexer[:, 1:] += image[:, :-1] * 2**3 + indexer[:, :] += image[:, :] * 2**4 + indexer[:, :-1] += image[:, 1:] * 2**5 + + indexer[:-1, 1:] += image[1:, :-1] * 2**6 + indexer[:-1, :] += image[1:, :] * 2**7 + indexer[:-1, :-1] += image[1:, 1:] * 2**8 + else: + indexer = _table_lookup_index(np.ascontiguousarray(image, np.uint8)) + image = table[indexer] + return image + + +def _skeletonize_lee(image): + """Compute the skeleton of a binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : ndarray, 2D or 3D + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray of bool + The thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + The method of [Lee94]_ uses an octree data structure to examine a 3x3x3 + neighborhood of a pixel. The algorithm proceeds by iteratively sweeping + over the image, and removing pixels at each iteration until the image + stops changing. Each iteration consists of two steps: first, a list of + candidates for removal is assembled; then pixels from this list are + rechecked sequentially, to better preserve connectivity of the image. + + The algorithm this function implements is different from the algorithms + used by either `skeletonize` or `medial_axis`, thus for 2D images the + results produced by this function are generally different. + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + """ + # make sure the image is 3D or 2D + if image.ndim < 2 or image.ndim > 3: + raise ValueError( + "skeletonize can only handle 2D or 3D images; " + f"got image.ndim = {image.ndim} instead." + ) + + image_o = image.astype(bool, order="C", copy=False) + + # make a 2D input image 3D and pad it w/ zeros to simplify dealing w/ boundaries + # NB: careful here to not clobber the original *and* minimize copying + if image.ndim == 2: + image_o = image_o[np.newaxis, ...] + image_o = np.pad(image_o, pad_width=1, mode='constant') # copies + + # do the computation + image_o = _compute_thin_image(image_o) + + # crop it back and restore the original intensity range + image_o = crop(image_o, crop_width=1) + if image.ndim == 2: + image_o = image_o[0] + + return image_o diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_lee_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_lee_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..b3e468ec7a32ef3aef840691eeb882532e6cf7c8 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_lee_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_various_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_various_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..cb8a59afdbfa7cf7ec0181a45c004252851fde4f Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/morphology/_skeletonize_various_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/morphology/_util.py b/python_embeded/Lib/site-packages/skimage/morphology/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..58d48ad12318e16f25a990c557c409e6157adf69 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/_util.py @@ -0,0 +1,328 @@ +"""Utility functions used in the morphology subpackage.""" + +import numpy as np +from scipy import ndimage as ndi + + +def _validate_connectivity(image_dim, connectivity, offset): + """Convert any valid connectivity to a footprint and offset. + + Parameters + ---------- + image_dim : int + The number of dimensions of the input image. + connectivity : int, array, or None + The neighborhood connectivity. An integer is interpreted as in + ``scipy.ndimage.generate_binary_structure``, as the maximum number + of orthogonal steps to reach a neighbor. An array is directly + interpreted as a footprint and its shape is validated against + the input image shape. ``None`` is interpreted as a connectivity of 1. + offset : tuple of int, or None + The coordinates of the center of the footprint. + + Returns + ------- + c_connectivity : array of bool + The footprint (structuring element) corresponding to the input + `connectivity`. + offset : array of int + The offset corresponding to the center of the footprint. + + Raises + ------ + ValueError: + If the image dimension and the connectivity or offset dimensions don't + match. + """ + if connectivity is None: + connectivity = 1 + + if np.isscalar(connectivity): + c_connectivity = ndi.generate_binary_structure(image_dim, connectivity) + else: + c_connectivity = np.array(connectivity, bool) + if c_connectivity.ndim != image_dim: + raise ValueError("Connectivity dimension must be same as image") + + if offset is None: + if any([x % 2 == 0 for x in c_connectivity.shape]): + raise ValueError("Connectivity array must have an unambiguous " "center") + + offset = np.array(c_connectivity.shape) // 2 + + return c_connectivity, offset + + +def _raveled_offsets_and_distances( + image_shape, + *, + footprint=None, + connectivity=1, + center=None, + spacing=None, + order='C', +): + """Compute offsets to neighboring pixels in raveled coordinate space. + + This function also returns the corresponding distances from the center + pixel given a spacing (assumed to be 1 along each axis by default). + + Parameters + ---------- + image_shape : tuple of int + The shape of the image for which the offsets are being computed. + footprint : array of bool + The footprint of the neighborhood, expressed as an n-dimensional array + of 1s and 0s. If provided, the connectivity argument is ignored. + connectivity : {1, ..., ndim} + The square connectivity of the neighborhood: the number of orthogonal + steps allowed to consider a pixel a neighbor. See + `scipy.ndimage.generate_binary_structure`. Ignored if footprint is + provided. + center : tuple of int + Tuple of indices to the center of the footprint. If not provided, it + is assumed to be the center of the footprint, either provided or + generated by the connectivity argument. + spacing : tuple of float + The spacing between pixels/voxels along each axis. + order : 'C' or 'F' + The ordering of the array, either C or Fortran ordering. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + distances : ndarray + The pixel distances corresponding to each offset. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> off, d = _raveled_offsets_and_distances( + ... (4, 5), footprint=np.ones((4, 3)), center=(1, 1) + ... ) + >>> off + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> d[0] + 1.0 + >>> d[-1] # distance from (1, 1) to (3, 2) + 2.236... + """ + ndim = len(image_shape) + if footprint is None: + footprint = ndi.generate_binary_structure(rank=ndim, connectivity=connectivity) + if center is None: + center = tuple(s // 2 for s in footprint.shape) + + if not footprint.ndim == ndim == len(center): + raise ValueError( + "number of dimensions in image shape, footprint and its" + "center index does not match" + ) + + offsets = np.stack( + [(idx - c) for idx, c in zip(np.nonzero(footprint), center)], axis=-1 + ) + + if order == 'F': + offsets = offsets[:, ::-1] + image_shape = image_shape[::-1] + elif order != 'C': + raise ValueError("order must be 'C' or 'F'") + + # Scale offsets in each dimension and sum + ravel_factors = image_shape[1:] + (1,) + ravel_factors = np.cumprod(ravel_factors[::-1])[::-1] + raveled_offsets = (offsets * ravel_factors).sum(axis=1) + + # Sort by distance + if spacing is None: + spacing = np.ones(ndim) + weighted_offsets = offsets * spacing + distances = np.sqrt(np.sum(weighted_offsets**2, axis=1)) + sorted_raveled_offsets = raveled_offsets[np.argsort(distances, kind="stable")] + sorted_distances = np.sort(distances, kind="stable") + + # If any dimension in image_shape is smaller than footprint.shape + # duplicates might occur, remove them + if any(x < y for x, y in zip(image_shape, footprint.shape)): + # np.unique reorders, which we don't want + _, indices = np.unique(sorted_raveled_offsets, return_index=True) + indices = np.sort(indices, kind="stable") + sorted_raveled_offsets = sorted_raveled_offsets[indices] + sorted_distances = sorted_distances[indices] + + # Remove "offset to center" + sorted_raveled_offsets = sorted_raveled_offsets[1:] + sorted_distances = sorted_distances[1:] + + return sorted_raveled_offsets, sorted_distances + + +def _offsets_to_raveled_neighbors(image_shape, footprint, center, order='C'): + """Compute offsets to a samples neighbors if the image would be raveled. + + Parameters + ---------- + image_shape : tuple + The shape of the image for which the offsets are computed. + footprint : ndarray + The footprint (structuring element) determining the neighborhood + expressed as an n-D array of 1's and 0's. + center : tuple + Tuple of indices to the center of `footprint`. + order : {"C", "F"}, optional + Whether the image described by `image_shape` is in row-major (C-style) + or column-major (Fortran-style) order. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> _offsets_to_raveled_neighbors((4, 5), np.ones((4, 3)), (1, 1)) + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> _offsets_to_raveled_neighbors((2, 3, 2), np.ones((3, 3, 3)), (1, 1, 1)) + array([-6, -2, -1, 1, 2, 6, -8, -7, -5, -4, -3, 3, 4, 5, 7, 8, -9, + 9]) + """ + raveled_offsets = _raveled_offsets_and_distances( + image_shape, footprint=footprint, center=center, order=order + )[0] + + return raveled_offsets + + +def _resolve_neighborhood(footprint, connectivity, ndim, enforce_adjacency=True): + """Validate or create a footprint (structuring element). + + Depending on the values of `connectivity` and `footprint` this function + either creates a new footprint (`footprint` is None) using `connectivity` + or validates the given footprint (`footprint` is not None). + + Parameters + ---------- + footprint : ndarray + The footprint (structuring) element used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + ndim : int + Number of dimensions `footprint` ought to have. + enforce_adjacency : bool + A boolean that determines whether footprint must only specify direct + neighbors. + + Returns + ------- + footprint : ndarray + Validated or new footprint specifying the neighborhood. + + Examples + -------- + >>> _resolve_neighborhood(None, 1, 2) + array([[False, True, False], + [ True, True, True], + [False, True, False]]) + >>> _resolve_neighborhood(None, None, 3).shape + (3, 3, 3) + """ + if footprint is None: + if connectivity is None: + connectivity = ndim + footprint = ndi.generate_binary_structure(ndim, connectivity) + else: + # Validate custom structured element + footprint = np.asarray(footprint, dtype=bool) + # Must specify neighbors for all dimensions + if footprint.ndim != ndim: + raise ValueError( + "number of dimensions in image and footprint do not" "match" + ) + # Must only specify direct neighbors + if enforce_adjacency and any(s != 3 for s in footprint.shape): + raise ValueError("dimension size in footprint is not 3") + elif any((s % 2 != 1) for s in footprint.shape): + raise ValueError("footprint size must be odd along all dimensions") + + return footprint + + +def _set_border_values(image, value, border_width=1): + """Set edge values along all axes to a constant value. + + Parameters + ---------- + image : ndarray + The array to modify inplace. + value : scalar + The value to use. Should be compatible with `image`'s dtype. + border_width : int or sequence of tuples + A sequence with one 2-tuple per axis where the first and second values + are the width of the border at the start and end of the axis, + respectively. If an int is provided, a uniform border width along all + axes is used. + + Examples + -------- + >>> image = np.zeros((4, 5), dtype=int) + >>> _set_border_values(image, 1) + >>> image + array([[1, 1, 1, 1, 1], + [1, 0, 0, 0, 1], + [1, 0, 0, 0, 1], + [1, 1, 1, 1, 1]]) + >>> image = np.zeros((8, 8), dtype=int) + >>> _set_border_values(image, 1, border_width=((1, 1), (2, 3))) + >>> image + array([[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]]) + """ + if np.isscalar(border_width): + border_width = ((border_width, border_width),) * image.ndim + elif len(border_width) != image.ndim: + raise ValueError('length of `border_width` must match image.ndim') + for axis, npad in enumerate(border_width): + if len(npad) != 2: + raise ValueError('each sequence in `border_width` must have ' 'length 2') + w_start, w_end = npad + if w_start == w_end == 0: + continue + elif w_start == w_end == 1: + # Index first and last element in the current dimension + sl = (slice(None),) * axis + ((0, -1),) + (...,) + image[sl] = value + continue + if w_start > 0: + # set first w_start entries along axis to value + sl = (slice(None),) * axis + (slice(0, w_start),) + (...,) + image[sl] = value + if w_end > 0: + # set last w_end entries along axis to value + sl = (slice(None),) * axis + (slice(-w_end, None),) + (...,) + image[sl] = value diff --git a/python_embeded/Lib/site-packages/skimage/morphology/binary.py b/python_embeded/Lib/site-packages/skimage/morphology/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..ee049e71363295d2284d8d2eb628096258512345 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/binary.py @@ -0,0 +1,320 @@ +""" +Binary morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + +from .footprints import _footprint_is_sequence, pad_footprint +from .misc import default_footprint + + +def _iterate_binary_func(binary_func, image, footprint, out, border_value): + """Helper to call `binary_func` for each footprint in a sequence. + + binary_func is a binary morphology function that accepts "structure", + "output" and "iterations" keyword arguments + (e.g. `scipy.ndimage.binary_erosion`). + """ + fp, num_iter = footprint[0] + binary_func( + image, structure=fp, output=out, iterations=num_iter, border_value=border_value + ) + for fp, num_iter in footprint[1:]: + # Note: out.copy() because the computation cannot be in-place! + # SciPy <= 1.7 did not automatically make a copy if needed. + binary_func( + out.copy(), + structure=fp, + output=out, + iterations=num_iter, + border_value=border_value, + ) + return out + + +# The default_footprint decorator provides a diamond footprint as +# default with the same dimension as the input image and size 3 along each +# axis. +@default_footprint +def binary_erosion(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological erosion of an image. + + This function returns the same result as grayscale erosion but performs + faster for binary images. + + Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all + pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright + regions and enlarges dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'max' or 'ignore', pixels outside the image domain are assumed + to be `True`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + eroded : ndarray of bool or uint + The result of the morphological erosion taking values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For even-sized footprints, :func:`skimage.morphology.erosion` and + this function produce an output that differs: one is shifted by one pixel + compared to the other. + + See also + -------- + skimage.morphology.isotropic_erosion + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = False if mode == 'min' else True + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_erosion, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +def binary_dilation(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological dilation of an image. + + This function returns the same result as grayscale dilation but performs + faster for binary images. + + Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all + pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright + regions and shrinks dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'min' or 'ignore', pixels outside the image domain are assumed + to be `False`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + dilated : ndarray of bool or uint + The result of the morphological dilation with values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For non-symmetric footprints, :func:`skimage.morphology.binary_dilation` + and :func:`skimage.morphology.dilation` produce an output that differs: + `binary_dilation` mirrors the footprint, whereas `dilation` does not. + + See also + -------- + skimage.morphology.isotropic_dilation + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = True if mode == 'max' else False + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_dilation, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +def binary_opening(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological opening of an image. + + This function returns the same result as grayscale opening but performs + faster for binary images. + + The morphological opening on an image is defined as an erosion followed by + a dilation. Opening can remove small bright spots (i.e. "salt") and connect + small dark cracks. This tends to "open" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + opening : ndarray of bool + The result of the morphological opening. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_opening + + """ + tmp = binary_erosion(image, footprint, mode=mode) + out = binary_dilation(tmp, footprint, out=out, mode=mode) + return out + + +@default_footprint +def binary_closing(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological closing of an image. + + This function returns the same result as grayscale closing but performs + faster for binary images. + + The morphological closing on an image is defined as a dilation followed by + an erosion. Closing can remove small dark spots (i.e. "pepper") and connect + small bright cracks. This tends to "close" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + closing : ndarray of bool + The result of the morphological closing. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_closing + + """ + tmp = binary_dilation(image, footprint, mode=mode) + out = binary_erosion(tmp, footprint, out=out, mode=mode) + return out diff --git a/python_embeded/Lib/site-packages/skimage/morphology/convex_hull.py b/python_embeded/Lib/site-packages/skimage/morphology/convex_hull.py new file mode 100644 index 0000000000000000000000000000000000000000..a31827b04efea46ffeef93452f20fe88d5350302 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/convex_hull.py @@ -0,0 +1,222 @@ +"""Convex Hull.""" + +from itertools import product +import numpy as np +from scipy.spatial import ConvexHull, QhullError +from ..measure.pnpoly import grid_points_in_poly +from ._convex_hull import possible_hull +from ..measure._label import label +from ..util import unique_rows +from .._shared.utils import warn + +__all__ = ['convex_hull_image', 'convex_hull_object'] + + +def _offsets_diamond(ndim): + offsets = np.zeros((2 * ndim, ndim)) + for vertex, (axis, offset) in enumerate(product(range(ndim), (-0.5, 0.5))): + offsets[vertex, axis] = offset + return offsets + + +def _check_coords_in_hull(gridcoords, hull_equations, tolerance): + r"""Checks all the coordinates for inclusiveness in the convex hull. + + Parameters + ---------- + gridcoords : (M, N) ndarray + Coordinates of ``N`` points in ``M`` dimensions. + hull_equations : (M, N) ndarray + Hyperplane equations of the facets of the convex hull. + tolerance : float + Tolerance when determining whether a point is inside the hull. Due + to numerical floating point errors, a tolerance of 0 can result in + some points erroneously being classified as being outside the hull. + + Returns + ------- + coords_in_hull : ndarray of bool + Binary 1D ndarray representing points in n-dimensional space + with value ``True`` set for points inside the convex hull. + + Notes + ----- + Checking the inclusiveness of coordinates in a convex hull requires + intermediate calculations of dot products which are memory-intensive. + Thus, the convex hull equations are checked individually with all + coordinates to keep within the memory limit. + + References + ---------- + .. [1] https://github.com/scikit-image/scikit-image/issues/5019 + + """ + ndim, n_coords = gridcoords.shape + n_hull_equations = hull_equations.shape[0] + coords_in_hull = np.ones(n_coords, dtype=bool) + + # Pre-allocate arrays to cache intermediate results for reducing overheads + dot_array = np.empty(n_coords, dtype=np.float64) + test_ineq_temp = np.empty(n_coords, dtype=np.float64) + coords_single_ineq = np.empty(n_coords, dtype=bool) + + # A point is in the hull if it satisfies all of the hull's inequalities + for idx in range(n_hull_equations): + # Tests a hyperplane equation on all coordinates of volume + np.dot(hull_equations[idx, :ndim], gridcoords, out=dot_array) + np.add(dot_array, hull_equations[idx, ndim:], out=test_ineq_temp) + np.less(test_ineq_temp, tolerance, out=coords_single_ineq) + coords_in_hull *= coords_single_ineq + + return coords_in_hull + + +def convex_hull_image( + image, offset_coordinates=True, tolerance=1e-10, include_borders=True +): + """Compute the convex hull image of a binary image. + + The convex hull is the set of pixels included in the smallest convex + polygon that surround all white pixels in the input image. + + Parameters + ---------- + image : array + Binary input image. This array is cast to bool before processing. + offset_coordinates : bool, optional + If ``True``, a pixel at coordinate, e.g., (4, 7) will be represented + by coordinates (3.5, 7), (4.5, 7), (4, 6.5), and (4, 7.5). This adds + some "extent" to a pixel when computing the hull. + tolerance : float, optional + Tolerance when determining whether a point is inside the hull. Due + to numerical floating point errors, a tolerance of 0 can result in + some points erroneously being classified as being outside the hull. + include_borders: bool, optional + If ``False``, vertices/edges are excluded from the final hull mask. + + Returns + ------- + hull : (M, N) array of bool + Binary image with pixels in convex hull set to True. + + References + ---------- + .. [1] https://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/ + + """ + ndim = image.ndim + if np.count_nonzero(image) == 0: + warn( + "Input image is entirely zero, no valid convex hull. " + "Returning empty image", + UserWarning, + ) + return np.zeros(image.shape, dtype=bool) + # In 2D, we do an optimisation by choosing only pixels that are + # the starting or ending pixel of a row or column. This vastly + # limits the number of coordinates to examine for the virtual hull. + if ndim == 2: + coords = possible_hull(np.ascontiguousarray(image, dtype=np.uint8)) + else: + coords = np.transpose(np.nonzero(image)) + if offset_coordinates: + # when offsetting, we multiply number of vertices by 2 * ndim. + # therefore, we reduce the number of coordinates by using a + # convex hull on the original set, before offsetting. + try: + hull0 = ConvexHull(coords) + except QhullError as err: + warn( + f"Failed to get convex hull image. " + f"Returning empty image, see error message below:\n" + f"{err}" + ) + return np.zeros(image.shape, dtype=bool) + coords = hull0.points[hull0.vertices] + + # Add a vertex for the middle of each pixel edge + if offset_coordinates: + offsets = _offsets_diamond(image.ndim) + coords = (coords[:, np.newaxis, :] + offsets).reshape(-1, ndim) + + # repeated coordinates can *sometimes* cause problems in + # scipy.spatial.ConvexHull, so we remove them. + coords = unique_rows(coords) + + # Find the convex hull + try: + hull = ConvexHull(coords) + except QhullError as err: + warn( + f"Failed to get convex hull image. " + f"Returning empty image, see error message below:\n" + f"{err}" + ) + return np.zeros(image.shape, dtype=bool) + vertices = hull.points[hull.vertices] + + # If 2D, use fast Cython function to locate convex hull pixels + if ndim == 2: + labels = grid_points_in_poly(image.shape, vertices, binarize=False) + # If include_borders is True, we include vertices (2) and edge + # points (3) in the mask, otherwise only the inside of the hull (1) + mask = labels >= 1 if include_borders else labels == 1 + else: + gridcoords = np.reshape(np.mgrid[tuple(map(slice, image.shape))], (ndim, -1)) + + coords_in_hull = _check_coords_in_hull(gridcoords, hull.equations, tolerance) + mask = np.reshape(coords_in_hull, image.shape) + + return mask + + +def convex_hull_object(image, *, connectivity=2): + r"""Compute the convex hull image of individual objects in a binary image. + + The convex hull is the set of pixels included in the smallest convex + polygon that surround all white pixels in the input image. + + Parameters + ---------- + image : (M, N) ndarray + Binary input image. + connectivity : {1, 2}, int, optional + Determines the neighbors of each pixel. Adjacent elements + within a squared distance of ``connectivity`` from pixel center + are considered neighbors.:: + + 1-connectivity 2-connectivity + [ ] [ ] [ ] [ ] + | \ | / + [ ]--[x]--[ ] [ ]--[x]--[ ] + | / | \ + [ ] [ ] [ ] [ ] + + Returns + ------- + hull : ndarray of bool + Binary image with pixels inside convex hull set to ``True``. + + Notes + ----- + This function uses ``skimage.morphology.label`` to define unique objects, + finds the convex hull of each using ``convex_hull_image``, and combines + these regions with logical OR. Be aware the convex hulls of unconnected + objects may overlap in the result. If this is suspected, consider using + convex_hull_image separately on each object or adjust ``connectivity``. + """ + if image.ndim > 2: + raise ValueError("Input must be a 2D image") + + if connectivity not in (1, 2): + raise ValueError('`connectivity` must be either 1 or 2.') + + labeled_im = label(image, connectivity=connectivity, background=0) + convex_obj = np.zeros(image.shape, dtype=bool) + convex_img = np.zeros(image.shape, dtype=bool) + + for i in range(1, labeled_im.max() + 1): + convex_obj = convex_hull_image(labeled_im == i) + convex_img = np.logical_or(convex_img, convex_obj) + + return convex_img diff --git a/python_embeded/Lib/site-packages/skimage/morphology/extrema.py b/python_embeded/Lib/site-packages/skimage/morphology/extrema.py new file mode 100644 index 0000000000000000000000000000000000000000..61d2acb9f8c25bf57a59b2edc50d31dc814905e9 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/extrema.py @@ -0,0 +1,549 @@ +"""extrema.py - local minima and maxima + +This module provides functions to find local maxima and minima of an image. +Here, local maxima (minima) are defined as connected sets of pixels with equal +gray level which is strictly greater (smaller) than the gray level of all +pixels in direct neighborhood of the connected set. In addition, the module +provides the related functions h-maxima and h-minima. + +Soille, P. (2003). Morphological Image Analysis: Principles and Applications +(2nd ed.), Chapter 6. Springer-Verlag New York, Inc. +""" + +import numpy as np + +from .._shared.utils import warn +from ..util import dtype_limits, invert, crop +from . import grayreconstruct, _util +from ._extrema_cy import _local_maxima + + +def _add_constant_clip(image, const_value): + """Add constant to the image while handling overflow issues gracefully.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The added constant is not compatible" "with the image data type." + ) + + result = image + const_value + result[image > max_dtype - const_value] = max_dtype + return result + + +def _subtract_constant_clip(image, const_value): + """Subtract constant from image while handling underflow issues.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The subtracted constant is not compatible" "with the image data type." + ) + + result = image - const_value + result[image < (const_value + min_dtype)] = min_dtype + return result + + +def h_maxima(image, h, footprint=None): + """Determine all maxima of the image with height >= h. + + The local maxima are defined as connected sets of pixels with equal + gray level strictly greater than the gray level of all pixels in direct + neighborhood of the set. + + A local maximum M of height h is a local maximum for which + there is at least one path joining M with an equal or higher local maximum + on which the minimal value is f(M) - h (i.e. the values along the path + are not decreasing by more than h with respect to the maximum's value) + and no path to an equal or higher local maximum for which the minimal + value is greater. + + The global maxima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the maxima are to be calculated. + h : unsigned integer + The minimal height of all extracted maxima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_max : ndarray + The local maxima of height >= h and the global maxima. + The resulting image is a binary image, where pixels belonging to + the determined maxima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_minima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a maximum in the center and + 4 additional constant maxima. + The heights of the maxima are: 1, 21, 41, 61, 81 + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all maxima with a height of at least 40: + + >>> maxima = extrema.h_maxima(f, 40) + + The resulting image will contain 3 local maxima. + """ + + # Check for h value that is larger then range of the image. If this + # is True then there are no h-maxima in the image. + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + # Check for floating point h value. For this to work properly + # we need to explicitly convert image to float64. + # + # FIXME: This could give incorrect results if image is int64 and + # has a very high dynamic range. The dtype of image is + # changed to float64, and different integer values could + # become the same float due to rounding. + # + # >>> ii64 = np.iinfo(np.int64) + # >>> a = np.array([ii64.max, ii64.max - 2]) + # >>> a[0] == a[1] + # False + # >>> b = a.astype(np.float64) + # >>> b[0] == b[1] + # True + # + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_maxima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + # The purpose of the resolution variable is to allow for the + # small rounding errors that inevitably occur when doing + # floating point arithmetic. We want shifted_img to be + # guaranteed to be h less than image. If we only subtract h + # there may be pixels were shifted_img ends up being + # slightly greater than image - h. + # + # The resolution is scaled based on the pixel values in the + # image because floating point precision is relative. A + # very large value of 1.0e10 will have a large precision, + # say +-1.0e4, and a very small value of 1.0e-10 will have + # a very small precision, say +-1.0e-16. + # + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image - h - resolution + else: + shifted_img = _subtract_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='dilation', footprint=footprint + ) + residue_img = image - rec_img + return (residue_img >= h).astype(np.uint8) + + +def h_minima(image, h, footprint=None): + """Determine all minima of the image with depth >= h. + + The local minima are defined as connected sets of pixels with equal + gray level strictly smaller than the gray levels of all pixels in direct + neighborhood of the set. + + A local minimum M of depth h is a local minimum for which + there is at least one path joining M with an equal or lower local minimum + on which the maximal value is f(M) + h (i.e. the values along the path + are not increasing by more than h with respect to the minimum's value) + and no path to an equal or lower local minimum for which the maximal + value is smaller. + + The global minima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the minima are to be calculated. + h : unsigned integer + The minimal depth of all extracted minima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_min : ndarray + The local minima of depth >= h and the global minima. + The resulting image is a binary image, where pixels belonging to + the determined minima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_maxima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a minimum in the center and + 4 additional constant maxima. + The depth of the minima are: 1, 21, 41, 61, 81 + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 160; f[2:4,7:9] = 140; f[7:9,2:4] = 120; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all minima with a depth of at least 40: + + >>> minima = extrema.h_minima(f, 40) + + The resulting image will contain 3 local minima. + """ + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_minima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image + h + resolution + else: + shifted_img = _add_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='erosion', footprint=footprint + ) + residue_img = rec_img - image + return (residue_img >= h).astype(np.uint8) + + +def local_maxima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local maxima of n-dimensional array. + + The local maxima are defined as connected sets of pixels with equal gray + level (plateaus) strictly greater than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local maxima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid maxima. + + Returns + ------- + maxima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local maxima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found maxima. + + Warns + ----- + UserWarning + If `allow_borders` is false and any dimension of the given `image` is + shorter than 3 samples, maxima can't exist and a warning is shown. + + See Also + -------- + skimage.morphology.local_minima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local maxima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a higher gray level, mark the plateau as a definite local maximum. + + Examples + -------- + >>> from skimage.morphology import local_maxima + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Find local maxima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_maxima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_maxima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local maxima without comparing to diagonal pixels (connectivity 1): + + >>> local_maxima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude maxima that border the image edge: + + >>> local_maxima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + image = np.asarray(image, order="C") + if image.size == 0: + # Return early for empty input + if indices: + # Make sure that output is a tuple of 1 empty array per dimension + return np.nonzero(image) + else: + return np.zeros(image.shape, dtype=bool) + + if allow_borders: + # Ensure that local maxima are always at least one smaller sample away + # from the image border + image = np.pad(image, 1, mode='constant', constant_values=image.min()) + + # Array of flags used to store the state of each pixel during evaluation. + # See _extrema_cy.pyx for their meaning + flags = np.zeros(image.shape, dtype=np.uint8) + _util._set_border_values(flags, value=3) + + if any(s < 3 for s in image.shape): + # Warn and skip if any dimension is smaller than 3 + # -> no maxima can exist & footprint can't be applied + warn( + "maxima can't exist for an image with any dimension smaller 3 " + "if borders aren't allowed", + stacklevel=3, + ) + else: + footprint = _util._resolve_neighborhood(footprint, connectivity, image.ndim) + neighbor_offsets = _util._offsets_to_raveled_neighbors( + image.shape, footprint, center=((1,) * image.ndim) + ) + + try: + _local_maxima(image.ravel(), flags.ravel(), neighbor_offsets) + except TypeError: + if image.dtype == np.float16: + # Provide the user with clearer error message + raise TypeError( + "dtype of `image` is float16 which is not " + "supported, try upcasting to float32" + ) + else: + raise # Otherwise raise original message + + if allow_borders: + # Revert padding performed at the beginning of the function + flags = crop(flags, 1) + else: + # No padding was performed but set edge values back to 0 + _util._set_border_values(flags, value=0) + + if indices: + return np.nonzero(flags) + else: + return flags.view(bool) + + +def local_minima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local minima of n-dimensional array. + + The local minima are defined as connected sets of pixels with equal gray + level (plateaus) strictly smaller than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local minima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid minima. + + Returns + ------- + minima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local minima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found minima. + + See Also + -------- + skimage.morphology.local_maxima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local minima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a smaller gray level, mark the plateau as a definite local minimum. + + Examples + -------- + >>> from skimage.morphology import local_minima + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = -1 + >>> image[3, 0] = -1 + >>> image[1:3, 4:6] = -2 + >>> image[3, 6] = -3 + >>> image + array([[ 0, 0, 0, 0, 0, 0, 0], + [ 0, -1, -1, 0, -2, -2, 0], + [ 0, -1, -1, 0, -2, -2, 0], + [-1, 0, 0, 0, 0, 0, -3]]) + + Find local minima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_minima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_minima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local minima without comparing to diagonal pixels (connectivity 1): + + >>> local_minima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude minima that border the image edge: + + >>> local_minima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + return local_maxima( + image=invert(image, signed_float=True), + footprint=footprint, + connectivity=connectivity, + indices=indices, + allow_borders=allow_borders, + ) diff --git a/python_embeded/Lib/site-packages/skimage/morphology/footprints.py b/python_embeded/Lib/site-packages/skimage/morphology/footprints.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8c5f223434ded25e36c3c0a8502e27d18229e6 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/footprints.py @@ -0,0 +1,1110 @@ +import os +import warnings +from collections.abc import Sequence +from numbers import Integral + +import numpy as np + +from .. import draw +from skimage import morphology +from .._shared.utils import deprecate_func + + +# Precomputed ball and disk decompositions were saved as 2D arrays where the +# radius of the desired decomposition is used to index into the first axis of +# the array. The values at a given radius corresponds to the number of +# repetitions of 3 different types elementary of structuring elements. +# +# See _nsphere_series_decomposition for full details. +_nsphere_decompositions = {} +_nsphere_decompositions[2] = np.load( + os.path.join(os.path.dirname(__file__), 'disk_decompositions.npy') +) +_nsphere_decompositions[3] = np.load( + os.path.join(os.path.dirname(__file__), 'ball_decompositions.npy') +) + + +def _footprint_is_sequence(footprint): + if hasattr(footprint, '__array_interface__'): + return False + + def _validate_sequence_element(t): + return ( + isinstance(t, Sequence) + and len(t) == 2 + and hasattr(t[0], '__array_interface__') + and isinstance(t[1], Integral) + ) + + if isinstance(footprint, Sequence): + if not all(_validate_sequence_element(t) for t in footprint): + raise ValueError( + "All elements of footprint sequence must be a 2-tuple where " + "the first element of the tuple is an ndarray and the second " + "is an integer indicating the number of iterations." + ) + else: + raise ValueError("footprint must be either an ndarray or Sequence") + return True + + +def _shape_from_sequence(footprints, require_odd_size=False): + """Determine the shape of composite footprint + + In the future if we only want to support odd-sized square, we may want to + change this to require_odd_size + """ + if not _footprint_is_sequence(footprints): + raise ValueError("expected a sequence of footprints") + ndim = footprints[0][0].ndim + shape = [0] * ndim + + def _odd_size(size, require_odd_size): + if require_odd_size and size % 2 == 0: + raise ValueError("expected all footprint elements to have odd size") + + for d in range(ndim): + fp, nreps = footprints[0] + _odd_size(fp.shape[d], require_odd_size) + shape[d] = fp.shape[d] + (nreps - 1) * (fp.shape[d] - 1) + for fp, nreps in footprints[1:]: + _odd_size(fp.shape[d], require_odd_size) + shape[d] += nreps * (fp.shape[d] - 1) + return tuple(shape) + + +def footprint_from_sequence(footprints): + """Convert a footprint sequence into an equivalent ndarray. + + Parameters + ---------- + footprints : tuple of 2-tuples + A sequence of footprint tuples where the first element of each tuple + is an array corresponding to a footprint and the second element is the + number of times it is to be applied. Currently, all footprints should + have odd size. + + Returns + ------- + footprint : ndarray + An single array equivalent to applying the sequence of ``footprints``. + """ + + # Create a single pixel image of sufficient size and apply binary dilation. + shape = _shape_from_sequence(footprints) + imag = np.zeros(shape, dtype=bool) + imag[tuple(s // 2 for s in shape)] = 1 + return morphology.binary_dilation(imag, footprints) + + +def footprint_rectangle(shape, *, dtype=np.uint8, decomposition=None): + """Generate a rectangular or hyper-rectangular footprint. + + Generates, depending on the length and dimensions requested with `shape`, + a square, rectangle, cube, cuboid, or even higher-dimensional versions + of these shapes. + + Parameters + ---------- + shape : tuple[int, ...] + The length of the footprint in each dimension. The length of the + sequence determines the number of dimensions of the footprint. + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + give an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : array or tuple[tuple[ndarray, int], ...] + A footprint consisting only of ones, i.e. every pixel belongs to the + neighborhood. When `decomposition` is None, this is just an array. + Otherwise, this will be a tuple whose length is equal to the number of + unique structuring elements to apply (see Examples for more detail). + + Examples + -------- + >>> import skimage as ski + >>> ski.morphology.footprint_rectangle((3, 5)) + array([[1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]], dtype=uint8) + + Decomposition will return multiple footprints that combine into a simple + footprint of the requested shape. + + >>> ski.morphology.footprint_rectangle((9, 9), decomposition="sequence") + ((array([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]], dtype=uint8), + 4),) + + `"sequence"` makes sure that the decomposition only returns 1D footprints. + + >>> ski.morphology.footprint_rectangle((3, 5), decomposition="separable") + ((array([[1], + [1], + [1]], dtype=uint8), + 1), + (array([[1, 1, 1, 1, 1]], dtype=uint8), 1)) + + Generate a 5-dimensional hypercube with 3 samples in each dimension + + >>> ski.morphology.footprint_rectangle((3,) * 5).shape + (3, 3, 3, 3, 3) + """ + has_even_width = any(width % 2 == 0 for width in shape) + if decomposition == "sequence" and has_even_width: + warnings.warn( + "decomposition='sequence' is only supported for uneven footprints, " + "falling back to decomposition='separable'", + stacklevel=2, + ) + decomposition = "sequence_fallback" + + def partial_footprint(dim, width): + shape_ = (1,) * dim + (width,) + (1,) * (len(shape) - dim - 1) + fp = (np.ones(shape_, dtype=dtype), 1) + return fp + + if decomposition is None: + footprint = np.ones(shape, dtype=dtype) + + elif decomposition in ("separable", "sequence_fallback"): + footprint = tuple( + partial_footprint(dim, width) for dim, width in enumerate(shape) + ) + + elif decomposition == "sequence": + min_width = min(shape) + sq_reps = _decompose_size(min_width, 3) + footprint = [(np.ones((3,) * len(shape), dtype=dtype), sq_reps)] + for dim, width in enumerate(shape): + if width > min_width: + nextra = width - min_width + 1 + component = partial_footprint(dim, nextra) + footprint.append(component) + footprint = tuple(footprint) + + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + + return footprint + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def square(width, dtype=np.uint8, *, decomposition=None): + """Generates a flat, square-shaped footprint. + + Every pixel along the perimeter has a chessboard distance + no greater than radius (radius=floor(width/2)) pixels. + + Parameters + ---------- + width : int + The width and height of the square. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + give an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` or + ``decomposition='separable'`` were observed to give better performance than + ``decomposition=None``, with the magnitude of the performance increase + rapidly increasing with footprint size. For grayscale morphology with + square footprints, it is recommended to use ``decomposition=None`` since + the internal SciPy functions that are called already have a fast + implementation based on separable 1D sliding windows. + + The 'sequence' decomposition mode only supports odd valued `width`. If + `width` is even, the sequence used will be identical to the 'separable' + mode. + """ + footprint = footprint_rectangle( + shape=(width, width), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def _decompose_size(size, kernel_size=3): + """Determine number of repeated iterations for a `kernel_size` kernel. + + Returns how many repeated morphology operations with an element of size + `kernel_size` is equivalent to a morphology with a single kernel of size + `n`. + + """ + if kernel_size % 2 != 1: + raise ValueError("only odd length kernel_size is supported") + return 1 + (size - kernel_size) // (kernel_size - 1) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def rectangle(nrows, ncols, dtype=np.uint8, *, decomposition=None): + """Generates a flat, rectangular-shaped footprint. + + Every pixel in the rectangle generated for a given width and given height + belongs to the neighborhood. + + Parameters + ---------- + nrows : int + The number of rows of the rectangle. + ncols : int + The number of columns of the rectangle. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : ndarray or tuple + A footprint consisting only of ones, i.e. every pixel belongs to the + neighborhood. When `decomposition` is None, this is just a + numpy.ndarray. Otherwise, this will be a tuple whose length is equal to + the number of unique structuring elements to apply (see Notes for more + detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` + was observed to give better performance, with the magnitude of the + performance increase rapidly increasing with footprint size. For grayscale + morphology with rectangular footprints, it is recommended to use + ``decomposition=None`` since the internal SciPy functions that are called + already have a fast implementation based on separable 1D sliding windows. + + The `sequence` decomposition mode only supports odd valued `nrows` and + `ncols`. If either `nrows` or `ncols` is even, the sequence used will be + identical to ``decomposition='separable'``. + + - The use of ``width`` and ``height`` has been deprecated in + version 0.18.0. Use ``nrows`` and ``ncols`` instead. + """ + footprint = footprint_rectangle( + shape=(nrows, ncols), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def diamond(radius, dtype=np.uint8, *, decomposition=None): + """Generates a flat, diamond-shaped footprint. + + A pixel is part of the neighborhood (i.e. labeled 1) if + the city block/Manhattan distance between it and the center of + the neighborhood is no greater than radius. + + Parameters + ---------- + radius : int + The radius of the diamond-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + + """ + if decomposition is None: + L = np.arange(0, radius * 2 + 1) + I, J = np.meshgrid(L, L) + footprint = np.array( + np.abs(I - radius) + np.abs(J - radius) <= radius, dtype=dtype + ) + elif decomposition == 'sequence': + fp = diamond(1, dtype=dtype, decomposition=None) + nreps = _decompose_size(2 * radius + 1, fp.shape[0]) + footprint = ((fp, nreps),) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def _nsphere_series_decomposition(radius, ndim, dtype=np.uint8): + """Generate a sequence of footprints approximating an n-sphere. + + Morphological operations with an n-sphere (hypersphere) footprint can be + approximated by applying a series of smaller footprints of extent 3 along + each axis. Specific solutions for this are given in [1]_ for the case of + 2D disks with radius 2 through 10. + + Here we used n-dimensional extensions of the "square", "diamond" and + "t-shaped" elements from that publication. All of these elementary elements + have size ``(3,) * ndim``. We numerically computed the number of + repetitions of each element that gives the closest match to the disk + (in 2D) or ball (in 3D) computed with ``decomposition=None``. + + The approach can be extended to higher dimensions, but we have only stored + results for 2D and 3D at this point. + + Empirically, the shapes at large radius approach a hexadecagon + (16-sides [2]_) in 2D and a rhombicuboctahedron (26-faces, [3]_) in 3D. + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Hexadecagon + .. [3] https://en.wikipedia.org/wiki/Rhombicuboctahedron + """ + + if radius == 1: + # for radius 1 just use the exact shape (3,) * ndim solution + kwargs = dict(dtype=dtype, strict_radius=False, decomposition=None) + if ndim == 2: + return ((disk(1, **kwargs), 1),) + elif ndim == 3: + return ((ball(1, **kwargs), 1),) + + # load precomputed decompositions + if ndim not in _nsphere_decompositions: + raise ValueError( + "sequence decompositions are only currently available for " + "2d disks or 3d balls" + ) + precomputed_decompositions = _nsphere_decompositions[ndim] + max_radius = precomputed_decompositions.shape[0] + if radius > max_radius: + raise ValueError( + f"precomputed {ndim}D decomposition unavailable for " + f"radius > {max_radius}" + ) + num_t_series, num_diamond, num_square = precomputed_decompositions[radius] + + sequence = [] + if num_t_series > 0: + # shape (3,) * ndim "T-shaped" footprints + all_t = _t_shaped_element_series(ndim=ndim, dtype=dtype) + [sequence.append((t, num_t_series)) for t in all_t] + if num_diamond > 0: + d = np.zeros((3,) * ndim, dtype=dtype) + sl = [slice(1, 2)] * ndim + for ax in range(ndim): + sl[ax] = slice(None) + d[tuple(sl)] = 1 + sl[ax] = slice(1, 2) + sequence.append((d, num_diamond)) + if num_square > 0: + sq = np.ones((3,) * ndim, dtype=dtype) + sequence.append((sq, num_square)) + return tuple(sequence) + + +def _t_shaped_element_series(ndim=2, dtype=np.uint8): + """A series of T-shaped structuring elements. + + In the 2D case this is a T-shaped element and its rotation at multiples of + 90 degrees. This series is used in efficient decompositions of disks of + various radius as published in [1]_. + + The generalization to the n-dimensional case can be performed by having the + "top" of the T to extend in (ndim - 1) dimensions and then producing a + series of rotations such that the bottom end of the T points along each of + ``2 * ndim`` orthogonal directions. + """ + if ndim == 2: + # The n-dimensional case produces the same set of footprints, but + # the 2D example is retained here for clarity. + t0 = np.array([[1, 1, 1], [0, 1, 0], [0, 1, 0]], dtype=dtype) + t90 = np.rot90(t0, 1) + t180 = np.rot90(t0, 2) + t270 = np.rot90(t0, 3) + return t0, t90, t180, t270 + else: + # ndimensional generalization of the 2D case above + all_t = [] + for ax in range(ndim): + for idx in [0, 2]: + t = np.zeros((3,) * ndim, dtype=dtype) + sl = [slice(None)] * ndim + sl[ax] = slice(idx, idx + 1) + t[tuple(sl)] = 1 + sl = [slice(1, 2)] * ndim + sl[ax] = slice(None) + t[tuple(sl)] = 1 + all_t.append(t) + return tuple(all_t) + + +def disk(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None): + """Generates a flat, disk-shaped footprint. + + A pixel is within the neighborhood if the Euclidean distance between + it and the origin is no greater than radius (This is only approximately + True, when `decomposition == 'sequence'`). + + Parameters + ---------- + radius : int + The radius of the disk-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + strict_radius : bool, optional + If False, extend the radius by 0.5. This allows the circle to expand + further within a cube that remains of size ``2 * radius + 1`` along + each axis. This parameter is ignored if decomposition is not None. + decomposition : {None, 'sequence', 'crosses'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given a result equivalent to a single, larger footprint, but with + better computational performance. For disk footprints, the 'sequence' + or 'crosses' decompositions are not always exactly equivalent to + ``decomposition=None``. See Notes for more details. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + The disk produced by the ``decomposition='sequence'`` mode may not be + identical to that with ``decomposition=None``. A disk footprint can be + approximated by applying a series of smaller footprints of extent 3 along + each axis. Specific solutions for this are given in [1]_ for the case of + 2D disks with radius 2 through 10. Here, we numerically computed the number + of repetitions of each element that gives the closest match to the disk + computed with kwargs ``strict_radius=False, decomposition=None``. + + Empirically, the series decomposition at large radius approaches a + hexadecagon (a 16-sided polygon [2]_). In [3]_, the authors demonstrate + that a hexadecagon is the closest approximation to a disk that can be + achieved for decomposition with footprints of shape (3, 3). + + The disk produced by the ``decomposition='crosses'`` is often but not + always identical to that with ``decomposition=None``. It tends to give a + closer approximation than ``decomposition='sequence'``, at a performance + that is fairly comparable. The individual cross-shaped elements are not + limited to extent (3, 3) in size. Unlike the 'seqeuence' decomposition, the + 'crosses' decomposition can also accurately approximate the shape of disks + with ``strict_radius=True``. The method is based on an adaption of + algorithm 1 given in [4]_. + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Hexadecagon + .. [3] Vanrell, M and Vitrià, J. Optimal 3 × 3 decomposable disks for + morphological transformations. Image and Vision Computing, Vol. 15, + Issue 11, 1997. + :DOI:`10.1016/S0262-8856(97)00026-7` + .. [4] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + """ + if decomposition is None: + L = np.arange(-radius, radius + 1) + X, Y = np.meshgrid(L, L) + if not strict_radius: + radius += 0.5 + return np.array((X**2 + Y**2) <= radius**2, dtype=dtype) + elif decomposition == 'sequence': + sequence = _nsphere_series_decomposition(radius, ndim=2, dtype=dtype) + elif decomposition == 'crosses': + fp = disk(radius, dtype, strict_radius=strict_radius, decomposition=None) + sequence = _cross_decomposition(fp) + return sequence + + +def _cross(r0, r1, dtype=np.uint8): + """Cross-shaped structuring element of shape (r0, r1). + + Only the central row and column are ones. + """ + s0 = int(2 * r0 + 1) + s1 = int(2 * r1 + 1) + c = np.zeros((s0, s1), dtype=dtype) + if r1 != 0: + c[r0, :] = 1 + if r0 != 0: + c[:, r1] = 1 + return c + + +def _cross_decomposition(footprint, dtype=np.uint8): + """Decompose a symmetric convex footprint into cross-shaped elements. + + This is a decomposition of the footprint into a sequence of + (possibly asymmetric) cross-shaped elements. This technique was proposed in + [1]_ and corresponds roughly to algorithm 1 of that publication (some + details had to be modified to get reliable operation). + + .. [1] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + """ + quadrant = footprint[footprint.shape[0] // 2 :, footprint.shape[1] // 2 :] + col_sums = quadrant.sum(0, dtype=int) + col_sums = np.concatenate((col_sums, np.asarray([0], dtype=int))) + i_prev = 0 + idx = {} + sum0 = 0 + for i in range(col_sums.size - 1): + if col_sums[i] > col_sums[i + 1]: + if i == 0: + continue + key = (col_sums[i_prev] - col_sums[i], i - i_prev) + sum0 += key[0] + if key not in idx: + idx[key] = 1 + else: + idx[key] += 1 + i_prev = i + n = quadrant.shape[0] - 1 - sum0 + if n > 0: + key = (n, 0) + idx[key] = idx.get(key, 0) + 1 + return tuple([(_cross(r0, r1, dtype), n) for (r0, r1), n in idx.items()]) + + +def ellipse(width, height, dtype=np.uint8, *, decomposition=None): + """Generates a flat, ellipse-shaped footprint. + + Every pixel along the perimeter of ellipse satisfies + the equation ``(x/width+1)**2 + (y/height+1)**2 = 1``. + + Parameters + ---------- + width : int + The width of the ellipse-shaped footprint. + height : int + The height of the ellipse-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'crosses'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + The footprint will have shape ``(2 * height + 1, 2 * width + 1)``. + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + The ellipse produced by the ``decomposition='crosses'`` is often but not + always identical to that with ``decomposition=None``. The method is based + on an adaption of algorithm 1 given in [1]_. + + References + ---------- + .. [1] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + + Examples + -------- + >>> from skimage.morphology import footprints + >>> footprints.ellipse(5, 3) + array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=uint8) + + """ + if decomposition is None: + footprint = np.zeros((2 * height + 1, 2 * width + 1), dtype=dtype) + rows, cols = draw.ellipse(height, width, height + 1, width + 1) + footprint[rows, cols] = 1 + return footprint + elif decomposition == 'crosses': + fp = ellipse(width, height, dtype, decomposition=None) + sequence = _cross_decomposition(fp) + return sequence + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def cube(width, dtype=np.uint8, *, decomposition=None): + """Generates a cube-shaped footprint. + + This is the 3D equivalent of a square. + Every pixel along the perimeter has a chessboard distance + no greater than radius (radius=floor(width/2)) pixels. + + Parameters + ---------- + width : int + The width, height and depth of the cube. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` + was observed to give better performance, with the magnitude of the + performance increase rapidly increasing with footprint size. For grayscale + morphology with square footprints, it is recommended to use + ``decomposition=None`` since the internal SciPy functions that are called + already have a fast implementation based on separable 1D sliding windows. + + The 'sequence' decomposition mode only supports odd valued `width`. If + `width` is even, the sequence used will be identical to the 'separable' + mode. + """ + footprint = footprint_rectangle( + shape=(width, width, width), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def octahedron(radius, dtype=np.uint8, *, decomposition=None): + """Generates a octahedron-shaped footprint. + + This is the 3D equivalent of a diamond. + A pixel is part of the neighborhood (i.e. labeled 1) if + the city block/Manhattan distance between it and the center of + the neighborhood is no greater than radius. + + Parameters + ---------- + radius : int + The radius of the octahedron-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + """ + # note that in contrast to diamond(), this method allows non-integer radii + if decomposition is None: + n = 2 * radius + 1 + Z, Y, X = np.mgrid[ + -radius : radius : n * 1j, + -radius : radius : n * 1j, + -radius : radius : n * 1j, + ] + s = np.abs(X) + np.abs(Y) + np.abs(Z) + footprint = np.array(s <= radius, dtype=dtype) + elif decomposition == 'sequence': + fp = octahedron(1, dtype=dtype, decomposition=None) + nreps = _decompose_size(2 * radius + 1, fp.shape[0]) + footprint = ((fp, nreps),) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def ball(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None): + """Generates a ball-shaped footprint. + + This is the 3D equivalent of a disk. + A pixel is within the neighborhood if the Euclidean distance between + it and the origin is no greater than radius. + + Parameters + ---------- + radius : float + The radius of the ball-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + strict_radius : bool, optional + If False, extend the radius by 0.5. This allows the circle to expand + further within a cube that remains of size ``2 * radius + 1`` along + each axis. This parameter is ignored if decomposition is not None. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given a result equivalent to a single, larger footprint, but with + better computational performance. For ball footprints, the sequence + decomposition is not exactly equivalent to decomposition=None. + See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + Notes + ----- + The disk produced by the decomposition='sequence' mode is not identical + to that with decomposition=None. Here we extend the approach taken in [1]_ + for disks to the 3D case, using 3-dimensional extensions of the "square", + "diamond" and "t-shaped" elements from that publication. All of these + elementary elements have size ``(3,) * ndim``. We numerically computed the + number of repetitions of each element that gives the closest match to the + ball computed with kwargs ``strict_radius=False, decomposition=None``. + + Empirically, the equivalent composite footprint to the sequence + decomposition approaches a rhombicuboctahedron (26-faces [2]_). + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Rhombicuboctahedron + """ + if decomposition is None: + n = 2 * radius + 1 + Z, Y, X = np.mgrid[ + -radius : radius : n * 1j, + -radius : radius : n * 1j, + -radius : radius : n * 1j, + ] + s = X**2 + Y**2 + Z**2 + if not strict_radius: + radius += 0.5 + return np.array(s <= radius * radius, dtype=dtype) + elif decomposition == 'sequence': + sequence = _nsphere_series_decomposition(radius, ndim=3, dtype=dtype) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return sequence + + +def octagon(m, n, dtype=np.uint8, *, decomposition=None): + """Generates an octagon shaped footprint. + + For a given size of (m) horizontal and vertical sides + and a given (n) height or width of slanted sides octagon is generated. + The slanted sides are 45 or 135 degrees to the horizontal axis + and hence the widths and heights are equal. The overall size of the + footprint along a single axis will be ``m + 2 * n``. + + Parameters + ---------- + m : int + The size of the horizontal and vertical sides. + n : int + The height or width of the slanted sides. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + """ + if m == n == 0: + raise ValueError("m and n cannot both be zero") + + # TODO?: warn about even footprint size when m is even + + if decomposition is None: + from . import convex_hull_image + + footprint = np.zeros((m + 2 * n, m + 2 * n)) + footprint[0, n] = 1 + footprint[n, 0] = 1 + footprint[0, m + n - 1] = 1 + footprint[m + n - 1, 0] = 1 + footprint[-1, n] = 1 + footprint[n, -1] = 1 + footprint[-1, m + n - 1] = 1 + footprint[m + n - 1, -1] = 1 + footprint = convex_hull_image(footprint).astype(dtype) + elif decomposition == 'sequence': + # special handling for edge cases with small m and/or n + if m <= 2 and n <= 2: + return ((octagon(m, n, dtype=dtype, decomposition=None), 1),) + + # general approach for larger m and/or n + if m == 0: + m = 2 + n -= 1 + sequence = [] + if m > 1: + sequence += list( + footprint_rectangle((m, m), dtype=dtype, decomposition='sequence') + ) + if n > 0: + sequence += [(diamond(1, dtype=dtype, decomposition=None), n)] + footprint = tuple(sequence) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def star(a, dtype=np.uint8): + """Generates a star shaped footprint. + + Start has 8 vertices and is an overlap of square of size `2*a + 1` + with its 45 degree rotated version. + The slanted sides are 45 or 135 degrees to the horizontal axis. + + Parameters + ---------- + a : int + Parameter deciding the size of the star structural element. The side + of the square array returned is `2*a + 1 + 2*floor(a / 2)`. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + """ + from . import convex_hull_image + + if a == 1: + bfilter = np.zeros((3, 3), dtype) + bfilter[:] = 1 + return bfilter + + m = 2 * a + 1 + n = a // 2 + footprint_square = np.zeros((m + 2 * n, m + 2 * n)) + footprint_square[n : m + n, n : m + n] = 1 + + c = (m + 2 * n - 1) // 2 + footprint_rotated = np.zeros((m + 2 * n, m + 2 * n)) + footprint_rotated[0, c] = footprint_rotated[-1, c] = 1 + footprint_rotated[c, 0] = footprint_rotated[c, -1] = 1 + footprint_rotated = convex_hull_image(footprint_rotated).astype(int) + + footprint = footprint_square + footprint_rotated + footprint[footprint > 0] = 1 + + return footprint.astype(dtype) + + +def mirror_footprint(footprint): + """Mirror each dimension in the footprint. + + Parameters + ---------- + footprint : ndarray or tuple + The input footprint or sequence of footprints + + Returns + ------- + inverted : ndarray or tuple + The footprint, mirrored along each dimension. + + Examples + -------- + >>> footprint = np.array([[0, 0, 0], + ... [0, 1, 1], + ... [0, 1, 1]], np.uint8) + >>> mirror_footprint(footprint) + array([[1, 1, 0], + [1, 1, 0], + [0, 0, 0]], dtype=uint8) + + """ + if _footprint_is_sequence(footprint): + return tuple((mirror_footprint(fp), n) for fp, n in footprint) + footprint = np.asarray(footprint) + return footprint[(slice(None, None, -1),) * footprint.ndim] + + +def pad_footprint(footprint, *, pad_end=True): + """Pad the footprint to an odd size along each dimension. + + Parameters + ---------- + footprint : ndarray or tuple + The input footprint or sequence of footprints + pad_end : bool, optional + If ``True``, pads at the end of each dimension (right side), otherwise + pads on the front (left side). + + Returns + ------- + padded : ndarray or tuple + The footprint, padded to an odd size along each dimension. + + Examples + -------- + >>> footprint = np.array([[0, 0], + ... [1, 1], + ... [1, 1]], np.uint8) + >>> pad_footprint(footprint) + array([[0, 0, 0], + [1, 1, 0], + [1, 1, 0]], dtype=uint8) + + """ + if _footprint_is_sequence(footprint): + return tuple((pad_footprint(fp, pad_end=pad_end), n) for fp, n in footprint) + footprint = np.asarray(footprint) + padding = [] + for sz in footprint.shape: + padding.append(((0, 1) if pad_end else (1, 0)) if sz % 2 == 0 else (0, 0)) + return np.pad(footprint, padding) diff --git a/python_embeded/Lib/site-packages/skimage/morphology/gray.py b/python_embeded/Lib/site-packages/skimage/morphology/gray.py new file mode 100644 index 0000000000000000000000000000000000000000..ccfe2a0c6deea5042aa7e7296c24dca005656789 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/gray.py @@ -0,0 +1,703 @@ +""" +Grayscale morphological operations +""" + +import warnings + +import numpy as np +from scipy import ndimage as ndi + +from .footprints import _footprint_is_sequence, mirror_footprint, pad_footprint +from .misc import default_footprint +from .._shared.utils import DEPRECATED + + +__all__ = ['erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat'] + + +def _iterate_gray_func(gray_func, image, footprints, out, mode, cval): + """Helper to call `gray_func` for each footprint in a sequence. + + `gray_func` is a morphology function that accepts `footprint`, `output`, + `mode` and `cval` keyword arguments (e.g. `scipy.ndimage.grey_erosion`). + """ + fp, num_iter = footprints[0] + gray_func(image, footprint=fp, output=out, mode=mode, cval=cval) + for _ in range(1, num_iter): + gray_func(out.copy(), footprint=fp, output=out, mode=mode, cval=cval) + for fp, num_iter in footprints[1:]: + # Note: out.copy() because the computation cannot be in-place! + for _ in range(num_iter): + gray_func(out.copy(), footprint=fp, output=out, mode=mode, cval=cval) + return out + + +def _shift_footprint(footprint, shift_x, shift_y): + """Shift the binary image `footprint` in the left and/or up. + + This only affects 2D footprints with even number of rows + or columns. + + Parameters + ---------- + footprint : 2D array, shape (M, N) + The input footprint. + shift_x, shift_y : bool or None + Whether to move `footprint` along each axis. If ``None``, the + array is not modified along that dimension. + + Returns + ------- + out : 2D array, shape (M + int(shift_x), N + int(shift_y)) + The shifted footprint. + """ + footprint = np.asarray(footprint) + if footprint.ndim != 2: + # do nothing for 1D or 3D or higher footprints + return footprint + m, n = footprint.shape + if m % 2 == 0: + extra_row = np.zeros((1, n), footprint.dtype) + if shift_x: + footprint = np.vstack((footprint, extra_row)) + else: + footprint = np.vstack((extra_row, footprint)) + m += 1 + if n % 2 == 0: + extra_col = np.zeros((m, 1), footprint.dtype) + if shift_y: + footprint = np.hstack((footprint, extra_col)) + else: + footprint = np.hstack((extra_col, footprint)) + return footprint + + +def _shift_footprints(footprint, shift_x, shift_y): + """Shifts the footprints, whether it's a single array or a sequence. + + See `_shift_footprint`, which is called for each array in the sequence. + """ + if shift_x is DEPRECATED and shift_y is DEPRECATED: + return footprint + + warning_msg = ( + "The parameters `shift_x` and `shift_y` are deprecated since v0.23 and " + "will be removed in v0.26. Use `pad_footprint` or modify the footprint" + "manually instead." + ) + warnings.warn(warning_msg, FutureWarning, stacklevel=4) + + if _footprint_is_sequence(footprint): + return tuple((_shift_footprint(fp, shift_x, shift_y), n) for fp, n in footprint) + return _shift_footprint(footprint, shift_x, shift_y) + + +def _min_max_to_constant_mode(dtype, mode, cval): + """Replace 'max' and 'min' with appropriate 'cval' and 'constant' mode.""" + if mode == "max": + mode = "constant" + if np.issubdtype(dtype, bool): + cval = True + elif np.issubdtype(dtype, np.integer): + cval = np.iinfo(dtype).max + else: + cval = np.inf + elif mode == "min": + mode = "constant" + if np.issubdtype(dtype, bool): + cval = False + elif np.issubdtype(dtype, np.integer): + cval = np.iinfo(dtype).min + else: + cval = -np.inf + return mode, cval + + +_SUPPORTED_MODES = { + "reflect", + "constant", + "nearest", + "mirror", + "wrap", + "max", + "min", + "ignore", +} + + +@default_footprint +def erosion( + image, + footprint=None, + out=None, + shift_x=DEPRECATED, + shift_y=DEPRECATED, + *, + mode="reflect", + cval=0.0, +): + """Return grayscale morphological erosion of an image. + + Morphological erosion sets a pixel at (i,j) to the minimum over all pixels + in the neighborhood centered at (i,j). Erosion shrinks bright regions and + enlarges dark regions. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarrays, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'max' or 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype, which causes them to not + influence the result. Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + eroded : array, same shape as `image` + The result of the morphological erosion. + + Other Parameters + ---------------- + shift_x, shift_y : DEPRECATED + + .. deprecated:: 0.23 + + Notes + ----- + For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the + lower algorithm complexity makes the :func:`skimage.filters.rank.minimum` + function more efficient for larger images and footprints. + + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + For even-sized footprints, :func:`skimage.morphology.binary_erosion` and + this function produce an output that differs: one is shifted by one pixel + compared to the other. + + Examples + -------- + >>> # Erosion shrinks bright regions + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bright_square = np.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]], dtype=np.uint8) + >>> erosion(bright_square, footprint_rectangle((3, 3))) + 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]], dtype=uint8) + + """ + if out is None: + out = np.empty_like(image) + + if mode not in _SUPPORTED_MODES: + raise ValueError(f"unsupported mode, got {mode!r}") + if mode == "ignore": + mode = "max" + mode, cval = _min_max_to_constant_mode(image.dtype, mode, cval) + + footprint = _shift_footprints(footprint, shift_x, shift_y) + footprint = pad_footprint(footprint, pad_end=False) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_gray_func( + gray_func=ndi.grey_erosion, + image=image, + footprints=footprint, + out=out, + mode=mode, + cval=cval, + ) + return out + + +@default_footprint +def dilation( + image, + footprint=None, + out=None, + shift_x=DEPRECATED, + shift_y=DEPRECATED, + *, + mode="reflect", + cval=0.0, +): + """Return grayscale morphological dilation of an image. + + Morphological dilation sets the value of a pixel to the maximum over all + pixel values within a local neighborhood centered about it. The values + where the footprint is 1 define this neighborhood. + Dilation enlarges bright regions and shrinks dark regions. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'min' or 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype, which causes them to not + influence the result. Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + dilated : uint8 array, same shape and type as `image` + The result of the morphological dilation. + + Other Parameters + ---------------- + shift_x, shift_y : DEPRECATED + + .. deprecated:: 0.23 + + Notes + ----- + For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the lower + algorithm complexity makes the :func:`skimage.filters.rank.maximum` + function more efficient for larger images and footprints. + + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + For non-symmetric footprints, :func:`skimage.morphology.binary_dilation` + and :func:`skimage.morphology.dilation` produce an output that differs: + `binary_dilation` mirrors the footprint, whereas `dilation` does not. + + Examples + -------- + >>> # Dilation enlarges bright regions + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bright_pixel = np.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]], dtype=np.uint8) + >>> dilation(bright_pixel, footprint_rectangle((3, 3))) + 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]], dtype=uint8) + + """ + if out is None: + out = np.empty_like(image) + + if mode not in _SUPPORTED_MODES: + raise ValueError(f"unsupported mode, got {mode!r}") + if mode == "ignore": + mode = "min" + mode, cval = _min_max_to_constant_mode(image.dtype, mode, cval) + + footprint = _shift_footprints(footprint, shift_x, shift_y) + footprint = pad_footprint(footprint, pad_end=False) + # Note that `ndi.grey_dilation` mirrors the footprint and this + # additional inversion should be removed in skimage2, see gh-6676. + footprint = mirror_footprint(footprint) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_gray_func( + gray_func=ndi.grey_dilation, + image=image, + footprints=footprint, + out=out, + mode=mode, + cval=cval, + ) + return out + + +@default_footprint +def opening(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return grayscale morphological opening of an image. + + The morphological opening of an image is defined as an erosion followed by + a dilation. Opening can remove small bright spots (i.e. "salt") and connect + small dark cracks. This tends to "open" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype in the erosion, and minimum + in the dilation, which causes them to not influence the result. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + opening : array, same shape and type as `image` + The result of the morphological opening. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + Examples + -------- + >>> # Open up gap between two bright regions (but also shrink regions) + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bad_connection = np.array([[1, 0, 0, 0, 1], + ... [1, 1, 0, 1, 1], + ... [1, 1, 1, 1, 1], + ... [1, 1, 0, 1, 1], + ... [1, 0, 0, 0, 1]], dtype=np.uint8) + >>> opening(bad_connection, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [1, 1, 0, 1, 1], + [1, 1, 0, 1, 1], + [1, 1, 0, 1, 1], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + footprint = pad_footprint(footprint, pad_end=False) + eroded = erosion(image, footprint, mode=mode, cval=cval) + out = dilation(eroded, mirror_footprint(footprint), out=out, mode=mode, cval=cval) + return out + + +@default_footprint +def closing(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return grayscale morphological closing of an image. + + The morphological closing of an image is defined as a dilation followed by + an erosion. Closing can remove small dark spots (i.e. "pepper") and connect + small bright cracks. This tends to "close" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None, + a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype in the erosion, and minimum + in the dilation, which causes them to not influence the result. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + closing : array, same shape and type as `image` + The result of the morphological closing. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + Examples + -------- + >>> # Close a gap between two bright lines + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> broken_line = np.array([[0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0], + ... [1, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> closing(broken_line, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + footprint = pad_footprint(footprint, pad_end=False) + dilated = dilation(image, footprint, mode=mode, cval=cval) + out = erosion(dilated, mirror_footprint(footprint), out=out, mode=mode, cval=cval) + return out + + +@default_footprint +def white_tophat(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return white top hat of an image. + + The white top hat of an image is defined as the image minus its + morphological opening. This operation returns the bright spots of the image + that are smaller than the footprint. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. See :func:`skimage.morphology.opening`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + out : array, same shape and type as `image` + The result of the morphological white top hat. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + See Also + -------- + black_tophat + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Top-hat_transform + + Examples + -------- + >>> # Subtract gray background from bright peak + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> 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]], dtype=np.uint8) + >>> white_tophat(bright_on_gray, footprint_rectangle((3, 3))) + 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]], dtype=uint8) + + """ + if out is image: + # We need a temporary image + opened = opening(image, footprint, mode=mode, cval=cval) + if np.issubdtype(opened.dtype, bool): + np.logical_xor(out, opened, out=out) + else: + out -= opened + return out + + # Else write intermediate result into output image + out = opening(image, footprint, out=out, mode=mode, cval=cval) + if np.issubdtype(out.dtype, bool): + np.logical_xor(image, out, out=out) + else: + np.subtract(image, out, out=out) + return out + + +@default_footprint +def black_tophat(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return black top hat of an image. + + The black top hat of an image is defined as its morphological closing minus + the original image. This operation returns the dark spots of the image that + are smaller than the footprint. Note that dark spots in the + original image are bright spots after the black top hat. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. See :func:`skimage.morphology.closing`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + out : array, same shape and type as `image` + The result of the morphological black top hat. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + See Also + -------- + white_tophat + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Top-hat_transform + + Examples + -------- + >>> # Change dark peak to bright peak and subtract background + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> 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]], dtype=np.uint8) + >>> black_tophat(dark_on_gray, footprint_rectangle((3, 3))) + 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]], dtype=uint8) + + """ + if out is image: + # We need a temporary image + closed = closing(image, footprint, mode=mode, cval=cval) + if np.issubdtype(closed.dtype, bool): + np.logical_xor(closed, out, out=out) + else: + np.subtract(closed, out, out=out) + return out + + out = closing(image, footprint, out=out, mode=mode, cval=cval) + if np.issubdtype(out.dtype, np.bool_): + np.logical_xor(out, image, out=out) + else: + out -= image + return out diff --git a/python_embeded/Lib/site-packages/skimage/morphology/grayreconstruct.py b/python_embeded/Lib/site-packages/skimage/morphology/grayreconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f00e9f6558fe4fa8c4f510e7132820547e5396 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/grayreconstruct.py @@ -0,0 +1,217 @@ +import numpy as np + +from .._shared.utils import _supported_float_type +from ..filters._rank_order import rank_order +from ._grayreconstruct import reconstruction_loop + + +def reconstruction(seed, mask, method='dilation', footprint=None, offset=None): + """Perform a morphological reconstruction of an image. + + Morphological reconstruction by dilation is similar to basic morphological + dilation: high-intensity values will replace nearby low-intensity values. + The basic dilation operator, however, uses a footprint to + determine how far a value in the input image can spread. In contrast, + reconstruction uses two images: a "seed" image, which specifies the values + that spread, and a "mask" image, which gives the maximum allowed value at + each pixel. The mask image, like the footprint, limits the spread + of high-intensity values. Reconstruction by erosion is simply the inverse: + low-intensity values spread from the seed image and are limited by the mask + image, which represents the minimum allowed value. + + Alternatively, you can think of reconstruction as a way to isolate the + connected regions of an image. For dilation, reconstruction connects + regions marked by local maxima in the seed image: neighboring pixels + less-than-or-equal-to those seeds are connected to the seeded region. + Local maxima with values larger than the seed image will get truncated to + the seed value. + + Parameters + ---------- + seed : ndarray + The seed image (a.k.a. marker image), which specifies the values that + are dilated or eroded. + mask : ndarray + The maximum (dilation) / minimum (erosion) allowed value at each pixel. + method : {'dilation'|'erosion'}, optional + Perform reconstruction by dilation or erosion. In dilation (or + erosion), the seed image is dilated (or eroded) until limited by the + mask image. For dilation, each seed value must be less than or equal + to the corresponding mask value; for erosion, the reverse is true. + Default is 'dilation'. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the n-D square of radius equal to 1 (i.e. a 3x3 square + for 2D images, a 3x3x3 cube for 3D images, etc.) + offset : ndarray, optional + The coordinates of the center of the footprint. + Default is located on the geometrical center of the footprint, in that + case footprint dimensions must be odd. + + Returns + ------- + reconstructed : ndarray + The result of morphological reconstruction. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import reconstruction + + First, we create a sinusoidal mask image with peaks at middle and ends. + + >>> x = np.linspace(0, 4 * np.pi) + >>> y_mask = np.cos(x) + + Then, we create a seed image initialized to the minimum mask value (for + reconstruction by dilation, min-intensity values don't spread) and add + "seeds" to the left and right peak, but at a fraction of peak value (1). + + >>> y_seed = y_mask.min() * np.ones_like(x) + >>> y_seed[0] = 0.5 + >>> y_seed[-1] = 0 + >>> y_rec = reconstruction(y_seed, y_mask) + + The reconstructed image (or curve, in this case) is exactly the same as the + mask image, except that the peaks are truncated to 0.5 and 0. The middle + peak disappears completely: Since there were no seed values in this peak + region, its reconstructed value is truncated to the surrounding value (-1). + + As a more practical example, we try to extract the bright features of an + image by subtracting a background image created by reconstruction. + + >>> y, x = np.mgrid[:20:0.5, :20:0.5] + >>> bumps = np.sin(x) + np.sin(y) + + To create the background image, set the mask image to the original image, + and the seed image to the original image with an intensity offset, `h`. + + >>> h = 0.3 + >>> seed = bumps - h + >>> background = reconstruction(seed, bumps) + + The resulting reconstructed image looks exactly like the original image, + but with the peaks of the bumps cut off. Subtracting this reconstructed + image from the original image leaves just the peaks of the bumps + + >>> hdome = bumps - background + + This operation is known as the h-dome of the image and leaves features + of height `h` in the subtracted image. + + Notes + ----- + The algorithm is taken from [1]_. Applications for grayscale reconstruction + are discussed in [2]_ and [3]_. + + References + ---------- + .. [1] Robinson, "Efficient morphological reconstruction: a downhill + filter", Pattern Recognition Letters 25 (2004) 1759-1767. + .. [2] Vincent, L., "Morphological Grayscale Reconstruction in Image + Analysis: Applications and Efficient Algorithms", IEEE Transactions + on Image Processing (1993) + .. [3] Soille, P., "Morphological Image Analysis: Principles and + Applications", Chapter 6, 2nd edition (2003), ISBN 3540429883. + """ + assert tuple(seed.shape) == tuple(mask.shape) + if method == 'dilation' and np.any(seed > mask): + raise ValueError( + "Intensity of seed image must be less than that " + "of the mask image for reconstruction by dilation." + ) + elif method == 'erosion' and np.any(seed < mask): + raise ValueError( + "Intensity of seed image must be greater than that " + "of the mask image for reconstruction by erosion." + ) + + if footprint is None: + footprint = np.ones([3] * seed.ndim, dtype=bool) + else: + footprint = footprint.astype(bool, copy=True) + + if offset is None: + if not all([d % 2 == 1 for d in footprint.shape]): + raise ValueError("Footprint dimensions must all be odd") + offset = np.array([d // 2 for d in footprint.shape]) + else: + if offset.ndim != footprint.ndim: + raise ValueError("Offset and footprint ndims must be equal.") + if not all([(0 <= o < d) for o, d in zip(offset, footprint.shape)]): + raise ValueError("Offset must be included inside footprint") + + # Cross out the center of the footprint + footprint[tuple(slice(d, d + 1) for d in offset)] = False + + # Make padding for edges of reconstructed image so we can ignore boundaries + dims = np.zeros(seed.ndim + 1, dtype=int) + dims[1:] = np.array(seed.shape) + (np.array(footprint.shape) - 1) + dims[0] = 2 + inside_slices = tuple(slice(o, o + s) for o, s in zip(offset, seed.shape)) + # Set padded region to minimum image intensity and mask along first axis so + # we can interleave image and mask pixels when sorting. + if method == 'dilation': + pad_value = np.min(seed) + elif method == 'erosion': + pad_value = np.max(seed) + else: + raise ValueError( + "Reconstruction method can be one of 'erosion' " + f"or 'dilation'. Got '{method}'." + ) + float_dtype = _supported_float_type(mask.dtype) + images = np.full(dims, pad_value, dtype=float_dtype) + images[(0, *inside_slices)] = seed + images[(1, *inside_slices)] = mask + + # determine whether image is large enough to require 64-bit integers + isize = images.size + # use -isize so we get a signed dtype rather than an unsigned one + signed_int_dtype = np.result_type(np.min_scalar_type(-isize), np.int32) + # the corresponding unsigned type has same char, but uppercase + unsigned_int_dtype = np.dtype(signed_int_dtype.char.upper()) + + # Create a list of strides across the array to get the neighbors within + # a flattened array + value_stride = np.array(images.strides[1:]) // images.dtype.itemsize + image_stride = images.strides[0] // images.dtype.itemsize + footprint_mgrid = np.mgrid[ + [slice(-o, d - o) for d, o in zip(footprint.shape, offset)] + ] + footprint_offsets = footprint_mgrid[:, footprint].transpose() + nb_strides = np.array( + [ + np.sum(value_stride * footprint_offset) + for footprint_offset in footprint_offsets + ], + signed_int_dtype, + ) + images = images.reshape(-1) + + # Erosion goes smallest to largest; dilation goes largest to smallest. + index_sorted = np.argsort(images).astype(signed_int_dtype, copy=False) + if method == 'dilation': + index_sorted = index_sorted[::-1] + + # Make a linked list of pixels sorted by value. -1 is the list terminator. + prev = np.full(isize, -1, signed_int_dtype) + next = np.full(isize, -1, signed_int_dtype) + prev[index_sorted[1:]] = index_sorted[:-1] + next[index_sorted[:-1]] = index_sorted[1:] + + # Cython inner-loop compares the rank of pixel values. + if method == 'dilation': + value_rank, value_map = rank_order(images) + elif method == 'erosion': + value_rank, value_map = rank_order(-images) + value_map = -value_map + + start = index_sorted[0] + value_rank = value_rank.astype(unsigned_int_dtype, copy=False) + reconstruction_loop(value_rank, prev, next, nb_strides, start, image_stride) + + # Reshape reconstructed image to original image shape and remove padding. + rec_img = value_map[value_rank[:image_stride]] + rec_img.shape = np.array(seed.shape) + (np.array(footprint.shape) - 1) + return rec_img[inside_slices] diff --git a/python_embeded/Lib/site-packages/skimage/morphology/isotropic.py b/python_embeded/Lib/site-packages/skimage/morphology/isotropic.py new file mode 100644 index 0000000000000000000000000000000000000000..e7caf07f54b7ebbb2be22d1592524a3b2230fd00 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/isotropic.py @@ -0,0 +1,194 @@ +""" +Binary morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + + +def isotropic_erosion(image, radius, out=None, spacing=None): + """Return binary morphological erosion of an image. + + This function returns the same result as :func:`skimage.morphology.binary_erosion` + but performs faster for large circular structuring elements. + This works by applying a threshold to the exact Euclidean distance map + of the image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius by which regions should be eroded. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + eroded : ndarray of bool + The result of the morphological erosion taking values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dist = ndi.distance_transform_edt(image, sampling=spacing) + return np.greater(dist, radius, out=out) + + +def isotropic_dilation(image, radius, out=None, spacing=None): + """Return binary morphological dilation of an image. + + This function returns the same result as :func:`skimage.morphology.binary_dilation` + but performs faster for large circular structuring elements. + This works by applying a threshold to the exact Euclidean distance map + of the inverted image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius by which regions should be dilated. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + dilated : ndarray of bool + The result of the morphological dilation with values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dist = ndi.distance_transform_edt(np.logical_not(image), sampling=spacing) + return np.less_equal(dist, radius, out=out) + + +def isotropic_opening(image, radius, out=None, spacing=None): + """Return binary morphological opening of an image. + + This function returns the same result as :func:`skimage.morphology.binary_opening` + but performs faster for large circular structuring elements. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius with which the regions should be opened. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + opened : ndarray of bool + The result of the morphological opening. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + eroded = isotropic_erosion(image, radius, out=out, spacing=spacing) + return isotropic_dilation(eroded, radius, out=out, spacing=spacing) + + +def isotropic_closing(image, radius, out=None, spacing=None): + """Return binary morphological closing of an image. + + This function returns the same result as binary :func:`skimage.morphology.binary_closing` + but performs faster for large circular structuring elements. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius with which the regions should be closed. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + closed : ndarray of bool + The result of the morphological closing. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + """ + + dilated = isotropic_dilation(image, radius, out=out, spacing=spacing) + return isotropic_erosion(dilated, radius, out=out, spacing=spacing) diff --git a/python_embeded/Lib/site-packages/skimage/morphology/max_tree.py b/python_embeded/Lib/site-packages/skimage/morphology/max_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..053576fb23292139569820f4a00b6cb7efa4b447 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/max_tree.py @@ -0,0 +1,700 @@ +"""max_tree.py - max_tree representation of images. + +This module provides operators based on the max-tree representation of images. +A grayscale image can be seen as a pile of nested sets, each of which is the +result of a threshold operation. These sets can be efficiently represented by +max-trees, where the inclusion relation between connected components at +different levels are represented by parent-child relationships. + +These representations allow efficient implementations of many algorithms, such +as attribute operators. Unlike morphological openings and closings, these +operators do not require a fixed footprint, but rather act with a flexible +footprint that meets a certain criterion. + +This implementation provides functions for: +1. max-tree generation +2. area openings / closings +3. diameter openings / closings +4. local maxima + +References: + .. [1] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [2] Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., + Bertin, E. (2007). Effective Component Tree Computation with + Application to Pattern Recognition in Astronomical Imaging. + In International Conference on Image Processing (ICIP) (pp. 41-44). + :DOI:`10.1109/ICIP.2007.4379949` + .. [3] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [4] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` +""" + +import numpy as np + +from ._util import _validate_connectivity, _offsets_to_raveled_neighbors +from ..util import invert + +from . import _max_tree + +unsigned_int_types = [np.uint8, np.uint16, np.uint32, np.uint64] +signed_int_types = [np.int8, np.int16, np.int32, np.int64] +signed_float_types = [np.float16, np.float32, np.float64] + + +# building the max tree. +def max_tree(image, connectivity=1): + """Build the max tree from an image. + + Component trees represent the hierarchical structure of the connected + components resulting from sequential thresholding operations applied to an + image. A connected component at one level is parent of a component at a + higher level if the latter is included in the first. A max-tree is an + efficient representation of a component tree. A connected component at + one level is represented by one reference pixel at this level, which is + parent to all other pixels at that level and to the reference pixel at the + level above. The max-tree is the basis for many morphological operators, + namely connected operators. + + Parameters + ---------- + image : ndarray + The input image for which the max-tree is to be calculated. + This image can be of any type. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + + Returns + ------- + parent : ndarray, int64 + Array of same shape as image. The value of each pixel is the index of + its parent in the ravelled array. + tree_traverser : 1D array, int64 + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + References + ---------- + .. [1] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [2] Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., + Bertin, E. (2007). Effective Component Tree Computation with + Application to Pattern Recognition in Astronomical Imaging. + In International Conference on Image Processing (ICIP) (pp. 41-44). + :DOI:`10.1109/ICIP.2007.4379949` + .. [3] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [4] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create a small sample image (Figure 1 from [4]) and build the max-tree. + + >>> image = np.array([[15, 13, 16], [12, 12, 10], [16, 12, 14]]) + >>> P, S = max_tree(image, connectivity=2) + """ + # User defined masks are not allowed, as there might be more than one + # connected component in the mask (and therefore not a single tree that + # represents the image). Mask here is an image that is 0 on the border + # and 1 everywhere else. + mask = np.ones(image.shape) + for k in range(len(image.shape)): + np.moveaxis(mask, k, 0)[0] = 0 + np.moveaxis(mask, k, 0)[-1] = 0 + + neighbors, offset = _validate_connectivity(image.ndim, connectivity, offset=None) + + # initialization of the parent image + parent = np.zeros(image.shape, dtype=np.int64) + + # flat_neighborhood contains a list of offsets allowing one to find the + # neighbors in the ravelled image. + flat_neighborhood = _offsets_to_raveled_neighbors( + image.shape, neighbors, offset + ).astype(np.int32) + + # pixels need to be sorted according to their gray level. + tree_traverser = np.argsort(image.ravel(), kind="stable").astype(np.int64) + + # call of cython function. + _max_tree._max_tree( + image.ravel(), + mask.ravel().astype(np.uint8), + flat_neighborhood, + offset.astype(np.int32), + np.array(image.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + return parent, tree_traverser + + +def area_opening( + image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None +): + """Perform an area opening of the image. + + Area opening removes all bright structures of an image with + a surface smaller than area_threshold. + The output image is thus the largest image smaller than the input + for which all local maxima have at least a surface of + area_threshold pixels. + + Area openings are similar to morphological openings, but + they do not use a fixed footprint, but rather a deformable + one, with surface = area_threshold. Consequently, the area_opening + with area_threshold=1 is the identity. + + In the binary case, area openings are equivalent to + remove_small_objects; this operator is thus extended to gray-level images. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_opening is to be calculated. + This image can be of any type. + area_threshold : unsigned int + The size parameter (number of pixels). The default value is arbitrarily + chosen to be 64. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the image. The + value of each pixel is the index of its parent in the ravelled array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as the input image. + + See Also + -------- + skimage.morphology.area_closing + skimage.morphology.diameter_opening + skimage.morphology.diameter_closing + skimage.morphology.max_tree + skimage.morphology.remove_small_objects + skimage.morphology.remove_small_holes + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional local maxima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the area opening: + + >>> open = area_opening(f, 8, connectivity=1) + + The peaks with a surface smaller than 8 are removed. + """ + output = image.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + area = _max_tree._compute_area(image.ravel(), parent.ravel(), tree_traverser) + + _max_tree._direct_filter( + image.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + area, + area_threshold, + ) + return output + + +def diameter_opening( + image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None +): + """Perform a diameter opening of the image. + + Diameter opening removes all bright structures of an image with + maximal extension smaller than diameter_threshold. The maximal + extension is defined as the maximal extension of the bounding box. + The operator is also called Bounding Box Opening. In practice, + the result is similar to a morphological opening, but long and thin + structures are not removed. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_opening is to be calculated. + This image can be of any type. + diameter_threshold : unsigned int + The maximal extension parameter (number of pixels). The default value + is 8. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the image. The + value of each pixel is the index of its parent in the ravelled array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as the input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.area_closing + skimage.morphology.diameter_closing + skimage.morphology.max_tree + + References + ---------- + .. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of + Microaneurysms in Color Fundus Images of the Human Retina by Means + of the Bounding Box Closing. In A. Colosimo, P. Sirabella, + A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer + Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. + :DOI:`10.1007/3-540-36104-9_23` + .. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional local maxima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the diameter opening: + + >>> open = diameter_opening(f, 3, connectivity=1) + + The peaks with a maximal extension of 2 or less are removed. + The remaining peaks have all a maximal extension of at least 3. + """ + output = image.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + diam = _max_tree._compute_extension( + image.ravel(), + np.array(image.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + _max_tree._direct_filter( + image.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + diam, + diameter_threshold, + ) + return output + + +def area_closing( + image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None +): + """Perform an area closing of the image. + + Area closing removes all dark structures of an image with + a surface smaller than area_threshold. + The output image is larger than or equal to the input image + for every pixel and all local minima have at least a surface of + area_threshold pixels. + + Area closings are similar to morphological closings, but + they do not use a fixed footprint, but rather a deformable + one, with surface = area_threshold. + + In the binary case, area closings are equivalent to + remove_small_holes; this operator is thus extended to gray-level images. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_closing is to be calculated. + This image can be of any type. + area_threshold : unsigned int + The size parameter (number of pixels). The default value is arbitrarily + chosen to be 64. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the inverted image. The + value of each pixel is the index of its parent in the ravelled array. + See Note for further details. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.diameter_opening + skimage.morphology.diameter_closing + skimage.morphology.max_tree + skimage.morphology.remove_small_objects + skimage.morphology.remove_small_holes + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a minimum in the center and + 4 additional local minima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the area closing: + + >>> closed = area_closing(f, 8, connectivity=1) + + All small minima are removed, and the remaining minima have at least + a size of 8. + + Notes + ----- + If a max-tree representation (parent and tree_traverser) are given to the + function, they must be calculated from the inverted image for this + function, i.e.: + >>> P, S = max_tree(invert(f)) + >>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S) + """ + # inversion of the input image + image_inv = invert(image) + output = image_inv.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image_inv, connectivity) + + area = _max_tree._compute_area(image_inv.ravel(), parent.ravel(), tree_traverser) + + _max_tree._direct_filter( + image_inv.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + area, + area_threshold, + ) + + # inversion of the output image + output = invert(output) + + return output + + +def diameter_closing( + image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None +): + """Perform a diameter closing of the image. + + Diameter closing removes all dark structures of an image with + maximal extension smaller than diameter_threshold. The maximal + extension is defined as the maximal extension of the bounding box. + The operator is also called Bounding Box Closing. In practice, + the result is similar to a morphological closing, but long and thin + structures are not removed. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the diameter_closing is to be calculated. + This image can be of any type. + diameter_threshold : unsigned int + The maximal extension parameter (number of pixels). The default value + is 8. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Precomputed parent image representing the max tree of the inverted + image. This function is fast, if precomputed parent and tree_traverser + are provided. See Note for further details. + tree_traverser : 1D array, int64, optional + Precomputed traverser, where the pixels are ordered such that every + pixel is preceded by its parent (except for the root which has no + parent). This function is fast, if precomputed parent and + tree_traverser are provided. See Note for further details. + + Returns + ------- + output : ndarray + Output image of the same shape and type as input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.area_closing + skimage.morphology.diameter_opening + skimage.morphology.max_tree + + References + ---------- + .. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of + Microaneurysms in Color Fundus Images of the Human Retina by Means + of the Bounding Box Closing. In A. Colosimo, P. Sirabella, + A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer + Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. + :DOI:`10.1007/3-540-36104-9_23` + .. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a minimum in the center and + 4 additional local minima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the diameter closing: + + >>> closed = diameter_closing(f, 3, connectivity=1) + + All small minima with a maximal extension of 2 or less are removed. + The remaining minima have all a maximal extension of at least 3. + + Notes + ----- + If a max-tree representation (parent and tree_traverser) are given to the + function, they must be calculated from the inverted image for this + function, i.e.: + >>> P, S = max_tree(invert(f)) + >>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S) + """ + # inversion of the input image + image_inv = invert(image) + output = image_inv.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image_inv, connectivity) + + diam = _max_tree._compute_extension( + image_inv.ravel(), + np.array(image_inv.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + _max_tree._direct_filter( + image_inv.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + diam, + diameter_threshold, + ) + output = invert(output) + return output + + +def max_tree_local_maxima(image, connectivity=1, parent=None, tree_traverser=None): + """Determine all local maxima of the image. + + The local maxima are defined as connected sets of pixels with equal + gray level strictly greater than the gray levels of all pixels in direct + neighborhood of the set. The function labels the local maxima. + + Technically, the implementation is based on the max-tree representation + of an image. The function is very efficient if the max-tree representation + has already been computed. Otherwise, it is preferable to use + the function local_maxima. + + Parameters + ---------- + image : ndarray + The input image for which the maxima are to be calculated. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + The value of each pixel is the index of its parent in the ravelled + array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + local_max : ndarray, uint64 + Labeled local maxima of the image. + + See Also + -------- + skimage.morphology.local_maxima + skimage.morphology.max_tree + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional constant maxima. + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all local maxima: + + >>> maxima = max_tree_local_maxima(f) + + The resulting image contains the labeled local maxima. + """ + + output = np.ones(image.shape, dtype=np.uint64) + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + _max_tree._max_tree_local_maxima( + image.ravel(), output.ravel(), parent.ravel(), tree_traverser + ) + + return output diff --git a/python_embeded/Lib/site-packages/skimage/morphology/misc.py b/python_embeded/Lib/site-packages/skimage/morphology/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..c64e52e2cd15d37e4e34d24ead0efd86c89ebd1b --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/morphology/misc.py @@ -0,0 +1,454 @@ +"""Miscellaneous morphology functions.""" + +import numpy as np +import functools +from scipy import ndimage as ndi +from scipy.spatial import cKDTree + +from .._shared.utils import warn +from ._misc_cy import _remove_objects_by_distance + + +# Our function names don't exactly correspond to ndimages. +# This dictionary translates from our names to scipy's. +funcs = ('erosion', 'dilation', 'opening', 'closing') +skimage2ndimage = {x: 'grey_' + x for x in funcs} + +# These function names are the same in ndimage. +funcs = ( + 'binary_erosion', + 'binary_dilation', + 'binary_opening', + 'binary_closing', + 'black_tophat', + 'white_tophat', +) +skimage2ndimage.update({x: x for x in funcs}) + + +def default_footprint(func): + """Decorator to add a default footprint to morphology functions. + + Parameters + ---------- + func : function + A morphology function such as erosion, dilation, opening, closing, + white_tophat, or black_tophat. + + Returns + ------- + func_out : function + The function, using a default footprint of same dimension + as the input image with connectivity 1. + + """ + + @functools.wraps(func) + def func_out(image, footprint=None, *args, **kwargs): + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, 1) + return func(image, footprint=footprint, *args, **kwargs) + + return func_out + + +def _check_dtype_supported(ar): + # Should use `issubdtype` for bool below, but there's a bug in numpy 1.7 + if not (ar.dtype == bool or np.issubdtype(ar.dtype, np.integer)): + raise TypeError( + "Only bool or integer image types are supported. " f"Got {ar.dtype}." + ) + + +def remove_small_objects(ar, min_size=64, connectivity=1, *, out=None): + """Remove objects smaller than the specified size. + + Expects ar to be an array with labeled objects, and removes objects + smaller than min_size. If `ar` is bool, the image is first labeled. + This leads to potentially different behavior for bool and 0-and-1 + arrays. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the objects of interest. If the array type is + int, the ints must be non-negative. + min_size : int, optional (default: 64) + The smallest allowable object size. + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. Used during + labelling if `ar` is bool. + out : ndarray + Array of the same shape as `ar`, into which the output is + placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small connected components removed. + + See Also + -------- + skimage.morphology.remove_objects_by_distance + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[0, 0, 0, 1, 0], + ... [1, 1, 1, 0, 0], + ... [1, 1, 1, 0, 1]], bool) + >>> b = morphology.remove_small_objects(a, 6) + >>> b + array([[False, False, False, False, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> c = morphology.remove_small_objects(a, 7, connectivity=2) + >>> c + array([[False, False, False, True, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> d = morphology.remove_small_objects(a, 6, out=a) + >>> d is a + True + + """ + # Raising type error if not int or bool + _check_dtype_supported(ar) + + if out is None: + out = ar.copy() + else: + out[:] = ar + + if min_size == 0: # shortcut for efficiency + return out + + if out.dtype == bool: + footprint = ndi.generate_binary_structure(ar.ndim, connectivity) + ccs = np.zeros_like(ar, dtype=np.int32) + ndi.label(ar, footprint, output=ccs) + else: + ccs = out + + try: + component_sizes = np.bincount(ccs.ravel()) + except ValueError: + raise ValueError( + "Negative value labels are not supported. Try " + "relabeling the input with `scipy.ndimage.label` or " + "`skimage.morphology.label`." + ) + + if len(component_sizes) == 2 and out.dtype != bool: + warn( + "Only one label was provided to `remove_small_objects`. " + "Did you mean to use a boolean array?" + ) + + too_small = component_sizes < min_size + too_small_mask = too_small[ccs] + out[too_small_mask] = 0 + + return out + + +def remove_small_holes(ar, area_threshold=64, connectivity=1, *, out=None): + """Remove contiguous holes smaller than the specified size. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the connected components of interest. + area_threshold : int, optional (default: 64) + The maximum area, in pixels, of a contiguous hole that will be filled. + Replaces `min_size`. + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. + out : ndarray + Array of the same shape as `ar` and bool dtype, into which the + output is placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small holes within connected components removed. + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[1, 1, 1, 1, 1, 0], + ... [1, 1, 1, 0, 1, 0], + ... [1, 0, 0, 1, 1, 0], + ... [1, 1, 1, 1, 1, 0]], bool) + >>> b = morphology.remove_small_holes(a, 2) + >>> b + array([[ True, True, True, True, True, False], + [ True, True, True, True, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> c = morphology.remove_small_holes(a, 2, connectivity=2) + >>> c + array([[ True, True, True, True, True, False], + [ True, True, True, False, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> d = morphology.remove_small_holes(a, 2, out=a) + >>> d is a + True + + Notes + ----- + If the array type is int, it is assumed that it contains already-labeled + objects. The labels are not kept in the output image (this function always + outputs a bool image). It is suggested that labeling is completed after + using this function. + + """ + _check_dtype_supported(ar) + + # Creates warning if image is an integer image + if ar.dtype != bool: + warn( + "Any labeled images will be returned as a boolean array. " + "Did you mean to use a boolean array?", + UserWarning, + ) + + if out is not None: + if out.dtype != bool: + raise TypeError("out dtype must be bool") + else: + out = ar.astype(bool, copy=True) + + # Creating the inverse of ar + np.logical_not(ar, out=out) + + # removing small objects from the inverse of ar + out = remove_small_objects(out, area_threshold, connectivity, out=out) + + np.logical_not(out, out=out) + + return out + + +def remove_objects_by_distance( + label_image, + min_distance, + *, + priority=None, + p_norm=2, + spacing=None, + out=None, +): + """Remove objects, in specified order, until remaining are a minimum distance apart. + + Remove labeled objects from an image until the remaining ones are spaced + more than a given distance from one another. By default, smaller objects + are removed first. + + Parameters + ---------- + label_image : ndarray of integers + An n-dimensional array containing object labels, e.g. as returned by + :func:`~.label`. A value of zero is considered background, all other + object IDs must be positive integers. + min_distance : int or float + Remove objects whose distance to other objects is not greater than this + positive value. Objects with a lower `priority` are removed first. + priority : ndarray, optional + Defines the priority with which objects are removed. Expects a + 1-dimensional array of length + :func:`np.amax(label_image) + 1 ` that contains the priority + for each object's label at the respective index. Objects with a lower value + are removed first until all remaining objects fulfill the distance + requirement. If not given, priority is given to objects with a higher + number of samples and their label value second. + p_norm : int or float, optional + The Minkowski distance of order p, used to calculate the distance + between objects. The default ``2`` corresponds to the Euclidean + distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the + Chebyshev distance. + spacing : sequence of float, optional + The pixel spacing along each axis of `label_image`. If not specified, + a grid spacing of unity (1) is implied. + out : ndarray, optional + Array of the same shape and dtype as `image`, into which the output is + placed. By default, a new array is created. + + Returns + ------- + out : ndarray + Array of the same shape as `label_image`, for which objects that violate + the `min_distance` condition were removed. + + See Also + -------- + skimage.morphology.remove_small_objects + Remove objects smaller than the specified size. + + Notes + ----- + The basic steps of this algorithm work as follows: + + 1. Find the indices for of all given objects and separate them depending on + if they point to an object's border or not. + 2. Sort indices by their label value, ensuring that indices which point to + the same object are next to each other. This optimization allows finding + all parts of an object, simply by stepping to the neighboring indices. + 3. Sort boundary indices by `priority`. Use a stable-sort to preserve the + ordering from the previous sorting step. If `priority` is not given, + use :func:`numpy.bincount` as a fallback. + 4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices. + 5. Iterate across boundary indices in priority-sorted order, and query the + kd-tree for objects that are too close. Remove ones that are and don't + take them into account when evaluating other objects later on. + + The performance of this algorithm depends on the number of samples in + `label_image` that belong to an object's border. + + Examples + -------- + >>> import skimage as ski + >>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2) + array([0, 0, 1, 1]) + >>> ski.morphology.remove_objects_by_distance( + ... np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9]) + ... ) + array([2, 0, 0, 0]) + >>> label_image = np.array( + ... [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + ... [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + ... [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0], + ... [2, 0, 0, 0, 0, 1, 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, 7, 7]] + ... ) + >>> ski.morphology.remove_objects_by_distance( + ... label_image, min_distance=3 + ... ) + array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]]) + """ + if min_distance < 0: + raise ValueError(f"min_distance must be >= 0, was {min_distance}") + if not np.issubdtype(label_image.dtype, np.integer): + raise ValueError( + f"`label_image` must be of integer dtype, got {label_image.dtype}" + ) + if out is None: + out = label_image.copy(order="C") + elif out is not label_image: + out[:] = label_image + # May create a copy if order is not C, account for that later + out_raveled = out.ravel(order="C") + + if spacing is not None: + spacing = np.array(spacing) + if spacing.shape != (out.ndim,) or spacing.min() <= 0: + raise ValueError( + "`spacing` must contain exactly one positive factor " + "for each dimension of `label_image`" + ) + + indices = np.flatnonzero(out_raveled) + # Optimization: Split indices into those on the object boundaries and inner + # ones. The KDTree is built only from the boundary indices, which reduces + # the size of the critical loop significantly! Remaining indices are only + # used to remove the inner parts of objects as well. + if (spacing is None or np.all(spacing[0] == spacing)) and p_norm <= 2: + # For unity spacing we can make the borders more sparse by using a + # lower connectivity + footprint = ndi.generate_binary_structure(out.ndim, 1) + else: + footprint = ndi.generate_binary_structure(out.ndim, out.ndim) + border = ( + ndi.maximum_filter(out, footprint=footprint) + != ndi.minimum_filter(out, footprint=footprint) + ).ravel()[indices] + border_indices = indices[border] + inner_indices = indices[~border] + + if border_indices.size == 0: + # Image without any or only one object, return early + return out + + # Sort by label ID first, so that IDs of the same object are contiguous + # in the sorted index. This allows fast discovery of the whole object by + # simple iteration up or down the index! + border_indices = border_indices[np.argsort(out_raveled[border_indices])] + inner_indices = inner_indices[np.argsort(out_raveled[inner_indices])] + + if priority is None: + if not np.can_cast(out.dtype, np.intp, casting="safe"): + # bincount expects intp (32-bit) on WASM or i386, so down-cast to that + priority = np.bincount(out_raveled.astype(np.intp, copy=False)) + else: + priority = np.bincount(out_raveled) + # `priority` can only be indexed by positive object IDs, + # `border_indices` contains all unique sorted IDs so check the lowest / first + smallest_id = out_raveled[border_indices[0]] + if smallest_id < 0: + raise ValueError(f"found object with negative ID {smallest_id!r}") + + try: + # Sort by priority second using a stable sort to preserve the contiguous + # sorting of objects. Because each pixel in an object has the same + # priority we don't need to worry about separating objects. + border_indices = border_indices[ + np.argsort(priority[out_raveled[border_indices]], kind="stable")[::-1] + ] + except IndexError as error: + # Use np.amax only for the exception path to provide a nicer error message + expected_shape = (np.amax(out_raveled) + 1,) + if priority.shape != expected_shape: + raise ValueError( + "shape of `priority` must be (np.amax(label_image) + 1,), " + f"expected {expected_shape}, got {priority.shape} instead" + ) from error + else: + raise + + # Construct kd-tree from unraveled border indices (optionally scale by `spacing`) + unraveled_indices = np.unravel_index(border_indices, out.shape) + if spacing is not None: + unraveled_indices = tuple( + unraveled_indices[dim] * spacing[dim] for dim in range(out.ndim) + ) + kdtree = cKDTree(data=np.asarray(unraveled_indices, dtype=np.float64).T) + + _remove_objects_by_distance( + out=out_raveled, + border_indices=border_indices, + inner_indices=inner_indices, + kdtree=kdtree, + min_distance=min_distance, + p_norm=p_norm, + shape=label_image.shape, + ) + + if out_raveled.base is not out: + # `out_raveled` is a copy, re-assign + out[:] = out_raveled.reshape(out.shape) + return out diff --git a/python_embeded/Lib/site-packages/skimage/registration/__init__.py b/python_embeded/Lib/site-packages/skimage/registration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fef91732fd434370d0be8af5e4b577a9b30f148 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/__init__.py @@ -0,0 +1,5 @@ +"""Image registration algorithms, e.g., optical flow or phase cross correlation.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/registration/__init__.pyi b/python_embeded/Lib/site-packages/skimage/registration/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b1c10ab0b961ce41257d26d3f7640e71284e8868 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/__init__.pyi @@ -0,0 +1,8 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = ['optical_flow_ilk', 'optical_flow_tvl1', 'phase_cross_correlation'] + +from ._optical_flow import optical_flow_tvl1, optical_flow_ilk +from ._phase_cross_correlation import phase_cross_correlation diff --git a/python_embeded/Lib/site-packages/skimage/registration/_masked_phase_cross_correlation.py b/python_embeded/Lib/site-packages/skimage/registration/_masked_phase_cross_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..a37e8789b5b98604a7513287d4fc8472d30dfac2 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/_masked_phase_cross_correlation.py @@ -0,0 +1,306 @@ +""" +Implementation of the masked normalized cross-correlation. + +Based on the following publication: +D. Padfield. Masked object registration in the Fourier domain. +IEEE Transactions on Image Processing (2012) + +and the author's original MATLAB implementation, available on this website: +http://www.dirkpadfield.com/ +""" + +from functools import partial + +import numpy as np +import scipy.fft as fftmodule +from scipy.fft import next_fast_len + +from .._shared.utils import _supported_float_type + + +def _masked_phase_cross_correlation( + reference_image, moving_image, reference_mask, moving_mask=None, overlap_ratio=0.3 +): + """Masked image translation registration by masked normalized + cross-correlation. + + Parameters + ---------- + reference_image : ndarray + Reference image. + moving_image : ndarray + Image to register. Must be same dimensionality as ``reference_image``, + but not necessarily the same size. + reference_mask : ndarray + Boolean mask for ``reference_image``. The mask should evaluate + to ``True`` (or 1) on valid pixels. ``reference_mask`` should + have the same shape as ``reference_image``. + moving_mask : ndarray or None, optional + Boolean mask for ``moving_image``. The mask should evaluate to ``True`` + (or 1) on valid pixels. ``moving_mask`` should have the same shape + as ``moving_image``. If ``None``, ``reference_mask`` will be used. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. + + Returns + ------- + shifts : ndarray + Shift vector (in pixels) required to register ``moving_image`` + with ``reference_image``. Axis ordering is consistent with numpy. + + References + ---------- + .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + + """ + if moving_mask is None: + if reference_image.shape != moving_image.shape: + raise ValueError( + "Input images have different shapes, moving_mask must " + "be explicitly set." + ) + moving_mask = reference_mask.astype(bool) + + # We need masks to be of the same size as their respective images + for im, mask in [(reference_image, reference_mask), (moving_image, moving_mask)]: + if im.shape != mask.shape: + raise ValueError("Image sizes must match their respective mask sizes.") + + xcorr = cross_correlate_masked( + moving_image, + reference_image, + moving_mask, + reference_mask, + axes=tuple(range(moving_image.ndim)), + mode='full', + overlap_ratio=overlap_ratio, + ) + + # Generalize to the average of multiple equal maxima + maxima = np.stack(np.nonzero(xcorr == xcorr.max()), axis=1) + center = np.mean(maxima, axis=0) + shifts = center - np.array(reference_image.shape) + 1 + + # The mismatch in size will impact the center location of the + # cross-correlation + size_mismatch = np.array(moving_image.shape) - np.array(reference_image.shape) + + return -shifts + (size_mismatch / 2) + + +def cross_correlate_masked( + arr1, arr2, m1, m2, mode='full', axes=(-2, -1), overlap_ratio=0.3 +): + """ + Masked normalized cross-correlation between arrays. + + Parameters + ---------- + arr1 : ndarray + First array. + arr2 : ndarray + Seconds array. The dimensions of `arr2` along axes that are not + transformed should be equal to that of `arr1`. + m1 : ndarray + Mask of `arr1`. The mask should evaluate to `True` + (or 1) on valid pixels. `m1` should have the same shape as `arr1`. + m2 : ndarray + Mask of `arr2`. The mask should evaluate to `True` + (or 1) on valid pixels. `m2` should have the same shape as `arr2`. + mode : {'full', 'same'}, optional + 'full': + This returns the convolution at each point of overlap. At + the end-points of the convolution, the signals do not overlap + completely, and boundary effects may be seen. + 'same': + The output is the same size as `arr1`, centered with respect + to the `‘full’` output. Boundary effects are less prominent. + axes : tuple of ints, optional + Axes along which to compute the cross-correlation. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. + + Returns + ------- + out : ndarray + Masked normalized cross-correlation. + + Raises + ------ + ValueError : if correlation `mode` is not valid, or array dimensions along + non-transformation axes are not equal. + + References + ---------- + .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + """ + if mode not in {'full', 'same'}: + raise ValueError(f"Correlation mode '{mode}' is not valid.") + + fixed_image = np.asarray(arr1) + moving_image = np.asarray(arr2) + float_dtype = _supported_float_type((fixed_image.dtype, moving_image.dtype)) + if float_dtype.kind == 'c': + raise ValueError("complex-valued arr1, arr2 are not supported") + + fixed_image = fixed_image.astype(float_dtype) + fixed_mask = np.array(m1, dtype=bool) + moving_image = moving_image.astype(float_dtype) + moving_mask = np.array(m2, dtype=bool) + eps = np.finfo(float_dtype).eps + + # Array dimensions along non-transformation axes should be equal. + all_axes = set(range(fixed_image.ndim)) + for axis in all_axes - set(axes): + if fixed_image.shape[axis] != moving_image.shape[axis]: + raise ValueError( + f'Array shapes along non-transformation axes should be ' + f'equal, but dimensions along axis {axis} are not.' + ) + + # Determine final size along transformation axes + # Note that it might be faster to compute Fourier transform in a slightly + # larger shape (`fast_shape`). Then, after all fourier transforms are done, + # we slice back to`final_shape` using `final_slice`. + final_shape = list(arr1.shape) + for axis in axes: + final_shape[axis] = fixed_image.shape[axis] + moving_image.shape[axis] - 1 + final_shape = tuple(final_shape) + final_slice = tuple([slice(0, int(sz)) for sz in final_shape]) + + # Extent transform axes to the next fast length (i.e. multiple of 3, 5, or + # 7) + fast_shape = tuple([next_fast_len(final_shape[ax]) for ax in axes]) + + # We use the new scipy.fft because they allow leaving the transform axes + # unchanged which was not possible with scipy.fftpack's + # fftn/ifftn in older versions of SciPy. + # E.g. arr shape (2, 3, 7), transform along axes (0, 1) with shape (4, 4) + # results in arr_fft shape (4, 4, 7) + fft = partial(fftmodule.fftn, s=fast_shape, axes=axes) + _ifft = partial(fftmodule.ifftn, s=fast_shape, axes=axes) + + def ifft(x): + return _ifft(x).real + + fixed_image[np.logical_not(fixed_mask)] = 0.0 + moving_image[np.logical_not(moving_mask)] = 0.0 + + # N-dimensional analog to rotation by 180deg is flip over all relevant axes. + # See [1] for discussion. + rotated_moving_image = _flip(moving_image, axes=axes) + rotated_moving_mask = _flip(moving_mask, axes=axes) + + fixed_fft = fft(fixed_image) + rotated_moving_fft = fft(rotated_moving_image) + fixed_mask_fft = fft(fixed_mask.astype(float_dtype)) + rotated_moving_mask_fft = fft(rotated_moving_mask.astype(float_dtype)) + + # Calculate overlap of masks at every point in the convolution. + # Locations with high overlap should not be taken into account. + number_overlap_masked_px = ifft(rotated_moving_mask_fft * fixed_mask_fft) + number_overlap_masked_px[:] = np.round(number_overlap_masked_px) + number_overlap_masked_px[:] = np.fmax(number_overlap_masked_px, eps) + masked_correlated_fixed_fft = ifft(rotated_moving_mask_fft * fixed_fft) + masked_correlated_rotated_moving_fft = ifft(fixed_mask_fft * rotated_moving_fft) + + numerator = ifft(rotated_moving_fft * fixed_fft) + numerator -= ( + masked_correlated_fixed_fft + * masked_correlated_rotated_moving_fft + / number_overlap_masked_px + ) + + fixed_squared_fft = fft(np.square(fixed_image)) + fixed_denom = ifft(rotated_moving_mask_fft * fixed_squared_fft) + fixed_denom -= np.square(masked_correlated_fixed_fft) / number_overlap_masked_px + fixed_denom[:] = np.fmax(fixed_denom, 0.0) + + rotated_moving_squared_fft = fft(np.square(rotated_moving_image)) + moving_denom = ifft(fixed_mask_fft * rotated_moving_squared_fft) + moving_denom -= ( + np.square(masked_correlated_rotated_moving_fft) / number_overlap_masked_px + ) + moving_denom[:] = np.fmax(moving_denom, 0.0) + + denom = np.sqrt(fixed_denom * moving_denom) + + # Slice back to expected convolution shape. + numerator = numerator[final_slice] + denom = denom[final_slice] + number_overlap_masked_px = number_overlap_masked_px[final_slice] + + if mode == 'same': + _centering = partial(_centered, newshape=fixed_image.shape, axes=axes) + denom = _centering(denom) + numerator = _centering(numerator) + number_overlap_masked_px = _centering(number_overlap_masked_px) + + # Pixels where `denom` is very small will introduce large + # numbers after division. To get around this problem, + # we zero-out problematic pixels. + tol = 1e3 * eps * np.max(np.abs(denom), axis=axes, keepdims=True) + nonzero_indices = denom > tol + + # explicitly set out dtype for compatibility with SciPy < 1.4, where + # fftmodule will be numpy.fft which always uses float64 dtype. + out = np.zeros_like(denom, dtype=float_dtype) + out[nonzero_indices] = numerator[nonzero_indices] / denom[nonzero_indices] + np.clip(out, a_min=-1, a_max=1, out=out) + + # Apply overlap ratio threshold + number_px_threshold = overlap_ratio * np.max( + number_overlap_masked_px, axis=axes, keepdims=True + ) + out[number_overlap_masked_px < number_px_threshold] = 0.0 + + return out + + +def _centered(arr, newshape, axes): + """Return the center `newshape` portion of `arr`, leaving axes not + in `axes` untouched.""" + newshape = np.asarray(newshape) + currshape = np.array(arr.shape) + + slices = [slice(None, None)] * arr.ndim + + for ax in axes: + startind = (currshape[ax] - newshape[ax]) // 2 + endind = startind + newshape[ax] + slices[ax] = slice(startind, endind) + + return arr[tuple(slices)] + + +def _flip(arr, axes=None): + """Reverse array over many axes. Generalization of arr[::-1] for many + dimensions. If `axes` is `None`, flip along all axes.""" + if axes is None: + reverse = [slice(None, None, -1)] * arr.ndim + else: + reverse = [slice(None, None, None)] * arr.ndim + for axis in axes: + reverse[axis] = slice(None, None, -1) + + return arr[tuple(reverse)] diff --git a/python_embeded/Lib/site-packages/skimage/registration/_optical_flow.py b/python_embeded/Lib/site-packages/skimage/registration/_optical_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9307f522c64c672dea940ebd13da3ad1bd6b37 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/_optical_flow.py @@ -0,0 +1,429 @@ +"""TV-L1 optical flow algorithm implementation.""" + +from functools import partial +from itertools import combinations_with_replacement + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.filters import gaussian as gaussian_filter +from .._shared.utils import _supported_float_type +from ..transform import warp +from ._optical_flow_utils import _coarse_to_fine, _get_warp_points + + +def _tvl1( + reference_image, + moving_image, + flow0, + attachment, + tightness, + num_warp, + num_iter, + tol, + prefilter, +): + """TV-L1 solver for optical flow estimation. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + flow0 : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + Initialization for the vector field. + attachment : float + Attachment parameter. The smaller this parameter is, + the smoother is the solutions. + tightness : float + Tightness parameter. It should have a small value in order to + maintain attachment and regularization parts in + correspondence. + num_warp : int + Number of times moving_image is warped. + num_iter : int + Number of fixed point iteration. + tol : float + Tolerance used as stopping criterion based on the L² distance + between two consecutive values of (u, v). + prefilter : bool + Whether to prefilter the estimated optical flow before each + image warp. + + Returns + ------- + flow : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + """ + + dtype = reference_image.dtype + grid = np.meshgrid( + *[np.arange(n, dtype=dtype) for n in reference_image.shape], + indexing='ij', + sparse=True, + ) + + # dt corresponds to tau in [3]_, i.e. the time step + dt = 0.5 / reference_image.ndim + reg_num_iter = 2 + f0 = attachment * tightness + f1 = dt / tightness + tol *= reference_image.size + + flow_current = flow_previous = flow0 + + g = np.zeros((reference_image.ndim,) + reference_image.shape, dtype=dtype) + proj = np.zeros( + ( + reference_image.ndim, + reference_image.ndim, + ) + + reference_image.shape, + dtype=dtype, + ) + + s_g = [ + slice(None), + ] * g.ndim + s_p = [ + slice(None), + ] * proj.ndim + s_d = [ + slice(None), + ] * (proj.ndim - 2) + + for _ in range(num_warp): + if prefilter: + flow_current = ndi.median_filter( + flow_current, [1] + reference_image.ndim * [3] + ) + + image1_warp = warp( + moving_image, _get_warp_points(grid, flow_current), mode='edge' + ) + grad = np.array(np.gradient(image1_warp)) + NI = (grad * grad).sum(0) + NI[NI == 0] = 1 + + rho_0 = image1_warp - reference_image - (grad * flow_current).sum(0) + + for _ in range(num_iter): + # Data term + + rho = rho_0 + (grad * flow_current).sum(0) + + idx = abs(rho) <= f0 * NI + + flow_auxiliary = flow_current + + flow_auxiliary[:, idx] -= rho[idx] * grad[:, idx] / NI[idx] + + idx = ~idx + srho = f0 * np.sign(rho[idx]) + flow_auxiliary[:, idx] -= srho * grad[:, idx] + + # Regularization term + flow_current = flow_auxiliary.copy() + + for idx in range(reference_image.ndim): + s_p[0] = idx + for _ in range(reg_num_iter): + for ax in range(reference_image.ndim): + s_g[0] = ax + s_g[ax + 1] = slice(0, -1) + g[tuple(s_g)] = np.diff(flow_current[idx], axis=ax) + s_g[ax + 1] = slice(None) + + norm = np.sqrt((g**2).sum(0))[np.newaxis, ...] + norm *= f1 + norm += 1.0 + proj[idx] -= dt * g + proj[idx] /= norm + + # d will be the (negative) divergence of proj[idx] + d = -proj[idx].sum(0) + for ax in range(reference_image.ndim): + s_p[1] = ax + s_p[ax + 2] = slice(0, -1) + s_d[ax] = slice(1, None) + d[tuple(s_d)] += proj[tuple(s_p)] + s_p[ax + 2] = slice(None) + s_d[ax] = slice(None) + + flow_current[idx] = flow_auxiliary[idx] + d + + flow_previous -= flow_current # The difference as stopping criteria + if (flow_previous * flow_previous).sum() < tol: + break + + flow_previous = flow_current + + return flow_current + + +def optical_flow_tvl1( + reference_image, + moving_image, + *, + attachment=15, + tightness=0.3, + num_warp=5, + num_iter=10, + tol=1e-4, + prefilter=False, + dtype=np.float32, +): + r"""Coarse to fine optical flow estimator. + + The TV-L1 solver is applied at each level of the image + pyramid. TV-L1 is a popular algorithm for optical flow estimation + introduced by Zack et al. [1]_, improved in [2]_ and detailed in [3]_. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + attachment : float, optional + Attachment parameter (:math:`\lambda` in [1]_). The smaller + this parameter is, the smoother the returned result will be. + tightness : float, optional + Tightness parameter (:math:`\theta` in [1]_). It should have + a small value in order to maintain attachment and + regularization parts in correspondence. + num_warp : int, optional + Number of times moving_image is warped. + num_iter : int, optional + Number of fixed point iteration. + tol : float, optional + Tolerance used as stopping criterion based on the L² distance + between two consecutive values of (u, v). + prefilter : bool, optional + Whether to prefilter the estimated optical flow before each + image warp. When True, a median filter with window size 3 + along each axis is applied. This helps to remove potential + outliers. + dtype : dtype, optional + Output data type: must be floating point. Single precision + provides good results and saves memory usage and computation + time compared to double precision. + + Returns + ------- + flow : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + Notes + ----- + Color images are not supported. + + References + ---------- + .. [1] Zach, C., Pock, T., & Bischof, H. (2007, September). A + duality based approach for realtime TV-L 1 optical flow. In Joint + pattern recognition symposium (pp. 214-223). Springer, Berlin, + Heidelberg. :DOI:`10.1007/978-3-540-74936-3_22` + .. [2] Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, + D. (2009). An improved algorithm for TV-L 1 optical flow. In + Statistical and geometrical approaches to visual motion analysis + (pp. 23-45). Springer, Berlin, Heidelberg. + :DOI:`10.1007/978-3-642-03061-1_2` + .. [3] Pérez, J. S., Meinhardt-Llopis, E., & Facciolo, + G. (2013). TV-L1 optical flow estimation. Image Processing On + Line, 2013, 137-150. :DOI:`10.5201/ipol.2013.26` + + Examples + -------- + >>> from skimage.color import rgb2gray + >>> from skimage.data import stereo_motorcycle + >>> from skimage.registration import optical_flow_tvl1 + >>> image0, image1, disp = stereo_motorcycle() + >>> # --- Convert the images to gray level: color is not supported. + >>> image0 = rgb2gray(image0) + >>> image1 = rgb2gray(image1) + >>> flow = optical_flow_tvl1(image1, image0) + + """ + + solver = partial( + _tvl1, + attachment=attachment, + tightness=tightness, + num_warp=num_warp, + num_iter=num_iter, + tol=tol, + prefilter=prefilter, + ) + + if np.dtype(dtype) != _supported_float_type(dtype): + msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'" + raise ValueError(msg) + + return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype) + + +def _ilk(reference_image, moving_image, flow0, radius, num_warp, gaussian, prefilter): + """Iterative Lucas-Kanade (iLK) solver for optical flow estimation. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + flow0 : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + Initialization for the vector field. + radius : int + Radius of the window considered around each pixel. + num_warp : int + Number of times moving_image is warped. + gaussian : bool + if True, a gaussian kernel is used for the local + integration. Otherwise, a uniform kernel is used. + prefilter : bool + Whether to prefilter the estimated optical flow before each + image warp. This helps to remove potential outliers. + + Returns + ------- + flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + """ + dtype = reference_image.dtype + ndim = reference_image.ndim + size = 2 * radius + 1 + + if gaussian: + sigma = ndim * (size / 4,) + filter_func = partial(gaussian_filter, sigma=sigma, mode='mirror') + else: + filter_func = partial(ndi.uniform_filter, size=ndim * (size,), mode='mirror') + + flow = flow0 + # For each pixel location (i, j), the optical flow X = flow[:, i, j] + # is the solution of the ndim x ndim linear system + # A[i, j] * X = b[i, j] + A = np.zeros(reference_image.shape + (ndim, ndim), dtype=dtype) + b = np.zeros(reference_image.shape + (ndim, 1), dtype=dtype) + + grid = np.meshgrid( + *[np.arange(n, dtype=dtype) for n in reference_image.shape], + indexing='ij', + sparse=True, + ) + + for _ in range(num_warp): + if prefilter: + flow = ndi.median_filter(flow, (1,) + ndim * (3,)) + + moving_image_warp = warp( + moving_image, _get_warp_points(grid, flow), mode='edge' + ) + grad = np.stack(np.gradient(moving_image_warp), axis=0) + error_image = (grad * flow).sum(axis=0) + reference_image - moving_image_warp + + # Local linear systems creation + for i, j in combinations_with_replacement(range(ndim), 2): + A[..., i, j] = A[..., j, i] = filter_func(grad[i] * grad[j]) + + for i in range(ndim): + b[..., i, 0] = filter_func(grad[i] * error_image) + + # Don't consider badly conditioned linear systems + idx = abs(np.linalg.det(A)) < 1e-14 + A[idx] = np.eye(ndim, dtype=dtype) + b[idx] = 0 + + # Solve the local linear systems + flow = np.moveaxis(np.linalg.solve(A, b)[..., 0], ndim, 0) + + return flow + + +def optical_flow_ilk( + reference_image, + moving_image, + *, + radius=7, + num_warp=10, + gaussian=False, + prefilter=False, + dtype=np.float32, +): + """Coarse to fine optical flow estimator. + + The iterative Lucas-Kanade (iLK) solver is applied at each level + of the image pyramid. iLK [1]_ is a fast and robust alternative to + TVL1 algorithm although less accurate for rendering flat surfaces + and object boundaries (see [2]_). + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + radius : int, optional + Radius of the window considered around each pixel. + num_warp : int, optional + Number of times moving_image is warped. + gaussian : bool, optional + If True, a Gaussian kernel is used for the local + integration. Otherwise, a uniform kernel is used. + prefilter : bool, optional + Whether to prefilter the estimated optical flow before each + image warp. When True, a median filter with window size 3 + along each axis is applied. This helps to remove potential + outliers. + dtype : dtype, optional + Output data type: must be floating point. Single precision + provides good results and saves memory usage and computation + time compared to double precision. + + Returns + ------- + flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + Notes + ----- + - The implemented algorithm is described in **Table2** of [1]_. + - Color images are not supported. + + References + ---------- + .. [1] Le Besnerais, G., & Champagnat, F. (2005, September). Dense + optical flow by iterative local window registration. In IEEE + International Conference on Image Processing 2005 (Vol. 1, + pp. I-137). IEEE. :DOI:`10.1109/ICIP.2005.1529706` + .. [2] Plyer, A., Le Besnerais, G., & Champagnat, + F. (2016). Massively parallel Lucas Kanade optical flow for + real-time video processing applications. Journal of Real-Time + Image Processing, 11(4), 713-730. :DOI:`10.1007/s11554-014-0423-0` + + Examples + -------- + >>> from skimage.color import rgb2gray + >>> from skimage.data import stereo_motorcycle + >>> from skimage.registration import optical_flow_ilk + >>> reference_image, moving_image, disp = stereo_motorcycle() + >>> # --- Convert the images to gray level: color is not supported. + >>> reference_image = rgb2gray(reference_image) + >>> moving_image = rgb2gray(moving_image) + >>> flow = optical_flow_ilk(moving_image, reference_image) + + """ + + solver = partial( + _ilk, radius=radius, num_warp=num_warp, gaussian=gaussian, prefilter=prefilter + ) + + if np.dtype(dtype) != _supported_float_type(dtype): + msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'" + raise ValueError(msg) + + return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype) diff --git a/python_embeded/Lib/site-packages/skimage/registration/_optical_flow_utils.py b/python_embeded/Lib/site-packages/skimage/registration/_optical_flow_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3f2a7eafb2b2025ddcd7e889f739dd532c9996 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/_optical_flow_utils.py @@ -0,0 +1,150 @@ +"""Common tools to optical flow algorithms.""" + +import numpy as np +from scipy import ndimage as ndi + +from ..transform import pyramid_reduce +from ..util.dtype import _convert + + +def _get_warp_points(grid, flow): + """Compute warp point coordinates. + + Parameters + ---------- + grid : iterable + The sparse grid to be warped (obtained using + ``np.meshgrid(..., sparse=True)).``) + flow : ndarray + The warping motion field. + + Returns + ------- + out : ndarray + The warp point coordinates. + + """ + out = flow.copy() + for idx, g in enumerate(grid): + out[idx, ...] += g + return out + + +def _resize_flow(flow, shape): + """Rescale the values of the vector field (u, v) to the desired shape. + + The values of the output vector field are scaled to the new + resolution. + + Parameters + ---------- + flow : ndarray + The motion field to be processed. + shape : iterable + Couple of integers representing the output shape. + + Returns + ------- + rflow : ndarray + The resized and rescaled motion field. + + """ + + scale = [n / o for n, o in zip(shape, flow.shape[1:])] + scale_factor = np.array(scale, dtype=flow.dtype) + + for _ in shape: + scale_factor = scale_factor[..., np.newaxis] + + rflow = scale_factor * ndi.zoom( + flow, [1] + scale, order=0, mode='nearest', prefilter=False + ) + + return rflow + + +def _get_pyramid(I, downscale=2.0, nlevel=10, min_size=16): + """Construct image pyramid. + + Parameters + ---------- + I : ndarray + The image to be preprocessed (Grayscale or RGB). + downscale : float + The pyramid downscale factor. + nlevel : int + The maximum number of pyramid levels. + min_size : int + The minimum size for any dimension of the pyramid levels. + + Returns + ------- + pyramid : list[ndarray] + The coarse to fine images pyramid. + + """ + + pyramid = [I] + size = min(I.shape) + count = 1 + + while (count < nlevel) and (size > downscale * min_size): + J = pyramid_reduce(pyramid[-1], downscale, channel_axis=None) + pyramid.append(J) + size = min(J.shape) + count += 1 + + return pyramid[::-1] + + +def _coarse_to_fine( + I0, I1, solver, downscale=2, nlevel=10, min_size=16, dtype=np.float32 +): + """Generic coarse to fine solver. + + Parameters + ---------- + I0 : ndarray + The first grayscale image of the sequence. + I1 : ndarray + The second grayscale image of the sequence. + solver : callable + The solver applied at each pyramid level. + downscale : float + The pyramid downscale factor. + nlevel : int + The maximum number of pyramid levels. + min_size : int + The minimum size for any dimension of the pyramid levels. + dtype : dtype + Output data type. + + Returns + ------- + flow : ndarray + The estimated optical flow components for each axis. + + """ + + if I0.shape != I1.shape: + raise ValueError("Input images should have the same shape") + + if np.dtype(dtype).char not in 'efdg': + raise ValueError("Only floating point data type are valid" " for optical flow") + + pyramid = list( + zip( + _get_pyramid(_convert(I0, dtype), downscale, nlevel, min_size), + _get_pyramid(_convert(I1, dtype), downscale, nlevel, min_size), + ) + ) + + # Initialization to 0 at coarsest level. + flow = np.zeros((pyramid[0][0].ndim,) + pyramid[0][0].shape, dtype=dtype) + + flow = solver(pyramid[0][0], pyramid[0][1], flow) + + for J0, J1 in pyramid[1:]: + flow = solver(J0, J1, _resize_flow(flow, J0.shape)) + + return flow diff --git a/python_embeded/Lib/site-packages/skimage/registration/_phase_cross_correlation.py b/python_embeded/Lib/site-packages/skimage/registration/_phase_cross_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..2c83eb13678f11c28fe7a96e7bac19ac37645673 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/registration/_phase_cross_correlation.py @@ -0,0 +1,420 @@ +""" +Port of Manuel Guizar's code from: +http://www.mathworks.com/matlabcentral/fileexchange/18401-efficient-subpixel-image-registration-by-cross-correlation +""" + +import itertools +import warnings + +import numpy as np +from scipy.fft import fftn, ifftn, fftfreq +from scipy import ndimage as ndi + +from ._masked_phase_cross_correlation import _masked_phase_cross_correlation + + +def _upsampled_dft(data, upsampled_region_size, upsample_factor=1, axis_offsets=None): + """ + Upsampled DFT by matrix multiplication. + + This code is intended to provide the same result as if the following + operations were performed: + - Embed the array "data" in an array that is ``upsample_factor`` times + larger in each dimension. ifftshift to bring the center of the + image to (1,1). + - Take the FFT of the larger array. + - Extract an ``[upsampled_region_size]`` region of the result, starting + with the ``[axis_offsets+1]`` element. + + It achieves this result by computing the DFT in the output array without + the need to zeropad. Much faster and memory efficient than the zero-padded + FFT approach if ``upsampled_region_size`` is much smaller than + ``data.size * upsample_factor``. + + Parameters + ---------- + data : array + The input data array (DFT of original data) to upsample. + upsampled_region_size : integer or tuple of integers, optional + The size of the region to be sampled. If one integer is provided, it + is duplicated up to the dimensionality of ``data``. + upsample_factor : integer, optional + The upsampling factor. Defaults to 1. + axis_offsets : tuple of integers, optional + The offsets of the region to be sampled. Defaults to None (uses + image center) + + Returns + ------- + output : ndarray + The upsampled DFT of the specified region. + """ + # if people pass in an integer, expand it to a list of equal-sized sections + if not hasattr(upsampled_region_size, "__iter__"): + upsampled_region_size = [ + upsampled_region_size, + ] * data.ndim + else: + if len(upsampled_region_size) != data.ndim: + raise ValueError( + "shape of upsampled region sizes must be equal " + "to input data's number of dimensions." + ) + + if axis_offsets is None: + axis_offsets = [ + 0, + ] * data.ndim + else: + if len(axis_offsets) != data.ndim: + raise ValueError( + "number of axis offsets must be equal to input " + "data's number of dimensions." + ) + + im2pi = 1j * 2 * np.pi + + dim_properties = list(zip(data.shape, upsampled_region_size, axis_offsets)) + + for n_items, ups_size, ax_offset in dim_properties[::-1]: + kernel = (np.arange(ups_size) - ax_offset)[:, None] * fftfreq( + n_items, upsample_factor + ) + kernel = np.exp(-im2pi * kernel) + # use kernel with same precision as the data + kernel = kernel.astype(data.dtype, copy=False) + + # Equivalent to: + # data[i, j, k] = kernel[i, :] @ data[j, k].T + data = np.tensordot(kernel, data, axes=(1, -1)) + return data + + +def _compute_phasediff(cross_correlation_max): + """ + Compute global phase difference between the two images (should be + zero if images are non-negative). + + Parameters + ---------- + cross_correlation_max : complex + The complex value of the cross correlation at its maximum point. + """ + return np.arctan2(cross_correlation_max.imag, cross_correlation_max.real) + + +def _compute_error(cross_correlation_max, src_amp, target_amp): + """ + Compute RMS error metric between ``src_image`` and ``target_image``. + + Parameters + ---------- + cross_correlation_max : complex + The complex value of the cross correlation at its maximum point. + src_amp : float + The normalized average image intensity of the source image + target_amp : float + The normalized average image intensity of the target image + """ + amp = src_amp * target_amp + if amp == 0: + warnings.warn( + "Could not determine RMS error between images with the normalized " + f"average intensities {src_amp!r} and {target_amp!r}. Either the " + "reference or moving image may be empty.", + UserWarning, + stacklevel=3, + ) + with np.errstate(invalid="ignore"): + error = 1.0 - cross_correlation_max * cross_correlation_max.conj() / amp + return np.sqrt(np.abs(error)) + + +def _disambiguate_shift(reference_image, moving_image, shift): + """Determine the correct real-space shift based on periodic shift. + + When determining a translation shift from phase cross-correlation in + Fourier space, the shift is only correct to within a period of the image + size along each axis, resulting in $2^n$ possible shifts, where $n$ is the + number of dimensions of the image. This function checks the + cross-correlation in real space for each of those shifts, and returns the + one with the highest cross-correlation. + + The strategy we use is to perform the shift on the moving image *using the + 'grid-wrap' mode* in `scipy.ndimage`. The moving image's original borders + then define $2^n$ quadrants, which we cross-correlate with the reference + image in turn using slicing. The entire operation is thus $O(2^n + m)$, + where $m$ is the number of pixels in the image (and typically dominates). + + Parameters + ---------- + reference_image : numpy array + The reference (non-moving) image. + moving_image : numpy array + The moving image: applying the shift to this image overlays it on the + reference image. Must be the same shape as the reference image. + shift : ndarray + The shift to apply to each axis of the moving image, *modulo* image + size. The length of ``shift`` must be equal to ``moving_image.ndim``. + + Returns + ------- + real_shift : ndarray + The shift disambiguated in real space. + """ + shape = reference_image.shape + positive_shift = [shift_i % s for shift_i, s in zip(shift, shape)] + negative_shift = [shift_i - s for shift_i, s in zip(positive_shift, shape)] + subpixel = np.any(np.array(shift) % 1 != 0) + interp_order = 3 if subpixel else 0 + shifted = ndi.shift(moving_image, shift, mode='grid-wrap', order=interp_order) + indices = np.round(positive_shift).astype(int) + splits_per_dim = [(slice(0, i), slice(i, None)) for i in indices] + max_corr = -1.0 + max_slice = None + for test_slice in itertools.product(*splits_per_dim): + reference_tile = np.reshape(reference_image[test_slice], -1) + moving_tile = np.reshape(shifted[test_slice], -1) + corr = -1.0 + if reference_tile.size > 2: + # In the case of zero std, np.corrcoef returns NaN and warns + # about division by zero. This is expected and handled below. + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=RuntimeWarning) + corr = np.corrcoef(reference_tile, moving_tile)[0, 1] + if corr > max_corr: + max_corr = corr + max_slice = test_slice + if max_slice is None: + warnings.warn( + f"Could not determine real-space shift for periodic shift {shift!r} " + f"as requested by `disambiguate=True` (disambiguation is degenerate).", + stacklevel=3, + ) + return shift + real_shift_acc = [] + for sl, pos_shift, neg_shift in zip(max_slice, positive_shift, negative_shift): + real_shift_acc.append(pos_shift if sl.stop is None else neg_shift) + + return np.array(real_shift_acc) + + +def phase_cross_correlation( + reference_image, + moving_image, + *, + upsample_factor=1, + space="real", + disambiguate=False, + reference_mask=None, + moving_mask=None, + overlap_ratio=0.3, + normalization="phase", +): + """Efficient subpixel image translation registration by cross-correlation. + + This code gives the same precision as the FFT upsampled cross-correlation + in a fraction of the computation time and with reduced memory requirements. + It obtains an initial estimate of the cross-correlation peak by an FFT and + then refines the shift estimation by upsampling the DFT only in a small + neighborhood of that estimate by means of a matrix-multiply DFT [1]_. + + Parameters + ---------- + reference_image : array + Reference image. + moving_image : array + Image to register. Must be same dimensionality as + ``reference_image``. + upsample_factor : int, optional + Upsampling factor. Images will be registered to within + ``1 / upsample_factor`` of a pixel. For example + ``upsample_factor == 20`` means the images will be registered + within 1/20th of a pixel. Default is 1 (no upsampling). + Not used if any of ``reference_mask`` or ``moving_mask`` is not None. + space : string, one of "real" or "fourier", optional + Defines how the algorithm interprets input data. "real" means + data will be FFT'd to compute the correlation, while "fourier" + data will bypass FFT of input data. Case insensitive. Not + used if any of ``reference_mask`` or ``moving_mask`` is not + None. + disambiguate : bool + The shift returned by this function is only accurate *modulo* the + image shape, due to the periodic nature of the Fourier transform. If + this parameter is set to ``True``, the *real* space cross-correlation + is computed for each possible shift, and the shift with the highest + cross-correlation within the overlapping area is returned. + reference_mask : ndarray + Boolean mask for ``reference_image``. The mask should evaluate + to ``True`` (or 1) on valid pixels. ``reference_mask`` should + have the same shape as ``reference_image``. + moving_mask : ndarray or None, optional + Boolean mask for ``moving_image``. The mask should evaluate to ``True`` + (or 1) on valid pixels. ``moving_mask`` should have the same shape + as ``moving_image``. If ``None``, ``reference_mask`` will be used. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. Used only if one of ``reference_mask`` or + ``moving_mask`` is not None. + normalization : {"phase", None} + The type of normalization to apply to the cross-correlation. This + parameter is unused when masks (`reference_mask` and `moving_mask`) are + supplied. + + Returns + ------- + shift : ndarray + Shift vector (in pixels) required to register ``moving_image`` + with ``reference_image``. Axis ordering is consistent with + the axis order of the input array. + error : float + Translation invariant normalized RMS error between + ``reference_image`` and ``moving_image``. For masked cross-correlation + this error is not available and NaN is returned. + phasediff : float + Global phase difference between the two images (should be + zero if images are non-negative). For masked cross-correlation + this phase difference is not available and NaN is returned. + + Notes + ----- + The use of cross-correlation to estimate image translation has a long + history dating back to at least [2]_. The "phase correlation" + method (selected by ``normalization="phase"``) was first proposed in [3]_. + Publications [1]_ and [2]_ use an unnormalized cross-correlation + (``normalization=None``). Which form of normalization is better is + application-dependent. For example, the phase correlation method works + well in registering images under different illumination, but is not very + robust to noise. In a high noise scenario, the unnormalized method may be + preferable. + + When masks are provided, a masked normalized cross-correlation algorithm is + used [5]_, [6]_. + + References + ---------- + .. [1] Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, + "Efficient subpixel image registration algorithms," + Optics Letters 33, 156-158 (2008). :DOI:`10.1364/OL.33.000156` + .. [2] P. Anuta, Spatial registration of multispectral and multitemporal + digital imagery using fast Fourier transform techniques, IEEE Trans. + Geosci. Electron., vol. 8, no. 4, pp. 353–368, Oct. 1970. + :DOI:`10.1109/TGE.1970.271435`. + .. [3] C. D. Kuglin D. C. Hines. The phase correlation image alignment + method, Proceeding of IEEE International Conference on Cybernetics + and Society, pp. 163-165, New York, NY, USA, 1975, pp. 163–165. + .. [4] James R. Fienup, "Invariant error metrics for image reconstruction" + Optics Letters 36, 8352-8357 (1997). :DOI:`10.1364/AO.36.008352` + .. [5] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [6] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + """ + if (reference_mask is not None) or (moving_mask is not None): + shift = _masked_phase_cross_correlation( + reference_image, moving_image, reference_mask, moving_mask, overlap_ratio + ) + return shift, np.nan, np.nan + + # images must be the same shape + if reference_image.shape != moving_image.shape: + raise ValueError("images must be same shape") + + # assume complex data is already in Fourier space + if space.lower() == 'fourier': + src_freq = reference_image + target_freq = moving_image + # real data needs to be fft'd. + elif space.lower() == 'real': + src_freq = fftn(reference_image) + target_freq = fftn(moving_image) + else: + raise ValueError('space argument must be "real" of "fourier"') + + # Whole-pixel shift - Compute cross-correlation by an IFFT + shape = src_freq.shape + image_product = src_freq * target_freq.conj() + if normalization == "phase": + eps = np.finfo(image_product.real.dtype).eps + image_product /= np.maximum(np.abs(image_product), 100 * eps) + elif normalization is not None: + raise ValueError("normalization must be either phase or None") + cross_correlation = ifftn(image_product) + + # Locate maximum + maxima = np.unravel_index( + np.argmax(np.abs(cross_correlation)), cross_correlation.shape + ) + midpoint = np.array([np.fix(axis_size / 2) for axis_size in shape]) + + float_dtype = image_product.real.dtype + + shift = np.stack(maxima).astype(float_dtype, copy=False) + shift[shift > midpoint] -= np.array(shape)[shift > midpoint] + + if upsample_factor == 1: + src_amp = np.sum(np.real(src_freq * src_freq.conj())) + src_amp /= src_freq.size + target_amp = np.sum(np.real(target_freq * target_freq.conj())) + target_amp /= target_freq.size + CCmax = cross_correlation[maxima] + # If upsampling > 1, then refine estimate with matrix multiply DFT + else: + # Initial shift estimate in upsampled grid + upsample_factor = np.array(upsample_factor, dtype=float_dtype) + shift = np.round(shift * upsample_factor) / upsample_factor + upsampled_region_size = np.ceil(upsample_factor * 1.5) + # Center of output array at dftshift + 1 + dftshift = np.fix(upsampled_region_size / 2.0) + # Matrix multiply DFT around the current shift estimate + sample_region_offset = dftshift - shift * upsample_factor + cross_correlation = _upsampled_dft( + image_product.conj(), + upsampled_region_size, + upsample_factor, + sample_region_offset, + ).conj() + # Locate maximum and map back to original pixel grid + maxima = np.unravel_index( + np.argmax(np.abs(cross_correlation)), cross_correlation.shape + ) + CCmax = cross_correlation[maxima] + + maxima = np.stack(maxima).astype(float_dtype, copy=False) + maxima -= dftshift + + shift += maxima / upsample_factor + + src_amp = np.sum(np.real(src_freq * src_freq.conj())) + target_amp = np.sum(np.real(target_freq * target_freq.conj())) + + # If its only one row or column the shift along that dimension has no + # effect. We set to zero. + for dim in range(src_freq.ndim): + if shape[dim] == 1: + shift[dim] = 0 + + if disambiguate: + if space.lower() != 'real': + reference_image = ifftn(reference_image) + moving_image = ifftn(moving_image) + shift = _disambiguate_shift(reference_image, moving_image, shift) + + # Redirect user to masked_phase_cross_correlation if NaNs are observed + if np.isnan(CCmax) or np.isnan(src_amp) or np.isnan(target_amp): + raise ValueError( + "NaN values found, please remove NaNs from your " + "input data or use the `reference_mask`/`moving_mask` " + "keywords, eg: " + "phase_cross_correlation(reference_image, moving_image, " + "reference_mask=~np.isnan(reference_image), " + "moving_mask=~np.isnan(moving_image))" + ) + + return shift, _compute_error(CCmax, src_amp, target_amp), _compute_phasediff(CCmax) diff --git a/python_embeded/Lib/site-packages/skimage/restoration/__init__.py b/python_embeded/Lib/site-packages/skimage/restoration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4df831d813b003c476aa855d1d1eee15080cf33a --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/__init__.py @@ -0,0 +1,5 @@ +"""Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/python_embeded/Lib/site-packages/skimage/restoration/__init__.pyi b/python_embeded/Lib/site-packages/skimage/restoration/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..35ea3c438ea2c95b1f6a0b527cfb530cc7a24045 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/__init__.pyi @@ -0,0 +1,38 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'wiener', + 'unsupervised_wiener', + 'richardson_lucy', + 'unwrap_phase', + 'denoise_tv_bregman', + 'denoise_tv_chambolle', + 'denoise_bilateral', + 'denoise_wavelet', + 'denoise_nl_means', + 'denoise_invariant', + 'estimate_sigma', + 'inpaint_biharmonic', + 'cycle_spin', + 'calibrate_denoiser', + 'rolling_ball', + 'ellipsoid_kernel', + 'ball_kernel', +] + +from .deconvolution import wiener, unsupervised_wiener, richardson_lucy +from .unwrap import unwrap_phase +from ._denoise import ( + denoise_tv_chambolle, + denoise_tv_bregman, + denoise_bilateral, + denoise_wavelet, + estimate_sigma, +) +from ._cycle_spin import cycle_spin +from .non_local_means import denoise_nl_means +from .inpaint import inpaint_biharmonic +from .j_invariant import calibrate_denoiser, denoise_invariant +from ._rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_cycle_spin.py b/python_embeded/Lib/site-packages/skimage/restoration/_cycle_spin.py new file mode 100644 index 0000000000000000000000000000000000000000..b3572229932fcd8d53f91334b3f49b7900379bf0 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/_cycle_spin.py @@ -0,0 +1,164 @@ +from itertools import product +import numpy as np +from .._shared import utils +from .._shared.utils import warn + +try: + import dask + + dask_available = True +except ImportError: + dask_available = False + + +def _generate_shifts(ndim, multichannel, max_shifts, shift_steps=1): + """Returns all combinations of shifts in n dimensions over the specified + max_shifts and step sizes. + + Examples + -------- + >>> s = list(_generate_shifts(2, False, max_shifts=(1, 2), shift_steps=1)) + >>> print(s) + [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)] + """ + mc = int(multichannel) + if np.isscalar(max_shifts): + max_shifts = (max_shifts,) * (ndim - mc) + (0,) * mc + elif multichannel and len(max_shifts) == ndim - 1: + max_shifts = tuple(max_shifts) + (0,) + elif len(max_shifts) != ndim: + raise ValueError("max_shifts should have length ndim") + + if np.isscalar(shift_steps): + shift_steps = (shift_steps,) * (ndim - mc) + (1,) * mc + elif multichannel and len(shift_steps) == ndim - 1: + shift_steps = tuple(shift_steps) + (1,) + elif len(shift_steps) != ndim: + raise ValueError("max_shifts should have length ndim") + + if any(s < 1 for s in shift_steps): + raise ValueError("shift_steps must all be >= 1") + + if multichannel and max_shifts[-1] != 0: + raise ValueError( + "Multichannel cycle spinning should not have shifts along the " "last axis." + ) + + return product(*[range(0, s + 1, t) for s, t in zip(max_shifts, shift_steps)]) + + +@utils.channel_as_last_axis() +def cycle_spin( + x, + func, + max_shifts, + shift_steps=1, + num_workers=None, + func_kw=None, + *, + channel_axis=None, +): + """Cycle spinning (repeatedly apply func to shifted versions of x). + + Parameters + ---------- + x : array-like + Data for input to ``func``. + func : function + A function to apply to circularly shifted versions of ``x``. Should + take ``x`` as its first argument. Any additional arguments can be + supplied via ``func_kw``. + max_shifts : int or tuple + If an integer, shifts in ``range(0, max_shifts+1)`` will be used along + each axis of ``x``. If a tuple, ``range(0, max_shifts[i]+1)`` will be + along axis i. + shift_steps : int or tuple, optional + The step size for the shifts applied along axis, i, are:: + ``range((0, max_shifts[i]+1, shift_steps[i]))``. If an integer is + provided, the same step size is used for all axes. + num_workers : int or None, optional + The number of parallel threads to use during cycle spinning. If set to + ``None``, the full set of available cores are used. + func_kw : dict, optional + Additional keyword arguments to supply to ``func``. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + avg_y : np.ndarray + The output of ``func(x, **func_kw)`` averaged over all combinations of + the specified axis shifts. + + Notes + ----- + Cycle spinning was proposed as a way to approach shift-invariance via + performing several circular shifts of a shift-variant transform [1]_. + + For a n-level discrete wavelet transforms, one may wish to perform all + shifts up to ``max_shifts = 2**n - 1``. In practice, much of the benefit + can often be realized with only a small number of shifts per axis. + + For transforms such as the blockwise discrete cosine transform, one may + wish to evaluate shifts up to the block size used by the transform. + + References + ---------- + .. [1] R.R. Coifman and D.L. Donoho. "Translation-Invariant De-Noising". + Wavelets and Statistics, Lecture Notes in Statistics, vol.103. + Springer, New York, 1995, pp.125-150. + :DOI:`10.1007/978-1-4612-2544-7_9` + + Examples + -------- + >>> import skimage.data + >>> from skimage import img_as_float + >>> from skimage.restoration import denoise_tv_chambolle, cycle_spin + >>> img = img_as_float(skimage.data.camera()) + >>> sigma = 0.1 + >>> img = img + sigma * np.random.standard_normal(img.shape) + >>> denoised = cycle_spin(img, func=denoise_tv_chambolle, + ... max_shifts=3) # doctest: +IGNORE_WARNINGS + + """ + if func_kw is None: + func_kw = {} + + x = np.asanyarray(x) + multichannel = channel_axis is not None + all_shifts = _generate_shifts(x.ndim, multichannel, max_shifts, shift_steps) + all_shifts = list(all_shifts) + roll_axes = tuple(range(x.ndim)) + + def _run_one_shift(shift): + # shift, apply function, inverse shift + xs = np.roll(x, shift, axis=roll_axes) + tmp = func(xs, **func_kw) + return np.roll(tmp, tuple(-s for s in shift), axis=roll_axes) + + if not dask_available and (num_workers is None or num_workers > 1): + num_workers = 1 + warn( + 'The optional dask dependency is not installed. ' + 'The number of workers is set to 1. To silence ' + 'this warning, install dask or explicitly set `num_workers=1` ' + 'when calling the `cycle_spin` function' + ) + # compute a running average across the cycle shifts + if num_workers == 1: + # serial processing + mean = _run_one_shift(all_shifts[0]) + for shift in all_shifts[1:]: + mean += _run_one_shift(shift) + mean /= len(all_shifts) + else: + # multithreaded via dask + futures = [dask.delayed(_run_one_shift)(s) for s in all_shifts] + mean = sum(futures) / len(futures) + mean = mean.compute(num_workers=num_workers) + return mean diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_denoise.py b/python_embeded/Lib/site-packages/skimage/restoration/_denoise.py new file mode 100644 index 0000000000000000000000000000000000000000..21a507a255e9140f695e6a45b1aadaef766461a4 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/_denoise.py @@ -0,0 +1,1128 @@ +import functools +from math import ceil +import numbers + +import scipy.stats +import numpy as np + +from ..util.dtype import img_as_float +from .._shared import utils +from .._shared.utils import _supported_float_type, warn +from ._denoise_cy import _denoise_bilateral, _denoise_tv_bregman +from .. import color +from ..color.colorconv import ycbcr_from_rgb + + +def _gaussian_weight(array, sigma_squared, *, dtype=float): + """Helping function. Define a Gaussian weighting from array and + sigma_square. + + Parameters + ---------- + array : ndarray + Input array. + sigma_squared : float + The squared standard deviation used in the filter. + dtype : data type object, optional (default : float) + The type and size of the data to be returned. + + Returns + ------- + gaussian : ndarray + The input array filtered by the Gaussian. + """ + return np.exp(-0.5 * (array**2 / sigma_squared), dtype=dtype) + + +def _compute_color_lut(bins, sigma, max_value, *, dtype=float): + """Helping function. Define a lookup table containing Gaussian filter + values using the color distance sigma. + + Parameters + ---------- + bins : int + Number of discrete values for Gaussian weights of color filtering. + A larger value results in improved accuracy. + sigma : float + Standard deviation for grayvalue/color distance (radiometric + similarity). A larger value results in averaging of pixels with larger + radiometric differences. Note, that the image will be converted using + the `img_as_float` function and thus the standard deviation is in + respect to the range ``[0, 1]``. If the value is ``None`` the standard + deviation of the ``image`` will be used. + max_value : float + Maximum value of the input image. + dtype : data type object, optional (default : float) + The type and size of the data to be returned. + + Returns + ------- + color_lut : ndarray + Lookup table for the color distance sigma. + """ + values = np.linspace(0, max_value, bins, endpoint=False) + return _gaussian_weight(values, sigma**2, dtype=dtype) + + +def _compute_spatial_lut(win_size, sigma, *, dtype=float): + """Helping function. Define a lookup table containing Gaussian filter + values using the spatial sigma. + + Parameters + ---------- + win_size : int + Window size for filtering. + If win_size is not specified, it is calculated as + ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``. + sigma : float + Standard deviation for range distance. A larger value results in + averaging of pixels with larger spatial differences. + dtype : data type object + The type and size of the data to be returned. + + Returns + ------- + spatial_lut : ndarray + Lookup table for the spatial sigma. + """ + grid_points = np.arange(-win_size // 2, win_size // 2 + 1) + rr, cc = np.meshgrid(grid_points, grid_points, indexing='ij') + distances = np.hypot(rr, cc) + return _gaussian_weight(distances, sigma**2, dtype=dtype).ravel() + + +@utils.channel_as_last_axis() +def denoise_bilateral( + image, + win_size=None, + sigma_color=None, + sigma_spatial=1, + bins=10000, + mode='constant', + cval=0, + *, + channel_axis=None, +): + """Denoise image using bilateral filter. + + Parameters + ---------- + image : ndarray, shape (M, N[, 3]) + Input image, 2D grayscale or RGB. + win_size : int + Window size for filtering. + If win_size is not specified, it is calculated as + ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``. + sigma_color : float + Standard deviation for grayvalue/color distance (radiometric + similarity). A larger value results in averaging of pixels with larger + radiometric differences. If ``None``, the standard deviation of + ``image`` will be used. + sigma_spatial : float + Standard deviation for range distance. A larger value results in + averaging of pixels with larger spatial differences. + bins : int + Number of discrete values for Gaussian weights of color filtering. + A larger value results in improved accuracy. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'} + How to handle values outside the image borders. See + `numpy.pad` for detail. + cval : int or float + Used in conjunction with mode 'constant', the value outside + the image boundaries. + channel_axis : int or None, optional + If ``None``, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + denoised : ndarray + Denoised image. + + Notes + ----- + This is an edge-preserving, denoising filter. It averages pixels based on + their spatial closeness and radiometric similarity [1]_. + + Spatial closeness is measured by the Gaussian function of the Euclidean + distance between two pixels and a certain standard deviation + (`sigma_spatial`). + + Radiometric similarity is measured by the Gaussian function of the + Euclidean distance between two color values and a certain standard + deviation (`sigma_color`). + + Note that, if the image is of any `int` dtype, ``image`` will be + converted using the `img_as_float` function and thus the standard + deviation (`sigma_color`) will be in range ``[0, 1]``. + + For more information on scikit-image's data type conversions and how + images are rescaled in these conversions, + see: https://scikit-image.org/docs/stable/user_guide/data_types.html. + + References + ---------- + .. [1] C. Tomasi and R. Manduchi. "Bilateral Filtering for Gray and Color + Images." IEEE International Conference on Computer Vision (1998) + 839-846. :DOI:`10.1109/ICCV.1998.710815` + + Examples + -------- + >>> from skimage import data, img_as_float + >>> astro = img_as_float(data.astronaut()) + >>> astro = astro[220:300, 220:320] + >>> rng = np.random.default_rng() + >>> noisy = astro + 0.6 * astro.std() * rng.random(astro.shape) + >>> noisy = np.clip(noisy, 0, 1) + >>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15, + ... channel_axis=-1) + """ + if channel_axis is not None: + if image.ndim != 3: + if image.ndim == 2: + raise ValueError( + "Use ``channel_axis=None`` for 2D grayscale " + "images. The last axis of the input image " + "must be multiple color channels not another " + "spatial dimension." + ) + else: + raise ValueError( + f'Bilateral filter is only implemented for ' + f'2D grayscale images (image.ndim == 2) and ' + f'2D multichannel (image.ndim == 3) images, ' + f'but the input image has {image.ndim} dimensions.' + ) + elif image.shape[2] not in (3, 4): + if image.shape[2] > 4: + msg = ( + f'The last axis of the input image is ' + f'interpreted as channels. Input image with ' + f'shape {image.shape} has {image.shape[2]} channels ' + f'in last axis. ``denoise_bilateral``is implemented ' + f'for 2D grayscale and color images only.' + ) + warn(msg) + else: + msg = ( + f'Input image must be grayscale, RGB, or RGBA; ' + f'but has shape {image.shape}.' + ) + warn(msg) + else: + if image.ndim > 2: + raise ValueError( + f'Bilateral filter is not implemented for ' + f'grayscale images of 3 or more dimensions, ' + f'but input image has {image.shape} shape. Use ' + f'``channel_axis=-1`` for 2D RGB images.' + ) + + if win_size is None: + win_size = max(5, 2 * int(ceil(3 * sigma_spatial)) + 1) + + min_value = image.min() + max_value = image.max() + + if min_value == max_value: + return image + + # if image.max() is 0, then dist_scale can have an unverified value + # and color_lut[(dist * dist_scale)] may cause a segmentation fault + # so we verify we have a positive image and that the max is not 0.0. + + image = np.atleast_3d(img_as_float(image)) + image = np.ascontiguousarray(image) + + sigma_color = sigma_color or image.std() + + color_lut = _compute_color_lut(bins, sigma_color, max_value, dtype=image.dtype) + + range_lut = _compute_spatial_lut(win_size, sigma_spatial, dtype=image.dtype) + + out = np.empty(image.shape, dtype=image.dtype) + + dims = image.shape[2] + + # There are a number of arrays needed in the Cython function. + # It's easier to allocate them outside of Cython so that all + # arrays are in the same type, then just copy the empty array + # where needed within Cython. + empty_dims = np.empty(dims, dtype=image.dtype) + + if min_value < 0: + image = image - min_value + max_value -= min_value + _denoise_bilateral( + image, + max_value, + win_size, + sigma_color, + sigma_spatial, + bins, + mode, + cval, + color_lut, + range_lut, + empty_dims, + out, + ) + # need to drop the added channels axis for grayscale images + out = np.squeeze(out) + if min_value < 0: + out += min_value + return out + + +@utils.channel_as_last_axis() +def denoise_tv_bregman( + image, weight=5.0, max_num_iter=100, eps=1e-3, isotropic=True, *, channel_axis=None +): + r"""Perform total variation denoising using split-Bregman optimization. + + Given :math:`f`, a noisy image (input data), + total variation denoising (also known as total variation regularization) + aims to find an image :math:`u` with less total variation than :math:`f`, + under the constraint that :math:`u` remain similar to :math:`f`. + This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization + problem: + + .. math:: + + \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right) + + where :math:`\lambda` is a positive parameter. + The first term of this cost function is the total variation; + the second term represents data fidelity. As :math:`\lambda \to 0`, + the total variation term dominates, forcing the solution to have smaller + total variation, at the expense of looking less like the input data. + + This code is an implementation of the split Bregman algorithm of Goldstein + and Osher to solve the ROF problem ([1]_, [2]_, [3]_). + + Parameters + ---------- + image : ndarray + Input image to be denoised (converted using :func:`~.img_as_float`). + weight : float, optional + Denoising weight. It is equal to :math:`\frac{\lambda}{2}`. Therefore, + the smaller the `weight`, the more denoising (at + the expense of less similarity to `image`). + eps : float, optional + Tolerance :math:`\varepsilon > 0` for the stop criterion: + The algorithm stops when :math:`\|u_n - u_{n-1}\|_2 < \varepsilon`. + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + isotropic : boolean, optional + Switch between isotropic and anisotropic TV denoising. + channel_axis : int or None, optional + If ``None``, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + u : ndarray + Denoised image. + + Notes + ----- + Ensure that `channel_axis` parameter is set appropriately for color + images. + + The principle of total variation denoising is explained in [4]_. + It is about minimizing the total variation of an image, + which can be roughly described as + the integral of the norm of the image gradient. Total variation + denoising tends to produce cartoon-like images, that is, + piecewise-constant images. + + See Also + -------- + denoise_tv_chambolle : Perform total variation denoising in nD. + + References + ---------- + .. [1] Tom Goldstein and Stanley Osher, "The Split Bregman Method For L1 + Regularized Problems", + https://ww3.math.ucla.edu/camreport/cam08-29.pdf + .. [2] Pascal Getreuer, "Rudin–Osher–Fatemi Total Variation Denoising + using Split Bregman" in Image Processing On Line on 2012–05–19, + https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf + .. [3] https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf + .. [4] https://en.wikipedia.org/wiki/Total_variation_denoising + + """ + image = np.atleast_3d(img_as_float(image)) + + rows = image.shape[0] + cols = image.shape[1] + dims = image.shape[2] + + shape_ext = (rows + 2, cols + 2, dims) + + out = np.zeros(shape_ext, image.dtype) + + if channel_axis is not None: + channel_out = np.zeros(shape_ext[:2] + (1,), dtype=out.dtype) + for c in range(image.shape[-1]): + # the algorithm below expects 3 dimensions to always be present. + # slicing the array in this fashion preserves the channel dimension + # for us + channel_in = np.ascontiguousarray(image[..., c : c + 1]) + + _denoise_tv_bregman( + channel_in, + image.dtype.type(weight), + max_num_iter, + eps, + isotropic, + channel_out, + ) + + out[..., c] = channel_out[..., 0] + + else: + image = np.ascontiguousarray(image) + + _denoise_tv_bregman( + image, image.dtype.type(weight), max_num_iter, eps, isotropic, out + ) + + return np.squeeze(out[1:-1, 1:-1]) + + +def _denoise_tv_chambolle_nd(image, weight=0.1, eps=2.0e-4, max_num_iter=200): + """Perform total-variation denoising on n-dimensional images. + + Parameters + ---------- + image : ndarray + n-D input data to be denoised. + weight : float, optional + Denoising weight. The greater `weight`, the more denoising (at + the expense of fidelity to `input`). + eps : float, optional + Relative difference of the value of the cost function that determines + the stop criterion. The algorithm stops when: + + (E_(n-1) - E_n) < eps * E_0 + + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + + Returns + ------- + out : ndarray + Denoised array of floats. + + Notes + ----- + Rudin, Osher and Fatemi algorithm. + """ + + ndim = image.ndim + p = np.zeros((image.ndim,) + image.shape, dtype=image.dtype) + g = np.zeros_like(p) + d = np.zeros_like(image) + i = 0 + while i < max_num_iter: + if i > 0: + # d will be the (negative) divergence of p + d = -p.sum(0) + slices_d = [ + slice(None), + ] * ndim + slices_p = [ + slice(None), + ] * (ndim + 1) + for ax in range(ndim): + slices_d[ax] = slice(1, None) + slices_p[ax + 1] = slice(0, -1) + slices_p[0] = ax + d[tuple(slices_d)] += p[tuple(slices_p)] + slices_d[ax] = slice(None) + slices_p[ax + 1] = slice(None) + out = image + d + else: + out = image + E = (d**2).sum() + + # g stores the gradients of out along each axis + # e.g. g[0] is the first order finite difference along axis 0 + slices_g = [ + slice(None), + ] * (ndim + 1) + for ax in range(ndim): + slices_g[ax + 1] = slice(0, -1) + slices_g[0] = ax + g[tuple(slices_g)] = np.diff(out, axis=ax) + slices_g[ax + 1] = slice(None) + + norm = np.sqrt((g**2).sum(axis=0))[np.newaxis, ...] + E += weight * norm.sum() + tau = 1.0 / (2.0 * ndim) + norm *= tau / weight + norm += 1.0 + p -= tau * g + p /= norm + E /= float(image.size) + if i == 0: + E_init = E + E_previous = E + else: + if np.abs(E_previous - E) < eps * E_init: + break + else: + E_previous = E + i += 1 + return out + + +def denoise_tv_chambolle( + image, weight=0.1, eps=2.0e-4, max_num_iter=200, *, channel_axis=None +): + r"""Perform total variation denoising in nD. + + Given :math:`f`, a noisy image (input data), + total variation denoising (also known as total variation regularization) + aims to find an image :math:`u` with less total variation than :math:`f`, + under the constraint that :math:`u` remain similar to :math:`f`. + This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization + problem: + + .. math:: + + \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right) + + where :math:`\lambda` is a positive parameter. + The first term of this cost function is the total variation; + the second term represents data fidelity. As :math:`\lambda \to 0`, + the total variation term dominates, forcing the solution to have smaller + total variation, at the expense of looking less like the input data. + + This code is an implementation of the algorithm proposed by Chambolle + in [1]_ to solve the ROF problem. + + Parameters + ---------- + image : ndarray + Input image to be denoised. If its dtype is not float, it gets + converted with :func:`~.img_as_float`. + weight : float, optional + Denoising weight. It is equal to :math:`\frac{1}{\lambda}`. Therefore, + the greater the `weight`, the more denoising (at the expense of + fidelity to `image`). + eps : float, optional + Tolerance :math:`\varepsilon > 0` for the stop criterion (compares to + absolute value of relative difference of the cost function :math:`E`): + The algorithm stops when :math:`|E_{n-1} - E_n| < \varepsilon * E_0`. + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + channel_axis : int or None, optional + If ``None``, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + u : ndarray + Denoised image. + + Notes + ----- + Make sure to set the `channel_axis` parameter appropriately for color + images. + + The principle of total variation denoising is explained in [2]_. + It is about minimizing the total variation of an image, + which can be roughly described as + the integral of the norm of the image gradient. Total variation + denoising tends to produce cartoon-like images, that is, + piecewise-constant images. + + See Also + -------- + denoise_tv_bregman : Perform total variation denoising using split-Bregman + optimization. + + References + ---------- + .. [1] A. Chambolle, An algorithm for total variation minimization and + applications, Journal of Mathematical Imaging and Vision, + Springer, 2004, 20, 89-97. + .. [2] https://en.wikipedia.org/wiki/Total_variation_denoising + + Examples + -------- + 2D example on astronaut image: + + >>> from skimage import color, data + >>> img = color.rgb2gray(data.astronaut())[:50, :50] + >>> rng = np.random.default_rng() + >>> img += 0.5 * img.std() * rng.standard_normal(img.shape) + >>> denoised_img = denoise_tv_chambolle(img, weight=60) + + 3D example on synthetic data: + + >>> x, y, z = np.ogrid[0:20, 0:20, 0:20] + >>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 + >>> mask = mask.astype(float) + >>> rng = np.random.default_rng() + >>> mask += 0.2 * rng.standard_normal(mask.shape) + >>> res = denoise_tv_chambolle(mask, weight=100) + + """ + + im_type = image.dtype + if not im_type.kind == 'f': + image = img_as_float(image) + + # enforce float16->float32 and float128->float64 + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + out = np.zeros_like(image) + for c in range(image.shape[channel_axis]): + out[_at(c)] = _denoise_tv_chambolle_nd( + image[_at(c)], weight, eps, max_num_iter + ) + else: + out = _denoise_tv_chambolle_nd(image, weight, eps, max_num_iter) + return out + + +def _bayes_thresh(details, var): + """BayesShrink threshold for a zero-mean details coeff array.""" + # Equivalent to: dvar = np.var(details) for 0-mean details array + dvar = np.mean(details * details) + eps = np.finfo(details.dtype).eps + thresh = var / np.sqrt(max(dvar - var, eps)) + return thresh + + +def _universal_thresh(img, sigma): + """Universal threshold used by the VisuShrink method""" + return sigma * np.sqrt(2 * np.log(img.size)) + + +def _sigma_est_dwt(detail_coeffs, distribution='Gaussian'): + """Calculate the robust median estimator of the noise standard deviation. + + Parameters + ---------- + detail_coeffs : ndarray + The detail coefficients corresponding to the discrete wavelet + transform of an image. + distribution : str + The underlying noise distribution. + + Returns + ------- + sigma : float + The estimated noise standard deviation (see section 4.2 of [1]_). + + References + ---------- + .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + """ + # Consider regions with detail coefficients exactly zero to be masked out + detail_coeffs = detail_coeffs[np.nonzero(detail_coeffs)] + + if distribution.lower() == 'gaussian': + # 75th quantile of the underlying, symmetric noise distribution + denom = scipy.stats.norm.ppf(0.75) + sigma = np.median(np.abs(detail_coeffs)) / denom + else: + raise ValueError("Only Gaussian noise estimation is currently " "supported") + return sigma + + +def _wavelet_threshold( + image, + wavelet, + method=None, + threshold=None, + sigma=None, + mode='soft', + wavelet_levels=None, +): + """Perform wavelet thresholding. + + Parameters + ---------- + image : ndarray (2d or 3d) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into an ndarray of floats for the computation + of the denoised image. + wavelet : string + The type of wavelet to perform. Can be any of the options + pywt.wavelist outputs. For example, this may be any of ``{db1, db2, + db3, db4, haar}``. + method : {'BayesShrink', 'VisuShrink'}, optional + Thresholding method to be used. The currently supported methods are + "BayesShrink" [1]_ and "VisuShrink" [2]_. If it is set to None, a + user-specified ``threshold`` must be supplied instead. + threshold : float, optional + The thresholding value to apply during wavelet coefficient + thresholding. The default value (None) uses the selected ``method`` to + estimate appropriate threshold(s) for noise removal. + sigma : float, optional + The standard deviation of the noise. The noise is estimated when sigma + is None (the default) by the method in [2]_. + mode : {'soft', 'hard'}, optional + An optional argument to choose the type of denoising performed. It + noted that choosing soft thresholding given additive noise finds the + best approximation of the original image. + wavelet_levels : int or None, optional + The number of wavelet decomposition levels to use. The default is + three less than the maximum number of possible decomposition levels + (see Notes below). + + Returns + ------- + out : ndarray + Denoised image. + + References + ---------- + .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet + thresholding for image denoising and compression." Image Processing, + IEEE Transactions on 9.9 (2000): 1532-1546. + :DOI:`10.1109/83.862633` + .. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + """ + try: + import pywt + except ImportError: + raise ImportError( + 'PyWavelets is not installed. Please ensure it is installed in ' + 'order to use this function.' + ) + + wavelet = pywt.Wavelet(wavelet) + if not wavelet.orthogonal: + warn( + f'Wavelet thresholding was designed for ' + f'use with orthogonal wavelets. For nonorthogonal ' + f'wavelets such as {wavelet.name},results are ' + f'likely to be suboptimal.' + ) + + # original_extent is used to workaround PyWavelets issue #80 + # odd-sized input results in an image with 1 extra sample after waverecn + original_extent = tuple(slice(s) for s in image.shape) + + # Determine the number of wavelet decomposition levels + if wavelet_levels is None: + # Determine the maximum number of possible levels for image + wavelet_levels = pywt.dwtn_max_level(image.shape, wavelet) + + # Skip coarsest wavelet scales (see Notes in docstring). + wavelet_levels = max(wavelet_levels - 3, 1) + + coeffs = pywt.wavedecn(image, wavelet=wavelet, level=wavelet_levels) + # Detail coefficients at each decomposition level + dcoeffs = coeffs[1:] + + if sigma is None: + # Estimate the noise via the method in [2]_ + detail_coeffs = dcoeffs[-1]['d' * image.ndim] + sigma = _sigma_est_dwt(detail_coeffs, distribution='Gaussian') + + if method is not None and threshold is not None: + warn( + f'Thresholding method {method} selected. The ' + f'user-specified threshold will be ignored.' + ) + + if threshold is None: + var = sigma**2 + if method is None: + raise ValueError("If method is None, a threshold must be provided.") + elif method == "BayesShrink": + # The BayesShrink thresholds from [1]_ in docstring + threshold = [ + {key: _bayes_thresh(level[key], var) for key in level} + for level in dcoeffs + ] + elif method == "VisuShrink": + # The VisuShrink thresholds from [2]_ in docstring + threshold = _universal_thresh(image, sigma) + else: + raise ValueError(f'Unrecognized method: {method}') + + if np.isscalar(threshold): + # A single threshold for all coefficient arrays + denoised_detail = [ + { + key: pywt.threshold(level[key], value=threshold, mode=mode) + for key in level + } + for level in dcoeffs + ] + else: + # Dict of unique threshold coefficients for each detail coeff. array + denoised_detail = [ + { + key: pywt.threshold(level[key], value=thresh[key], mode=mode) + for key in level + } + for thresh, level in zip(threshold, dcoeffs) + ] + denoised_coeffs = [coeffs[0]] + denoised_detail + out = pywt.waverecn(denoised_coeffs, wavelet)[original_extent] + out = out.astype(image.dtype) + return out + + +def _scale_sigma_and_image_consistently(image, sigma, multichannel, rescale_sigma): + """If the ``image`` is rescaled, also rescale ``sigma`` consistently. + + Images that are not floating point will be rescaled via ``img_as_float``. + Half-precision images will be promoted to single precision. + """ + if multichannel: + if isinstance(sigma, numbers.Number) or sigma is None: + sigma = [sigma] * image.shape[-1] + elif len(sigma) != image.shape[-1]: + raise ValueError( + "When channel_axis is not None, sigma must be a scalar or have " + "length equal to the number of channels" + ) + if image.dtype.kind != 'f': + if rescale_sigma: + range_pre = image.max() - image.min() + image = img_as_float(image) + if rescale_sigma: + range_post = image.max() - image.min() + # apply the same magnitude scaling to sigma + scale_factor = range_post / range_pre + if multichannel: + sigma = [s * scale_factor if s is not None else s for s in sigma] + elif sigma is not None: + sigma *= scale_factor + elif image.dtype == np.float16: + image = image.astype(np.float32) + return image, sigma + + +def _rescale_sigma_rgb2ycbcr(sigmas): + """Convert user-provided noise standard deviations to YCbCr space. + + Notes + ----- + If R, G, B are linearly independent random variables and a1, a2, a3 are + scalars, then random variable C: + C = a1 * R + a2 * G + a3 * B + has variance, var_C, given by: + var_C = a1**2 * var_R + a2**2 * var_G + a3**2 * var_B + """ + if sigmas[0] is None: + return sigmas + sigmas = np.asarray(sigmas) + rgv_variances = sigmas * sigmas + for i in range(3): + scalars = ycbcr_from_rgb[i, :] + var_channel = np.sum(scalars * scalars * rgv_variances) + sigmas[i] = np.sqrt(var_channel) + return sigmas + + +@utils.channel_as_last_axis() +def denoise_wavelet( + image, + sigma=None, + wavelet='db1', + mode='soft', + wavelet_levels=None, + convert2ycbcr=False, + method='BayesShrink', + rescale_sigma=True, + *, + channel_axis=None, +): + """Perform wavelet denoising on an image. + + Parameters + ---------- + image : ndarray (M[, N[, ...P]][, C]) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into an ndarray of floats for the computation + of the denoised image. + sigma : float or list, optional + The noise standard deviation used when computing the wavelet detail + coefficient threshold(s). When None (default), the noise standard + deviation is estimated via the method in [2]_. + wavelet : string, optional + The type of wavelet to perform and can be any of the options + ``pywt.wavelist`` outputs. The default is `'db1'`. For example, + ``wavelet`` can be any of ``{'db2', 'haar', 'sym9'}`` and many more. + mode : {'soft', 'hard'}, optional + An optional argument to choose the type of denoising performed. It + noted that choosing soft thresholding given additive noise finds the + best approximation of the original image. + wavelet_levels : int or None, optional + The number of wavelet decomposition levels to use. The default is + three less than the maximum number of possible decomposition levels. + convert2ycbcr : bool, optional + If True and channel_axis is set, do the wavelet denoising in the YCbCr + colorspace instead of the RGB color space. This typically results in + better performance for RGB images. + method : {'BayesShrink', 'VisuShrink'}, optional + Thresholding method to be used. The currently supported methods are + "BayesShrink" [1]_ and "VisuShrink" [2]_. Defaults to "BayesShrink". + rescale_sigma : bool, optional + If False, no rescaling of the user-provided ``sigma`` will be + performed. The default of ``True`` rescales sigma appropriately if the + image is rescaled internally. + + .. versionadded:: 0.16 + ``rescale_sigma`` was introduced in 0.16 + channel_axis : int or None, optional + If ``None``, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : ndarray + Denoised image. + + Notes + ----- + The wavelet domain is a sparse representation of the image, and can be + thought of similarly to the frequency domain of the Fourier transform. + Sparse representations have most values zero or near-zero and truly random + noise is (usually) represented by many small values in the wavelet domain. + Setting all values below some threshold to 0 reduces the noise in the + image, but larger thresholds also decrease the detail present in the image. + + If the input is 3D, this function performs wavelet denoising on each color + plane separately. + + .. versionchanged:: 0.16 + For floating point inputs, the original input range is maintained and + there is no clipping applied to the output. Other input types will be + converted to a floating point value in the range [-1, 1] or [0, 1] + depending on the input image range. Unless ``rescale_sigma = False``, + any internal rescaling applied to the ``image`` will also be applied + to ``sigma`` to maintain the same relative amplitude. + + Many wavelet coefficient thresholding approaches have been proposed. By + default, ``denoise_wavelet`` applies BayesShrink, which is an adaptive + thresholding method that computes separate thresholds for each wavelet + sub-band as described in [1]_. + + If ``method == "VisuShrink"``, a single "universal threshold" is applied to + all wavelet detail coefficients as described in [2]_. This threshold + is designed to remove all Gaussian noise at a given ``sigma`` with high + probability, but tends to produce images that appear overly smooth. + + Although any of the wavelets from ``PyWavelets`` can be selected, the + thresholding methods assume an orthogonal wavelet transform and may not + choose the threshold appropriately for biorthogonal wavelets. Orthogonal + wavelets are desirable because white noise in the input remains white noise + in the subbands. Biorthogonal wavelets lead to colored noise in the + subbands. Additionally, the orthogonal wavelets in PyWavelets are + orthonormal so that noise variance in the subbands remains identical to the + noise variance of the input. Example orthogonal wavelets are the Daubechies + (e.g. 'db2') or symmlet (e.g. 'sym2') families. + + References + ---------- + .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet + thresholding for image denoising and compression." Image Processing, + IEEE Transactions on 9.9 (2000): 1532-1546. + :DOI:`10.1109/83.862633` + .. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('pywt') + + >>> from skimage import color, data + >>> img = img_as_float(data.astronaut()) + >>> img = color.rgb2gray(img) + >>> rng = np.random.default_rng() + >>> img += 0.1 * rng.standard_normal(img.shape) + >>> img = np.clip(img, 0, 1) + >>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True) + + """ + multichannel = channel_axis is not None + if method not in ["BayesShrink", "VisuShrink"]: + raise ValueError( + f'Invalid method: {method}. The currently supported ' + f'methods are "BayesShrink" and "VisuShrink".' + ) + + # floating-point inputs are not rescaled, so don't clip their output. + clip_output = image.dtype.kind != 'f' + + if convert2ycbcr and not multichannel: + raise ValueError("convert2ycbcr requires channel_axis to be set") + + image, sigma = _scale_sigma_and_image_consistently( + image, sigma, multichannel, rescale_sigma + ) + if multichannel: + if convert2ycbcr: + out = color.rgb2ycbcr(image) + # convert user-supplied sigmas to the new colorspace as well + if rescale_sigma: + sigma = _rescale_sigma_rgb2ycbcr(sigma) + for i in range(3): + # renormalizing this color channel to live in [0, 1] + _min, _max = out[..., i].min(), out[..., i].max() + scale_factor = _max - _min + if scale_factor == 0: + # skip any channel containing only zeros! + continue + channel = out[..., i] - _min + channel /= scale_factor + sigma_channel = sigma[i] + if sigma_channel is not None: + sigma_channel /= scale_factor + out[..., i] = denoise_wavelet( + channel, + wavelet=wavelet, + method=method, + sigma=sigma_channel, + mode=mode, + wavelet_levels=wavelet_levels, + rescale_sigma=rescale_sigma, + ) + out[..., i] = out[..., i] * scale_factor + out[..., i] += _min + out = color.ycbcr2rgb(out) + else: + out = np.empty_like(image) + for c in range(image.shape[-1]): + out[..., c] = _wavelet_threshold( + image[..., c], + wavelet=wavelet, + method=method, + sigma=sigma[c], + mode=mode, + wavelet_levels=wavelet_levels, + ) + else: + out = _wavelet_threshold( + image, + wavelet=wavelet, + method=method, + sigma=sigma, + mode=mode, + wavelet_levels=wavelet_levels, + ) + + if clip_output: + clip_range = (-1, 1) if image.min() < 0 else (0, 1) + out = np.clip(out, *clip_range, out=out) + return out + + +def estimate_sigma(image, average_sigmas=False, *, channel_axis=None): + """ + Robust wavelet-based estimator of the (Gaussian) noise standard deviation. + + Parameters + ---------- + image : ndarray + Image for which to estimate the noise standard deviation. + average_sigmas : bool, optional + If true, average the channel estimates of `sigma`. Otherwise return + a list of sigmas corresponding to each channel. + channel_axis : int or None, optional + If ``None``, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + sigma : float or list + Estimated noise standard deviation(s). If `multichannel` is True and + `average_sigmas` is False, a separate noise estimate for each channel + is returned. Otherwise, the average of the individual channel + estimates is returned. + + Notes + ----- + This function assumes the noise follows a Gaussian distribution. The + estimation algorithm is based on the median absolute deviation of the + wavelet detail coefficients as described in section 4.2 of [1]_. + + References + ---------- + .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + + Examples + -------- + .. testsetup:: + >>> import pytest; _ = pytest.importorskip('pywt') + + >>> import skimage.data + >>> from skimage import img_as_float + >>> img = img_as_float(skimage.data.camera()) + >>> sigma = 0.1 + >>> rng = np.random.default_rng() + >>> img = img + sigma * rng.standard_normal(img.shape) + >>> sigma_hat = estimate_sigma(img, channel_axis=None) + """ + try: + import pywt + except ImportError: + raise ImportError( + 'PyWavelets is not installed. Please ensure it is installed in ' + 'order to use this function.' + ) + + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + nchannels = image.shape[channel_axis] + sigmas = [ + estimate_sigma(image[_at(c)], channel_axis=None) for c in range(nchannels) + ] + if average_sigmas: + sigmas = np.mean(sigmas) + return sigmas + elif image.shape[-1] <= 4: + msg = ( + f'image is size {image.shape[-1]} on the last axis, ' + f'but channel_axis is None. If this is a color image, ' + f'please set channel_axis=-1 for proper noise estimation.' + ) + warn(msg) + coeffs = pywt.dwtn(image, wavelet='db2') + detail_coeffs = coeffs['d' * image.ndim] + return _sigma_est_dwt(detail_coeffs, distribution='Gaussian') diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_denoise_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_denoise_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..e08a8e49e8d77b6726753dfdcb23162c48ceeaa1 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_denoise_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_inpaint.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_inpaint.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..19c80730d3fbcd63cb9498fe3a3f769e9b64b2fd Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_inpaint.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_nl_means_denoising.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_nl_means_denoising.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..1362cb28fb77da9c5142047ad774eb831d4c9668 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_nl_means_denoising.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball.py b/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball.py new file mode 100644 index 0000000000000000000000000000000000000000..4366604761418643f1add5b8bae0b56d261b6630 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball.py @@ -0,0 +1,198 @@ +import numpy as np + +from .._shared.utils import _supported_float_type +from ._rolling_ball_cy import apply_kernel, apply_kernel_nan + + +def rolling_ball(image, *, radius=100, kernel=None, nansafe=False, num_threads=None): + """Estimate background intensity using the rolling-ball algorithm. + + This function is a generalization of the rolling-ball algorithm [1]_ to + estimate the background intensity of an n-dimensional image. This is + typically useful for background subtraction in case of uneven exposure. + Think of the image as a landscape (where altitude is determined by + intensity), under which a ball of given radius is rolled. At each + position, the ball's apex gives the resulting background intensity. + + Parameters + ---------- + image : ndarray + The image to be filtered. + radius : int, optional + Radius of the ball-shaped kernel to be rolled under the + image landscape. Used only if `kernel` is ``None``. + kernel : ndarray, optional + An alternative way to specify the rolling ball, as an arbitrary + kernel. It must have the same number of axes as `image`. + nansafe: bool, optional + If ``False`` (default), the function assumes that none of the values + in `image` are ``np.nan``, and uses a faster implementation. + num_threads: int, optional + The maximum number of threads to use. If ``None``, the function uses + the OpenMP default value; typically, it is equal to the maximum number + of virtual cores. + Note: This is an upper limit to the number of threads. The exact number + is determined by the system's OpenMP library. + + Returns + ------- + background : ndarray + The estimated background of the image. + + Notes + ----- + This implementation assumes that dark pixels correspond to the background. If + you have a bright background, invert the image before passing it to this + function, e.g., using :func:`skimage.util.invert`. + + For this method to give meaningful results, the radius of the ball (or + typical size of the kernel, in the general case) should be larger than the + typical size of the image features of interest. + + This algorithm is sensitive to noise (in particular salt-and-pepper + noise). If this is a problem in your image, you can apply mild + Gaussian smoothing before passing the image to this function. + + This algorithm's complexity is polynomial in the radius, with degree equal + to the image dimensionality (a 2D image is N^2, a 3D image is N^3, etc.), + so it can take a long time as the radius grows beyond 30 or so ([2]_, [3]_). + It is an exact N-dimensional calculation; if all you need is an + approximation, faster options to consider are top-hat filtering [4]_ or + downscaling-then-upscaling to reduce the size of the input processed. + + References + ---------- + .. [1] Sternberg, Stanley R. "Biomedical image processing." Computer 1 + (1983): 22-34. :DOI:`10.1109/MC.1983.1654163` + .. [2] https://github.com/scikit-image/scikit-image/issues/5193 + .. [3] https://github.com/scikit-image/scikit-image/issues/7423 + .. [4] https://forum.image.sc/t/59267/7 + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + >>> image = ski.data.coins() + >>> background = ski.restoration.rolling_ball(image) + >>> filtered_image = image - background + + >>> import numpy as np + >>> import skimage as ski + >>> image = ski.data.coins() + >>> kernel = ski.restoration.ellipsoid_kernel((101, 101), 75) + >>> background = ski.restoration.rolling_ball(image, kernel=kernel) + >>> filtered_image = image - background + """ + + image = np.asarray(image) + float_type = _supported_float_type(image.dtype) + img = image.astype(float_type, copy=False) + + if num_threads is None: + num_threads = 0 + + if kernel is None: + kernel = ball_kernel(radius, image.ndim) + + kernel = kernel.astype(float_type) + kernel_shape = np.asarray(kernel.shape) + kernel_center = kernel_shape // 2 + center_intensity = kernel[tuple(kernel_center)] + + intensity_difference = center_intensity - kernel + intensity_difference[kernel == np.inf] = np.inf + intensity_difference = intensity_difference.astype(img.dtype) + intensity_difference = intensity_difference.reshape(-1) + + img = np.pad( + img, kernel_center[:, np.newaxis], constant_values=np.inf, mode="constant" + ) + + func = apply_kernel_nan if nansafe else apply_kernel + background = func( + img.reshape(-1), + intensity_difference, + np.zeros_like(image, dtype=img.dtype).reshape(-1), + np.array(image.shape, dtype=np.intp), + np.array(img.shape, dtype=np.intp), + kernel_shape.astype(np.intp), + num_threads, + ) + + background = background.astype(image.dtype, copy=False) + + return background + + +def ball_kernel(radius, ndim): + """Create a ball kernel for restoration.rolling_ball. + + Parameters + ---------- + radius : int + Radius of the ball. + ndim : int + Number of dimensions of the ball. ``ndim`` should match the + dimensionality of the image the kernel will be applied to. + + Returns + ------- + kernel : ndarray + The kernel containing the surface intensity of the top half + of the ellipsoid. + + See Also + -------- + rolling_ball + """ + + kernel_coords = np.stack( + np.meshgrid( + *[np.arange(-x, x + 1) for x in [np.ceil(radius)] * ndim], indexing='ij' + ), + axis=-1, + ) + + sum_of_squares = np.sum(kernel_coords**2, axis=-1) + distance_from_center = np.sqrt(sum_of_squares) + kernel = np.sqrt(np.clip(radius**2 - sum_of_squares, 0, None)) + kernel[distance_from_center > radius] = np.inf + + return kernel + + +def ellipsoid_kernel(shape, intensity): + """Create an ellipoid kernel for restoration.rolling_ball. + + Parameters + ---------- + shape : array-like + Length of the principal axis of the ellipsoid (excluding + the intensity axis). The kernel needs to have the same + dimensionality as the image it will be applied to. + intensity : int + Length of the intensity axis of the ellipsoid. + + Returns + ------- + kernel : ndarray + The kernel containing the surface intensity of the top half + of the ellipsoid. + + See Also + -------- + rolling_ball + """ + + shape = np.asarray(shape) + semi_axis = np.clip(shape // 2, 1, None) + + kernel_coords = np.stack( + np.meshgrid(*[np.arange(-x, x + 1) for x in semi_axis], indexing='ij'), axis=-1 + ) + + intensity_scaling = 1 - np.sum((kernel_coords / semi_axis) ** 2, axis=-1) + kernel = intensity * np.sqrt(np.clip(intensity_scaling, 0, None)) + kernel[intensity_scaling < 0] = np.inf + + return kernel diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball_cy.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball_cy.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..d99e0fb1f7c6a3a428eb724cc446b822b9fe6e55 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_rolling_ball_cy.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_1d.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_1d.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..ed7f722158026da12f9147956beeb3855fd6cc6d Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_1d.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_2d.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_2d.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..2dd384d7364e6ba2c42b3d88265557d5a54bd4ab Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_2d.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_3d.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_3d.cp312-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..9e8b40224df872cad37d3c551365d08c9c59c0e9 Binary files /dev/null and b/python_embeded/Lib/site-packages/skimage/restoration/_unwrap_3d.cp312-win_amd64.lib differ diff --git a/python_embeded/Lib/site-packages/skimage/restoration/deconvolution.py b/python_embeded/Lib/site-packages/skimage/restoration/deconvolution.py new file mode 100644 index 0000000000000000000000000000000000000000..c2551cf0aaf4496c37f7187f401e5e0283d168dc --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/deconvolution.py @@ -0,0 +1,424 @@ +"""Implementations restoration functions""" + +import numpy as np +from scipy.signal import convolve + +from .._shared.utils import _supported_float_type +from . import uft + + +def wiener(image, psf, balance, reg=None, is_real=True, clip=True): + r"""Wiener-Hunt deconvolution + + Return the deconvolution with a Wiener-Hunt approach (i.e. with + Fourier diagonalisation). + + Parameters + ---------- + image : ndarray + Input degraded image (can be n-dimensional). + psf : ndarray + Point Spread Function. This is assumed to be the impulse + response (input image space) if the data-type is real, or the + transfer function (Fourier space) if the data-type is + complex. There is no constraints on the shape of the impulse + response. The transfer function must be of shape + `(N1, N2, ..., ND)` if `is_real is True`, + `(N1, N2, ..., ND // 2 + 1)` otherwise (see `np.fft.rfftn`). + balance : float + The regularisation parameter value that tunes the balance + between the data adequacy that improve frequency restoration + and the prior adequacy that reduce frequency restoration (to + avoid noise artifacts). + reg : ndarray, optional + The regularisation operator. The Laplacian by default. It can + be an impulse response or a transfer function, as for the + psf. Shape constraint is the same as for the `psf` parameter. + is_real : boolean, optional + True by default. Specify if ``psf`` and ``reg`` are provided + with hermitian hypothesis, that is only half of the frequency + plane is provided (due to the redundancy of Fourier transform + of real signal). It's apply only if ``psf`` and/or ``reg`` are + provided as transfer function. For the hermitian property see + ``uft`` module or ``np.fft.rfftn``. + clip : boolean, optional + True by default. If True, pixel values of the result above 1 or + under -1 are thresholded for skimage pipeline compatibility. + + Returns + ------- + im_deconv : (M, N) ndarray + The deconvolved image. + + Examples + -------- + >>> from skimage import color, data, restoration + >>> img = color.rgb2gray(data.astronaut()) + >>> from scipy.signal import convolve2d + >>> psf = np.ones((5, 5)) / 25 + >>> img = convolve2d(img, psf, 'same') + >>> rng = np.random.default_rng() + >>> img += 0.1 * img.std() * rng.standard_normal(img.shape) + >>> deconvolved_img = restoration.wiener(img, psf, 0.1) + + Notes + ----- + This function applies the Wiener filter to a noisy and degraded + image by an impulse response (or PSF). If the data model is + + .. math:: y = Hx + n + + where :math:`n` is noise, :math:`H` the PSF and :math:`x` the + unknown original image, the Wiener filter is + + .. math:: + \hat x = F^\dagger \left( |\Lambda_H|^2 + \lambda |\Lambda_D|^2 \right)^{-1} + \Lambda_H^\dagger F y + + where :math:`F` and :math:`F^\dagger` are the Fourier and inverse + Fourier transforms respectively, :math:`\Lambda_H` the transfer + function (or the Fourier transform of the PSF, see [Hunt] below) + and :math:`\Lambda_D` the filter to penalize the restored image + frequencies (Laplacian by default, that is penalization of high + frequency). The parameter :math:`\lambda` tunes the balance + between the data (that tends to increase high frequency, even + those coming from noise), and the regularization. + + These methods are then specific to a prior model. Consequently, + the application or the true image nature must correspond to the + prior model. By default, the prior model (Laplacian) introduce + image smoothness or pixel correlation. It can also be interpreted + as high-frequency penalization to compensate the instability of + the solution with respect to the data (sometimes called noise + amplification or "explosive" solution). + + Finally, the use of Fourier space implies a circulant property of + :math:`H`, see [2]_. + + References + ---------- + .. [1] François Orieux, Jean-François Giovannelli, and Thomas + Rodet, "Bayesian estimation of regularization and point + spread function parameters for Wiener-Hunt deconvolution", + J. Opt. Soc. Am. A 27, 1593-1607 (2010) + + https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 + + https://hal.archives-ouvertes.fr/hal-00674508 + + .. [2] B. R. Hunt "A matrix theory proof of the discrete + convolution theorem", IEEE Trans. on Audio and + Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971 + """ + if reg is None: + reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) + if not np.iscomplexobj(reg): + reg = uft.ir2tf(reg, image.shape, is_real=is_real) + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.real.astype(float_type, copy=False) + reg = reg.real.astype(float_type, copy=False) + + if psf.shape != reg.shape: + trans_func = uft.ir2tf(psf, image.shape, is_real=is_real) + else: + trans_func = psf + + wiener_filter = np.conj(trans_func) / ( + np.abs(trans_func) ** 2 + balance * np.abs(reg) ** 2 + ) + if is_real: + deconv = uft.uirfftn(wiener_filter * uft.urfftn(image), shape=image.shape) + else: + deconv = uft.uifftn(wiener_filter * uft.ufftn(image)) + + if clip: + deconv[deconv > 1] = 1 + deconv[deconv < -1] = -1 + + return deconv + + +def unsupervised_wiener( + image, psf, reg=None, user_params=None, is_real=True, clip=True, *, rng=None +): + """Unsupervised Wiener-Hunt deconvolution. + + Return the deconvolution with a Wiener-Hunt approach, where the + hyperparameters are automatically estimated. The algorithm is a + stochastic iterative process (Gibbs sampler) described in the + reference below. See also ``wiener`` function. + + Parameters + ---------- + image : (M, N) ndarray + The input degraded image. + psf : ndarray + The impulse response (input image's space) or the transfer + function (Fourier space). Both are accepted. The transfer + function is automatically recognized as being complex + (``np.iscomplexobj(psf)``). + reg : ndarray, optional + The regularisation operator. The Laplacian by default. It can + be an impulse response or a transfer function, as for the psf. + user_params : dict, optional + Dictionary of parameters for the Gibbs sampler. See below. + clip : boolean, optional + True by default. If true, pixel values of the result above 1 or + under -1 are thresholded for skimage pipeline compatibility. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + .. versionadded:: 0.19 + + Returns + ------- + x_postmean : (M, N) ndarray + The deconvolved image (the posterior mean). + chains : dict + The keys ``noise`` and ``prior`` contain the chain list of + noise and prior precision respectively. + + Other parameters + ---------------- + The keys of ``user_params`` are: + + threshold : float + The stopping criterion: the norm of the difference between to + successive approximated solution (empirical mean of object + samples, see Notes section). 1e-4 by default. + burnin : int + The number of sample to ignore to start computation of the + mean. 15 by default. + min_num_iter : int + The minimum number of iterations. 30 by default. + max_num_iter : int + The maximum number of iterations if ``threshold`` is not + satisfied. 200 by default. + callback : callable (None by default) + A user provided callable to which is passed, if the function + exists, the current image sample for whatever purpose. The user + can store the sample, or compute other moments than the + mean. It has no influence on the algorithm execution and is + only for inspection. + + Examples + -------- + >>> from skimage import color, data, restoration + >>> img = color.rgb2gray(data.astronaut()) + >>> from scipy.signal import convolve2d + >>> psf = np.ones((5, 5)) / 25 + >>> img = convolve2d(img, psf, 'same') + >>> rng = np.random.default_rng() + >>> img += 0.1 * img.std() * rng.standard_normal(img.shape) + >>> deconvolved_img = restoration.unsupervised_wiener(img, psf) + + Notes + ----- + The estimated image is design as the posterior mean of a + probability law (from a Bayesian analysis). The mean is defined as + a sum over all the possible images weighted by their respective + probability. Given the size of the problem, the exact sum is not + tractable. This algorithm use of MCMC to draw image under the + posterior law. The practical idea is to only draw highly probable + images since they have the biggest contribution to the mean. At the + opposite, the less probable images are drawn less often since + their contribution is low. Finally, the empirical mean of these + samples give us an estimation of the mean, and an exact + computation with an infinite sample set. + + References + ---------- + .. [1] François Orieux, Jean-François Giovannelli, and Thomas + Rodet, "Bayesian estimation of regularization and point + spread function parameters for Wiener-Hunt deconvolution", + J. Opt. Soc. Am. A 27, 1593-1607 (2010) + + https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 + + https://hal.archives-ouvertes.fr/hal-00674508 + """ + params = { + 'threshold': 1e-4, + 'max_num_iter': 200, + 'min_num_iter': 30, + 'burnin': 15, + 'callback': None, + } + params.update(user_params or {}) + + if reg is None: + reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) + if not np.iscomplexobj(reg): + reg = uft.ir2tf(reg, image.shape, is_real=is_real) + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.real.astype(float_type, copy=False) + reg = reg.real.astype(float_type, copy=False) + + if psf.shape != reg.shape: + trans_fct = uft.ir2tf(psf, image.shape, is_real=is_real) + else: + trans_fct = psf + + # The mean of the object + x_postmean = np.zeros(trans_fct.shape, dtype=float_type) + # The previous computed mean in the iterative loop + prev_x_postmean = np.zeros(trans_fct.shape, dtype=float_type) + + # Difference between two successive mean + delta = np.nan + + # Initial state of the chain + gn_chain, gx_chain = [1], [1] + + # The correlation of the object in Fourier space (if size is big, + # this can reduce computation time in the loop) + areg2 = np.abs(reg) ** 2 + atf2 = np.abs(trans_fct) ** 2 + + # The Fourier transform may change the image.size attribute, so we + # store it. + if is_real: + data_spectrum = uft.urfft2(image) + else: + data_spectrum = uft.ufft2(image) + + rng = np.random.default_rng(rng) + + # Gibbs sampling + for iteration in range(params['max_num_iter']): + # Sample of Eq. 27 p(circX^k | gn^k-1, gx^k-1, y). + + # weighting (correlation in direct space) + precision = gn_chain[-1] * atf2 + gx_chain[-1] * areg2 # Eq. 29 + # Note: Use astype instead of dtype argument to standard_normal to get + # similar random values across precisions, as needed for + # reference data used by test_unsupervised_wiener. + _rand1 = rng.standard_normal(data_spectrum.shape) + _rand1 = _rand1.astype(float_type, copy=False) + _rand2 = rng.standard_normal(data_spectrum.shape) + _rand2 = _rand2.astype(float_type, copy=False) + excursion = np.sqrt(0.5 / precision) * (_rand1 + 1j * _rand2) + + # mean Eq. 30 (RLS for fixed gn, gamma0 and gamma1 ...) + wiener_filter = gn_chain[-1] * np.conj(trans_fct) / precision + + # sample of X in Fourier space + x_sample = wiener_filter * data_spectrum + excursion + if params['callback']: + params['callback'](x_sample) + + # sample of Eq. 31 p(gn | x^k, gx^k, y) + gn_chain.append( + rng.gamma( + image.size / 2, + 2 / uft.image_quad_norm(data_spectrum - x_sample * trans_fct), + ) + ) + + # sample of Eq. 31 p(gx | x^k, gn^k-1, y) + gx_chain.append( + rng.gamma((image.size - 1) / 2, 2 / uft.image_quad_norm(x_sample * reg)) + ) + + # current empirical average + if iteration > params['burnin']: + x_postmean = prev_x_postmean + x_sample + + if iteration > (params['burnin'] + 1): + current = x_postmean / (iteration - params['burnin']) + previous = prev_x_postmean / (iteration - params['burnin'] - 1) + + delta = ( + np.sum(np.abs(current - previous)) + / np.sum(np.abs(x_postmean)) + / (iteration - params['burnin']) + ) + + prev_x_postmean = x_postmean + + # stop of the algorithm + if (iteration > params['min_num_iter']) and (delta < params['threshold']): + break + + # Empirical average \approx POSTMEAN Eq. 44 + x_postmean = x_postmean / (iteration - params['burnin']) + if is_real: + x_postmean = uft.uirfft2(x_postmean, shape=image.shape) + else: + x_postmean = uft.uifft2(x_postmean) + + if clip: + x_postmean[x_postmean > 1] = 1 + x_postmean[x_postmean < -1] = -1 + + return (x_postmean, {'noise': gn_chain, 'prior': gx_chain}) + + +def richardson_lucy(image, psf, num_iter=50, clip=True, filter_epsilon=None): + """Richardson-Lucy deconvolution. + + Parameters + ---------- + image : ([P, ]M, N) ndarray + Input degraded image (can be n-dimensional). If you keep the + default `clip=True` parameter, you may want to normalize + the image so that its values fall in the [-1, 1] interval to avoid + information loss. + psf : ndarray + The point spread function. + num_iter : int, optional + Number of iterations. This parameter plays the role of + regularisation. + clip : boolean, optional + True by default. If true, pixel value of the result above 1 or + under -1 are thresholded for skimage pipeline compatibility. + filter_epsilon: float, optional + Value below which intermediate results become 0 to avoid division + by small numbers. + + Returns + ------- + im_deconv : ndarray + The deconvolved image. + + Examples + -------- + >>> from skimage import img_as_float, data, restoration + >>> camera = img_as_float(data.camera()) + >>> from scipy.signal import convolve2d + >>> psf = np.ones((5, 5)) / 25 + >>> camera = convolve2d(camera, psf, 'same') + >>> rng = np.random.default_rng() + >>> camera += 0.1 * camera.std() * rng.standard_normal(camera.shape) + >>> deconvolved = restoration.richardson_lucy(camera, psf, 5) + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution + """ + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.astype(float_type, copy=False) + im_deconv = np.full(image.shape, 0.5, dtype=float_type) + psf_mirror = np.flip(psf) + + # Small regularization parameter used to avoid 0 divisions + eps = 1e-12 + + for _ in range(num_iter): + conv = convolve(im_deconv, psf, mode='same') + eps + if filter_epsilon: + relative_blur = np.where(conv < filter_epsilon, 0, image / conv) + else: + relative_blur = image / conv + im_deconv *= convolve(relative_blur, psf_mirror, mode='same') + + if clip: + im_deconv[im_deconv > 1] = 1 + im_deconv[im_deconv < -1] = -1 + + return im_deconv diff --git a/python_embeded/Lib/site-packages/skimage/restoration/inpaint.py b/python_embeded/Lib/site-packages/skimage/restoration/inpaint.py new file mode 100644 index 0000000000000000000000000000000000000000..16dd5ecb9ab69809d751a1923d154f61a88d9cfd --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/inpaint.py @@ -0,0 +1,340 @@ +import numpy as np +from scipy import sparse +from scipy.sparse.linalg import spsolve +import scipy.ndimage as ndi +from scipy.ndimage import laplace + +import skimage +from .._shared import utils +from ..measure import label +from ._inpaint import _build_matrix_inner + + +def _get_neighborhood(nd_idx, radius, nd_shape): + bounds_lo = np.maximum(nd_idx - radius, 0) + bounds_hi = np.minimum(nd_idx + radius + 1, nd_shape) + return bounds_lo, bounds_hi + + +def _get_neigh_coef(shape, center, dtype=float): + # Create biharmonic coefficients ndarray + neigh_coef = np.zeros(shape, dtype=dtype) + neigh_coef[center] = 1 + neigh_coef = laplace(laplace(neigh_coef)) + + # extract non-zero locations and values + coef_idx = np.where(neigh_coef) + coef_vals = neigh_coef[coef_idx] + + coef_idx = np.stack(coef_idx, axis=0) + return neigh_coef, coef_idx, coef_vals + + +def _inpaint_biharmonic_single_region( + image, mask, out, neigh_coef_full, coef_vals, raveled_offsets +): + """Solve a (sparse) linear system corresponding to biharmonic inpainting. + + This function creates a linear system of the form: + + ``A @ u = b`` + + where ``A`` is a sparse matrix, ``b`` is a vector enforcing smoothness and + boundary constraints and ``u`` is the vector of inpainted values to be + (uniquely) determined by solving the linear system. + + ``A`` is a sparse matrix of shape (n_mask, n_mask) where ``n_mask`` + corresponds to the number of non-zero values in ``mask`` (i.e. the number + of pixels to be inpainted). Each row in A will have a number of non-zero + values equal to the number of non-zero values in the biharmonic kernel, + ``neigh_coef_full``. In practice, biharmonic kernels with reduced extent + are used at the image borders. This matrix, ``A`` is the same for all + image channels (since the same inpainting mask is currently used for all + channels). + + ``u`` is a dense matrix of shape ``(n_mask, n_channels)`` and represents + the vector of unknown values for each channel. + + ``b`` is a dense matrix of shape ``(n_mask, n_channels)`` and represents + the desired output of convolving the solution with the biharmonic kernel. + At mask locations where there is no overlap with known values, ``b`` will + have a value of 0. This enforces the biharmonic smoothness constraint in + the interior of inpainting regions. For regions near the boundary that + overlap with known values, the entries in ``b`` enforce boundary conditions + designed to avoid discontinuity with the known values. + """ + + n_channels = out.shape[-1] + radius = neigh_coef_full.shape[0] // 2 + + edge_mask = np.ones(mask.shape, dtype=bool) + edge_mask[(slice(radius, -radius),) * mask.ndim] = 0 + boundary_mask = edge_mask * mask + center_mask = ~edge_mask * mask + + boundary_pts = np.where(boundary_mask) + boundary_i = np.flatnonzero(boundary_mask) + center_i = np.flatnonzero(center_mask) + mask_i = np.concatenate((boundary_i, center_i)) + + center_pts = np.where(center_mask) + mask_pts = tuple([np.concatenate((b, c)) for b, c in zip(boundary_pts, center_pts)]) + + # Use convolution to predetermine the number of non-zero entries in the + # sparse system matrix. + structure = neigh_coef_full != 0 + tmp = ndi.convolve(mask, structure, output=np.uint8, mode='constant') + nnz_matrix = tmp[mask].sum() + + # Need to estimate the number of zeros for the right hand side vector. + # The computation below will slightly overestimate the true number of zeros + # due to edge effects (the kernel itself gets shrunk in size near the + # edges, but that isn't accounted for here). We can trim any excess entries + # later. + n_mask = np.count_nonzero(mask) + n_struct = np.count_nonzero(structure) + nnz_rhs_vector_max = n_mask - np.count_nonzero(tmp == n_struct) + + # pre-allocate arrays storing sparse matrix indices and values + row_idx_known = np.empty(nnz_rhs_vector_max, dtype=np.intp) + data_known = np.zeros((nnz_rhs_vector_max, n_channels), dtype=out.dtype) + row_idx_unknown = np.empty(nnz_matrix, dtype=np.intp) + col_idx_unknown = np.empty(nnz_matrix, dtype=np.intp) + data_unknown = np.empty(nnz_matrix, dtype=out.dtype) + + # cache the various small, non-square Laplacians used near the boundary + coef_cache = {} + + # Iterate over masked points near the boundary + mask_flat = mask.reshape(-1) + out_flat = np.ascontiguousarray(out.reshape((-1, n_channels))) + idx_known = 0 + idx_unknown = 0 + mask_pt_n = -1 + boundary_pts = np.stack(boundary_pts, axis=1) + for mask_pt_n, nd_idx in enumerate(boundary_pts): + # Get bounded neighborhood of selected radius + b_lo, b_hi = _get_neighborhood(nd_idx, radius, mask.shape) + + # Create (truncated) biharmonic coefficients ndarray + coef_shape = tuple(b_hi - b_lo) + coef_center = tuple(nd_idx - b_lo) + coef_idx, coefs = coef_cache.get((coef_shape, coef_center), (None, None)) + if coef_idx is None: + _, coef_idx, coefs = _get_neigh_coef( + coef_shape, coef_center, dtype=out.dtype + ) + coef_cache[(coef_shape, coef_center)] = (coef_idx, coefs) + + # compute corresponding 1d indices into the mask + coef_idx = coef_idx + b_lo[:, np.newaxis] + index1d = np.ravel_multi_index(coef_idx, mask.shape) + + # Iterate over masked point's neighborhood + nvals = 0 + for coef, i in zip(coefs, index1d): + if mask_flat[i]: + row_idx_unknown[idx_unknown] = mask_pt_n + col_idx_unknown[idx_unknown] = i + data_unknown[idx_unknown] = coef + idx_unknown += 1 + else: + data_known[idx_known, :] -= coef * out_flat[i, :] + nvals += 1 + if nvals: + row_idx_known[idx_known] = mask_pt_n + idx_known += 1 + + # Call an efficient Cython-based implementation for all interior points + row_start = mask_pt_n + 1 + known_start_idx = idx_known + unknown_start_idx = idx_unknown + nnz_rhs = _build_matrix_inner( + # starting indices + row_start, + known_start_idx, + unknown_start_idx, + # input arrays + center_i, + raveled_offsets, + coef_vals, + mask_flat, + out_flat, + # output arrays + row_idx_known, + data_known, + row_idx_unknown, + col_idx_unknown, + data_unknown, + ) + + # trim RHS vector values and indices to the exact length + row_idx_known = row_idx_known[:nnz_rhs] + data_known = data_known[:nnz_rhs, :] + + # Form sparse matrix of unknown values + sp_shape = (n_mask, out.size) + matrix_unknown = sparse.csr_array( + (data_unknown, (row_idx_unknown, col_idx_unknown)), shape=sp_shape + ) + + # Solve linear system for masked points + matrix_unknown = matrix_unknown[:, mask_i] + + # dense vectors representing the right hand side for each channel + rhs = np.zeros((n_mask, n_channels), dtype=out.dtype) + rhs[row_idx_known, :] = data_known + + # set use_umfpack to False so float32 data is supported + result = spsolve(matrix_unknown, rhs, use_umfpack=False, permc_spec='MMD_ATA') + if result.ndim == 1: + result = result[:, np.newaxis] + + out[mask_pts] = result + return out + + +@utils.channel_as_last_axis() +def inpaint_biharmonic(image, mask, *, split_into_regions=False, channel_axis=None): + """Inpaint masked points in image with biharmonic equations. + + Parameters + ---------- + image : (M[, N[, ..., P]][, C]) ndarray + Input image. + mask : (M[, N[, ..., P]]) ndarray + Array of pixels to be inpainted. Have to be the same shape as one + of the 'image' channels. Unknown pixels have to be represented with 1, + known pixels - with 0. + split_into_regions : boolean, optional + If True, inpainting is performed on a region-by-region basis. This is + likely to be slower, but will have reduced memory requirements. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (M[, N[, ..., P]][, C]) ndarray + Input image with masked pixels inpainted. + + References + ---------- + .. [1] S.B.Damelin and N.S.Hoang. "On Surface Completion and Image + Inpainting by Biharmonic Functions: Numerical Aspects", + International Journal of Mathematics and Mathematical Sciences, + Vol. 2018, Article ID 3950312 + :DOI:`10.1155/2018/3950312` + .. [2] C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of + Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., + 28 (2010), 104-113, + :DOI:`10.1016/j.acha.2009.04.004` + + Examples + -------- + >>> img = np.tile(np.square(np.linspace(0, 1, 5)), (5, 1)) + >>> mask = np.zeros_like(img) + >>> mask[2, 2:] = 1 + >>> mask[1, 3:] = 1 + >>> mask[0, 4:] = 1 + >>> out = inpaint_biharmonic(img, mask) + """ + + if image.ndim < 1: + raise ValueError('Input array has to be at least 1D') + + multichannel = channel_axis is not None + img_baseshape = image.shape[:-1] if multichannel else image.shape + if img_baseshape != mask.shape: + raise ValueError('Input arrays have to be the same shape') + + if np.ma.isMaskedArray(image): + raise TypeError('Masked arrays are not supported') + + image = skimage.img_as_float(image) + + # float16->float32 and float128->float64 + float_dtype = utils._supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + mask = mask.astype(bool, copy=False) + if not multichannel: + image = image[..., np.newaxis] + out = np.copy(image, order='C') + + # Create biharmonic coefficients ndarray + radius = 2 + coef_shape = (2 * radius + 1,) * mask.ndim + coef_center = (radius,) * mask.ndim + neigh_coef_full, coef_idx, coef_vals = _get_neigh_coef( + coef_shape, coef_center, dtype=out.dtype + ) + + # stride for the last spatial dimension + channel_stride_bytes = out.strides[-2] + + # offsets to all neighboring non-zero elements in the footprint + offsets = coef_idx - radius + + # determine per-channel intensity limits + known_points = image[~mask] + limits = (known_points.min(axis=0), known_points.max(axis=0)) + + if split_into_regions: + # Split inpainting mask into independent regions + kernel = ndi.generate_binary_structure(mask.ndim, 1) + mask_dilated = ndi.binary_dilation(mask, structure=kernel) + mask_labeled = label(mask_dilated) + mask_labeled *= mask + + bbox_slices = ndi.find_objects(mask_labeled) + + for idx_region, bb_slice in enumerate(bbox_slices, 1): + # expand object bounding boxes by the biharmonic kernel radius + roi_sl = tuple( + slice(max(sl.start - radius, 0), min(sl.stop + radius, size)) + for sl, size in zip(bb_slice, mask_labeled.shape) + ) + # extract only the region surrounding the label of interest + mask_region = mask_labeled[roi_sl] == idx_region + # add slice for axes + roi_sl += (slice(None),) + # copy for contiguity and to account for possible ROI overlap + otmp = out[roi_sl].copy() + + # compute raveled offsets for the ROI + ostrides = np.array( + [s // channel_stride_bytes for s in otmp[..., 0].strides] + ) + raveled_offsets = np.sum(offsets * ostrides[..., np.newaxis], axis=0) + + _inpaint_biharmonic_single_region( + image[roi_sl], + mask_region, + otmp, + neigh_coef_full, + coef_vals, + raveled_offsets, + ) + # assign output to the + out[roi_sl] = otmp + else: + # compute raveled offsets for output image + ostrides = np.array([s // channel_stride_bytes for s in out[..., 0].strides]) + raveled_offsets = np.sum(offsets * ostrides[..., np.newaxis], axis=0) + + _inpaint_biharmonic_single_region( + image, mask, out, neigh_coef_full, coef_vals, raveled_offsets + ) + + # Handle enormous values on a per-channel basis + np.clip(out, a_min=limits[0], a_max=limits[1], out=out) + + if not multichannel: + out = out[..., 0] + + return out diff --git a/python_embeded/Lib/site-packages/skimage/restoration/j_invariant.py b/python_embeded/Lib/site-packages/skimage/restoration/j_invariant.py new file mode 100644 index 0000000000000000000000000000000000000000..9313422231aa2d468d57931ba332f5daa152a98a --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/j_invariant.py @@ -0,0 +1,358 @@ +import itertools +import functools + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type +from ..metrics import mean_squared_error +from ..util import img_as_float + + +def _interpolate_image(image, *, multichannel=False): + """Replacing each pixel in ``image`` with the average of its neighbors. + + Parameters + ---------- + image : ndarray + Input data to be interpolated. + multichannel : bool, optional + Whether the last axis of the image is to be interpreted as multiple + channels or another spatial dimension. + + Returns + ------- + interp : ndarray + Interpolated version of `image`. + """ + spatialdims = image.ndim if not multichannel else image.ndim - 1 + conv_filter = ndi.generate_binary_structure(spatialdims, 1).astype(image.dtype) + conv_filter.ravel()[conv_filter.size // 2] = 0 + conv_filter /= conv_filter.sum() + + if multichannel: + interp = np.zeros_like(image) + for i in range(image.shape[-1]): + interp[..., i] = ndi.convolve(image[..., i], conv_filter, mode='mirror') + else: + interp = ndi.convolve(image, conv_filter, mode='mirror') + return interp + + +def _generate_grid_slice(shape, *, offset, stride=3): + """Generate slices of uniformly-spaced points in an array. + + Parameters + ---------- + shape : tuple of int + Shape of the mask. + offset : int + The offset of the grid of ones. Iterating over ``offset`` will cover + the entire array. It should be between 0 and ``stride ** ndim``, not + inclusive, where ``ndim = len(shape)``. + stride : int, optional + The spacing between ones, used in each dimension. + + Returns + ------- + mask : ndarray + The mask. + + Examples + -------- + >>> shape = (4, 4) + >>> array = np.zeros(shape, dtype=int) + >>> grid_slice = _generate_grid_slice(shape, offset=0, stride=2) + >>> array[grid_slice] = 1 + >>> print(array) + [[1 0 1 0] + [0 0 0 0] + [1 0 1 0] + [0 0 0 0]] + + Changing the offset moves the location of the 1s: + + >>> array = np.zeros(shape, dtype=int) + >>> grid_slice = _generate_grid_slice(shape, offset=3, stride=2) + >>> array[grid_slice] = 1 + >>> print(array) + [[0 0 0 0] + [0 1 0 1] + [0 0 0 0] + [0 1 0 1]] + """ + phases = np.unravel_index(offset, (stride,) * len(shape)) + mask = tuple(slice(p, None, stride) for p in phases) + + return mask + + +def denoise_invariant( + image, denoise_function, *, stride=4, masks=None, denoiser_kwargs=None +): + """Apply a J-invariant version of a denoising function. + + Parameters + ---------- + image : ndarray (M[, N[, ...]][, C]) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into a ndarray of floats (using `img_as_float`) for the + computation of the denoised image. + denoise_function : function + Original denoising function. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + masks : list of ndarray, optional + Set of masks to use for computing J-invariant output. If `None`, + a full set of masks covering the image will be used. + denoiser_kwargs: + Keyword arguments passed to `denoise_function`. + + Returns + ------- + output : ndarray + Denoised image, of same shape as `image`. + + Notes + ----- + A denoising function is J-invariant if the prediction it makes for each + pixel does not depend on the value of that pixel in the original image. + The prediction for each pixel may instead use all the relevant information + contained in the rest of the image, which is typically quite significant. + Any function can be converted into a J-invariant one using a simple masking + procedure, as described in [1]. + + The pixel-wise error of a J-invariant denoiser is uncorrelated to the noise, + so long as the noise in each pixel is independent. Consequently, the average + difference between the denoised image and the oisy image, the + *self-supervised loss*, is the same as the difference between the denoised + image and the original clean image, the *ground-truth loss* (up to a + constant). + + This means that the best J-invariant denoiser for a given image can be found + using the noisy data alone, by selecting the denoiser minimizing the self- + supervised loss. + + References + ---------- + .. [1] J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, + International Conference on Machine Learning, p. 524-533 (2019). + + Examples + -------- + >>> import skimage + >>> from skimage.restoration import denoise_invariant, denoise_tv_chambolle + >>> image = skimage.util.img_as_float(skimage.data.chelsea()) + >>> noisy = skimage.util.random_noise(image, var=0.2 ** 2) + >>> denoised = denoise_invariant(noisy, denoise_function=denoise_tv_chambolle) + """ + image = img_as_float(image) + + # promote float16->float32 if needed + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if denoiser_kwargs is None: + denoiser_kwargs = {} + + multichannel = denoiser_kwargs.get('channel_axis', None) is not None + interp = _interpolate_image(image, multichannel=multichannel) + output = np.zeros_like(image) + + if masks is None: + spatialdims = image.ndim if not multichannel else image.ndim - 1 + n_masks = stride**spatialdims + masks = ( + _generate_grid_slice(image.shape[:spatialdims], offset=idx, stride=stride) + for idx in range(n_masks) + ) + + for mask in masks: + input_image = image.copy() + input_image[mask] = interp[mask] + output[mask] = denoise_function(input_image, **denoiser_kwargs)[mask] + return output + + +def _product_from_dict(dictionary): + """Utility function to convert parameter ranges to parameter combinations. + + Converts a dict of lists into a list of dicts whose values consist of the + cartesian product of the values in the original dict. + + Parameters + ---------- + dictionary : dict of lists + Dictionary of lists to be multiplied. + + Yields + ------ + selections : dicts of values + Dicts containing individual combinations of the values in the input + dict. + """ + keys = dictionary.keys() + for element in itertools.product(*dictionary.values()): + yield dict(zip(keys, element)) + + +def calibrate_denoiser( + image, + denoise_function, + denoise_parameters, + *, + stride=4, + approximate_loss=True, + extra_output=False, +): + """Calibrate a denoising function and return optimal J-invariant version. + + The returned function is partially evaluated with optimal parameter values + set for denoising the input image. + + Parameters + ---------- + image : ndarray + Input data to be denoised (converted using `img_as_float`). + denoise_function : function + Denoising function to be calibrated. + denoise_parameters : dict of list + Ranges of parameters for `denoise_function` to be calibrated over. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + approximate_loss : bool, optional + Whether to approximate the self-supervised loss used to evaluate the + denoiser by only computing it on one masked version of the image. + If False, the runtime will be a factor of `stride**image.ndim` longer. + extra_output : bool, optional + If True, return parameters and losses in addition to the calibrated + denoising function + + Returns + ------- + best_denoise_function : function + The optimal J-invariant version of `denoise_function`. + + If `extra_output` is True, the following tuple is also returned: + + (parameters_tested, losses) : tuple (list of dict, list of int) + List of parameters tested for `denoise_function`, as a dictionary of + kwargs + Self-supervised loss for each set of parameters in `parameters_tested`. + + + Notes + ----- + + The calibration procedure uses a self-supervised mean-square-error loss + to evaluate the performance of J-invariant versions of `denoise_function`. + The minimizer of the self-supervised loss is also the minimizer of the + ground-truth loss (i.e., the true MSE error) [1]. The returned function + can be used on the original noisy image, or other images with similar + characteristics. + + Increasing the stride increases the performance of `best_denoise_function` + at the expense of increasing its runtime. It has no effect on the runtime + of the calibration. + + References + ---------- + .. [1] J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, + International Conference on Machine Learning, p. 524-533 (2019). + + Examples + -------- + >>> from skimage import color, data + >>> from skimage.restoration import denoise_tv_chambolle + >>> import numpy as np + >>> img = color.rgb2gray(data.astronaut()[:50, :50]) + >>> rng = np.random.default_rng() + >>> noisy = img + 0.5 * img.std() * rng.standard_normal(img.shape) + >>> parameters = {'weight': np.arange(0.01, 0.3, 0.02)} + >>> denoising_function = calibrate_denoiser(noisy, denoise_tv_chambolle, + ... denoise_parameters=parameters) + >>> denoised_img = denoising_function(img) + + """ + parameters_tested, losses = _calibrate_denoiser_search( + image, + denoise_function, + denoise_parameters=denoise_parameters, + stride=stride, + approximate_loss=approximate_loss, + ) + + idx = np.argmin(losses) + best_parameters = parameters_tested[idx] + + best_denoise_function = functools.partial( + denoise_invariant, + denoise_function=denoise_function, + stride=stride, + denoiser_kwargs=best_parameters, + ) + + if extra_output: + return best_denoise_function, (parameters_tested, losses) + else: + return best_denoise_function + + +def _calibrate_denoiser_search( + image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True +): + """Return a parameter search history with losses for a denoise function. + + Parameters + ---------- + image : ndarray + Input data to be denoised (converted using `img_as_float`). + denoise_function : function + Denoising function to be calibrated. + denoise_parameters : dict of list + Ranges of parameters for `denoise_function` to be calibrated over. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + approximate_loss : bool, optional + Whether to approximate the self-supervised loss used to evaluate the + denoiser by only computing it on one masked version of the image. + If False, the runtime will be a factor of `stride**image.ndim` longer. + + Returns + ------- + parameters_tested : list of dict + List of parameters tested for `denoise_function`, as a dictionary of + kwargs. + losses : list of int + Self-supervised loss for each set of parameters in `parameters_tested`. + """ + image = img_as_float(image) + parameters_tested = list(_product_from_dict(denoise_parameters)) + losses = [] + + for denoiser_kwargs in parameters_tested: + multichannel = denoiser_kwargs.get('channel_axis', None) is not None + if not approximate_loss: + denoised = denoise_invariant( + image, denoise_function, stride=stride, denoiser_kwargs=denoiser_kwargs + ) + loss = mean_squared_error(image, denoised) + else: + spatialdims = image.ndim if not multichannel else image.ndim - 1 + n_masks = stride**spatialdims + mask = _generate_grid_slice( + image.shape[:spatialdims], offset=n_masks // 2, stride=stride + ) + + masked_denoised = denoise_invariant( + image, denoise_function, masks=[mask], denoiser_kwargs=denoiser_kwargs + ) + + loss = mean_squared_error(image[mask], masked_denoised[mask]) + + losses.append(loss) + + return parameters_tested, losses diff --git a/python_embeded/Lib/site-packages/skimage/restoration/non_local_means.py b/python_embeded/Lib/site-packages/skimage/restoration/non_local_means.py new file mode 100644 index 0000000000000000000000000000000000000000..0febe10dc45403a35337072de891b41396b942f4 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/non_local_means.py @@ -0,0 +1,187 @@ +import numpy as np + +from .._shared import utils +from .._shared.utils import convert_to_float +from ._nl_means_denoising import ( + _nl_means_denoising_2d, + _nl_means_denoising_3d, + _fast_nl_means_denoising_2d, + _fast_nl_means_denoising_3d, + _fast_nl_means_denoising_4d, +) + + +@utils.channel_as_last_axis() +def denoise_nl_means( + image, + patch_size=7, + patch_distance=11, + h=0.1, + fast_mode=True, + sigma=0.0, + *, + preserve_range=False, + channel_axis=None, +): + """Perform non-local means denoising on 2D-4D grayscale or RGB images. + + Parameters + ---------- + image : 2D or 3D ndarray + Input image to be denoised, which can be 2D or 3D, and grayscale + or RGB (for 2D images only, see ``channel_axis`` parameter). There can + be any number of channels (does not strictly have to be RGB). + patch_size : int, optional + Size of patches used for denoising. + patch_distance : int, optional + Maximal distance in pixels where to search patches used for denoising. + h : float, optional + Cut-off distance (in gray levels). The higher h, the more permissive + one is in accepting patches. A higher h results in a smoother image, + at the expense of blurring features. For a Gaussian noise of standard + deviation sigma, a rule of thumb is to choose the value of h to be + sigma of slightly less. + fast_mode : bool, optional + If True (default value), a fast version of the non-local means + algorithm is used. If False, the original version of non-local means is + used. See the Notes section for more details about the algorithms. + sigma : float, optional + The standard deviation of the (Gaussian) noise. If provided, a more + robust computation of patch weights is computed that takes the expected + noise variance into account (see Notes below). + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + result : ndarray + Denoised image, of same shape as `image`. + + Notes + ----- + + The non-local means algorithm is well suited for denoising images with + specific textures. The principle of the algorithm is to average the value + of a given pixel with values of other pixels in a limited neighborhood, + provided that the *patches* centered on the other pixels are similar enough + to the patch centered on the pixel of interest. + + In the original version of the algorithm [1]_, corresponding to + ``fast=False``, the computational complexity is:: + + image.size * patch_size ** image.ndim * patch_distance ** image.ndim + + Hence, changing the size of patches or their maximal distance has a + strong effect on computing times, especially for 3-D images. + + However, the default behavior corresponds to ``fast_mode=True``, for which + another version of non-local means [2]_ is used, corresponding to a + complexity of:: + + image.size * patch_distance ** image.ndim + + The computing time depends only weakly on the patch size, thanks to + the computation of the integral of patches distances for a given + shift, that reduces the number of operations [1]_. Therefore, this + algorithm executes faster than the classic algorithm + (``fast_mode=False``), at the expense of using twice as much memory. + This implementation has been proven to be more efficient compared to + other alternatives, see e.g. [3]_. + + Compared to the classic algorithm, all pixels of a patch contribute + to the distance to another patch with the same weight, no matter + their distance to the center of the patch. This coarser computation + of the distance can result in a slightly poorer denoising + performance. Moreover, for small images (images with a linear size + that is only a few times the patch size), the classic algorithm can + be faster due to boundary effects. + + The image is padded using the `reflect` mode of `skimage.util.pad` + before denoising. + + If the noise standard deviation, `sigma`, is provided a more robust + computation of patch weights is used. Subtracting the known noise variance + from the computed patch distances improves the estimates of patch + similarity, giving a moderate improvement to denoising performance [4]_. + It was also mentioned as an option for the fast variant of the algorithm in + [3]_. + + When `sigma` is provided, a smaller `h` should typically be used to + avoid oversmoothing. The optimal value for `h` depends on the image + content and noise level, but a reasonable starting point is + ``h = 0.8 * sigma`` when `fast_mode` is `True`, or ``h = 0.6 * sigma`` when + `fast_mode` is `False`. + + References + ---------- + .. [1] A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image + denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. + :DOI:`10.1109/CVPR.2005.38` + + .. [2] J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast + nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE + International Symposium on Biomedical Imaging: From Nano to Macro, + 2008, pp. 1331-1334. + :DOI:`10.1109/ISBI.2008.4541250` + + .. [3] Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means + Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. + :DOI:`10.5201/ipol.2014.120` + + .. [4] A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. + Image Processing On Line, 2011, vol. 1, pp. 208-212. + :DOI:`10.5201/ipol.2011.bcm_nlm` + + Examples + -------- + >>> a = np.zeros((40, 40)) + >>> a[10:-10, 10:-10] = 1. + >>> rng = np.random.default_rng() + >>> a += 0.3 * rng.standard_normal(a.shape) + >>> denoised_a = denoise_nl_means(a, 7, 5, 0.1) + """ + if channel_axis is None: + multichannel = False + image = image[..., np.newaxis] + else: + multichannel = True + + ndim_no_channel = image.ndim - 1 + if (ndim_no_channel < 2) or (ndim_no_channel > 4): + raise NotImplementedError( + "Non-local means denoising is only implemented for 2D, " + "3D or 4D grayscale or multichannel images." + ) + + image = convert_to_float(image, preserve_range) + if not image.flags.c_contiguous: + image = np.ascontiguousarray(image) + + kwargs = dict(s=patch_size, d=patch_distance, h=h, var=sigma * sigma) + if ndim_no_channel == 2: + nlm_func = _fast_nl_means_denoising_2d if fast_mode else _nl_means_denoising_2d + elif ndim_no_channel == 3: + if multichannel and not fast_mode: + raise NotImplementedError("Multichannel 3D requires fast_mode to be True.") + if fast_mode: + nlm_func = _fast_nl_means_denoising_3d + else: + # have to drop the size 1 channel axis for slow mode + image = image[..., 0] + nlm_func = _nl_means_denoising_3d + elif ndim_no_channel == 4: + if fast_mode: + nlm_func = _fast_nl_means_denoising_4d + else: + raise NotImplementedError("4D requires fast_mode to be True.") + dn = np.asarray(nlm_func(image, **kwargs)) + return dn diff --git a/python_embeded/Lib/site-packages/skimage/restoration/uft.py b/python_embeded/Lib/site-packages/skimage/restoration/uft.py new file mode 100644 index 0000000000000000000000000000000000000000..82016a6a66a08a6b2222a2a9b62b0e4d650fe961 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/uft.py @@ -0,0 +1,451 @@ +r"""Function of unitary fourier transform (uft) and utilities + +This module implements the unitary fourier transform, also known as +the ortho-normal transform. It is especially useful for convolution +[1], as it respects the Parseval equality. The value of the null +frequency is equal to + +.. math:: \frac{1}{\sqrt{n}} \sum_i x_i + +so the Fourier transform has the same energy as the original image +(see ``image_quad_norm`` function). The transform is applied from the +last axis for performance (assuming a C-order array input). + +References +---------- +.. [1] B. R. Hunt "A matrix theory proof of the discrete convolution + theorem", IEEE Trans. on Audio and Electroacoustics, + vol. au-19, no. 4, pp. 285-288, dec. 1971 + +""" + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type + + +def ufftn(inarray, dim=None): + """N-dimensional unitary Fourier transform. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray (same shape than inarray) + The unitary N-D Fourier transform of ``inarray``. + + Examples + -------- + >>> input = np.ones((3, 3, 3)) + >>> output = ufftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (3, 3, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.fftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def uifftn(inarray, dim=None): + """N-dimensional unitary inverse Fourier transform. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray + The unitary inverse nD Fourier transform of ``inarray``. Has the same shape as + ``inarray``. + + Examples + -------- + >>> input = np.ones((3, 3, 3)) + >>> output = uifftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (3, 3, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.ifftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def urfftn(inarray, dim=None): + """N-dimensional real unitary Fourier transform. + + This transform considers the Hermitian property of the transform on + real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray, shape (M[, ...], P / 2 + 1) + The unitary N-D real Fourier transform of ``inarray``. + + Notes + ----- + The ``urfft`` functions assume an input array of real + values. Consequently, the output has a Hermitian property and + redundant values are not computed or returned. + + Examples + -------- + >>> input = np.ones((5, 5, 5)) + >>> output = urfftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (5, 5, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.rfftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def uirfftn(inarray, dim=None, shape=None): + """N-dimensional inverse real unitary Fourier transform. + + This transform considers the Hermitian property of the transform + from complex to real input. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + shape : tuple of int, optional + The shape of the output. The shape of ``rfft`` is ambiguous in + case of odd-valued input shape. In this case, this parameter + should be provided. See ``np.fft.irfftn``. + + Returns + ------- + outarray : ndarray + The unitary N-D inverse real Fourier transform of ``inarray``. + + Notes + ----- + The ``uirfft`` function assumes that the output array is + real-valued. Consequently, the input is assumed to have a Hermitian + property and redundant values are implicit. + + Examples + -------- + >>> input = np.ones((5, 5, 5)) + >>> output = uirfftn(urfftn(input), shape=input.shape) + >>> np.allclose(input, output) + True + >>> output.shape + (5, 5, 5) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.irfftn(inarray, shape, axes=range(-dim, 0), norm='ortho') + return outarray + + +def ufft2(inarray): + """2-dimensional unitary Fourier transform. + + Compute the Fourier transform on the last 2 axes. + + Parameters + ---------- + inarray : ndarray + The array to transform. + + Returns + ------- + outarray : ndarray (same shape as inarray) + The unitary 2-D Fourier transform of ``inarray``. + + See Also + -------- + uifft2, ufftn, urfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = ufft2(input) + >>> np.allclose(np.sum(input[1, ...]) / np.sqrt(input[1, ...].size), + ... output[1, 0, 0]) + True + >>> output.shape + (10, 128, 128) + """ + return ufftn(inarray, 2) + + +def uifft2(inarray): + """2-dimensional inverse unitary Fourier transform. + + Compute the inverse Fourier transform on the last 2 axes. + + Parameters + ---------- + inarray : ndarray + The array to transform. + + Returns + ------- + outarray : ndarray (same shape as inarray) + The unitary 2-D inverse Fourier transform of ``inarray``. + + See Also + -------- + uifft2, uifftn, uirfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = uifft2(input) + >>> np.allclose(np.sum(input[1, ...]) / np.sqrt(input[1, ...].size), + ... output[0, 0, 0]) + True + >>> output.shape + (10, 128, 128) + """ + return uifftn(inarray, 2) + + +def urfft2(inarray): + """2-dimensional real unitary Fourier transform + + Compute the real Fourier transform on the last 2 axes. This + transform considers the Hermitian property of the transform from + complex to real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + + Returns + ------- + outarray : ndarray, shape (M[, ...], 2 * (P - 1)) + The unitary 2-D real Fourier transform of ``inarray``. + + See Also + -------- + ufft2, ufftn, urfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = urfft2(input) + >>> np.allclose(np.sum(input[1,...]) / np.sqrt(input[1,...].size), + ... output[1, 0, 0]) + True + >>> output.shape + (10, 128, 65) + """ + return urfftn(inarray, 2) + + +def uirfft2(inarray, shape=None): + """2-dimensional inverse real unitary Fourier transform. + + Compute the real inverse Fourier transform on the last 2 axes. + This transform considers the Hermitian property of the transform + from complex to real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + shape : tuple of int, optional + The shape of the output. The shape of ``rfft`` is ambiguous in + case of odd-valued input shape. In this case, this parameter + should be provided. See ``np.fft.irfftn``. + + Returns + ------- + outarray : ndarray, shape (M[, ...], 2 * (P - 1)) + The unitary 2-D inverse real Fourier transform of ``inarray``. + + See Also + -------- + urfft2, uifftn, uirfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = uirfftn(urfftn(input), shape=input.shape) + >>> np.allclose(input, output) + True + >>> output.shape + (10, 128, 128) + """ + return uirfftn(inarray, 2, shape=shape) + + +def image_quad_norm(inarray): + """Return the quadratic norm of images in Fourier space. + + This function detects whether the input image satisfies the + Hermitian property. + + Parameters + ---------- + inarray : ndarray + Input image. The image data should reside in the final two + axes. + + Returns + ------- + norm : float + The quadratic norm of ``inarray``. + + Examples + -------- + >>> input = np.ones((5, 5)) + >>> image_quad_norm(ufft2(input)) == np.sum(np.abs(input)**2) + True + >>> image_quad_norm(ufft2(input)) == image_quad_norm(urfft2(input)) + True + """ + # If there is a Hermitian symmetry + if inarray.shape[-1] != inarray.shape[-2]: + return 2 * np.sum(np.sum(np.abs(inarray) ** 2, axis=-1), axis=-1) - np.sum( + np.abs(inarray[..., 0]) ** 2, axis=-1 + ) + else: + return np.sum(np.sum(np.abs(inarray) ** 2, axis=-1), axis=-1) + + +def ir2tf(imp_resp, shape, dim=None, is_real=True): + """Compute the transfer function of an impulse response (IR). + + This function makes the necessary correct zero-padding, zero + convention, correct fft2, etc... to compute the transfer function + of IR. To use with unitary Fourier transform for the signal (ufftn + or equivalent). + + Parameters + ---------- + imp_resp : ndarray + The impulse responses. + shape : tuple of int + A tuple of integer corresponding to the target shape of the + transfer function. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + is_real : boolean, optional + If True (default), imp_resp is supposed real and the Hermitian property + is used with rfftn Fourier transform. + + Returns + ------- + y : complex ndarray + The transfer function of shape ``shape``. + + See Also + -------- + ufftn, uifftn, urfftn, uirfftn + + Examples + -------- + >>> np.all(np.array([[4, 0], [0, 0]]) == ir2tf(np.ones((2, 2)), (2, 2))) + True + >>> ir2tf(np.ones((2, 2)), (512, 512)).shape == (512, 257) + True + >>> ir2tf(np.ones((2, 2)), (512, 512), is_real=False).shape == (512, 512) + True + + Notes + ----- + The input array can be composed of multiple-dimensional IR with + an arbitrary number of IR. The individual IR must be accessed + through the first axes. The last ``dim`` axes contain the space + definition. + """ + if not dim: + dim = imp_resp.ndim + # Zero padding and fill + irpadded_dtype = _supported_float_type(imp_resp.dtype) + irpadded = np.zeros(shape, dtype=irpadded_dtype) + irpadded[tuple([slice(0, s) for s in imp_resp.shape])] = imp_resp + # Roll for zero convention of the fft to avoid the phase + # problem. Work with odd and even size. + for axis, axis_size in enumerate(imp_resp.shape): + if axis >= imp_resp.ndim - dim: + irpadded = np.roll(irpadded, shift=-int(np.floor(axis_size / 2)), axis=axis) + + func = fft.rfftn if is_real else fft.fftn + out = func(irpadded, axes=(range(-dim, 0))) + + # TODO: remove .astype call once SciPy >= 1.4 is required + cplx_dtype = np.promote_types(irpadded_dtype, np.complex64) + return out.astype(cplx_dtype, copy=False) + + +def laplacian(ndim, shape, is_real=True): + """Return the transfer function of the Laplacian. + + Laplacian is the second order difference, on row and column. + + Parameters + ---------- + ndim : int + The dimension of the Laplacian. + shape : tuple + The support on which to compute the transfer function. + is_real : boolean, optional + If True (default), imp_resp is assumed to be real-valued and + the Hermitian property is used with rfftn Fourier transform + to return the transfer function. + + Returns + ------- + tf : array_like, complex + The transfer function. + impr : array_like, real + The Laplacian. + + Examples + -------- + >>> tf, ir = laplacian(2, (32, 32)) + >>> np.all(ir == np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])) + True + >>> np.all(tf == ir2tf(ir, (32, 32))) + True + """ + impr = np.zeros([3] * ndim) + for dim in range(ndim): + idx = tuple( + [slice(1, 2)] * dim + [slice(None)] + [slice(1, 2)] * (ndim - dim - 1) + ) + impr[idx] = np.array([-1.0, 0.0, -1.0]).reshape( + [-1 if i == dim else 1 for i in range(ndim)] + ) + impr[(slice(1, 2),) * ndim] = 2.0 * ndim + return ir2tf(impr, shape, is_real=is_real), impr diff --git a/python_embeded/Lib/site-packages/skimage/restoration/unwrap.py b/python_embeded/Lib/site-packages/skimage/restoration/unwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..935e80b7b85ef322a4df5a1cc5141233dc2207c9 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/restoration/unwrap.py @@ -0,0 +1,116 @@ +import numpy as np + +from .._shared.utils import warn + +from ._unwrap_1d import unwrap_1d +from ._unwrap_2d import unwrap_2d +from ._unwrap_3d import unwrap_3d + + +def unwrap_phase(image, wrap_around=False, rng=None): + '''Recover the original from a wrapped phase image. + + From an image wrapped to lie in the interval [-pi, pi), recover the + original, unwrapped image. + + Parameters + ---------- + image : (M[, N[, P]]) ndarray or masked array of floats + The values should be in the range [-pi, pi). If a masked array is + provided, the masked entries will not be changed, and their values + will not be used to guide the unwrapping of neighboring, unmasked + values. Masked 1D arrays are not allowed, and will raise a + `ValueError`. + wrap_around : bool or sequence of bool, optional + When an element of the sequence is `True`, the unwrapping process + will regard the edges along the corresponding axis of the image to be + connected and use this connectivity to guide the phase unwrapping + process. If only a single boolean is given, it will apply to all axes. + Wrap around is not supported for 1D arrays. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + Unwrapping relies on a random initialization. This sets the + PRNG to use to achieve deterministic behavior. + + Returns + ------- + image_unwrapped : array_like, double + Unwrapped image of the same shape as the input. If the input `image` + was a masked array, the mask will be preserved. + + Raises + ------ + ValueError + If called with a masked 1D array or called with a 1D array and + ``wrap_around=True``. + + Examples + -------- + >>> c0, c1 = np.ogrid[-1:1:128j, -1:1:128j] + >>> image = 12 * np.pi * np.exp(-(c0**2 + c1**2)) + >>> image_wrapped = np.angle(np.exp(1j * image)) + >>> image_unwrapped = unwrap_phase(image_wrapped) + >>> np.std(image_unwrapped - image) < 1e-6 # A constant offset is normal + True + + References + ---------- + .. [1] Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, + and Munther A. Gdeisat, "Fast two-dimensional phase-unwrapping + algorithm based on sorting by reliability following a noncontinuous + path", Journal Applied Optics, Vol. 41, No. 35 (2002) 7437, + .. [2] Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., "Fast + three-dimensional phase-unwrapping algorithm based on sorting by + reliability following a non-continuous path. In W. Osten, + C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32--40, + International Society for Optics and Photonics. + ''' + if image.ndim not in (1, 2, 3): + raise ValueError('Image must be 1, 2, or 3 dimensional') + if isinstance(wrap_around, bool): + wrap_around = [wrap_around] * image.ndim + elif hasattr(wrap_around, '__getitem__') and not isinstance(wrap_around, str): + if len(wrap_around) != image.ndim: + raise ValueError( + 'Length of `wrap_around` must equal the ' 'dimensionality of image' + ) + wrap_around = [bool(wa) for wa in wrap_around] + else: + raise ValueError( + '`wrap_around` must be a bool or a sequence with ' + 'length equal to the dimensionality of image' + ) + if image.ndim == 1: + if np.ma.isMaskedArray(image): + raise ValueError('1D masked images cannot be unwrapped') + if wrap_around[0]: + raise ValueError('`wrap_around` is not supported for 1D images') + if image.ndim in (2, 3) and 1 in image.shape: + warn( + 'Image has a length 1 dimension. Consider using an ' + 'array of lower dimensionality to use a more efficient ' + 'algorithm' + ) + + if np.ma.isMaskedArray(image): + mask = np.require(np.ma.getmaskarray(image), np.uint8, ['C']) + else: + mask = np.zeros_like(image, dtype=np.uint8, order='C') + + image_not_masked = np.asarray(np.ma.getdata(image), dtype=np.float64, order='C') + image_unwrapped = np.empty_like(image, dtype=np.float64, order='C', subok=False) + + if image.ndim == 1: + unwrap_1d(image_not_masked, image_unwrapped) + elif image.ndim == 2: + unwrap_2d(image_not_masked, mask, image_unwrapped, wrap_around, rng) + elif image.ndim == 3: + unwrap_3d(image_not_masked, mask, image_unwrapped, wrap_around, rng) + + if np.ma.isMaskedArray(image): + return np.ma.array(image_unwrapped, mask=mask, fill_value=image.fill_value) + else: + return image_unwrapped diff --git a/python_embeded/Lib/site-packages/skimage/segmentation/active_contour_model.py b/python_embeded/Lib/site-packages/skimage/segmentation/active_contour_model.py new file mode 100644 index 0000000000000000000000000000000000000000..aa7f7d7d160541177d1c78e95a6a9cdfae1184e3 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/segmentation/active_contour_model.py @@ -0,0 +1,250 @@ +import numpy as np +from scipy.interpolate import RectBivariateSpline + +from .._shared.utils import _supported_float_type +from ..util import img_as_float +from ..filters import sobel + + +def active_contour( + image, + snake, + alpha=0.01, + beta=0.1, + w_line=0.0, + w_edge=1, + gamma=0.01, + max_px_move=1.0, + max_num_iter=2500, + convergence=0.1, + *, + boundary_condition='periodic', +): + """Active contour model. + + Active contours by fitting snakes to features of images. Supports single + and multichannel 2D images. Snakes can be periodic (for segmentation) or + have fixed and/or free ends. + The output snake has the same length as the input boundary. + As the number of points is constant, make sure that the initial snake + has enough points to capture the details of the final contour. + + Parameters + ---------- + image : (M, N) or (M, N, 3) ndarray + Input image. + snake : (K, 2) ndarray + Initial snake coordinates. For periodic boundary conditions, endpoints + must not be duplicated. + alpha : float, optional + Snake length shape parameter. Higher values makes snake contract + faster. + beta : float, optional + Snake smoothness shape parameter. Higher values makes snake smoother. + w_line : float, optional + Controls attraction to brightness. Use negative values to attract + toward dark regions. + w_edge : float, optional + Controls attraction to edges. Use negative values to repel snake from + edges. + gamma : float, optional + Explicit time stepping parameter. + max_px_move : float, optional + Maximum pixel distance to move per iteration. + max_num_iter : int, optional + Maximum iterations to optimize snake shape. + convergence : float, optional + Convergence criteria. + boundary_condition : string, optional + Boundary conditions for the contour. Can be one of 'periodic', + 'free', 'fixed', 'free-fixed', or 'fixed-free'. 'periodic' attaches + the two ends of the snake, 'fixed' holds the end-points in place, + and 'free' allows free movement of the ends. 'fixed' and 'free' can + be combined by parsing 'fixed-free', 'free-fixed'. Parsing + 'fixed-fixed' or 'free-free' yields same behaviour as 'fixed' and + 'free', respectively. + + Returns + ------- + snake : (K, 2) ndarray + Optimised snake, same shape as input parameter. + + References + ---------- + .. [1] Kass, M.; Witkin, A.; Terzopoulos, D. "Snakes: Active contour + models". International Journal of Computer Vision 1 (4): 321 + (1988). :DOI:`10.1007/BF00133570` + + Examples + -------- + >>> from skimage.draw import circle_perimeter + >>> from skimage.filters import gaussian + + Create and smooth image: + + >>> img = np.zeros((100, 100)) + >>> rr, cc = circle_perimeter(35, 45, 25) + >>> img[rr, cc] = 1 + >>> img = gaussian(img, sigma=2, preserve_range=False) + + Initialize spline: + + >>> s = np.linspace(0, 2*np.pi, 100) + >>> init = 50 * np.array([np.sin(s), np.cos(s)]).T + 50 + + Fit spline to image: + + >>> snake = active_contour(img, init, w_edge=0, w_line=1) # doctest: +SKIP + >>> dist = np.sqrt((45-snake[:, 0])**2 + (35-snake[:, 1])**2) # doctest: +SKIP + >>> int(np.mean(dist)) # doctest: +SKIP + 25 + + """ + max_num_iter = int(max_num_iter) + if max_num_iter <= 0: + raise ValueError("max_num_iter should be >0.") + convergence_order = 10 + valid_bcs = [ + 'periodic', + 'free', + 'fixed', + 'free-fixed', + 'fixed-free', + 'fixed-fixed', + 'free-free', + ] + if boundary_condition not in valid_bcs: + raise ValueError( + "Invalid boundary condition.\n" + + "Should be one of: " + + ", ".join(valid_bcs) + + '.' + ) + + img = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + img = img.astype(float_dtype, copy=False) + + RGB = img.ndim == 3 + + # Find edges using sobel: + if w_edge != 0: + if RGB: + edge = [sobel(img[:, :, 0]), sobel(img[:, :, 1]), sobel(img[:, :, 2])] + else: + edge = [sobel(img)] + else: + edge = [0] + + # Superimpose intensity and edge images: + if RGB: + img = w_line * np.sum(img, axis=2) + w_edge * sum(edge) + else: + img = w_line * img + w_edge * edge[0] + + # Interpolate for smoothness: + intp = RectBivariateSpline( + np.arange(img.shape[1]), np.arange(img.shape[0]), img.T, kx=2, ky=2, s=0 + ) + + snake_xy = snake[:, ::-1] + x = snake_xy[:, 0].astype(float_dtype) + y = snake_xy[:, 1].astype(float_dtype) + n = len(x) + xsave = np.empty((convergence_order, n), dtype=float_dtype) + ysave = np.empty((convergence_order, n), dtype=float_dtype) + + # Build snake shape matrix for Euler equation in double precision + eye_n = np.eye(n, dtype=float) + a = ( + np.roll(eye_n, -1, axis=0) + np.roll(eye_n, -1, axis=1) - 2 * eye_n + ) # second order derivative, central difference + b = ( + np.roll(eye_n, -2, axis=0) + + np.roll(eye_n, -2, axis=1) + - 4 * np.roll(eye_n, -1, axis=0) + - 4 * np.roll(eye_n, -1, axis=1) + + 6 * eye_n + ) # fourth order derivative, central difference + A = -alpha * a + beta * b + + # Impose boundary conditions different from periodic: + sfixed = False + if boundary_condition.startswith('fixed'): + A[0, :] = 0 + A[1, :] = 0 + A[1, :3] = [1, -2, 1] + sfixed = True + efixed = False + if boundary_condition.endswith('fixed'): + A[-1, :] = 0 + A[-2, :] = 0 + A[-2, -3:] = [1, -2, 1] + efixed = True + sfree = False + if boundary_condition.startswith('free'): + A[0, :] = 0 + A[0, :3] = [1, -2, 1] + A[1, :] = 0 + A[1, :4] = [-1, 3, -3, 1] + sfree = True + efree = False + if boundary_condition.endswith('free'): + A[-1, :] = 0 + A[-1, -3:] = [1, -2, 1] + A[-2, :] = 0 + A[-2, -4:] = [-1, 3, -3, 1] + efree = True + + # Only one inversion is needed for implicit spline energy minimization: + inv = np.linalg.inv(A + gamma * eye_n) + # can use float_dtype once we have computed the inverse in double precision + inv = inv.astype(float_dtype, copy=False) + + # Explicit time stepping for image energy minimization: + for i in range(max_num_iter): + # RectBivariateSpline always returns float64, so call astype here + fx = intp(x, y, dx=1, grid=False).astype(float_dtype, copy=False) + fy = intp(x, y, dy=1, grid=False).astype(float_dtype, copy=False) + + if sfixed: + fx[0] = 0 + fy[0] = 0 + if efixed: + fx[-1] = 0 + fy[-1] = 0 + if sfree: + fx[0] *= 2 + fy[0] *= 2 + if efree: + fx[-1] *= 2 + fy[-1] *= 2 + xn = inv @ (gamma * x + fx) + yn = inv @ (gamma * y + fy) + + # Movements are capped to max_px_move per iteration: + dx = max_px_move * np.tanh(xn - x) + dy = max_px_move * np.tanh(yn - y) + if sfixed: + dx[0] = 0 + dy[0] = 0 + if efixed: + dx[-1] = 0 + dy[-1] = 0 + x += dx + y += dy + + # Convergence criteria needs to compare to a number of previous + # configurations since oscillations can occur. + j = i % (convergence_order + 1) + if j < convergence_order: + xsave[j, :] = x + ysave[j, :] = y + else: + dist = np.min( + np.max(np.abs(xsave - x[None, :]) + np.abs(ysave - y[None, :]), 1) + ) + if dist < convergence: + break + + return np.stack([y, x], axis=1) diff --git a/python_embeded/Lib/site-packages/skimage/segmentation/boundaries.py b/python_embeded/Lib/site-packages/skimage/segmentation/boundaries.py new file mode 100644 index 0000000000000000000000000000000000000000..c081b6d8f1140635afc9e5a5d2ec9ae43ec77f96 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/segmentation/boundaries.py @@ -0,0 +1,240 @@ +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type +from ..morphology import dilation, erosion, footprint_rectangle +from ..util import img_as_float, view_as_windows +from ..color import gray2rgb + + +def _find_boundaries_subpixel(label_img): + """See ``find_boundaries(..., mode='subpixel')``. + + Notes + ----- + This function puts in an empty row and column between each *actual* + row and column of the image, for a corresponding shape of ``2s - 1`` + for every image dimension of size ``s``. These "interstitial" rows + and columns are filled as ``True`` if they separate two labels in + `label_img`, ``False`` otherwise. + + I used ``view_as_windows`` to get the neighborhood of each pixel. + Then I check whether there are two labels or more in that + neighborhood. + """ + ndim = label_img.ndim + max_label = np.iinfo(label_img.dtype).max + + label_img_expanded = np.zeros( + [(2 * s - 1) for s in label_img.shape], label_img.dtype + ) + pixels = (slice(None, None, 2),) * ndim + label_img_expanded[pixels] = label_img + + edges = np.ones(label_img_expanded.shape, dtype=bool) + edges[pixels] = False + label_img_expanded[edges] = max_label + windows = view_as_windows(np.pad(label_img_expanded, 1, mode='edge'), (3,) * ndim) + + boundaries = np.zeros_like(edges) + for index in np.ndindex(label_img_expanded.shape): + if edges[index]: + values = np.unique(windows[index].ravel()) + if len(values) > 2: # single value and max_label + boundaries[index] = True + return boundaries + + +def find_boundaries(label_img, connectivity=1, mode='thick', background=0): + """Return bool array where boundaries between labeled regions are True. + + Parameters + ---------- + label_img : array of int or bool + An array in which different regions are labeled with either different + integers or boolean values. + connectivity : int in {1, ..., `label_img.ndim`}, optional + A pixel is considered a boundary pixel if any of its neighbors + has a different label. `connectivity` controls which pixels are + considered neighbors. A connectivity of 1 (default) means + pixels sharing an edge (in 2D) or a face (in 3D) will be + considered neighbors. A connectivity of `label_img.ndim` means + pixels sharing a corner will be considered neighbors. + mode : string in {'thick', 'inner', 'outer', 'subpixel'} + How to mark the boundaries: + + - thick: any pixel not completely surrounded by pixels of the + same label (defined by `connectivity`) is marked as a boundary. + This results in boundaries that are 2 pixels thick. + - inner: outline the pixels *just inside* of objects, leaving + background pixels untouched. + - outer: outline pixels in the background around object + boundaries. When two objects touch, their boundary is also + marked. + - subpixel: return a doubled image, with pixels *between* the + original pixels marked as boundary where appropriate. + background : int, optional + For modes 'inner' and 'outer', a definition of a background + label is required. See `mode` for descriptions of these two. + + Returns + ------- + boundaries : array of bool, same shape as `label_img` + A bool image where ``True`` represents a boundary pixel. For + `mode` equal to 'subpixel', ``boundaries.shape[i]`` is equal + to ``2 * label_img.shape[i] - 1`` for all ``i`` (a pixel is + inserted in between all other pairs of pixels). + + Examples + -------- + >>> labels = 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, 0, 0, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) + >>> find_boundaries(labels, mode='thick').astype(np.uint8) + array([[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, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> find_boundaries(labels, mode='inner').astype(np.uint8) + 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, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], + [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]], dtype=uint8) + >>> find_boundaries(labels, mode='outer').astype(np.uint8) + array([[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, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> labels_small = labels[::2, ::3] + >>> labels_small + array([[0, 0, 0, 0], + [0, 0, 5, 0], + [0, 1, 5, 0], + [0, 0, 5, 0], + [0, 0, 0, 0]], dtype=uint8) + >>> find_boundaries(labels_small, mode='subpixel').astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 0, 0, 1, 0, 1, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> bool_image = np.array([[False, False, False, False, False], + ... [False, False, False, False, False], + ... [False, False, True, True, True], + ... [False, False, True, True, True], + ... [False, False, True, True, True]], + ... dtype=bool) + >>> find_boundaries(bool_image) + array([[False, False, False, False, False], + [False, False, True, True, True], + [False, True, True, True, True], + [False, True, True, False, False], + [False, True, True, False, False]]) + """ + if label_img.dtype == 'bool': + label_img = label_img.astype(np.uint8) + ndim = label_img.ndim + footprint = ndi.generate_binary_structure(ndim, connectivity) + if mode != 'subpixel': + boundaries = dilation(label_img, footprint) != erosion(label_img, footprint) + if mode == 'inner': + foreground_image = label_img != background + boundaries &= foreground_image + elif mode == 'outer': + max_label = np.iinfo(label_img.dtype).max + background_image = label_img == background + footprint = ndi.generate_binary_structure(ndim, ndim) + inverted_background = np.array(label_img, copy=True) + inverted_background[background_image] = max_label + adjacent_objects = ( + dilation(label_img, footprint) + != erosion(inverted_background, footprint) + ) & ~background_image + boundaries &= background_image | adjacent_objects + return boundaries + else: + boundaries = _find_boundaries_subpixel(label_img) + return boundaries + + +def mark_boundaries( + image, + label_img, + color=(1, 1, 0), + outline_color=None, + mode='outer', + background_label=0, +): + """Return image with boundaries between labeled regions highlighted. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + label_img : (M, N) array of int + Label array where regions are marked by different integer values. + color : length-3 sequence, optional + RGB color of boundaries in the output image. + outline_color : length-3 sequence, optional + RGB color surrounding boundaries in the output image. If None, no + outline is drawn. + mode : string in {'thick', 'inner', 'outer', 'subpixel'}, optional + The mode for finding boundaries. + background_label : int, optional + Which label to consider background (this is only useful for + modes ``inner`` and ``outer``). + + Returns + ------- + marked : (M, N, 3) array of float + An image in which the boundaries between labels are + superimposed on the original image. + + See Also + -------- + find_boundaries + """ + float_dtype = _supported_float_type(image.dtype) + marked = img_as_float(image, force_copy=True) + marked = marked.astype(float_dtype, copy=False) + if marked.ndim == 2: + marked = gray2rgb(marked) + if mode == 'subpixel': + # Here, we want to interpose an extra line of pixels between + # each original line - except for the last axis which holds + # the RGB information. ``ndi.zoom`` then performs the (cubic) + # interpolation, filling in the values of the interposed pixels + marked = ndi.zoom( + marked, [2 - 1 / s for s in marked.shape[:-1]] + [1], mode='mirror' + ) + boundaries = find_boundaries(label_img, mode=mode, background=background_label) + if outline_color is not None: + outlines = dilation(boundaries, footprint_rectangle((3, 3))) + marked[outlines] = outline_color + marked[boundaries] = color + return marked diff --git a/python_embeded/Lib/site-packages/skimage/segmentation/morphsnakes.py b/python_embeded/Lib/site-packages/skimage/segmentation/morphsnakes.py new file mode 100644 index 0000000000000000000000000000000000000000..0d18d0cb6b0ea8982975f801657d575ceb02046e --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/segmentation/morphsnakes.py @@ -0,0 +1,449 @@ +from itertools import cycle + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD + +__all__ = [ + 'morphological_chan_vese', + 'morphological_geodesic_active_contour', + 'inverse_gaussian_gradient', + 'disk_level_set', + 'checkerboard_level_set', +] + + +class _fcycle: + def __init__(self, iterable): + """Call functions from the iterable each time it is called.""" + self.funcs = cycle(iterable) + + def __call__(self, *args, **kwargs): + f = next(self.funcs) + return f(*args, **kwargs) + + +# SI and IS operators for 2D and 3D. +_P2 = [ + np.eye(3), + np.array([[0, 1, 0]] * 3), + np.flipud(np.eye(3)), + np.rot90([[0, 1, 0]] * 3), +] +_P3 = [np.zeros((3, 3, 3)) for i in range(9)] + +_P3[0][:, :, 1] = 1 +_P3[1][:, 1, :] = 1 +_P3[2][1, :, :] = 1 +_P3[3][:, [0, 1, 2], [0, 1, 2]] = 1 +_P3[4][:, [0, 1, 2], [2, 1, 0]] = 1 +_P3[5][[0, 1, 2], :, [0, 1, 2]] = 1 +_P3[6][[0, 1, 2], :, [2, 1, 0]] = 1 +_P3[7][[0, 1, 2], [0, 1, 2], :] = 1 +_P3[8][[0, 1, 2], [2, 1, 0], :] = 1 + + +def sup_inf(u): + """SI operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + erosions = [] + for P_i in P: + erosions.append(ndi.binary_erosion(u, P_i).astype(np.int8)) + + return np.stack(erosions, axis=0).max(0) + + +def inf_sup(u): + """IS operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + dilations = [] + for P_i in P: + dilations.append(ndi.binary_dilation(u, P_i).astype(np.int8)) + + return np.stack(dilations, axis=0).min(0) + + +_curvop = _fcycle( + [lambda u: sup_inf(inf_sup(u)), lambda u: inf_sup(sup_inf(u))] # SIoIS +) # ISoSI + + +def _check_input(image, init_level_set): + """Check that shapes of `image` and `init_level_set` match.""" + check_nD(image, [2, 3]) + + if len(image.shape) != len(init_level_set.shape): + raise ValueError( + "The dimensions of the initial level set do not " + "match the dimensions of the image." + ) + + +def _init_level_set(init_level_set, image_shape): + """Auxiliary function for initializing level sets with a string. + + If `init_level_set` is not a string, it is returned as is. + """ + if isinstance(init_level_set, str): + if init_level_set == 'checkerboard': + res = checkerboard_level_set(image_shape) + elif init_level_set == 'disk': + res = disk_level_set(image_shape) + else: + raise ValueError("`init_level_set` not in " "['checkerboard', 'disk']") + else: + res = init_level_set + return res + + +def disk_level_set(image_shape, *, center=None, radius=None): + """Create a disk level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image + center : tuple of positive integers, optional + Coordinates of the center of the disk given in (row, column). If not + given, it defaults to the center of the image. + radius : float, optional + Radius of the disk. If not given, it is set to the 75% of the + smallest image dimension. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the disk with the given `radius` and `center`. + + See Also + -------- + checkerboard_level_set + """ + + if center is None: + center = tuple(i // 2 for i in image_shape) + + if radius is None: + radius = min(image_shape) * 3.0 / 8.0 + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = (grid.T - center).T + phi = radius - np.sqrt(np.sum((grid) ** 2, 0)) + res = np.int8(phi > 0) + return res + + +def checkerboard_level_set(image_shape, square_size=5): + """Create a checkerboard level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image. + square_size : int, optional + Size of the squares of the checkerboard. It defaults to 5. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the checkerboard. + + See Also + -------- + disk_level_set + """ + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = grid // square_size + + # Alternate 0/1 for even/odd numbers. + grid = grid & 1 + + checkerboard = np.bitwise_xor.reduce(grid, axis=0) + res = np.int8(checkerboard) + return res + + +def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0): + """Inverse of gradient magnitude. + + Compute the magnitude of the gradients in the image and then inverts the + result in the range [0, 1]. Flat areas are assigned values close to 1, + while areas close to borders are assigned values close to 0. + + This function or a similar one defined by the user should be applied over + the image as a preprocessing step before calling + `morphological_geodesic_active_contour`. + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume. + alpha : float, optional + Controls the steepness of the inversion. A larger value will make the + transition between the flat areas and border areas steeper in the + resulting array. + sigma : float, optional + Standard deviation of the Gaussian filter applied over the image. + + Returns + ------- + gimage : (M, N) or (L, M, N) array + Preprocessed image (or volume) suitable for + `morphological_geodesic_active_contour`. + """ + gradnorm = ndi.gaussian_gradient_magnitude(image, sigma, mode='nearest') + return 1.0 / np.sqrt(1.0 + alpha * gradnorm) + + +def morphological_chan_vese( + image, + num_iter, + init_level_set='checkerboard', + smoothing=1, + lambda1=1, + lambda2=1, + iter_callback=lambda x: None, +): + """Morphological Active Contours without Edges (MorphACWE) + + Active contours without edges implemented with morphological operators. It + can be used to segment objects in images and volumes without well defined + borders. It is required that the inside of the object looks different on + average than the outside (i.e., the inner area of the object should be + darker or lighter than the outer area on average). + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume to be segmented. + num_iter : uint + Number of num_iter to run + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + lambda1 : float, optional + Weight parameter for the outer region. If `lambda1` is larger than + `lambda2`, the outer region will contain a larger range of values than + the inner region. + lambda2 : float, optional + Weight parameter for the inner region. If `lambda2` is larger than + `lambda1`, the inner region will contain a larger range of values than + the outer region. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Chan-Vese algorithm that uses morphological + operators instead of solving a partial differential equation (PDE) for the + evolution of the contour. The set of morphological operators used in this + algorithm are proved to be infinitesimally equivalent to the Chan-Vese PDE + (see [1]_). However, morphological operators are do not suffer from the + numerical stability issues typically found in PDEs (it is not necessary to + find the right time step for the evolution), and are computationally + faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # inside = u > 0 + # outside = u <= 0 + c0 = (image * (1 - u)).sum() / float((1 - u).sum() + 1e-8) + c1 = (image * u).sum() / float(u.sum() + 1e-8) + + # Image attachment + du = np.gradient(u) + abs_du = np.abs(du).sum(0) + aux = abs_du * (lambda1 * (image - c1) ** 2 - lambda2 * (image - c0) ** 2) + + u[aux < 0] = 1 + u[aux > 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u + + +def morphological_geodesic_active_contour( + gimage, + num_iter, + init_level_set='disk', + smoothing=1, + threshold='auto', + balloon=0, + iter_callback=lambda x: None, +): + """Morphological Geodesic Active Contours (MorphGAC). + + Geodesic active contours implemented with morphological operators. It can + be used to segment objects with visible but noisy, cluttered, broken + borders. + + Parameters + ---------- + gimage : (M, N) or (L, M, N) array + Preprocessed image or volume to be segmented. This is very rarely the + original image. Instead, this is usually a preprocessed version of the + original image that enhances and highlights the borders (or other + structures) of the object to segment. + :func:`morphological_geodesic_active_contour` will try to stop the contour + evolution in areas where `gimage` is small. See + :func:`inverse_gaussian_gradient` as an example function to + perform this preprocessing. Note that the quality of + :func:`morphological_geodesic_active_contour` might greatly depend on this + preprocessing. + num_iter : uint + Number of num_iter to run. + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + threshold : float, optional + Areas of the image with a value smaller than this threshold will be + considered borders. The evolution of the contour will stop in these + areas. + balloon : float, optional + Balloon force to guide the contour in non-informative areas of the + image, i.e., areas where the gradient of the image is too small to push + the contour towards a border. A negative value will shrink the contour, + while a positive value will expand the contour in these areas. Setting + this to zero will disable the balloon force. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + inverse_gaussian_gradient, disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Geodesic Active Contours (GAC) algorithm that uses + morphological operators instead of solving partial differential equations + (PDEs) for the evolution of the contour. The set of morphological operators + used in this algorithm are proved to be infinitesimally equivalent to the + GAC PDEs (see [1]_). However, morphological operators are do not suffer + from the numerical stability issues typically found in PDEs (e.g., it is + not necessary to find the right time step for the evolution), and are + computationally faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + image = gimage + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + if threshold == 'auto': + threshold = np.percentile(image, 40) + + structure = np.ones((3,) * len(image.shape), dtype=np.int8) + dimage = np.gradient(image) + # threshold_mask = image > threshold + if balloon != 0: + threshold_mask_balloon = image > threshold / np.abs(balloon) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # Balloon + if balloon > 0: + aux = ndi.binary_dilation(u, structure) + elif balloon < 0: + aux = ndi.binary_erosion(u, structure) + if balloon != 0: + u[threshold_mask_balloon] = aux[threshold_mask_balloon] + + # Image attachment + aux = np.zeros_like(image) + du = np.gradient(u) + for el1, el2 in zip(dimage, du): + aux += el1 * el2 + u[aux > 0] = 1 + u[aux < 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u diff --git a/python_embeded/Lib/site-packages/skimage/segmentation/random_walker_segmentation.py b/python_embeded/Lib/site-packages/skimage/segmentation/random_walker_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f4701d3fd2ff11d9a986bb0bba6c078cfecd88 --- /dev/null +++ b/python_embeded/Lib/site-packages/skimage/segmentation/random_walker_segmentation.py @@ -0,0 +1,593 @@ +""" +Random walker segmentation algorithm + +from *Random walks for image segmentation*, Leo Grady, IEEE Trans +Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83. + +Installing pyamg and using the 'cg_mg' mode of random_walker improves +significantly the performance. +""" + +import numpy as np +from scipy import sparse, ndimage as ndi + +from .._shared import utils +from .._shared.utils import warn +from .._shared.compat import SCIPY_CG_TOL_PARAM_NAME + +# executive summary for next code block: try to import umfpack from +# scipy, but make sure not to raise a fuss if it fails since it's only +# needed to speed up a few cases. +# See discussions at: +# https://groups.google.com/d/msg/scikit-image/FrM5IGP6wh4/1hp-FtVZmfcJ +# https://stackoverflow.com/questions/13977970/ignore-exceptions-printed-to-stderr-in-del/13977992?noredirect=1#comment28386412_13977992 +try: + from scipy.sparse.linalg.dsolve.linsolve import umfpack + + old_del = umfpack.UmfpackContext.__del__ + + def new_del(self): + try: + old_del(self) + except AttributeError: + pass + + umfpack.UmfpackContext.__del__ = new_del + UmfpackContext = umfpack.UmfpackContext() +except ImportError: + UmfpackContext = None + +try: + from pyamg import ruge_stuben_solver + + amg_loaded = True +except ImportError: + amg_loaded = False + +from ..util import img_as_float + +from scipy.sparse.linalg import cg, spsolve + + +def _make_graph_edges_3d(n_x, n_y, n_z): + """Returns a list of edges for a 3D image. + + Parameters + ---------- + n_x : integer + The size of the grid in the x direction. + n_y : integer + The size of the grid in the y direction + n_z : integer + The size of the grid in the z direction + + Returns + ------- + edges : (2, N) ndarray + with the total number of edges:: + + N = n_x * n_y * (nz - 1) + + n_x * (n_y - 1) * nz + + (n_x - 1) * n_y * nz + + Graph edges with each column describing a node-id pair. + """ + vertices = np.arange(n_x * n_y * n_z).reshape((n_x, n_y, n_z)) + edges_deep = np.vstack((vertices[..., :-1].ravel(), vertices[..., 1:].ravel())) + edges_right = np.vstack((vertices[:, :-1].ravel(), vertices[:, 1:].ravel())) + edges_down = np.vstack((vertices[:-1].ravel(), vertices[1:].ravel())) + edges = np.hstack((edges_deep, edges_right, edges_down)) + return edges + + +def _compute_weights_3d(data, spacing, beta, eps, multichannel): + # Weight calculation is main difference in multispectral version + # Original gradient**2 replaced with sum of gradients ** 2 + gradients = ( + np.concatenate( + [ + np.diff(data[..., 0], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + for channel in range(1, data.shape[-1]): + gradients += ( + np.concatenate( + [ + np.diff(data[..., channel], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + + # All channels considered together in this standard deviation + scale_factor = -beta / (10 * data.std()) + if multichannel: + # New final term in beta to give == results in trivial case where + # multiple identical spectra are passed. + scale_factor /= np.sqrt(data.shape[-1]) + weights = np.exp(scale_factor * gradients) + weights += eps + return -weights + + +def _build_laplacian(data, spacing, mask, beta, multichannel): + l_x, l_y, l_z = data.shape[:3] + edges = _make_graph_edges_3d(l_x, l_y, l_z) + weights = _compute_weights_3d( + data, spacing, beta=beta, eps=1.0e-10, multichannel=multichannel + ) + if mask is not None: + # Remove edges of the graph connected to masked nodes, as well + # as corresponding weights of the edges. + mask0 = np.hstack( + [mask[..., :-1].ravel(), mask[:, :-1].ravel(), mask[:-1].ravel()] + ) + mask1 = np.hstack( + [mask[..., 1:].ravel(), mask[:, 1:].ravel(), mask[1:].ravel()] + ) + ind_mask = np.logical_and(mask0, mask1) + edges, weights = edges[:, ind_mask], weights[ind_mask] + + # Reassign edges labels to 0, 1, ... edges_number - 1 + _, inv_idx = np.unique(edges, return_inverse=True) + edges = inv_idx.reshape(edges.shape) + + # Build the sparse linear system + pixel_nb = l_x * l_y * l_z + i_indices = edges.ravel() + j_indices = edges[::-1].ravel() + data = np.hstack((weights, weights)) + lap = sparse.csr_array((data, (i_indices, j_indices)), shape=(pixel_nb, pixel_nb)) + lap.setdiag(-np.ravel(lap.sum(axis=0))) + return lap + + +def _build_linear_system(data, spacing, labels, nlabels, mask, beta, multichannel): + """ + Build the matrix A and rhs B of the linear system to solve. + A and B are two block of the laplacian of the image graph. + """ + if mask is None: + labels = labels.ravel() + else: + labels = labels[mask] + + indices = np.arange(labels.size) + seeds_mask = labels > 0 + unlabeled_indices = indices[~seeds_mask] + seeds_indices = indices[seeds_mask] + + lap_sparse = _build_laplacian( + data, spacing, mask=mask, beta=beta, multichannel=multichannel + ) + + rows = lap_sparse[unlabeled_indices, :] + lap_sparse = rows[:, unlabeled_indices] + B = -rows[:, seeds_indices] + + seeds = labels[seeds_mask] + seeds_mask = sparse.csc_array( + np.hstack([np.atleast_2d(seeds == lab).T for lab in range(1, nlabels + 1)]) + ) + rhs = B @ seeds_mask + + return lap_sparse, rhs + + +def _solve_linear_system(lap_sparse, B, tol, mode): + if mode is None: + mode = 'cg_j' + + if mode == 'cg_mg' and not amg_loaded: + warn( + '"cg_mg" not available, it requires pyamg to be installed. ' + 'The "cg_j" mode will be used instead.', + stacklevel=2, + ) + mode = 'cg_j' + + if mode == 'bf': + X = spsolve(lap_sparse, B.toarray()).T + else: + maxiter = None + if mode == 'cg': + if UmfpackContext is None: + warn( + '"cg" mode may be slow because UMFPACK is not available. ' + 'Consider building Scipy with UMFPACK or use a ' + 'preconditioned version of CG ("cg_j" or "cg_mg" modes).', + stacklevel=2, + ) + M = None + elif mode == 'cg_j': + n = lap_sparse.shape[-1] + M = sparse.dia_array((1.0 / lap_sparse.diagonal(), 0), shape=(n, n)) + else: + # mode == 'cg_mg' + lap_sparse.indices, lap_sparse.indptr = _safe_downcast_indices( + lap_sparse, np.int32, "index values too large for int32 mode 'cg_mg'" + ) + ml = ruge_stuben_solver(lap_sparse, coarse_solver='pinv') + M = ml.aspreconditioner(cycle='V') + maxiter = 30 + rtol = {SCIPY_CG_TOL_PARAM_NAME: tol} + cg_out = [ + cg(lap_sparse, B[:, [i]].toarray(), **rtol, atol=0, M=M, maxiter=maxiter) + for i in range(B.shape[1]) + ] + if np.any([info > 0 for _, info in cg_out]): + warn( + "Conjugate gradient convergence to tolerance not achieved. " + "Consider decreasing beta to improve system conditionning.", + stacklevel=2, + ) + X = np.asarray([x for x, _ in cg_out]) + + return X + + +def _safe_downcast_indices(A, itype, msg): + # check for safe downcasting + max_value = np.iinfo(itype).max + + if A.indptr[-1] > max_value: # indptr[-1] is max b/c indptr always sorted + raise ValueError(msg) + + if max(*A.shape) > max_value: # only check large enough arrays + if np.any(A.indices > max_value): + raise ValueError(msg) + + indices = A.indices.astype(itype, copy=False) + indptr = A.indptr.astype(itype, copy=False) + return indices, indptr + + +def _preprocess(labels): + label_values, inv_idx = np.unique(labels, return_inverse=True) + if max(label_values) <= 0: + raise ValueError( + 'No seeds provided in label image: please ensure ' + 'it contains at least one positive value' + ) + + if not (label_values == 0).any(): + warn( + 'Random walker only segments unlabeled areas, where ' + 'labels == 0. No zero valued areas in labels were ' + 'found. Returning provided labels.', + stacklevel=2, + ) + + return labels, None, None, None, None + + # If some labeled pixels are isolated inside pruned zones, prune them + # as well and keep the labels for the final output + + null_mask = labels == 0 + pos_mask = labels > 0 + mask = labels >= 0 + + fill = ndi.binary_propagation(null_mask, mask=mask) + isolated = np.logical_and(pos_mask, np.logical_not(fill)) + + pos_mask[isolated] = False + + # If the array has pruned zones, be sure that no isolated pixels + # exist between pruned zones (they could not be determined) + if label_values[0] < 0 or np.any(isolated): + isolated = np.logical_and( + np.logical_not(ndi.binary_propagation(pos_mask, mask=mask)), null_mask + ) + + labels[isolated] = -1 + if np.all(isolated[null_mask]): + warn( + 'All unlabeled pixels are isolated, they could not be ' + 'determined by the random walker algorithm.', + stacklevel=2, + ) + return labels, None, None, None, None + + mask[isolated] = False + mask = np.atleast_3d(mask) + else: + mask = None + + # Reorder label values to have consecutive integers (no gaps) + zero_idx = np.searchsorted(label_values, 0) + labels = np.atleast_3d(inv_idx.reshape(labels.shape) - zero_idx) + + nlabels = label_values[zero_idx + 1 :].shape[0] + + inds_isolated_seeds = np.nonzero(isolated) + isolated_values = labels[inds_isolated_seeds] + + return labels, nlabels, mask, inds_isolated_seeds, isolated_values + + +@utils.channel_as_last_axis(multichannel_output=False) +def random_walker( + data, + labels, + beta=130, + mode='cg_j', + tol=1.0e-3, + copy=True, + return_full_prob=False, + spacing=None, + *, + prob_tol=1e-3, + channel_axis=None, +): + """Random walker algorithm for segmentation from markers. + + Random walker algorithm is implemented for gray-level or multichannel + images. + + Parameters + ---------- + data : (M, N[, P][, C]) ndarray + Image to be segmented in phases. Gray-level `data` can be two- or + three-dimensional; multichannel data can be three- or four- + dimensional with `channel_axis` specifying the dimension containing + channels. Data spacing is assumed isotropic unless the `spacing` + keyword argument is used. + labels : (M, N[, P]) array of ints + Array of seed markers labeled with different positive integers + for different phases. Zero-labeled pixels are unlabeled pixels. + Negative labels correspond to inactive pixels that are not taken + into account (they are removed from the graph). If labels are not + consecutive integers, the labels array will be transformed so that + labels are consecutive. In the multichannel case, `labels` should have + the same shape as a single channel of `data`, i.e. without the final + dimension denoting channels. + beta : float, optional + Penalization coefficient for the random walker motion + (the greater `beta`, the more difficult the diffusion). + mode : string, available options {'cg', 'cg_j', 'cg_mg', 'bf'} + Mode for solving the linear system in the random walker algorithm. + + - 'bf' (brute force): an LU factorization of the Laplacian is + computed. This is fast for small images (<1024x1024), but very slow + and memory-intensive for large images (e.g., 3-D volumes). + - 'cg' (conjugate gradient): the linear system is solved iteratively + using the Conjugate Gradient method from scipy.sparse.linalg. This is + less memory-consuming than the brute force method for large images, + but it is quite slow. + - 'cg_j' (conjugate gradient with Jacobi preconditionner): the + Jacobi preconditionner is applied during the Conjugate + gradient method iterations. This may accelerate the + convergence of the 'cg' method. + - 'cg_mg' (conjugate gradient with multigrid preconditioner): a + preconditioner is computed using a multigrid solver, then the + solution is computed with the Conjugate Gradient method. This mode + requires that the pyamg module is installed. + tol : float, optional + Tolerance to achieve when solving the linear system using + the conjugate gradient based modes ('cg', 'cg_j' and 'cg_mg'). + copy : bool, optional + If copy is False, the `labels` array will be overwritten with + the result of the segmentation. Use copy=False if you want to + save on memory. + return_full_prob : bool, optional + If True, the probability that a pixel belongs to each of the + labels will be returned, instead of only the most likely + label. + spacing : iterable of floats, optional + Spacing between voxels in each spatial dimension. If `None`, then + the spacing between pixels/voxels in each dimension is assumed 1. + prob_tol : float, optional + Tolerance on the resulting probability to be in the interval [0, 1]. + If the tolerance is not satisfied, a warning is displayed. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + output : ndarray + * If `return_full_prob` is False, array of ints of same shape + and data type as `labels`, in which each pixel has been + labeled according to the marker that reached the pixel first + by anisotropic diffusion. + * If `return_full_prob` is True, array of floats of shape + `(nlabels, labels.shape)`. `output[label_nb, i, j]` is the + probability that label `label_nb` reaches the pixel `(i, j)` + first. + + See Also + -------- + skimage.segmentation.watershed + A segmentation algorithm based on mathematical morphology + and "flooding" of regions from markers. + + Notes + ----- + Multichannel inputs are scaled with all channel data combined. Ensure all + channels are separately normalized prior to running this algorithm. + + The `spacing` argument is specifically for anisotropic datasets, where + data points are spaced differently in one or more spatial dimensions. + Anisotropic data is commonly encountered in medical imaging. + + The algorithm was first proposed in [1]_. + + The algorithm solves the diffusion equation at infinite times for + sources placed on markers of each phase in turn. A pixel is labeled with + the phase that has the greatest probability to diffuse first to the pixel. + + The diffusion equation is solved by minimizing x.T L x for each phase, + where L is the Laplacian of the weighted graph of the image, and x is + the probability that a marker of the given phase arrives first at a pixel + by diffusion (x=1 on markers of the phase, x=0 on the other markers, and + the other coefficients are looked for). Each pixel is attributed the label + for which it has a maximal value of x. The Laplacian L of the image + is defined as: + + - L_ii = d_i, the number of neighbors of pixel i (the degree of i) + - L_ij = -w_ij if i and j are adjacent pixels + + The weight w_ij is a decreasing function of the norm of the local gradient. + This ensures that diffusion is easier between pixels of similar values. + + When the Laplacian is decomposed into blocks of marked and unmarked + pixels:: + + L = M B.T + B A + + with first indices corresponding to marked pixels, and then to unmarked + pixels, minimizing x.T L x for one phase amount to solving:: + + A x = - B x_m + + where x_m = 1 on markers of the given phase, and 0 on other markers. + This linear system is solved in the algorithm using a direct method for + small images, and an iterative method for larger images. + + References + ---------- + .. [1] Leo Grady, Random walks for image segmentation, IEEE Trans Pattern + Anal Mach Intell. 2006 Nov;28(11):1768-83. + :DOI:`10.1109/TPAMI.2006.233`. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> a = np.zeros((10, 10)) + 0.2 * rng.random((10, 10)) + >>> a[5:8, 5:8] += 1 + >>> b = np.zeros_like(a, dtype=np.int32) + >>> b[3, 3] = 1 # Marker for first phase + >>> b[6, 6] = 2 # Marker for second phase + >>> random_walker(a, b) # doctest: +SKIP + 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, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32) + + """ + # Parse input data + if mode not in ('cg_mg', 'cg', 'bf', 'cg_j', None): + raise ValueError( + f"{mode} is not a valid mode. Valid modes are 'cg_mg', " + f"'cg', 'cg_j', 'bf', and None" + ) + + if data.dtype == np.float16: + # SciPy sparse, which is used later on, doesn't officially support float16 + # This led to failures when testing with NumPy 1.26 (see gh-7635). + data = data.astype(np.float32, casting="safe") + + # Spacing kwarg checks + if spacing is None: + spacing = np.ones(3) + elif len(spacing) == labels.ndim: + if len(spacing) == 2: + # Need a dummy spacing for singleton 3rd dim + spacing = np.r_[spacing, 1.0] + spacing = np.asarray(spacing) + else: + raise ValueError( + 'Input argument `spacing` incorrect, should be an ' + 'iterable with one number per spatial dimension.' + ) + + # This algorithm expects 4-D arrays of floats, where the first three + # dimensions are spatial and the final denotes channels. 2-D images have + # a singleton placeholder dimension added for the third spatial dimension, + # and single channel images likewise have a singleton added for channels. + # The following block ensures valid input and coerces it to the correct + # form. + multichannel = channel_axis is not None + if not multichannel: + if data.ndim not in (2, 3): + raise ValueError( + 'For non-multichannel input, data must be of ' 'dimension 2 or 3.' + ) + if data.shape != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = np.atleast_3d(img_as_float(data))[..., np.newaxis] + else: + if data.ndim not in (3, 4): + raise ValueError( + 'For multichannel input, data must have 3 or 4 ' 'dimensions.' + ) + if data.shape[:-1] != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = img_as_float(data) + if data.ndim == 3: # 2D multispectral, needs singleton in 3rd axis + data = data[:, :, np.newaxis, :] + + labels_shape = labels.shape + labels_dtype = labels.dtype + + if copy: + labels = np.copy(labels) + + (labels, nlabels, mask, inds_isolated_seeds, isolated_values) = _preprocess(labels) + + if isolated_values is None: + # No non isolated zero valued areas in labels were + # found. Returning provided labels. + if return_full_prob: + # Return the concatenation of the masks of each unique label + return np.concatenate( + [np.atleast_3d(labels == lab) for lab in np.unique(labels) if lab > 0], + axis=-1, + ) + return labels + + # Build the linear system (lap_sparse, B) + lap_sparse, B = _build_linear_system( + data, spacing, labels, nlabels, mask, beta, multichannel + ) + + # Solve the linear system lap_sparse X = B + # where X[i, j] is the probability that a marker of label i arrives + # first at pixel j by anisotropic diffusion. + X = _solve_linear_system(lap_sparse, B, tol, mode) + + if X.min() < -prob_tol or X.max() > 1 + prob_tol: + warn( + 'The probability range is outside [0, 1] given the tolerance ' + '`prob_tol`. Consider decreasing `beta` and/or decreasing ' + '`tol`.' + ) + + # Build the output according to return_full_prob value + # Put back labels of isolated seeds + labels[inds_isolated_seeds] = isolated_values + labels = labels.reshape(labels_shape) + + mask = labels == 0 + mask[inds_isolated_seeds] = False + + if return_full_prob: + out = np.zeros((nlabels,) + labels_shape) + for lab, (label_prob, prob) in enumerate(zip(out, X), start=1): + label_prob[mask] = prob + label_prob[labels == lab] = 1 + else: + X = np.argmax(X, axis=0) + 1 + out = labels.astype(labels_dtype) + out[mask] = X + + return out diff --git a/python_embeded/Lib/site-packages/sklearn/.libs/msvcp140.dll b/python_embeded/Lib/site-packages/sklearn/.libs/msvcp140.dll new file mode 100644 index 0000000000000000000000000000000000000000..1d2ddcb95e9c8247311dd4bc488d8ae3d57a3b98 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/.libs/msvcp140.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e2e2bcb916931f0ee6d0a567212511244e7442da574757c331c1b91087f2a0f +size 557136 diff --git a/python_embeded/Lib/site-packages/sklearn/.libs/vcomp140.dll b/python_embeded/Lib/site-packages/sklearn/.libs/vcomp140.dll new file mode 100644 index 0000000000000000000000000000000000000000..8f6790dde403668e22c135b8bed73a1bd175870f --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/.libs/vcomp140.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac49e2e62421880bd76fa5945a5dc6130f603cfe663537b41b6610fd10730ca2 +size 192616 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40966/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40966/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_42074/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_42074/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_42585/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_42585/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_561/__init__.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_561/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_classification.txt b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_classification.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4b53167c4ccc823f78f880014aa7cd89cf7cccd --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_classification.txt @@ -0,0 +1,9 @@ +# comment +# note: the next line contains a tab +1.0 3:2.5 11:-5.2 16:1.5 # and an inline comment +2.0 6:1.0 13:-3 +# another comment +3.0 21:27 +4.0 2:1.234567890123456e10 # double precision value +1.0 # empty line, all zeros +2.0 3:0 # explicit zeros diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid.txt b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f97ffaabf6f1bc869647273924dac8b2b3662d1 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid.txt @@ -0,0 +1,3 @@ +python 2:2.5 10:-5.2 15:1.5 +2.0 5:1.0 12:-3 +3.0 20:27 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid_order.txt b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid_order.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a98bf580658b4fc8e432819bcf0248d2d04d4af --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_invalid_order.txt @@ -0,0 +1 @@ +-1 5:2.5 2:-5.2 15:1.5 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_multilabel.txt b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_multilabel.txt new file mode 100644 index 0000000000000000000000000000000000000000..9731a8c4e1d750ed1667b10491675207c55a316c --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/svmlight_multilabel.txt @@ -0,0 +1,5 @@ +# multilabel dataset in SVMlight format +1,0 2:2.5 10:-5.2 15:1.5 +2 5:1.0 12:-3 + 2:3.5 11:26 +1,2 20:27 diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_20news.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_20news.py new file mode 100644 index 0000000000000000000000000000000000000000..ea56465eada836596719dda790533cc5783fdf3a --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_20news.py @@ -0,0 +1,143 @@ +"""Test the 20news downloader, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs).""" + +from functools import partial +from unittest.mock import patch + +import numpy as np +import pytest +import scipy.sparse as sp + +from sklearn.datasets.tests.test_common import ( + check_as_frame, + check_pandas_dependency_message, + check_return_X_y, +) +from sklearn.preprocessing import normalize +from sklearn.utils._testing import assert_allclose_dense_sparse + + +def test_20news(fetch_20newsgroups_fxt): + data = fetch_20newsgroups_fxt(subset="all", shuffle=False) + assert data.DESCR.startswith(".. _20newsgroups_dataset:") + + # Extract a reduced dataset + data2cats = fetch_20newsgroups_fxt( + subset="all", categories=data.target_names[-1:-3:-1], shuffle=False + ) + # Check that the ordering of the target_names is the same + # as the ordering in the full dataset + assert data2cats.target_names == data.target_names[-2:] + # Assert that we have only 0 and 1 as labels + assert np.unique(data2cats.target).tolist() == [0, 1] + + # Check that the number of filenames is consistent with data/target + assert len(data2cats.filenames) == len(data2cats.target) + assert len(data2cats.filenames) == len(data2cats.data) + + # Check that the first entry of the reduced dataset corresponds to + # the first entry of the corresponding category in the full dataset + entry1 = data2cats.data[0] + category = data2cats.target_names[data2cats.target[0]] + label = data.target_names.index(category) + entry2 = data.data[np.where(data.target == label)[0][0]] + assert entry1 == entry2 + + # check that return_X_y option + X, y = fetch_20newsgroups_fxt(subset="all", shuffle=False, return_X_y=True) + assert len(X) == len(data.data) + assert y.shape == data.target.shape + + +def test_20news_length_consistency(fetch_20newsgroups_fxt): + """Checks the length consistencies within the bunch + + This is a non-regression test for a bug present in 0.16.1. + """ + # Extract the full dataset + data = fetch_20newsgroups_fxt(subset="all") + assert len(data["data"]) == len(data.data) + assert len(data["target"]) == len(data.target) + assert len(data["filenames"]) == len(data.filenames) + + +def test_20news_vectorized(fetch_20newsgroups_vectorized_fxt): + # test subset = train + bunch = fetch_20newsgroups_vectorized_fxt(subset="train") + assert sp.issparse(bunch.data) and bunch.data.format == "csr" + assert bunch.data.shape == (11314, 130107) + assert bunch.target.shape[0] == 11314 + assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") + + # test subset = test + bunch = fetch_20newsgroups_vectorized_fxt(subset="test") + assert sp.issparse(bunch.data) and bunch.data.format == "csr" + assert bunch.data.shape == (7532, 130107) + assert bunch.target.shape[0] == 7532 + assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") + + # test return_X_y option + fetch_func = partial(fetch_20newsgroups_vectorized_fxt, subset="test") + check_return_X_y(bunch, fetch_func) + + # test subset = all + bunch = fetch_20newsgroups_vectorized_fxt(subset="all") + assert sp.issparse(bunch.data) and bunch.data.format == "csr" + assert bunch.data.shape == (11314 + 7532, 130107) + assert bunch.target.shape[0] == 11314 + 7532 + assert bunch.data.dtype == np.float64 + assert bunch.DESCR.startswith(".. _20newsgroups_dataset:") + + +def test_20news_normalization(fetch_20newsgroups_vectorized_fxt): + X = fetch_20newsgroups_vectorized_fxt(normalize=False) + X_ = fetch_20newsgroups_vectorized_fxt(normalize=True) + X_norm = X_["data"][:100] + X = X["data"][:100] + + assert_allclose_dense_sparse(X_norm, normalize(X)) + assert np.allclose(np.linalg.norm(X_norm.todense(), axis=1), 1) + + +def test_20news_as_frame(fetch_20newsgroups_vectorized_fxt): + pd = pytest.importorskip("pandas") + + bunch = fetch_20newsgroups_vectorized_fxt(as_frame=True) + check_as_frame(bunch, fetch_20newsgroups_vectorized_fxt) + + frame = bunch.frame + assert frame.shape == (11314, 130108) + assert all([isinstance(col, pd.SparseDtype) for col in bunch.data.dtypes]) + + # Check a small subset of features + for expected_feature in [ + "beginner", + "beginners", + "beginning", + "beginnings", + "begins", + "begley", + "begone", + ]: + assert expected_feature in frame.keys() + assert "category_class" in frame.keys() + assert bunch.target.name == "category_class" + + +def test_as_frame_no_pandas(fetch_20newsgroups_vectorized_fxt, hide_available_pandas): + check_pandas_dependency_message(fetch_20newsgroups_vectorized_fxt) + + +def test_outdated_pickle(fetch_20newsgroups_vectorized_fxt): + with patch("os.path.exists") as mock_is_exist: + with patch("joblib.load") as mock_load: + # mock that the dataset was cached + mock_is_exist.return_value = True + # mock that we have an outdated pickle with only X and y returned + mock_load.return_value = ("X", "y") + err_msg = "The cached dataset located in" + with pytest.raises(ValueError, match=err_msg): + fetch_20newsgroups_vectorized_fxt(as_frame=True) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_arff_parser.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_arff_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d7be2c045ae52002d832c6187075519579af65 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_arff_parser.py @@ -0,0 +1,284 @@ +import textwrap +from io import BytesIO + +import pytest + +from sklearn.datasets._arff_parser import ( + _liac_arff_parser, + _pandas_arff_parser, + _post_process_frame, + load_arff_from_gzip_file, +) + + +@pytest.mark.parametrize( + "feature_names, target_names", + [ + ( + [ + "col_int_as_integer", + "col_int_as_numeric", + "col_float_as_real", + "col_float_as_numeric", + ], + ["col_categorical", "col_string"], + ), + ( + [ + "col_int_as_integer", + "col_int_as_numeric", + "col_float_as_real", + "col_float_as_numeric", + ], + ["col_categorical"], + ), + ( + [ + "col_int_as_integer", + "col_int_as_numeric", + "col_float_as_real", + "col_float_as_numeric", + ], + [], + ), + ], +) +def test_post_process_frame(feature_names, target_names): + """Check the behaviour of the post-processing function for splitting a dataframe.""" + pd = pytest.importorskip("pandas") + + X_original = pd.DataFrame( + { + "col_int_as_integer": [1, 2, 3], + "col_int_as_numeric": [1, 2, 3], + "col_float_as_real": [1.0, 2.0, 3.0], + "col_float_as_numeric": [1.0, 2.0, 3.0], + "col_categorical": ["a", "b", "c"], + "col_string": ["a", "b", "c"], + } + ) + + X, y = _post_process_frame(X_original, feature_names, target_names) + assert isinstance(X, pd.DataFrame) + if len(target_names) >= 2: + assert isinstance(y, pd.DataFrame) + elif len(target_names) == 1: + assert isinstance(y, pd.Series) + else: + assert y is None + + +def test_load_arff_from_gzip_file_error_parser(): + """An error will be raised if the parser is not known.""" + # None of the input parameters are required to be accurate since the check + # of the parser will be carried out first. + + err_msg = "Unknown parser: 'xxx'. Should be 'liac-arff' or 'pandas'" + with pytest.raises(ValueError, match=err_msg): + load_arff_from_gzip_file("xxx", "xxx", "xxx", "xxx", "xxx", "xxx") + + +@pytest.mark.parametrize("parser_func", [_liac_arff_parser, _pandas_arff_parser]) +def test_pandas_arff_parser_strip_single_quotes(parser_func): + """Check that we properly strip single quotes from the data.""" + pd = pytest.importorskip("pandas") + + arff_file = BytesIO( + textwrap.dedent( + """ + @relation 'toy' + @attribute 'cat_single_quote' {'A', 'B', 'C'} + @attribute 'str_single_quote' string + @attribute 'str_nested_quote' string + @attribute 'class' numeric + @data + 'A','some text','\"expect double quotes\"',0 + """ + ).encode("utf-8") + ) + + columns_info = { + "cat_single_quote": { + "data_type": "nominal", + "name": "cat_single_quote", + }, + "str_single_quote": { + "data_type": "string", + "name": "str_single_quote", + }, + "str_nested_quote": { + "data_type": "string", + "name": "str_nested_quote", + }, + "class": { + "data_type": "numeric", + "name": "class", + }, + } + + feature_names = [ + "cat_single_quote", + "str_single_quote", + "str_nested_quote", + ] + target_names = ["class"] + + # We don't strip single quotes for string columns with the pandas parser. + expected_values = { + "cat_single_quote": "A", + "str_single_quote": ( + "some text" if parser_func is _liac_arff_parser else "'some text'" + ), + "str_nested_quote": ( + '"expect double quotes"' + if parser_func is _liac_arff_parser + else "'\"expect double quotes\"'" + ), + "class": 0, + } + + _, _, frame, _ = parser_func( + arff_file, + output_arrays_type="pandas", + openml_columns_info=columns_info, + feature_names_to_select=feature_names, + target_names_to_select=target_names, + ) + + assert frame.columns.tolist() == feature_names + target_names + pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0)) + + +@pytest.mark.parametrize("parser_func", [_liac_arff_parser, _pandas_arff_parser]) +def test_pandas_arff_parser_strip_double_quotes(parser_func): + """Check that we properly strip double quotes from the data.""" + pd = pytest.importorskip("pandas") + + arff_file = BytesIO( + textwrap.dedent( + """ + @relation 'toy' + @attribute 'cat_double_quote' {"A", "B", "C"} + @attribute 'str_double_quote' string + @attribute 'str_nested_quote' string + @attribute 'class' numeric + @data + "A","some text","\'expect double quotes\'",0 + """ + ).encode("utf-8") + ) + + columns_info = { + "cat_double_quote": { + "data_type": "nominal", + "name": "cat_double_quote", + }, + "str_double_quote": { + "data_type": "string", + "name": "str_double_quote", + }, + "str_nested_quote": { + "data_type": "string", + "name": "str_nested_quote", + }, + "class": { + "data_type": "numeric", + "name": "class", + }, + } + + feature_names = [ + "cat_double_quote", + "str_double_quote", + "str_nested_quote", + ] + target_names = ["class"] + + expected_values = { + "cat_double_quote": "A", + "str_double_quote": "some text", + "str_nested_quote": "'expect double quotes'", + "class": 0, + } + + _, _, frame, _ = parser_func( + arff_file, + output_arrays_type="pandas", + openml_columns_info=columns_info, + feature_names_to_select=feature_names, + target_names_to_select=target_names, + ) + + assert frame.columns.tolist() == feature_names + target_names + pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0)) + + +@pytest.mark.parametrize( + "parser_func", + [ + # internal quotes are not considered to follow the ARFF spec in LIAC ARFF + pytest.param(_liac_arff_parser, marks=pytest.mark.xfail), + _pandas_arff_parser, + ], +) +def test_pandas_arff_parser_strip_no_quotes(parser_func): + """Check that we properly parse with no quotes characters.""" + pd = pytest.importorskip("pandas") + + arff_file = BytesIO( + textwrap.dedent( + """ + @relation 'toy' + @attribute 'cat_without_quote' {A, B, C} + @attribute 'str_without_quote' string + @attribute 'str_internal_quote' string + @attribute 'class' numeric + @data + A,some text,'internal' quote,0 + """ + ).encode("utf-8") + ) + + columns_info = { + "cat_without_quote": { + "data_type": "nominal", + "name": "cat_without_quote", + }, + "str_without_quote": { + "data_type": "string", + "name": "str_without_quote", + }, + "str_internal_quote": { + "data_type": "string", + "name": "str_internal_quote", + }, + "class": { + "data_type": "numeric", + "name": "class", + }, + } + + feature_names = [ + "cat_without_quote", + "str_without_quote", + "str_internal_quote", + ] + target_names = ["class"] + + expected_values = { + "cat_without_quote": "A", + "str_without_quote": "some text", + "str_internal_quote": "'internal' quote", + "class": 0, + } + + _, _, frame, _ = parser_func( + arff_file, + output_arrays_type="pandas", + openml_columns_info=columns_info, + feature_names_to_select=feature_names, + target_names_to_select=target_names, + ) + + assert frame.columns.tolist() == feature_names + target_names + pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0)) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_base.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b3103426ab757d81b15b23f255a55259fc490e3a --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_base.py @@ -0,0 +1,658 @@ +import hashlib +import io +import os +import re +import shutil +import tempfile +import warnings +from functools import partial +from importlib import resources +from pathlib import Path +from pickle import dumps, loads +from unittest.mock import Mock +from urllib.error import HTTPError +from urllib.parse import urlparse + +import numpy as np +import pytest + +from sklearn.datasets import ( + clear_data_home, + fetch_file, + get_data_home, + load_breast_cancer, + load_diabetes, + load_digits, + load_files, + load_iris, + load_linnerud, + load_sample_image, + load_sample_images, + load_wine, +) +from sklearn.datasets._base import ( + RemoteFileMetadata, + _derive_folder_and_filename_from_url, + _fetch_remote, + load_csv_data, + load_gzip_compressed_csv_data, +) +from sklearn.datasets.tests.test_common import check_as_frame +from sklearn.preprocessing import scale +from sklearn.utils import Bunch + + +class _DummyPath: + """Minimal class that implements the os.PathLike interface.""" + + def __init__(self, path): + self.path = path + + def __fspath__(self): + return self.path + + +def _remove_dir(path): + if os.path.isdir(path): + shutil.rmtree(path) + + +@pytest.fixture(scope="module") +def data_home(tmpdir_factory): + tmp_file = str(tmpdir_factory.mktemp("scikit_learn_data_home_test")) + yield tmp_file + _remove_dir(tmp_file) + + +@pytest.fixture(scope="module") +def load_files_root(tmpdir_factory): + tmp_file = str(tmpdir_factory.mktemp("scikit_learn_load_files_test")) + yield tmp_file + _remove_dir(tmp_file) + + +@pytest.fixture +def test_category_dir_1(load_files_root): + test_category_dir1 = tempfile.mkdtemp(dir=load_files_root) + sample_file = tempfile.NamedTemporaryFile(dir=test_category_dir1, delete=False) + sample_file.write(b"Hello World!\n") + sample_file.close() + yield str(test_category_dir1) + _remove_dir(test_category_dir1) + + +@pytest.fixture +def test_category_dir_2(load_files_root): + test_category_dir2 = tempfile.mkdtemp(dir=load_files_root) + yield str(test_category_dir2) + _remove_dir(test_category_dir2) + + +@pytest.mark.parametrize("path_container", [None, Path, _DummyPath]) +def test_data_home(path_container, data_home): + # get_data_home will point to a pre-existing folder + if path_container is not None: + data_home = path_container(data_home) + data_home = get_data_home(data_home=data_home) + assert data_home == data_home + assert os.path.exists(data_home) + + # clear_data_home will delete both the content and the folder it-self + if path_container is not None: + data_home = path_container(data_home) + clear_data_home(data_home=data_home) + assert not os.path.exists(data_home) + + # if the folder is missing it will be created again + data_home = get_data_home(data_home=data_home) + assert os.path.exists(data_home) + + +def test_default_empty_load_files(load_files_root): + res = load_files(load_files_root) + assert len(res.filenames) == 0 + assert len(res.target_names) == 0 + assert res.DESCR is None + + +def test_default_load_files(test_category_dir_1, test_category_dir_2, load_files_root): + res = load_files(load_files_root) + assert len(res.filenames) == 1 + assert len(res.target_names) == 2 + assert res.DESCR is None + assert res.data == [b"Hello World!\n"] + + +def test_load_files_w_categories_desc_and_encoding( + test_category_dir_1, test_category_dir_2, load_files_root +): + category = os.path.abspath(test_category_dir_1).split(os.sep).pop() + res = load_files( + load_files_root, description="test", categories=[category], encoding="utf-8" + ) + + assert len(res.filenames) == 1 + assert len(res.target_names) == 1 + assert res.DESCR == "test" + assert res.data == ["Hello World!\n"] + + +def test_load_files_wo_load_content( + test_category_dir_1, test_category_dir_2, load_files_root +): + res = load_files(load_files_root, load_content=False) + assert len(res.filenames) == 1 + assert len(res.target_names) == 2 + assert res.DESCR is None + assert res.get("data") is None + + +@pytest.mark.parametrize("allowed_extensions", ([".txt"], [".txt", ".json"])) +def test_load_files_allowed_extensions(tmp_path, allowed_extensions): + """Check the behaviour of `allowed_extension` in `load_files`.""" + d = tmp_path / "sub" + d.mkdir() + files = ("file1.txt", "file2.json", "file3.json", "file4.md") + paths = [d / f for f in files] + for p in paths: + p.write_bytes(b"hello") + res = load_files(tmp_path, allowed_extensions=allowed_extensions) + assert set([str(p) for p in paths if p.suffix in allowed_extensions]) == set( + res.filenames + ) + + +@pytest.mark.parametrize( + "filename, expected_n_samples, expected_n_features, expected_target_names", + [ + ("wine_data.csv", 178, 13, ["class_0", "class_1", "class_2"]), + ("iris.csv", 150, 4, ["setosa", "versicolor", "virginica"]), + ("breast_cancer.csv", 569, 30, ["malignant", "benign"]), + ], +) +def test_load_csv_data( + filename, expected_n_samples, expected_n_features, expected_target_names +): + actual_data, actual_target, actual_target_names = load_csv_data(filename) + assert actual_data.shape[0] == expected_n_samples + assert actual_data.shape[1] == expected_n_features + assert actual_target.shape[0] == expected_n_samples + np.testing.assert_array_equal(actual_target_names, expected_target_names) + + +def test_load_csv_data_with_descr(): + data_file_name = "iris.csv" + descr_file_name = "iris.rst" + + res_without_descr = load_csv_data(data_file_name=data_file_name) + res_with_descr = load_csv_data( + data_file_name=data_file_name, descr_file_name=descr_file_name + ) + assert len(res_with_descr) == 4 + assert len(res_without_descr) == 3 + + np.testing.assert_array_equal(res_with_descr[0], res_without_descr[0]) + np.testing.assert_array_equal(res_with_descr[1], res_without_descr[1]) + np.testing.assert_array_equal(res_with_descr[2], res_without_descr[2]) + + assert res_with_descr[-1].startswith(".. _iris_dataset:") + + +@pytest.mark.parametrize( + "filename, kwargs, expected_shape", + [ + ("diabetes_data_raw.csv.gz", {}, [442, 10]), + ("diabetes_target.csv.gz", {}, [442]), + ("digits.csv.gz", {"delimiter": ","}, [1797, 65]), + ], +) +def test_load_gzip_compressed_csv_data(filename, kwargs, expected_shape): + actual_data = load_gzip_compressed_csv_data(filename, **kwargs) + assert actual_data.shape == tuple(expected_shape) + + +def test_load_gzip_compressed_csv_data_with_descr(): + data_file_name = "diabetes_target.csv.gz" + descr_file_name = "diabetes.rst" + + expected_data = load_gzip_compressed_csv_data(data_file_name=data_file_name) + actual_data, descr = load_gzip_compressed_csv_data( + data_file_name=data_file_name, + descr_file_name=descr_file_name, + ) + + np.testing.assert_array_equal(actual_data, expected_data) + assert descr.startswith(".. _diabetes_dataset:") + + +def test_load_sample_images(): + try: + res = load_sample_images() + assert len(res.images) == 2 + assert len(res.filenames) == 2 + images = res.images + + # assert is china image + assert np.all(images[0][0, 0, :] == np.array([174, 201, 231], dtype=np.uint8)) + # assert is flower image + assert np.all(images[1][0, 0, :] == np.array([2, 19, 13], dtype=np.uint8)) + assert res.DESCR + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_sample_image(): + try: + china = load_sample_image("china.jpg") + assert china.dtype == "uint8" + assert china.shape == (427, 640, 3) + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_diabetes_raw(): + """Test to check that we load a scaled version by default but that we can + get an unscaled version when setting `scaled=False`.""" + diabetes_raw = load_diabetes(scaled=False) + assert diabetes_raw.data.shape == (442, 10) + assert diabetes_raw.target.size == 442 + assert len(diabetes_raw.feature_names) == 10 + assert diabetes_raw.DESCR + + diabetes_default = load_diabetes() + + np.testing.assert_allclose( + scale(diabetes_raw.data) / (442**0.5), diabetes_default.data, atol=1e-04 + ) + + +@pytest.mark.parametrize( + "loader_func, data_shape, target_shape, n_target, has_descr, filenames", + [ + (load_breast_cancer, (569, 30), (569,), 2, True, ["filename"]), + (load_wine, (178, 13), (178,), 3, True, []), + (load_iris, (150, 4), (150,), 3, True, ["filename"]), + ( + load_linnerud, + (20, 3), + (20, 3), + 3, + True, + ["data_filename", "target_filename"], + ), + (load_diabetes, (442, 10), (442,), None, True, []), + (load_digits, (1797, 64), (1797,), 10, True, []), + (partial(load_digits, n_class=9), (1617, 64), (1617,), 10, True, []), + ], +) +def test_loader(loader_func, data_shape, target_shape, n_target, has_descr, filenames): + bunch = loader_func() + + assert isinstance(bunch, Bunch) + assert bunch.data.shape == data_shape + assert bunch.target.shape == target_shape + if hasattr(bunch, "feature_names"): + assert len(bunch.feature_names) == data_shape[1] + if n_target is not None: + assert len(bunch.target_names) == n_target + if has_descr: + assert bunch.DESCR + if filenames: + assert "data_module" in bunch + assert all( + [ + f in bunch + and (resources.files(bunch["data_module"]) / bunch[f]).is_file() + for f in filenames + ] + ) + + +@pytest.mark.parametrize( + "loader_func, data_dtype, target_dtype", + [ + (load_breast_cancer, np.float64, int), + (load_diabetes, np.float64, np.float64), + (load_digits, np.float64, int), + (load_iris, np.float64, int), + (load_linnerud, np.float64, np.float64), + (load_wine, np.float64, int), + ], +) +def test_toy_dataset_frame_dtype(loader_func, data_dtype, target_dtype): + default_result = loader_func() + check_as_frame( + default_result, + loader_func, + expected_data_dtype=data_dtype, + expected_target_dtype=target_dtype, + ) + + +def test_loads_dumps_bunch(): + bunch = Bunch(x="x") + bunch_from_pkl = loads(dumps(bunch)) + bunch_from_pkl.x = "y" + assert bunch_from_pkl["x"] == bunch_from_pkl.x + + +def test_bunch_pickle_generated_with_0_16_and_read_with_0_17(): + bunch = Bunch(key="original") + # This reproduces a problem when Bunch pickles have been created + # with scikit-learn 0.16 and are read with 0.17. Basically there + # is a surprising behaviour because reading bunch.key uses + # bunch.__dict__ (which is non empty for 0.16 Bunch objects) + # whereas assigning into bunch.key uses bunch.__setattr__. See + # https://github.com/scikit-learn/scikit-learn/issues/6196 for + # more details + bunch.__dict__["key"] = "set from __dict__" + bunch_from_pkl = loads(dumps(bunch)) + # After loading from pickle the __dict__ should have been ignored + assert bunch_from_pkl.key == "original" + assert bunch_from_pkl["key"] == "original" + # Making sure that changing the attr does change the value + # associated with __getitem__ as well + bunch_from_pkl.key = "changed" + assert bunch_from_pkl.key == "changed" + assert bunch_from_pkl["key"] == "changed" + + +def test_bunch_dir(): + # check that dir (important for autocomplete) shows attributes + data = load_iris() + assert "data" in dir(data) + + +def test_load_boston_error(): + """Check that we raise the ethical warning when trying to import `load_boston`.""" + msg = "The Boston housing prices dataset has an ethical problem" + with pytest.raises(ImportError, match=msg): + from sklearn.datasets import load_boston # noqa: F401 + + # other non-existing function should raise the usual import error + msg = "cannot import name 'non_existing_function' from 'sklearn.datasets'" + with pytest.raises(ImportError, match=msg): + from sklearn.datasets import non_existing_function # noqa: F401 + + +def test_fetch_remote_raise_warnings_with_invalid_url(monkeypatch): + """Check retry mechanism in _fetch_remote.""" + + url = "https://scikit-learn.org/this_file_does_not_exist.tar.gz" + invalid_remote_file = RemoteFileMetadata("invalid_file", url, None) + urlretrieve_mock = Mock( + side_effect=HTTPError( + url=url, code=404, msg="Not Found", hdrs=None, fp=io.BytesIO() + ) + ) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + with pytest.warns(UserWarning, match="Retry downloading") as record: + with pytest.raises(HTTPError, match="HTTP Error 404"): + _fetch_remote(invalid_remote_file, n_retries=3, delay=0) + + assert urlretrieve_mock.call_count == 4 + + for r in record: + assert str(r.message) == f"Retry downloading from url: {url}" + assert len(record) == 3 + + +def test_derive_folder_and_filename_from_url(): + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/file.tar.gz" + ) + assert folder == "example.com" + assert filename == "file.tar.gz" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/نمونه نماینده.data" + ) + assert folder == "example.com" + assert filename == "نمونه-نماینده.data" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/to-/.file.tar.gz" + ) + assert folder == "example.com/path_to" + assert filename == "file.tar.gz" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com/") + assert folder == "example.com" + assert filename == "downloaded_file" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com") + assert folder == "example.com" + assert filename == "downloaded_file" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/@to/data.json?param=value" + ) + assert folder == "example.com/path_to" + assert filename == "data.json" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/path/@@to._/-_.data.json.#anchor" + ) + assert folder == "example.com/path_to" + assert filename == "data.json" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com//some_file.txt" + ) + assert folder == "example.com" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "http://example/../some_file.txt" + ) + assert folder == "example" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/!.'.,/some_file.txt" + ) + assert folder == "example.com" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url( + "https://example.com/a/!.'.,/b/some_file.txt" + ) + assert folder == "example.com/a_b" + assert filename == "some_file.txt" + + folder, filename = _derive_folder_and_filename_from_url("https://example.com/!.'.,") + assert folder == "example.com" + assert filename == "downloaded_file" + + with pytest.raises(ValueError, match="Invalid URL"): + _derive_folder_and_filename_from_url("https:/../") + + +def _mock_urlretrieve(server_side): + def _urlretrieve_mock(url, local_path): + server_root = Path(server_side) + file_path = urlparse(url).path.strip("/") + if not (server_root / file_path).exists(): + raise HTTPError(url, 404, "Not Found", None, None) + shutil.copy(server_root / file_path, local_path) + + return Mock(side_effect=_urlretrieve_mock) + + +def test_fetch_file_using_data_home(monkeypatch, tmpdir): + tmpdir = Path(tmpdir) + server_side = tmpdir / "server_side" + server_side.mkdir() + data_file = server_side / "data.jsonl" + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + + server_subfolder = server_side / "subfolder" + server_subfolder.mkdir() + other_data_file = server_subfolder / "other_file.txt" + other_data_file.write_text("Some important text data.", encoding="utf-8") + + data_home = tmpdir / "data_home" + data_home.mkdir() + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + monkeypatch.setattr( + "sklearn.datasets._base.get_data_home", Mock(return_value=data_home) + ) + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + ) + assert fetched_file_path == data_home / "example.com" / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + + fetched_file_path = fetch_file( + "https://example.com/subfolder/other_file.txt", + ) + assert ( + fetched_file_path == data_home / "example.com" / "subfolder" / "other_file.txt" + ) + assert fetched_file_path.read_text(encoding="utf-8") == other_data_file.read_text( + "utf-8" + ) + + expected_warning_msg = re.escape( + "Retry downloading from url: https://example.com/subfolder/invalid.txt" + ) + with pytest.raises(HTTPError): + with pytest.warns(match=expected_warning_msg): + fetch_file( + "https://example.com/subfolder/invalid.txt", + delay=0, + ) + + local_subfolder = data_home / "example.com" / "subfolder" + assert sorted(local_subfolder.iterdir()) == [local_subfolder / "other_file.txt"] + + +def test_fetch_file_without_sha256(monkeypatch, tmpdir): + server_side = tmpdir.mkdir("server_side") + data_file = Path(server_side / "data.jsonl") + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + + client_side = tmpdir.mkdir("client_side") + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + # The first call should trigger a download: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Fetching again the same file to the same folder should do nothing: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Deleting and calling again should re-download + fetched_file_path.unlink() + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + +def test_fetch_file_with_sha256(monkeypatch, tmpdir): + server_side = tmpdir.mkdir("server_side") + data_file = Path(server_side / "data.jsonl") + server_data = '{"a": 1, "b": 2}\n' + data_file.write_text(server_data, encoding="utf-8") + expected_sha256 = hashlib.sha256(data_file.read_bytes()).hexdigest() + + client_side = tmpdir.mkdir("client_side") + + urlretrieve_mock = _mock_urlretrieve(server_side) + monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock) + + # The first call should trigger a download. + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Fetching again the same file to the same folder should do nothing when + # the sha256 match: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 1 + + # Corrupting the local data should yield a warning and trigger a new download: + fetched_file_path.write_text("corrupted contents", encoding="utf-8") + expected_msg = ( + r"SHA256 checksum of existing local file data.jsonl " + rf"\(.*\) differs from expected \({expected_sha256}\): " + r"re-downloading from https://example.com/data.jsonl \." + ) + with pytest.warns(match=expected_msg): + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + # Calling again should do nothing: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 2 + + # Deleting the local file and calling again should redownload without warning: + fetched_file_path.unlink() + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256 + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 3 + + # Calling without a sha256 should also work without redownloading: + fetched_file_path = fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + ) + assert fetched_file_path == client_side / "data.jsonl" + assert fetched_file_path.read_text(encoding="utf-8") == server_data + assert urlretrieve_mock.call_count == 3 + + # Calling with a wrong sha256 should raise an informative exception: + non_matching_sha256 = "deadbabecafebeef" + expected_warning_msg = "differs from expected" + expected_error_msg = re.escape( + f"The SHA256 checksum of data.jsonl ({expected_sha256}) differs from " + f"expected ({non_matching_sha256})." + ) + with pytest.raises(OSError, match=expected_error_msg): + with pytest.warns(match=expected_warning_msg): + fetch_file( + "https://example.com/data.jsonl", + folder=client_side, + sha256=non_matching_sha256, + ) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_common.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..5417a3bd8bbb1bc9095c2bab761869b902af5128 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_common.py @@ -0,0 +1,136 @@ +"""Test loaders for common functionality.""" + +import inspect +import os + +import numpy as np +import pytest + +import sklearn.datasets + + +def is_pillow_installed(): + try: + import PIL # noqa: F401 + + return True + except ImportError: + return False + + +FETCH_PYTEST_MARKERS = { + "return_X_y": { + "fetch_20newsgroups": pytest.mark.xfail( + reason="X is a list and does not have a shape argument" + ), + "fetch_openml": pytest.mark.xfail( + reason="fetch_opeml requires a dataset name or id" + ), + "fetch_lfw_people": pytest.mark.skipif( + not is_pillow_installed(), reason="pillow is not installed" + ), + }, + "as_frame": { + "fetch_openml": pytest.mark.xfail( + reason="fetch_opeml requires a dataset name or id" + ), + }, +} + + +def check_pandas_dependency_message(fetch_func): + try: + import pandas # noqa: F401 + + pytest.skip("This test requires pandas to not be installed") + except ImportError: + # Check that pandas is imported lazily and that an informative error + # message is raised when pandas is missing: + name = fetch_func.__name__ + expected_msg = f"{name} with as_frame=True requires pandas" + with pytest.raises(ImportError, match=expected_msg): + fetch_func(as_frame=True) + + +def check_return_X_y(bunch, dataset_func): + X_y_tuple = dataset_func(return_X_y=True) + assert isinstance(X_y_tuple, tuple) + assert X_y_tuple[0].shape == bunch.data.shape + assert X_y_tuple[1].shape == bunch.target.shape + + +def check_as_frame( + bunch, dataset_func, expected_data_dtype=None, expected_target_dtype=None +): + pd = pytest.importorskip("pandas") + frame_bunch = dataset_func(as_frame=True) + assert hasattr(frame_bunch, "frame") + assert isinstance(frame_bunch.frame, pd.DataFrame) + assert isinstance(frame_bunch.data, pd.DataFrame) + assert frame_bunch.data.shape == bunch.data.shape + if frame_bunch.target.ndim > 1: + assert isinstance(frame_bunch.target, pd.DataFrame) + else: + assert isinstance(frame_bunch.target, pd.Series) + assert frame_bunch.target.shape[0] == bunch.target.shape[0] + if expected_data_dtype is not None: + assert np.all(frame_bunch.data.dtypes == expected_data_dtype) + if expected_target_dtype is not None: + assert np.all(frame_bunch.target.dtypes == expected_target_dtype) + + # Test for return_X_y and as_frame=True + frame_X, frame_y = dataset_func(as_frame=True, return_X_y=True) + assert isinstance(frame_X, pd.DataFrame) + if frame_y.ndim > 1: + assert isinstance(frame_X, pd.DataFrame) + else: + assert isinstance(frame_y, pd.Series) + + +def _skip_network_tests(): + return os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", "1") == "1" + + +def _generate_func_supporting_param(param, dataset_type=("load", "fetch")): + markers_fetch = FETCH_PYTEST_MARKERS.get(param, {}) + for name, obj in inspect.getmembers(sklearn.datasets): + if not inspect.isfunction(obj): + continue + + is_dataset_type = any([name.startswith(t) for t in dataset_type]) + is_support_param = param in inspect.signature(obj).parameters + if is_dataset_type and is_support_param: + # check if we should skip if we don't have network support + marks = [ + pytest.mark.skipif( + condition=name.startswith("fetch") and _skip_network_tests(), + reason="Skip because fetcher requires internet network", + ) + ] + if name in markers_fetch: + marks.append(markers_fetch[name]) + + yield pytest.param(name, obj, marks=marks) + + +@pytest.mark.parametrize( + "name, dataset_func", _generate_func_supporting_param("return_X_y") +) +def test_common_check_return_X_y(name, dataset_func): + bunch = dataset_func() + check_return_X_y(bunch, dataset_func) + + +@pytest.mark.parametrize( + "name, dataset_func", _generate_func_supporting_param("as_frame") +) +def test_common_check_as_frame(name, dataset_func): + bunch = dataset_func() + check_as_frame(bunch, dataset_func) + + +@pytest.mark.parametrize( + "name, dataset_func", _generate_func_supporting_param("as_frame") +) +def test_common_check_pandas_dependency(name, dataset_func): + check_pandas_dependency_message(dataset_func) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_covtype.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_covtype.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4a3624fd010e55be9e417a6c29f3fa2c49e2cf --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_covtype.py @@ -0,0 +1,55 @@ +"""Test the covtype loader, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs).""" + +from functools import partial + +import pytest + +from sklearn.datasets.tests.test_common import check_return_X_y + + +def test_fetch(fetch_covtype_fxt, global_random_seed): + data1 = fetch_covtype_fxt(shuffle=True, random_state=global_random_seed) + data2 = fetch_covtype_fxt(shuffle=True, random_state=global_random_seed + 1) + + X1, X2 = data1["data"], data2["data"] + assert (581012, 54) == X1.shape + assert X1.shape == X2.shape + + assert X1.sum() == X2.sum() + + y1, y2 = data1["target"], data2["target"] + assert (X1.shape[0],) == y1.shape + assert (X1.shape[0],) == y2.shape + + descr_prefix = ".. _covtype_dataset:" + assert data1.DESCR.startswith(descr_prefix) + assert data2.DESCR.startswith(descr_prefix) + + # test return_X_y option + fetch_func = partial(fetch_covtype_fxt) + check_return_X_y(data1, fetch_func) + + +def test_fetch_asframe(fetch_covtype_fxt): + pytest.importorskip("pandas") + + bunch = fetch_covtype_fxt(as_frame=True) + assert hasattr(bunch, "frame") + frame = bunch.frame + assert frame.shape == (581012, 55) + assert bunch.data.shape == (581012, 54) + assert bunch.target.shape == (581012,) + + column_names = set(frame.columns) + + # enumerated names are added correctly + assert set(f"Wilderness_Area_{i}" for i in range(4)) < column_names + assert set(f"Soil_Type_{i}" for i in range(40)) < column_names + + +def test_pandas_dependency_message(fetch_covtype_fxt, hide_available_pandas): + expected_msg = "fetch_covtype with as_frame=True requires pandas" + with pytest.raises(ImportError, match=expected_msg): + fetch_covtype_fxt(as_frame=True) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_kddcup99.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_kddcup99.py new file mode 100644 index 0000000000000000000000000000000000000000..2eaafddcaaf16ccbe576476cf654c366b10a61fa --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_kddcup99.py @@ -0,0 +1,89 @@ +"""Test kddcup99 loader, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs). + +Only 'percent10' mode is tested, as the full data +is too big to use in unit-testing. +""" + +from functools import partial + +import pytest + +from sklearn.datasets.tests.test_common import ( + check_as_frame, + check_pandas_dependency_message, + check_return_X_y, +) + + +@pytest.mark.parametrize("as_frame", [True, False]) +@pytest.mark.parametrize( + "subset, n_samples, n_features", + [ + (None, 494021, 41), + ("SA", 100655, 41), + ("SF", 73237, 4), + ("http", 58725, 3), + ("smtp", 9571, 3), + ], +) +def test_fetch_kddcup99_percent10( + fetch_kddcup99_fxt, as_frame, subset, n_samples, n_features +): + data = fetch_kddcup99_fxt(subset=subset, as_frame=as_frame) + assert data.data.shape == (n_samples, n_features) + assert data.target.shape == (n_samples,) + if as_frame: + assert data.frame.shape == (n_samples, n_features + 1) + assert data.DESCR.startswith(".. _kddcup99_dataset:") + + +def test_fetch_kddcup99_return_X_y(fetch_kddcup99_fxt): + fetch_func = partial(fetch_kddcup99_fxt, subset="smtp") + data = fetch_func() + check_return_X_y(data, fetch_func) + + +def test_fetch_kddcup99_as_frame(fetch_kddcup99_fxt): + bunch = fetch_kddcup99_fxt() + check_as_frame(bunch, fetch_kddcup99_fxt) + + +def test_fetch_kddcup99_shuffle(fetch_kddcup99_fxt): + dataset = fetch_kddcup99_fxt( + random_state=0, + subset="SA", + percent10=True, + ) + dataset_shuffled = fetch_kddcup99_fxt( + random_state=0, + subset="SA", + shuffle=True, + percent10=True, + ) + assert set(dataset["target"]) == set(dataset_shuffled["target"]) + assert dataset_shuffled.data.shape == dataset.data.shape + assert dataset_shuffled.target.shape == dataset.target.shape + + +def test_pandas_dependency_message(fetch_kddcup99_fxt, hide_available_pandas): + check_pandas_dependency_message(fetch_kddcup99_fxt) + + +def test_corrupted_file_error_message(fetch_kddcup99_fxt, tmp_path): + """Check that a nice error message is raised when cache is corrupted.""" + kddcup99_dir = tmp_path / "kddcup99_10-py3" + kddcup99_dir.mkdir() + samples_path = kddcup99_dir / "samples" + + with samples_path.open("wb") as f: + f.write(b"THIS IS CORRUPTED") + + msg = ( + "The cache for fetch_kddcup99 is invalid, please " + f"delete {kddcup99_dir} and run the fetch_kddcup99 again" + ) + + with pytest.raises(OSError, match=msg): + fetch_kddcup99_fxt(data_home=str(tmp_path)) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_lfw.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_lfw.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b546058362c8d614f8110e7b34c7b33f0d3b94 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_lfw.py @@ -0,0 +1,229 @@ +"""This test for the LFW require medium-size data downloading and processing + +If the data has not been already downloaded by running the examples, +the tests won't run (skipped). + +If the test are run, the first execution will be long (typically a bit +more than a couple of minutes) but as the dataset loader is leveraging +joblib, successive runs will be fast (less than 200ms). +""" + +import random +from functools import partial + +import numpy as np +import pytest + +from sklearn.datasets import fetch_lfw_pairs, fetch_lfw_people +from sklearn.datasets.tests.test_common import check_return_X_y +from sklearn.utils._testing import assert_array_equal + +FAKE_NAMES = [ + "Abdelatif_Smith", + "Abhati_Kepler", + "Camara_Alvaro", + "Chen_Dupont", + "John_Lee", + "Lin_Bauman", + "Onur_Lopez", +] + + +@pytest.fixture(scope="module") +def mock_empty_data_home(tmp_path_factory): + data_dir = tmp_path_factory.mktemp("scikit_learn_empty_test") + + yield data_dir + + +@pytest.fixture(scope="module") +def mock_data_home(tmp_path_factory): + """Test fixture run once and common to all tests of this module""" + Image = pytest.importorskip("PIL.Image") + + data_dir = tmp_path_factory.mktemp("scikit_learn_lfw_test") + lfw_home = data_dir / "lfw_home" + lfw_home.mkdir(parents=True, exist_ok=True) + + random_state = random.Random(42) + np_rng = np.random.RandomState(42) + + # generate some random jpeg files for each person + counts = {} + for name in FAKE_NAMES: + folder_name = lfw_home / "lfw_funneled" / name + folder_name.mkdir(parents=True, exist_ok=True) + + n_faces = np_rng.randint(1, 5) + counts[name] = n_faces + for i in range(n_faces): + file_path = folder_name / (name + "_%04d.jpg" % i) + uniface = np_rng.randint(0, 255, size=(250, 250, 3)) + img = Image.fromarray(uniface.astype(np.uint8)) + img.save(file_path) + + # add some random file pollution to test robustness + (lfw_home / "lfw_funneled" / ".test.swp").write_bytes( + b"Text file to be ignored by the dataset loader." + ) + + # generate some pairing metadata files using the same format as LFW + with open(lfw_home / "pairsDevTrain.txt", "wb") as f: + f.write(b"10\n") + more_than_two = [name for name, count in counts.items() if count >= 2] + for i in range(5): + name = random_state.choice(more_than_two) + first, second = random_state.sample(range(counts[name]), 2) + f.write(("%s\t%d\t%d\n" % (name, first, second)).encode()) + + for i in range(5): + first_name, second_name = random_state.sample(FAKE_NAMES, 2) + first_index = np_rng.choice(np.arange(counts[first_name])) + second_index = np_rng.choice(np.arange(counts[second_name])) + f.write( + ( + "%s\t%d\t%s\t%d\n" + % (first_name, first_index, second_name, second_index) + ).encode() + ) + + (lfw_home / "pairsDevTest.txt").write_bytes( + b"Fake place holder that won't be tested" + ) + (lfw_home / "pairs.txt").write_bytes(b"Fake place holder that won't be tested") + + yield data_dir + + +def test_load_empty_lfw_people(mock_empty_data_home): + with pytest.raises(OSError): + fetch_lfw_people(data_home=mock_empty_data_home, download_if_missing=False) + + +def test_load_fake_lfw_people(mock_data_home): + lfw_people = fetch_lfw_people( + data_home=mock_data_home, min_faces_per_person=3, download_if_missing=False + ) + + # The data is croped around the center as a rectangular bounding box + # around the face. Colors are converted to gray levels: + assert lfw_people.images.shape == (10, 62, 47) + assert lfw_people.data.shape == (10, 2914) + + # the target is array of person integer ids + assert_array_equal(lfw_people.target, [2, 0, 1, 0, 2, 0, 2, 1, 1, 2]) + + # names of the persons can be found using the target_names array + expected_classes = ["Abdelatif Smith", "Abhati Kepler", "Onur Lopez"] + assert_array_equal(lfw_people.target_names, expected_classes) + + # It is possible to ask for the original data without any croping or color + # conversion and not limit on the number of picture per person + lfw_people = fetch_lfw_people( + data_home=mock_data_home, + resize=None, + slice_=None, + color=True, + download_if_missing=False, + ) + assert lfw_people.images.shape == (17, 250, 250, 3) + assert lfw_people.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:") + + # the ids and class names are the same as previously + assert_array_equal( + lfw_people.target, [0, 0, 1, 6, 5, 6, 3, 6, 0, 3, 6, 1, 2, 4, 5, 1, 2] + ) + assert_array_equal( + lfw_people.target_names, + [ + "Abdelatif Smith", + "Abhati Kepler", + "Camara Alvaro", + "Chen Dupont", + "John Lee", + "Lin Bauman", + "Onur Lopez", + ], + ) + + # test return_X_y option + fetch_func = partial( + fetch_lfw_people, + data_home=mock_data_home, + resize=None, + slice_=None, + color=True, + download_if_missing=False, + ) + check_return_X_y(lfw_people, fetch_func) + + +def test_load_fake_lfw_people_too_restrictive(mock_data_home): + with pytest.raises(ValueError): + fetch_lfw_people( + data_home=mock_data_home, + min_faces_per_person=100, + download_if_missing=False, + ) + + +def test_load_empty_lfw_pairs(mock_empty_data_home): + with pytest.raises(OSError): + fetch_lfw_pairs(data_home=mock_empty_data_home, download_if_missing=False) + + +def test_load_fake_lfw_pairs(mock_data_home): + lfw_pairs_train = fetch_lfw_pairs( + data_home=mock_data_home, download_if_missing=False + ) + + # The data is croped around the center as a rectangular bounding box + # around the face. Colors are converted to gray levels: + assert lfw_pairs_train.pairs.shape == (10, 2, 62, 47) + + # the target is whether the person is the same or not + assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) + + # names of the persons can be found using the target_names array + expected_classes = ["Different persons", "Same person"] + assert_array_equal(lfw_pairs_train.target_names, expected_classes) + + # It is possible to ask for the original data without any croping or color + # conversion + lfw_pairs_train = fetch_lfw_pairs( + data_home=mock_data_home, + resize=None, + slice_=None, + color=True, + download_if_missing=False, + ) + assert lfw_pairs_train.pairs.shape == (10, 2, 250, 250, 3) + + # the ids and class names are the same as previously + assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) + assert_array_equal(lfw_pairs_train.target_names, expected_classes) + + assert lfw_pairs_train.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:") + + +def test_fetch_lfw_people_internal_cropping(mock_data_home): + """Check that we properly crop the images. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/24942 + """ + # If cropping was not done properly and we don't resize the images, the images would + # have their original size (250x250) and the image would not fit in the NumPy array + # pre-allocated based on `slice_` parameter. + slice_ = (slice(70, 195), slice(78, 172)) + lfw = fetch_lfw_people( + data_home=mock_data_home, + min_faces_per_person=3, + download_if_missing=False, + resize=None, + slice_=slice_, + ) + assert lfw.images[0].shape == ( + slice_[0].stop - slice_[0].start, + slice_[1].stop - slice_[1].start, + ) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_olivetti_faces.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_olivetti_faces.py new file mode 100644 index 0000000000000000000000000000000000000000..83c377dbd3bee37778c10911856c4a3554bf3668 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_olivetti_faces.py @@ -0,0 +1,26 @@ +"""Test Olivetti faces fetcher, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs).""" + +import numpy as np + +from sklearn.datasets.tests.test_common import check_return_X_y +from sklearn.utils import Bunch +from sklearn.utils._testing import assert_array_equal + + +def test_olivetti_faces(fetch_olivetti_faces_fxt): + data = fetch_olivetti_faces_fxt(shuffle=True, random_state=0) + + assert isinstance(data, Bunch) + for expected_keys in ("data", "images", "target", "DESCR"): + assert expected_keys in data.keys() + + assert data.data.shape == (400, 4096) + assert data.images.shape == (400, 64, 64) + assert data.target.shape == (400,) + assert_array_equal(np.unique(np.sort(data.target)), np.arange(40)) + assert data.DESCR.startswith(".. _olivetti_faces_dataset:") + + # test the return_X_y option + check_return_X_y(data, fetch_olivetti_faces_fxt) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_openml.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_openml.py new file mode 100644 index 0000000000000000000000000000000000000000..db44396c7c562713c2b08f65fc92bca2b721820a --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_openml.py @@ -0,0 +1,1634 @@ +"""Test the openml loader.""" + +import gzip +import json +import os +import re +from functools import partial +from importlib import resources +from io import BytesIO +from urllib.error import HTTPError + +import numpy as np +import pytest +import scipy.sparse + +import sklearn +from sklearn import config_context +from sklearn.datasets import fetch_openml as fetch_openml_orig +from sklearn.datasets._openml import ( + _get_local_path, + _open_openml_url, + _retry_with_clean_cache, +) +from sklearn.utils import Bunch +from sklearn.utils._optional_dependencies import check_pandas_support +from sklearn.utils._testing import ( + SkipTest, + assert_allclose, + assert_array_equal, +) + +OPENML_TEST_DATA_MODULE = "sklearn.datasets.tests.data.openml" +# if True, urlopen will be monkey patched to only use local files +test_offline = True +_MONKEY_PATCH_LOCAL_OPENML_PATH = "data/v1/download/{}" + + +class _MockHTTPResponse: + def __init__(self, data, is_gzip): + self.data = data + self.is_gzip = is_gzip + + def read(self, amt=-1): + return self.data.read(amt) + + def close(self): + self.data.close() + + def info(self): + if self.is_gzip: + return {"Content-Encoding": "gzip"} + return {} + + def __iter__(self): + return iter(self.data) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + return False + + +# Disable the disk-based cache when testing `fetch_openml`: +# the mock data in sklearn/datasets/tests/data/openml/ is not always consistent +# with the version on openml.org. If one were to load the dataset outside of +# the tests, it may result in data that does not represent openml.org. +fetch_openml = partial(fetch_openml_orig, data_home=None) + + +def _monkey_patch_webbased_functions(context, data_id, gzip_response): + # monkey patches the urlopen function. Important note: Do NOT use this + # in combination with a regular cache directory, as the files that are + # stored as cache should not be mixed up with real openml datasets + url_prefix_data_description = "https://api.openml.org/api/v1/json/data/" + url_prefix_data_features = "https://api.openml.org/api/v1/json/data/features/" + url_prefix_download_data = "https://www.openml.org/data/v1/download" + url_prefix_data_list = "https://api.openml.org/api/v1/json/data/list/" + + path_suffix = ".gz" + read_fn = gzip.open + + data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}" + + def _file_name(url, suffix): + output = ( + re.sub(r"\W", "-", url[len("https://api.openml.org/") :]) + + suffix + + path_suffix + ) + # Shorten the filenames to have better compatibility with windows 10 + # and filenames > 260 characters + return ( + output.replace("-json-data-list", "-jdl") + .replace("-json-data-features", "-jdf") + .replace("-json-data-qualities", "-jdq") + .replace("-json-data", "-jd") + .replace("-data_name", "-dn") + .replace("-download", "-dl") + .replace("-limit", "-l") + .replace("-data_version", "-dv") + .replace("-status", "-s") + .replace("-deactivated", "-dact") + .replace("-active", "-act") + ) + + def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): + assert url.startswith(expected_prefix), ( + f"{expected_prefix!r} does not match {url!r}" + ) + + data_file_name = _file_name(url, suffix) + data_file_path = resources.files(data_module) / data_file_name + + with data_file_path.open("rb") as f: + if has_gzip_header and gzip_response: + fp = BytesIO(f.read()) + return _MockHTTPResponse(fp, True) + else: + decompressed_f = read_fn(f, "rb") + fp = BytesIO(decompressed_f.read()) + return _MockHTTPResponse(fp, False) + + def _mock_urlopen_data_description(url, has_gzip_header): + return _mock_urlopen_shared( + url=url, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_data_description, + suffix=".json", + ) + + def _mock_urlopen_data_features(url, has_gzip_header): + return _mock_urlopen_shared( + url=url, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_data_features, + suffix=".json", + ) + + def _mock_urlopen_download_data(url, has_gzip_header): + # For simplicity the mock filenames don't contain the filename, i.e. + # the last part of the data description url after the last /. + # For example for id_1, data description download url is: + # gunzip -c sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz | grep '"url" # noqa: E501 + # "https:\/\/www.openml.org\/data\/v1\/download\/1\/anneal.arff" + # but the mock filename does not contain anneal.arff and is: + # sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz. + # We only keep the part of the url before the last / + url_without_filename = url.rsplit("/", 1)[0] + + return _mock_urlopen_shared( + url=url_without_filename, + has_gzip_header=has_gzip_header, + expected_prefix=url_prefix_download_data, + suffix=".arff", + ) + + def _mock_urlopen_data_list(url, has_gzip_header): + assert url.startswith(url_prefix_data_list), ( + f"{url_prefix_data_list!r} does not match {url!r}" + ) + + data_file_name = _file_name(url, ".json") + data_file_path = resources.files(data_module) / data_file_name + + # load the file itself, to simulate a http error + with data_file_path.open("rb") as f: + decompressed_f = read_fn(f, "rb") + decoded_s = decompressed_f.read().decode("utf-8") + json_data = json.loads(decoded_s) + if "error" in json_data: + raise HTTPError( + url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO() + ) + + with data_file_path.open("rb") as f: + if has_gzip_header: + fp = BytesIO(f.read()) + return _MockHTTPResponse(fp, True) + else: + decompressed_f = read_fn(f, "rb") + fp = BytesIO(decompressed_f.read()) + return _MockHTTPResponse(fp, False) + + def _mock_urlopen(request, *args, **kwargs): + url = request.get_full_url() + has_gzip_header = request.get_header("Accept-encoding") == "gzip" + if url.startswith(url_prefix_data_list): + return _mock_urlopen_data_list(url, has_gzip_header) + elif url.startswith(url_prefix_data_features): + return _mock_urlopen_data_features(url, has_gzip_header) + elif url.startswith(url_prefix_download_data): + return _mock_urlopen_download_data(url, has_gzip_header) + elif url.startswith(url_prefix_data_description): + return _mock_urlopen_data_description(url, has_gzip_header) + else: + raise ValueError("Unknown mocking URL pattern: %s" % url) + + # XXX: Global variable + if test_offline: + context.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen) + + +############################################################################### +# Test the behaviour of `fetch_openml` depending of the input parameters. + + +@pytest.mark.parametrize( + "data_id, dataset_params, n_samples, n_features, n_targets", + [ + # iris + (61, {"data_id": 61}, 150, 4, 1), + (61, {"name": "iris", "version": 1}, 150, 4, 1), + # anneal + (2, {"data_id": 2}, 11, 38, 1), + (2, {"name": "anneal", "version": 1}, 11, 38, 1), + # cpu + (561, {"data_id": 561}, 209, 7, 1), + (561, {"name": "cpu", "version": 1}, 209, 7, 1), + # emotions + (40589, {"data_id": 40589}, 13, 72, 6), + # adult-census + (1119, {"data_id": 1119}, 10, 14, 1), + (1119, {"name": "adult-census"}, 10, 14, 1), + # miceprotein + (40966, {"data_id": 40966}, 7, 77, 1), + (40966, {"name": "MiceProtein"}, 7, 77, 1), + # titanic + (40945, {"data_id": 40945}, 1309, 13, 1), + ], +) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_fetch_openml_as_frame_true( + monkeypatch, + data_id, + dataset_params, + n_samples, + n_features, + n_targets, + parser, + gzip_response, +): + """Check the behaviour of `fetch_openml` with `as_frame=True`. + + Fetch by ID and/or name (depending if the file was previously cached). + """ + pd = pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response) + bunch = fetch_openml( + as_frame=True, + cache=False, + parser=parser, + **dataset_params, + ) + + assert int(bunch.details["id"]) == data_id + assert isinstance(bunch, Bunch) + + assert isinstance(bunch.frame, pd.DataFrame) + assert bunch.frame.shape == (n_samples, n_features + n_targets) + + assert isinstance(bunch.data, pd.DataFrame) + assert bunch.data.shape == (n_samples, n_features) + + if n_targets == 1: + assert isinstance(bunch.target, pd.Series) + assert bunch.target.shape == (n_samples,) + else: + assert isinstance(bunch.target, pd.DataFrame) + assert bunch.target.shape == (n_samples, n_targets) + + assert bunch.categories is None + + +@pytest.mark.parametrize( + "data_id, dataset_params, n_samples, n_features, n_targets", + [ + # iris + (61, {"data_id": 61}, 150, 4, 1), + (61, {"name": "iris", "version": 1}, 150, 4, 1), + # anneal + (2, {"data_id": 2}, 11, 38, 1), + (2, {"name": "anneal", "version": 1}, 11, 38, 1), + # cpu + (561, {"data_id": 561}, 209, 7, 1), + (561, {"name": "cpu", "version": 1}, 209, 7, 1), + # emotions + (40589, {"data_id": 40589}, 13, 72, 6), + # adult-census + (1119, {"data_id": 1119}, 10, 14, 1), + (1119, {"name": "adult-census"}, 10, 14, 1), + # miceprotein + (40966, {"data_id": 40966}, 7, 77, 1), + (40966, {"name": "MiceProtein"}, 7, 77, 1), + ], +) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_as_frame_false( + monkeypatch, + data_id, + dataset_params, + n_samples, + n_features, + n_targets, + parser, +): + """Check the behaviour of `fetch_openml` with `as_frame=False`. + + Fetch both by ID and/or name + version. + """ + pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + bunch = fetch_openml( + as_frame=False, + cache=False, + parser=parser, + **dataset_params, + ) + assert int(bunch.details["id"]) == data_id + assert isinstance(bunch, Bunch) + + assert bunch.frame is None + + assert isinstance(bunch.data, np.ndarray) + assert bunch.data.shape == (n_samples, n_features) + + assert isinstance(bunch.target, np.ndarray) + if n_targets == 1: + assert bunch.target.shape == (n_samples,) + else: + assert bunch.target.shape == (n_samples, n_targets) + + assert isinstance(bunch.categories, dict) + + +@pytest.mark.parametrize("data_id", [61, 1119, 40945]) +def test_fetch_openml_consistency_parser(monkeypatch, data_id): + """Check the consistency of the LIAC-ARFF and pandas parsers.""" + pd = pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + bunch_liac = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser="liac-arff", + ) + bunch_pandas = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser="pandas", + ) + + # The data frames for the input features should match up to some numerical + # dtype conversions (e.g. float64 <=> Int64) due to limitations of the + # LIAC-ARFF parser. + data_liac, data_pandas = bunch_liac.data, bunch_pandas.data + + def convert_numerical_dtypes(series): + pandas_series = data_pandas[series.name] + if pd.api.types.is_numeric_dtype(pandas_series): + return series.astype(pandas_series.dtype) + else: + return series + + data_liac_with_fixed_dtypes = data_liac.apply(convert_numerical_dtypes) + pd.testing.assert_frame_equal(data_liac_with_fixed_dtypes, data_pandas) + + # Let's also check that the .frame attributes also match + frame_liac, frame_pandas = bunch_liac.frame, bunch_pandas.frame + + # Note that the .frame attribute is a superset of the .data attribute: + pd.testing.assert_frame_equal(frame_pandas[bunch_pandas.feature_names], data_pandas) + + # However the remaining columns, typically the target(s), are not necessarily + # dtyped similarly by both parsers due to limitations of the LIAC-ARFF parser. + # Therefore, extra dtype conversions are required for those columns: + + def convert_numerical_and_categorical_dtypes(series): + pandas_series = frame_pandas[series.name] + if pd.api.types.is_numeric_dtype(pandas_series): + return series.astype(pandas_series.dtype) + elif isinstance(pandas_series.dtype, pd.CategoricalDtype): + # Compare categorical features by converting categorical liac uses + # strings to denote the categories, we rename the categories to make + # them comparable to the pandas parser. Fixing this behavior in + # LIAC-ARFF would allow to check the consistency in the future but + # we do not plan to maintain the LIAC-ARFF on the long term. + return series.cat.rename_categories(pandas_series.cat.categories) + else: + return series + + frame_liac_with_fixed_dtypes = frame_liac.apply( + convert_numerical_and_categorical_dtypes + ) + pd.testing.assert_frame_equal(frame_liac_with_fixed_dtypes, frame_pandas) + + +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): + """Check the equivalence of the dataset when using `as_frame=False` and + `as_frame=True`. + """ + pytest.importorskip("pandas") + + data_id = 61 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + bunch_as_frame_true = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser=parser, + ) + + bunch_as_frame_false = fetch_openml( + data_id=data_id, + as_frame=False, + cache=False, + parser=parser, + ) + + assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data) + assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target) + + +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_iris_pandas(monkeypatch, parser): + """Check fetching on a numerical only dataset with string labels.""" + pd = pytest.importorskip("pandas") + CategoricalDtype = pd.api.types.CategoricalDtype + data_id = 61 + data_shape = (150, 4) + target_shape = (150,) + frame_shape = (150, 5) + + target_dtype = CategoricalDtype( + ["Iris-setosa", "Iris-versicolor", "Iris-virginica"] + ) + data_dtypes = [np.float64] * 4 + data_names = ["sepallength", "sepalwidth", "petallength", "petalwidth"] + target_name = "class" + + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + + bunch = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser=parser, + ) + data = bunch.data + target = bunch.target + frame = bunch.frame + + assert isinstance(data, pd.DataFrame) + assert np.all(data.dtypes == data_dtypes) + assert data.shape == data_shape + assert np.all(data.columns == data_names) + assert np.all(bunch.feature_names == data_names) + assert bunch.target_names == [target_name] + + assert isinstance(target, pd.Series) + assert target.dtype == target_dtype + assert target.shape == target_shape + assert target.name == target_name + assert target.index.is_unique + + assert isinstance(frame, pd.DataFrame) + assert frame.shape == frame_shape + assert np.all(frame.dtypes == data_dtypes + [target_dtype]) + assert frame.index.is_unique + + +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +@pytest.mark.parametrize("target_column", ["petalwidth", ["petalwidth", "petallength"]]) +def test_fetch_openml_forcing_targets(monkeypatch, parser, target_column): + """Check that we can force the target to not be the default target.""" + pd = pytest.importorskip("pandas") + + data_id = 61 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + bunch_forcing_target = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + target_column=target_column, + parser=parser, + ) + bunch_default = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser=parser, + ) + + pd.testing.assert_frame_equal(bunch_forcing_target.frame, bunch_default.frame) + if isinstance(target_column, list): + pd.testing.assert_index_equal( + bunch_forcing_target.target.columns, pd.Index(target_column) + ) + assert bunch_forcing_target.data.shape == (150, 3) + else: + assert bunch_forcing_target.target.name == target_column + assert bunch_forcing_target.data.shape == (150, 4) + + +@pytest.mark.parametrize("data_id", [61, 2, 561, 40589, 1119]) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_equivalence_frame_return_X_y(monkeypatch, data_id, parser): + """Check the behaviour of `return_X_y=True` when `as_frame=True`.""" + pd = pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + bunch = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + return_X_y=False, + parser=parser, + ) + X, y = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + return_X_y=True, + parser=parser, + ) + + pd.testing.assert_frame_equal(bunch.data, X) + if isinstance(y, pd.Series): + pd.testing.assert_series_equal(bunch.target, y) + else: + pd.testing.assert_frame_equal(bunch.target, y) + + +@pytest.mark.parametrize("data_id", [61, 561, 40589, 1119]) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_equivalence_array_return_X_y(monkeypatch, data_id, parser): + """Check the behaviour of `return_X_y=True` when `as_frame=False`.""" + pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + bunch = fetch_openml( + data_id=data_id, + as_frame=False, + cache=False, + return_X_y=False, + parser=parser, + ) + X, y = fetch_openml( + data_id=data_id, + as_frame=False, + cache=False, + return_X_y=True, + parser=parser, + ) + + assert_array_equal(bunch.data, X) + assert_array_equal(bunch.target, y) + + +def test_fetch_openml_difference_parsers(monkeypatch): + """Check the difference between liac-arff and pandas parser.""" + pytest.importorskip("pandas") + + data_id = 1119 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) + # When `as_frame=False`, the categories will be ordinally encoded with + # liac-arff parser while this is not the case with pandas parser. + as_frame = False + bunch_liac_arff = fetch_openml( + data_id=data_id, + as_frame=as_frame, + cache=False, + parser="liac-arff", + ) + bunch_pandas = fetch_openml( + data_id=data_id, + as_frame=as_frame, + cache=False, + parser="pandas", + ) + + assert bunch_liac_arff.data.dtype.kind == "f" + assert bunch_pandas.data.dtype == "O" + + +############################################################################### +# Test the ARFF parsing on several dataset to check if detect the correct +# types (categories, integers, floats). + + +@pytest.fixture(scope="module") +def datasets_column_names(): + """Returns the columns names for each dataset.""" + return { + 61: ["sepallength", "sepalwidth", "petallength", "petalwidth", "class"], + 2: [ + "family", + "product-type", + "steel", + "carbon", + "hardness", + "temper_rolling", + "condition", + "formability", + "strength", + "non-ageing", + "surface-finish", + "surface-quality", + "enamelability", + "bc", + "bf", + "bt", + "bw%2Fme", + "bl", + "m", + "chrom", + "phos", + "cbond", + "marvi", + "exptl", + "ferro", + "corr", + "blue%2Fbright%2Fvarn%2Fclean", + "lustre", + "jurofm", + "s", + "p", + "shape", + "thick", + "width", + "len", + "oil", + "bore", + "packing", + "class", + ], + 561: ["vendor", "MYCT", "MMIN", "MMAX", "CACH", "CHMIN", "CHMAX", "class"], + 40589: [ + "Mean_Acc1298_Mean_Mem40_Centroid", + "Mean_Acc1298_Mean_Mem40_Rolloff", + "Mean_Acc1298_Mean_Mem40_Flux", + "Mean_Acc1298_Mean_Mem40_MFCC_0", + "Mean_Acc1298_Mean_Mem40_MFCC_1", + "Mean_Acc1298_Mean_Mem40_MFCC_2", + "Mean_Acc1298_Mean_Mem40_MFCC_3", + "Mean_Acc1298_Mean_Mem40_MFCC_4", + "Mean_Acc1298_Mean_Mem40_MFCC_5", + "Mean_Acc1298_Mean_Mem40_MFCC_6", + "Mean_Acc1298_Mean_Mem40_MFCC_7", + "Mean_Acc1298_Mean_Mem40_MFCC_8", + "Mean_Acc1298_Mean_Mem40_MFCC_9", + "Mean_Acc1298_Mean_Mem40_MFCC_10", + "Mean_Acc1298_Mean_Mem40_MFCC_11", + "Mean_Acc1298_Mean_Mem40_MFCC_12", + "Mean_Acc1298_Std_Mem40_Centroid", + "Mean_Acc1298_Std_Mem40_Rolloff", + "Mean_Acc1298_Std_Mem40_Flux", + "Mean_Acc1298_Std_Mem40_MFCC_0", + "Mean_Acc1298_Std_Mem40_MFCC_1", + "Mean_Acc1298_Std_Mem40_MFCC_2", + "Mean_Acc1298_Std_Mem40_MFCC_3", + "Mean_Acc1298_Std_Mem40_MFCC_4", + "Mean_Acc1298_Std_Mem40_MFCC_5", + "Mean_Acc1298_Std_Mem40_MFCC_6", + "Mean_Acc1298_Std_Mem40_MFCC_7", + "Mean_Acc1298_Std_Mem40_MFCC_8", + "Mean_Acc1298_Std_Mem40_MFCC_9", + "Mean_Acc1298_Std_Mem40_MFCC_10", + "Mean_Acc1298_Std_Mem40_MFCC_11", + "Mean_Acc1298_Std_Mem40_MFCC_12", + "Std_Acc1298_Mean_Mem40_Centroid", + "Std_Acc1298_Mean_Mem40_Rolloff", + "Std_Acc1298_Mean_Mem40_Flux", + "Std_Acc1298_Mean_Mem40_MFCC_0", + "Std_Acc1298_Mean_Mem40_MFCC_1", + "Std_Acc1298_Mean_Mem40_MFCC_2", + "Std_Acc1298_Mean_Mem40_MFCC_3", + "Std_Acc1298_Mean_Mem40_MFCC_4", + "Std_Acc1298_Mean_Mem40_MFCC_5", + "Std_Acc1298_Mean_Mem40_MFCC_6", + "Std_Acc1298_Mean_Mem40_MFCC_7", + "Std_Acc1298_Mean_Mem40_MFCC_8", + "Std_Acc1298_Mean_Mem40_MFCC_9", + "Std_Acc1298_Mean_Mem40_MFCC_10", + "Std_Acc1298_Mean_Mem40_MFCC_11", + "Std_Acc1298_Mean_Mem40_MFCC_12", + "Std_Acc1298_Std_Mem40_Centroid", + "Std_Acc1298_Std_Mem40_Rolloff", + "Std_Acc1298_Std_Mem40_Flux", + "Std_Acc1298_Std_Mem40_MFCC_0", + "Std_Acc1298_Std_Mem40_MFCC_1", + "Std_Acc1298_Std_Mem40_MFCC_2", + "Std_Acc1298_Std_Mem40_MFCC_3", + "Std_Acc1298_Std_Mem40_MFCC_4", + "Std_Acc1298_Std_Mem40_MFCC_5", + "Std_Acc1298_Std_Mem40_MFCC_6", + "Std_Acc1298_Std_Mem40_MFCC_7", + "Std_Acc1298_Std_Mem40_MFCC_8", + "Std_Acc1298_Std_Mem40_MFCC_9", + "Std_Acc1298_Std_Mem40_MFCC_10", + "Std_Acc1298_Std_Mem40_MFCC_11", + "Std_Acc1298_Std_Mem40_MFCC_12", + "BH_LowPeakAmp", + "BH_LowPeakBPM", + "BH_HighPeakAmp", + "BH_HighPeakBPM", + "BH_HighLowRatio", + "BHSUM1", + "BHSUM2", + "BHSUM3", + "amazed.suprised", + "happy.pleased", + "relaxing.calm", + "quiet.still", + "sad.lonely", + "angry.aggresive", + ], + 1119: [ + "age", + "workclass", + "fnlwgt:", + "education:", + "education-num:", + "marital-status:", + "occupation:", + "relationship:", + "race:", + "sex:", + "capital-gain:", + "capital-loss:", + "hours-per-week:", + "native-country:", + "class", + ], + 40966: [ + "DYRK1A_N", + "ITSN1_N", + "BDNF_N", + "NR1_N", + "NR2A_N", + "pAKT_N", + "pBRAF_N", + "pCAMKII_N", + "pCREB_N", + "pELK_N", + "pERK_N", + "pJNK_N", + "PKCA_N", + "pMEK_N", + "pNR1_N", + "pNR2A_N", + "pNR2B_N", + "pPKCAB_N", + "pRSK_N", + "AKT_N", + "BRAF_N", + "CAMKII_N", + "CREB_N", + "ELK_N", + "ERK_N", + "GSK3B_N", + "JNK_N", + "MEK_N", + "TRKA_N", + "RSK_N", + "APP_N", + "Bcatenin_N", + "SOD1_N", + "MTOR_N", + "P38_N", + "pMTOR_N", + "DSCR1_N", + "AMPKA_N", + "NR2B_N", + "pNUMB_N", + "RAPTOR_N", + "TIAM1_N", + "pP70S6_N", + "NUMB_N", + "P70S6_N", + "pGSK3B_N", + "pPKCG_N", + "CDK5_N", + "S6_N", + "ADARB1_N", + "AcetylH3K9_N", + "RRP1_N", + "BAX_N", + "ARC_N", + "ERBB4_N", + "nNOS_N", + "Tau_N", + "GFAP_N", + "GluR3_N", + "GluR4_N", + "IL1B_N", + "P3525_N", + "pCASP9_N", + "PSD95_N", + "SNCA_N", + "Ubiquitin_N", + "pGSK3B_Tyr216_N", + "SHH_N", + "BAD_N", + "BCL2_N", + "pS6_N", + "pCFOS_N", + "SYP_N", + "H3AcK18_N", + "EGR1_N", + "H3MeK4_N", + "CaNA_N", + "class", + ], + 40945: [ + "pclass", + "survived", + "name", + "sex", + "age", + "sibsp", + "parch", + "ticket", + "fare", + "cabin", + "embarked", + "boat", + "body", + "home.dest", + ], + } + + +@pytest.fixture(scope="module") +def datasets_missing_values(): + return { + 61: {}, + 2: { + "family": 11, + "temper_rolling": 9, + "condition": 2, + "formability": 4, + "non-ageing": 10, + "surface-finish": 11, + "enamelability": 11, + "bc": 11, + "bf": 10, + "bt": 11, + "bw%2Fme": 8, + "bl": 9, + "m": 11, + "chrom": 11, + "phos": 11, + "cbond": 10, + "marvi": 11, + "exptl": 11, + "ferro": 11, + "corr": 11, + "blue%2Fbright%2Fvarn%2Fclean": 11, + "lustre": 8, + "jurofm": 11, + "s": 11, + "p": 11, + "oil": 10, + "packing": 11, + }, + 561: {}, + 40589: {}, + 1119: {}, + 40966: {"BCL2_N": 7}, + 40945: { + "age": 263, + "fare": 1, + "cabin": 1014, + "embarked": 2, + "boat": 823, + "body": 1188, + "home.dest": 564, + }, + } + + +@pytest.mark.parametrize( + "data_id, parser, expected_n_categories, expected_n_floats, expected_n_ints", + [ + # iris dataset + (61, "liac-arff", 1, 4, 0), + (61, "pandas", 1, 4, 0), + # anneal dataset + (2, "liac-arff", 33, 6, 0), + (2, "pandas", 33, 2, 4), + # cpu dataset + (561, "liac-arff", 1, 7, 0), + (561, "pandas", 1, 0, 7), + # emotions dataset + (40589, "liac-arff", 6, 72, 0), + (40589, "pandas", 6, 69, 3), + # adult-census dataset + (1119, "liac-arff", 9, 6, 0), + (1119, "pandas", 9, 0, 6), + # miceprotein + (40966, "liac-arff", 1, 77, 0), + (40966, "pandas", 1, 77, 0), + # titanic + (40945, "liac-arff", 3, 6, 0), + (40945, "pandas", 3, 3, 3), + ], +) +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_fetch_openml_types_inference( + monkeypatch, + data_id, + parser, + expected_n_categories, + expected_n_floats, + expected_n_ints, + gzip_response, + datasets_column_names, + datasets_missing_values, +): + """Check that `fetch_openml` infer the right number of categories, integers, and + floats.""" + pd = pytest.importorskip("pandas") + CategoricalDtype = pd.api.types.CategoricalDtype + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response) + + bunch = fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser=parser, + ) + frame = bunch.frame + + n_categories = len( + [dtype for dtype in frame.dtypes if isinstance(dtype, CategoricalDtype)] + ) + n_floats = len([dtype for dtype in frame.dtypes if dtype.kind == "f"]) + n_ints = len([dtype for dtype in frame.dtypes if dtype.kind == "i"]) + + assert n_categories == expected_n_categories + assert n_floats == expected_n_floats + assert n_ints == expected_n_ints + + assert frame.columns.tolist() == datasets_column_names[data_id] + + frame_feature_to_n_nan = frame.isna().sum().to_dict() + for name, n_missing in frame_feature_to_n_nan.items(): + expected_missing = datasets_missing_values[data_id].get(name, 0) + assert n_missing == expected_missing + + +############################################################################### +# Test some more specific behaviour + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ( + {"parser": "unknown"}, + "The 'parser' parameter of fetch_openml must be a str among", + ), + ( + {"as_frame": "unknown"}, + "The 'as_frame' parameter of fetch_openml must be an instance", + ), + ], +) +def test_fetch_openml_validation_parameter(monkeypatch, params, err_msg): + data_id = 1119 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + with pytest.raises(ValueError, match=err_msg): + fetch_openml(data_id=data_id, **params) + + +@pytest.mark.parametrize( + "params", + [ + {"as_frame": True, "parser": "auto"}, + {"as_frame": "auto", "parser": "auto"}, + {"as_frame": False, "parser": "pandas"}, + {"as_frame": False, "parser": "auto"}, + ], +) +def test_fetch_openml_requires_pandas_error(monkeypatch, params): + """Check that we raise the proper errors when we require pandas.""" + data_id = 1119 + try: + check_pandas_support("test_fetch_openml_requires_pandas") + except ImportError: + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + err_msg = "requires pandas to be installed. Alternatively, explicitly" + with pytest.raises(ImportError, match=err_msg): + fetch_openml(data_id=data_id, **params) + else: + raise SkipTest("This test requires pandas to not be installed.") + + +@pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive") +@pytest.mark.parametrize( + "params, err_msg", + [ + ( + {"parser": "pandas"}, + "Sparse ARFF datasets cannot be loaded with parser='pandas'", + ), + ( + {"as_frame": True}, + "Sparse ARFF datasets cannot be loaded with as_frame=True.", + ), + ( + {"parser": "pandas", "as_frame": True}, + "Sparse ARFF datasets cannot be loaded with as_frame=True.", + ), + ], +) +def test_fetch_openml_sparse_arff_error(monkeypatch, params, err_msg): + """Check that we raise the expected error for sparse ARFF datasets and + a wrong set of incompatible parameters. + """ + pytest.importorskip("pandas") + data_id = 292 + + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + with pytest.raises(ValueError, match=err_msg): + fetch_openml( + data_id=data_id, + cache=False, + **params, + ) + + +@pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive") +@pytest.mark.parametrize( + "data_id, data_type", + [ + (61, "dataframe"), # iris dataset version 1 + (292, "sparse"), # Australian dataset version 1 + ], +) +def test_fetch_openml_auto_mode(monkeypatch, data_id, data_type): + """Check the auto mode of `fetch_openml`.""" + pd = pytest.importorskip("pandas") + + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + data = fetch_openml(data_id=data_id, as_frame="auto", cache=False) + klass = pd.DataFrame if data_type == "dataframe" else scipy.sparse.csr_matrix + assert isinstance(data.data, klass) + + +def test_convert_arff_data_dataframe_warning_low_memory_pandas(monkeypatch): + """Check that we raise a warning regarding the working memory when using + LIAC-ARFF parser.""" + pytest.importorskip("pandas") + + data_id = 1119 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + + msg = "Could not adhere to working_memory config." + with pytest.warns(UserWarning, match=msg): + with config_context(working_memory=1e-6): + fetch_openml( + data_id=data_id, + as_frame=True, + cache=False, + parser="liac-arff", + ) + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_fetch_openml_iris_warn_multiple_version(monkeypatch, gzip_response): + """Check that a warning is raised when multiple versions exist and no version is + requested.""" + data_id = 61 + data_name = "iris" + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + + msg = re.escape( + "Multiple active versions of the dataset matching the name" + " iris exist. Versions may be fundamentally different, " + "returning version 1. Available versions:\n" + "- version 1, status: active\n" + " url: https://www.openml.org/search?type=data&id=61\n" + "- version 3, status: active\n" + " url: https://www.openml.org/search?type=data&id=969\n" + ) + with pytest.warns(UserWarning, match=msg): + fetch_openml( + name=data_name, + as_frame=False, + cache=False, + parser="liac-arff", + ) + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_fetch_openml_no_target(monkeypatch, gzip_response): + """Check that we can get a dataset without target.""" + data_id = 61 + target_column = None + expected_observations = 150 + expected_features = 5 + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + data = fetch_openml( + data_id=data_id, + target_column=target_column, + cache=False, + as_frame=False, + parser="liac-arff", + ) + assert data.data.shape == (expected_observations, expected_features) + assert data.target is None + + +@pytest.mark.parametrize("gzip_response", [True, False]) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_missing_values_pandas(monkeypatch, gzip_response, parser): + """check that missing values in categories are compatible with pandas + categorical""" + pytest.importorskip("pandas") + + data_id = 42585 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response) + penguins = fetch_openml( + data_id=data_id, + cache=False, + as_frame=True, + parser=parser, + ) + + cat_dtype = penguins.data.dtypes["sex"] + # there are nans in the categorical + assert penguins.data["sex"].isna().any() + assert_array_equal(cat_dtype.categories, ["FEMALE", "MALE", "_"]) + + +@pytest.mark.parametrize("gzip_response", [True, False]) +@pytest.mark.parametrize( + "dataset_params", + [ + {"data_id": 40675}, + {"data_id": None, "name": "glass2", "version": 1}, + ], +) +def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params): + """Check that we raise a warning when the dataset is inactive.""" + data_id = 40675 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + msg = "Version 1 of dataset glass2 is inactive," + with pytest.warns(UserWarning, match=msg): + glass2 = fetch_openml( + cache=False, as_frame=False, parser="liac-arff", **dataset_params + ) + assert glass2.data.shape == (163, 9) + assert glass2.details["id"] == "40675" + + +@pytest.mark.parametrize("gzip_response", [True, False]) +@pytest.mark.parametrize( + "data_id, params, err_type, err_msg", + [ + (40675, {"name": "glass2"}, ValueError, "No active dataset glass2 found"), + ( + 61, + {"data_id": 61, "target_column": ["sepalwidth", "class"]}, + ValueError, + "Can only handle homogeneous multi-target datasets", + ), + ( + 40945, + {"data_id": 40945, "as_frame": False}, + ValueError, + ( + "STRING attributes are not supported for array representation. Try" + " as_frame=True" + ), + ), + ( + 2, + {"data_id": 2, "target_column": "family", "as_frame": True}, + ValueError, + "Target column 'family'", + ), + ( + 2, + {"data_id": 2, "target_column": "family", "as_frame": False}, + ValueError, + "Target column 'family'", + ), + ( + 61, + {"data_id": 61, "target_column": "undefined"}, + KeyError, + "Could not find target_column='undefined'", + ), + ( + 61, + {"data_id": 61, "target_column": ["undefined", "class"]}, + KeyError, + "Could not find target_column='undefined'", + ), + ], +) +@pytest.mark.parametrize("parser", ["liac-arff", "pandas"]) +def test_fetch_openml_error( + monkeypatch, gzip_response, data_id, params, err_type, err_msg, parser +): + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + if params.get("as_frame", True) or parser == "pandas": + pytest.importorskip("pandas") + with pytest.raises(err_type, match=err_msg): + fetch_openml(cache=False, parser=parser, **params) + + +@pytest.mark.parametrize( + "params, err_type, err_msg", + [ + ( + {"data_id": -1, "name": None, "version": "version"}, + ValueError, + "The 'version' parameter of fetch_openml must be an int in the range", + ), + ( + {"data_id": -1, "name": "nAmE"}, + ValueError, + "The 'data_id' parameter of fetch_openml must be an int in the range", + ), + ( + {"data_id": -1, "name": "nAmE", "version": "version"}, + ValueError, + "The 'version' parameter of fetch_openml must be an int", + ), + ( + {}, + ValueError, + "Neither name nor data_id are provided. Please provide name or data_id.", + ), + ], +) +def test_fetch_openml_raises_illegal_argument(params, err_type, err_msg): + with pytest.raises(err_type, match=err_msg): + fetch_openml(**params) + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_warn_ignore_attribute(monkeypatch, gzip_response): + data_id = 40966 + expected_row_id_msg = "target_column='{}' has flag is_row_identifier." + expected_ignore_msg = "target_column='{}' has flag is_ignore." + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + # single column test + target_col = "MouseID" + msg = expected_row_id_msg.format(target_col) + with pytest.warns(UserWarning, match=msg): + fetch_openml( + data_id=data_id, + target_column=target_col, + cache=False, + as_frame=False, + parser="liac-arff", + ) + target_col = "Genotype" + msg = expected_ignore_msg.format(target_col) + with pytest.warns(UserWarning, match=msg): + fetch_openml( + data_id=data_id, + target_column=target_col, + cache=False, + as_frame=False, + parser="liac-arff", + ) + # multi column test + target_col = "MouseID" + msg = expected_row_id_msg.format(target_col) + with pytest.warns(UserWarning, match=msg): + fetch_openml( + data_id=data_id, + target_column=[target_col, "class"], + cache=False, + as_frame=False, + parser="liac-arff", + ) + target_col = "Genotype" + msg = expected_ignore_msg.format(target_col) + with pytest.warns(UserWarning, match=msg): + fetch_openml( + data_id=data_id, + target_column=[target_col, "class"], + cache=False, + as_frame=False, + parser="liac-arff", + ) + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_dataset_with_openml_error(monkeypatch, gzip_response): + data_id = 1 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + msg = "OpenML registered a problem with the dataset. It might be unusable. Error:" + with pytest.warns(UserWarning, match=msg): + fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff") + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_dataset_with_openml_warning(monkeypatch, gzip_response): + data_id = 3 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + msg = "OpenML raised a warning on the dataset. It might be unusable. Warning:" + with pytest.warns(UserWarning, match=msg): + fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff") + + +def test_fetch_openml_overwrite_default_params_read_csv(monkeypatch): + """Check that we can overwrite the default parameters of `read_csv`.""" + pytest.importorskip("pandas") + data_id = 1590 + _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False) + + common_params = { + "data_id": data_id, + "as_frame": True, + "cache": False, + "parser": "pandas", + } + + # By default, the initial spaces are skipped. We checked that setting the parameter + # `skipinitialspace` to False will have an effect. + adult_without_spaces = fetch_openml(**common_params) + adult_with_spaces = fetch_openml( + **common_params, read_csv_kwargs={"skipinitialspace": False} + ) + assert all( + cat.startswith(" ") for cat in adult_with_spaces.frame["class"].cat.categories + ) + assert not any( + cat.startswith(" ") + for cat in adult_without_spaces.frame["class"].cat.categories + ) + + +############################################################################### +# Test cache, retry mechanisms, checksum, etc. + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_open_openml_url_cache(monkeypatch, gzip_response, tmpdir): + data_id = 61 + + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff" + url = f"https://www.openml.org/{openml_path}" + cache_directory = str(tmpdir.mkdir("scikit_learn_data")) + # first fill the cache + response1 = _open_openml_url(url, cache_directory) + # assert file exists + location = _get_local_path(openml_path, cache_directory) + assert os.path.isfile(location) + # redownload, to utilize cache + response2 = _open_openml_url(url, cache_directory) + assert response1.read() == response2.read() + + +@pytest.mark.parametrize("write_to_disk", [True, False]) +def test_open_openml_url_unlinks_local_path(monkeypatch, tmpdir, write_to_disk): + data_id = 61 + openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff" + url = f"https://www.openml.org/{openml_path}" + cache_directory = str(tmpdir.mkdir("scikit_learn_data")) + location = _get_local_path(openml_path, cache_directory) + + def _mock_urlopen(request, *args, **kwargs): + if write_to_disk: + with open(location, "w") as f: + f.write("") + raise ValueError("Invalid request") + + monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen) + + with pytest.raises(ValueError, match="Invalid request"): + _open_openml_url(url, cache_directory) + + assert not os.path.exists(location) + + +def test_retry_with_clean_cache(tmpdir): + data_id = 61 + openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + cache_directory = str(tmpdir.mkdir("scikit_learn_data")) + location = _get_local_path(openml_path, cache_directory) + os.makedirs(os.path.dirname(location)) + + with open(location, "w") as f: + f.write("") + + @_retry_with_clean_cache(openml_path, cache_directory) + def _load_data(): + # The first call will raise an error since location exists + if os.path.exists(location): + raise Exception("File exist!") + return 1 + + warn_msg = "Invalid cache, redownloading file" + with pytest.warns(RuntimeWarning, match=warn_msg): + result = _load_data() + assert result == 1 + + +def test_retry_with_clean_cache_http_error(tmpdir): + data_id = 61 + openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + cache_directory = str(tmpdir.mkdir("scikit_learn_data")) + + @_retry_with_clean_cache(openml_path, cache_directory) + def _load_data(): + raise HTTPError( + url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO() + ) + + error_msg = "Simulated mock error" + with pytest.raises(HTTPError, match=error_msg): + _load_data() + + +@pytest.mark.parametrize("gzip_response", [True, False]) +def test_fetch_openml_cache(monkeypatch, gzip_response, tmpdir): + def _mock_urlopen_raise(request, *args, **kwargs): + raise ValueError( + "This mechanism intends to test correct cache" + "handling. As such, urlopen should never be " + "accessed. URL: %s" % request.get_full_url() + ) + + data_id = 61 + cache_directory = str(tmpdir.mkdir("scikit_learn_data")) + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + X_fetched, y_fetched = fetch_openml( + data_id=data_id, + cache=True, + data_home=cache_directory, + return_X_y=True, + as_frame=False, + parser="liac-arff", + ) + + monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen_raise) + + X_cached, y_cached = fetch_openml( + data_id=data_id, + cache=True, + data_home=cache_directory, + return_X_y=True, + as_frame=False, + parser="liac-arff", + ) + np.testing.assert_array_equal(X_fetched, X_cached) + np.testing.assert_array_equal(y_fetched, y_cached) + + +@pytest.mark.parametrize( + "as_frame, parser", + [ + (True, "liac-arff"), + (False, "liac-arff"), + (True, "pandas"), + (False, "pandas"), + ], +) +def test_fetch_openml_verify_checksum(monkeypatch, as_frame, tmpdir, parser): + """Check that the checksum is working as expected.""" + if as_frame or parser == "pandas": + pytest.importorskip("pandas") + + data_id = 2 + _monkey_patch_webbased_functions(monkeypatch, data_id, True) + + # create a temporary modified arff file + original_data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}" + original_data_file_name = "data-v1-dl-1666876.arff.gz" + original_data_path = resources.files(original_data_module) / original_data_file_name + corrupt_copy_path = tmpdir / "test_invalid_checksum.arff" + with original_data_path.open("rb") as orig_file: + orig_gzip = gzip.open(orig_file, "rb") + data = bytearray(orig_gzip.read()) + data[len(data) - 1] = 37 + + with gzip.GzipFile(corrupt_copy_path, "wb") as modified_gzip: + modified_gzip.write(data) + + # Requests are already mocked by monkey_patch_webbased_functions. + # We want to reuse that mock for all requests except file download, + # hence creating a thin mock over the original mock + mocked_openml_url = sklearn.datasets._openml.urlopen + + def swap_file_mock(request, *args, **kwargs): + url = request.get_full_url() + if url.endswith("data/v1/download/1666876/anneal.arff"): + with open(corrupt_copy_path, "rb") as f: + corrupted_data = f.read() + return _MockHTTPResponse(BytesIO(corrupted_data), is_gzip=True) + else: + return mocked_openml_url(request) + + monkeypatch.setattr(sklearn.datasets._openml, "urlopen", swap_file_mock) + + # validate failed checksum + with pytest.raises(ValueError) as exc: + sklearn.datasets.fetch_openml( + data_id=data_id, cache=False, as_frame=as_frame, parser=parser + ) + # exception message should have file-path + assert exc.match("1666876") + + +def test_open_openml_url_retry_on_network_error(monkeypatch): + def _mock_urlopen_network_error(request, *args, **kwargs): + raise HTTPError( + url=None, code=404, msg="Simulated network error", hdrs=None, fp=BytesIO() + ) + + monkeypatch.setattr( + sklearn.datasets._openml, "urlopen", _mock_urlopen_network_error + ) + + invalid_openml_url = "https://api.openml.org/invalid-url" + + with pytest.warns( + UserWarning, + match=re.escape( + "A network error occurred while downloading" + f" {invalid_openml_url}. Retrying..." + ), + ) as record: + with pytest.raises(HTTPError, match="Simulated network error"): + _open_openml_url(invalid_openml_url, None, delay=0) + assert len(record) == 3 + + +############################################################################### +# Non-regressiont tests + + +@pytest.mark.parametrize("gzip_response", [True, False]) +@pytest.mark.parametrize("parser", ("liac-arff", "pandas")) +def test_fetch_openml_with_ignored_feature(monkeypatch, gzip_response, parser): + """Check that we can load the "zoo" dataset. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/14340 + """ + if parser == "pandas": + pytest.importorskip("pandas") + data_id = 62 + _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) + + dataset = sklearn.datasets.fetch_openml( + data_id=data_id, cache=False, as_frame=False, parser=parser + ) + assert dataset is not None + # The dataset has 17 features, including 1 ignored (animal), + # so we assert that we don't have the ignored feature in the final Bunch + assert dataset["data"].shape == (101, 16) + assert "animal" not in dataset["feature_names"] + + +def test_fetch_openml_strip_quotes(monkeypatch): + """Check that we strip the single quotes when used as a string delimiter. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/23381 + """ + pd = pytest.importorskip("pandas") + data_id = 40966 + _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False) + + common_params = {"as_frame": True, "cache": False, "data_id": data_id} + mice_pandas = fetch_openml(parser="pandas", **common_params) + mice_liac_arff = fetch_openml(parser="liac-arff", **common_params) + pd.testing.assert_series_equal(mice_pandas.target, mice_liac_arff.target) + assert not mice_pandas.target.str.startswith("'").any() + assert not mice_pandas.target.str.endswith("'").any() + + # similar behaviour should be observed when the column is not the target + mice_pandas = fetch_openml(parser="pandas", target_column="NUMB_N", **common_params) + mice_liac_arff = fetch_openml( + parser="liac-arff", target_column="NUMB_N", **common_params + ) + pd.testing.assert_series_equal( + mice_pandas.frame["class"], mice_liac_arff.frame["class"] + ) + assert not mice_pandas.frame["class"].str.startswith("'").any() + assert not mice_pandas.frame["class"].str.endswith("'").any() + + +def test_fetch_openml_leading_whitespace(monkeypatch): + """Check that we can strip leading whitespace in pandas parser. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/25311 + """ + pd = pytest.importorskip("pandas") + data_id = 1590 + _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False) + + common_params = {"as_frame": True, "cache": False, "data_id": data_id} + adult_pandas = fetch_openml(parser="pandas", **common_params) + adult_liac_arff = fetch_openml(parser="liac-arff", **common_params) + pd.testing.assert_series_equal( + adult_pandas.frame["class"], adult_liac_arff.frame["class"] + ) + + +def test_fetch_openml_quotechar_escapechar(monkeypatch): + """Check that we can handle escapechar and single/double quotechar. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/25478 + """ + pd = pytest.importorskip("pandas") + data_id = 42074 + _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False) + + common_params = {"as_frame": True, "cache": False, "data_id": data_id} + adult_pandas = fetch_openml(parser="pandas", **common_params) + adult_liac_arff = fetch_openml(parser="liac-arff", **common_params) + pd.testing.assert_frame_equal(adult_pandas.frame, adult_liac_arff.frame) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_rcv1.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_rcv1.py new file mode 100644 index 0000000000000000000000000000000000000000..c415c9df977c36221c61ed4803dd26f6d0cfbef4 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_rcv1.py @@ -0,0 +1,71 @@ +"""Test the rcv1 loader, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs).""" + +from functools import partial + +import numpy as np +import scipy.sparse as sp + +from sklearn.datasets.tests.test_common import check_return_X_y +from sklearn.utils._testing import assert_almost_equal, assert_array_equal + + +def test_fetch_rcv1(fetch_rcv1_fxt, global_random_seed): + data1 = fetch_rcv1_fxt(shuffle=False) + X1, Y1 = data1.data, data1.target + cat_list, s1 = data1.target_names.tolist(), data1.sample_id + + # test sparsity + assert sp.issparse(X1) + assert sp.issparse(Y1) + assert 60915113 == X1.data.size + assert 2606875 == Y1.data.size + + # test shapes + assert (804414, 47236) == X1.shape + assert (804414, 103) == Y1.shape + assert (804414,) == s1.shape + assert 103 == len(cat_list) + + # test descr + assert data1.DESCR.startswith(".. _rcv1_dataset:") + + # test ordering of categories + first_categories = ["C11", "C12", "C13", "C14", "C15", "C151"] + assert_array_equal(first_categories, cat_list[:6]) + + # test number of sample for some categories + some_categories = ("GMIL", "E143", "CCAT") + number_non_zero_in_cat = (5, 1206, 381327) + for num, cat in zip(number_non_zero_in_cat, some_categories): + j = cat_list.index(cat) + assert num == Y1[:, j].data.size + + # test shuffling and subset + data2 = fetch_rcv1_fxt( + shuffle=True, subset="train", random_state=global_random_seed + ) + X2, Y2 = data2.data, data2.target + s2 = data2.sample_id + + # test return_X_y option + fetch_func = partial(fetch_rcv1_fxt, shuffle=False, subset="train") + check_return_X_y(data2, fetch_func) + + # The first 23149 samples are the training samples + assert_array_equal(np.sort(s1[:23149]), np.sort(s2)) + + # test some precise values + some_sample_ids = (2286, 3274, 14042) + for sample_id in some_sample_ids: + idx1 = s1.tolist().index(sample_id) + idx2 = s2.tolist().index(sample_id) + + feature_values_1 = X1[idx1, :].toarray() + feature_values_2 = X2[idx2, :].toarray() + assert_almost_equal(feature_values_1, feature_values_2) + + target_values_1 = Y1[idx1, :].toarray() + target_values_2 = Y2[idx2, :].toarray() + assert_almost_equal(target_values_1, target_values_2) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_samples_generator.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_samples_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..f514080bf8a6f141792b1d28e14e8986ee6dd438 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_samples_generator.py @@ -0,0 +1,744 @@ +import re +from collections import defaultdict +from functools import partial + +import numpy as np +import pytest +import scipy.sparse as sp + +from sklearn.datasets import ( + make_biclusters, + make_blobs, + make_checkerboard, + make_circles, + make_classification, + make_friedman1, + make_friedman2, + make_friedman3, + make_hastie_10_2, + make_low_rank_matrix, + make_moons, + make_multilabel_classification, + make_regression, + make_s_curve, + make_sparse_coded_signal, + make_sparse_spd_matrix, + make_sparse_uncorrelated, + make_spd_matrix, + make_swiss_roll, +) +from sklearn.utils._testing import ( + assert_allclose, + assert_allclose_dense_sparse, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.validation import assert_all_finite + + +def test_make_classification(): + weights = [0.1, 0.25] + X, y = make_classification( + n_samples=100, + n_features=20, + n_informative=5, + n_redundant=1, + n_repeated=1, + n_classes=3, + n_clusters_per_class=1, + hypercube=False, + shift=None, + scale=None, + weights=weights, + random_state=0, + ) + + assert weights == [0.1, 0.25] + assert X.shape == (100, 20), "X shape mismatch" + assert y.shape == (100,), "y shape mismatch" + assert np.unique(y).shape == (3,), "Unexpected number of classes" + assert sum(y == 0) == 10, "Unexpected number of samples in class #0" + assert sum(y == 1) == 25, "Unexpected number of samples in class #1" + assert sum(y == 2) == 65, "Unexpected number of samples in class #2" + + # Test for n_features > 30 + X, y = make_classification( + n_samples=2000, + n_features=31, + n_informative=31, + n_redundant=0, + n_repeated=0, + hypercube=True, + scale=0.5, + random_state=0, + ) + + assert X.shape == (2000, 31), "X shape mismatch" + assert y.shape == (2000,), "y shape mismatch" + assert ( + np.unique(X.view([("", X.dtype)] * X.shape[1])) + .view(X.dtype) + .reshape(-1, X.shape[1]) + .shape[0] + == 2000 + ), "Unexpected number of unique rows" + + +def test_make_classification_informative_features(): + """Test the construction of informative features in make_classification + + Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and + fully-specified `weights`. + """ + # Create very separate clusters; check that vertices are unique and + # correspond to classes + class_sep = 1e6 + make = partial( + make_classification, + class_sep=class_sep, + n_redundant=0, + n_repeated=0, + flip_y=0, + shift=0, + scale=1, + shuffle=False, + ) + + for n_informative, weights, n_clusters_per_class in [ + (2, [1], 1), + (2, [1 / 3] * 3, 1), + (2, [1 / 4] * 4, 1), + (2, [1 / 2] * 2, 2), + (2, [3 / 4, 1 / 4], 2), + (10, [1 / 3] * 3, 10), + (64, [1], 1), + ]: + n_classes = len(weights) + n_clusters = n_classes * n_clusters_per_class + n_samples = n_clusters * 50 + + for hypercube in (False, True): + X, y = make( + n_samples=n_samples, + n_classes=n_classes, + weights=weights, + n_features=n_informative, + n_informative=n_informative, + n_clusters_per_class=n_clusters_per_class, + hypercube=hypercube, + random_state=0, + ) + + assert X.shape == (n_samples, n_informative) + assert y.shape == (n_samples,) + + # Cluster by sign, viewed as strings to allow uniquing + signs = np.sign(X) + signs = signs.view(dtype="|S{0}".format(signs.strides[0])).ravel() + unique_signs, cluster_index = np.unique(signs, return_inverse=True) + + assert len(unique_signs) == n_clusters, ( + "Wrong number of clusters, or not in distinct quadrants" + ) + + clusters_by_class = defaultdict(set) + for cluster, cls in zip(cluster_index, y): + clusters_by_class[cls].add(cluster) + for clusters in clusters_by_class.values(): + assert len(clusters) == n_clusters_per_class, ( + "Wrong number of clusters per class" + ) + assert len(clusters_by_class) == n_classes, "Wrong number of classes" + + assert_array_almost_equal( + np.bincount(y) / len(y) // weights, + [1] * n_classes, + err_msg="Wrong number of samples per class", + ) + + # Ensure on vertices of hypercube + for cluster in range(len(unique_signs)): + centroid = X[cluster_index == cluster].mean(axis=0) + if hypercube: + assert_array_almost_equal( + np.abs(centroid) / class_sep, + np.ones(n_informative), + decimal=5, + err_msg="Clusters are not centered on hypercube vertices", + ) + else: + with pytest.raises(AssertionError): + assert_array_almost_equal( + np.abs(centroid) / class_sep, + np.ones(n_informative), + decimal=5, + err_msg=( + "Clusters should not be centered on hypercube vertices" + ), + ) + + with pytest.raises(ValueError): + make(n_features=2, n_informative=2, n_classes=5, n_clusters_per_class=1) + with pytest.raises(ValueError): + make(n_features=2, n_informative=2, n_classes=3, n_clusters_per_class=2) + + +def test_make_classification_return_x_y(): + """ + Test that make_classification returns a Bunch when return_X_y is False. + + Also that bunch.X is the same as X + """ + + kwargs = { + "n_samples": 100, + "n_features": 20, + "n_informative": 5, + "n_redundant": 1, + "n_repeated": 1, + "n_classes": 3, + "n_clusters_per_class": 2, + "weights": None, + "flip_y": 0.01, + "class_sep": 1.0, + "hypercube": True, + "shift": 0.0, + "scale": 1.0, + "shuffle": True, + "random_state": 42, + "return_X_y": True, + } + + X, y = make_classification(**kwargs) + + kwargs["return_X_y"] = False + bunch = make_classification(**kwargs) + + assert ( + hasattr(bunch, "DESCR") + and hasattr(bunch, "parameters") + and hasattr(bunch, "feature_info") + and hasattr(bunch, "X") + and hasattr(bunch, "y") + ) + + def count(str_): + return bunch.feature_info.count(str_) + + assert np.array_equal(X, bunch.X) + assert np.array_equal(y, bunch.y) + assert bunch.DESCR == make_classification.__doc__ + assert bunch.parameters == kwargs + assert count("informative") == kwargs["n_informative"] + assert count("redundant") == kwargs["n_redundant"] + assert count("repeated") == kwargs["n_repeated"] + + +@pytest.mark.parametrize( + "weights, err_type, err_msg", + [ + ([], ValueError, "Weights specified but incompatible with number of classes."), + ( + [0.25, 0.75, 0.1], + ValueError, + "Weights specified but incompatible with number of classes.", + ), + ( + np.array([]), + ValueError, + "Weights specified but incompatible with number of classes.", + ), + ( + np.array([0.25, 0.75, 0.1]), + ValueError, + "Weights specified but incompatible with number of classes.", + ), + ( + np.random.random(3), + ValueError, + "Weights specified but incompatible with number of classes.", + ), + ], +) +def test_make_classification_weights_type(weights, err_type, err_msg): + with pytest.raises(err_type, match=err_msg): + make_classification(weights=weights) + + +@pytest.mark.parametrize("kwargs", [{}, {"n_classes": 3, "n_informative": 3}]) +def test_make_classification_weights_array_or_list_ok(kwargs): + X1, y1 = make_classification(weights=[0.1, 0.9], random_state=0, **kwargs) + X2, y2 = make_classification(weights=np.array([0.1, 0.9]), random_state=0, **kwargs) + assert_almost_equal(X1, X2) + assert_almost_equal(y1, y2) + + +def test_make_multilabel_classification_return_sequences(): + for allow_unlabeled, min_length in zip((True, False), (0, 1)): + X, Y = make_multilabel_classification( + n_samples=100, + n_features=20, + n_classes=3, + random_state=0, + return_indicator=False, + allow_unlabeled=allow_unlabeled, + ) + assert X.shape == (100, 20), "X shape mismatch" + if not allow_unlabeled: + assert max([max(y) for y in Y]) == 2 + assert min([len(y) for y in Y]) == min_length + assert max([len(y) for y in Y]) <= 3 + + +def test_make_multilabel_classification_return_indicator(): + for allow_unlabeled, min_length in zip((True, False), (0, 1)): + X, Y = make_multilabel_classification( + n_samples=25, + n_features=20, + n_classes=3, + random_state=0, + allow_unlabeled=allow_unlabeled, + ) + assert X.shape == (25, 20), "X shape mismatch" + assert Y.shape == (25, 3), "Y shape mismatch" + assert np.all(np.sum(Y, axis=0) > min_length) + + # Also test return_distributions and return_indicator with True + X2, Y2, p_c, p_w_c = make_multilabel_classification( + n_samples=25, + n_features=20, + n_classes=3, + random_state=0, + allow_unlabeled=allow_unlabeled, + return_distributions=True, + ) + + assert_array_almost_equal(X, X2) + assert_array_equal(Y, Y2) + assert p_c.shape == (3,) + assert_almost_equal(p_c.sum(), 1) + assert p_w_c.shape == (20, 3) + assert_almost_equal(p_w_c.sum(axis=0), [1] * 3) + + +def test_make_multilabel_classification_return_indicator_sparse(): + for allow_unlabeled, min_length in zip((True, False), (0, 1)): + X, Y = make_multilabel_classification( + n_samples=25, + n_features=20, + n_classes=3, + random_state=0, + return_indicator="sparse", + allow_unlabeled=allow_unlabeled, + ) + assert X.shape == (25, 20), "X shape mismatch" + assert Y.shape == (25, 3), "Y shape mismatch" + assert sp.issparse(Y) + + +def test_make_hastie_10_2(): + X, y = make_hastie_10_2(n_samples=100, random_state=0) + assert X.shape == (100, 10), "X shape mismatch" + assert y.shape == (100,), "y shape mismatch" + assert np.unique(y).shape == (2,), "Unexpected number of classes" + + +def test_make_regression(global_random_seed): + X, y, c = make_regression( + n_samples=200, + n_features=10, + n_informative=3, + effective_rank=5, + coef=True, + bias=0.0, + noise=1.0, + random_state=global_random_seed, + ) + + assert X.shape == (200, 10), "X shape mismatch" + assert y.shape == (200,), "y shape mismatch" + assert c.shape == (10,), "coef shape mismatch" + assert sum(c != 0.0) == 3, "Unexpected number of informative features" + + # Test that y ~= np.dot(X, c) + bias + N(0, 1.0). + assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) + + # Test with small number of features. + X, y = make_regression(n_samples=100, n_features=1) # n_informative=3 + assert X.shape == (100, 1) + + +def test_make_regression_multitarget(global_random_seed): + X, y, c = make_regression( + n_samples=100, + n_features=10, + n_informative=3, + n_targets=3, + coef=True, + noise=1.0, + random_state=global_random_seed, + ) + + assert X.shape == (100, 10), "X shape mismatch" + assert y.shape == (100, 3), "y shape mismatch" + assert c.shape == (10, 3), "coef shape mismatch" + assert_array_equal(sum(c != 0.0), 3, "Unexpected number of informative features") + + # Test that y ~= np.dot(X, c) + bias + N(0, 1.0) + assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) + + +def test_make_blobs(global_random_seed): + cluster_stds = np.array([0.05, 0.2, 0.4]) + cluster_centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) + X, y = make_blobs( + random_state=global_random_seed, + n_samples=50, + n_features=2, + centers=cluster_centers, + cluster_std=cluster_stds, + ) + + assert X.shape == (50, 2), "X shape mismatch" + assert y.shape == (50,), "y shape mismatch" + assert np.unique(y).shape == (3,), "Unexpected number of blobs" + for i, (ctr, std) in enumerate(zip(cluster_centers, cluster_stds)): + assert_almost_equal((X[y == i] - ctr).std(), std, 1, "Unexpected std") + + +def test_make_blobs_n_samples_list(): + n_samples = [50, 30, 20] + X, y = make_blobs(n_samples=n_samples, n_features=2, random_state=0) + + assert X.shape == (sum(n_samples), 2), "X shape mismatch" + assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), ( + "Incorrect number of samples per blob" + ) + + +def test_make_blobs_n_samples_list_with_centers(global_random_seed): + n_samples = [20, 20, 20] + centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) + cluster_stds = np.array([0.05, 0.2, 0.4]) + X, y = make_blobs( + n_samples=n_samples, + centers=centers, + cluster_std=cluster_stds, + random_state=global_random_seed, + ) + + assert X.shape == (sum(n_samples), 2), "X shape mismatch" + assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), ( + "Incorrect number of samples per blob" + ) + for i, (ctr, std) in enumerate(zip(centers, cluster_stds)): + assert_almost_equal((X[y == i] - ctr).std(), std, 1, "Unexpected std") + + +@pytest.mark.parametrize( + "n_samples", [[5, 3, 0], np.array([5, 3, 0]), tuple([5, 3, 0])] +) +def test_make_blobs_n_samples_centers_none(n_samples): + centers = None + X, y = make_blobs(n_samples=n_samples, centers=centers, random_state=0) + + assert X.shape == (sum(n_samples), 2), "X shape mismatch" + assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), ( + "Incorrect number of samples per blob" + ) + + +def test_make_blobs_return_centers(): + n_samples = [10, 20] + n_features = 3 + X, y, centers = make_blobs( + n_samples=n_samples, n_features=n_features, return_centers=True, random_state=0 + ) + + assert centers.shape == (len(n_samples), n_features) + + +def test_make_blobs_error(): + n_samples = [20, 20, 20] + centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) + cluster_stds = np.array([0.05, 0.2, 0.4]) + wrong_centers_msg = re.escape( + "Length of `n_samples` not consistent with number of centers. " + f"Got n_samples = {n_samples} and centers = {centers[:-1]}" + ) + with pytest.raises(ValueError, match=wrong_centers_msg): + make_blobs(n_samples, centers=centers[:-1]) + wrong_std_msg = re.escape( + "Length of `clusters_std` not consistent with number of centers. " + f"Got centers = {centers} and cluster_std = {cluster_stds[:-1]}" + ) + with pytest.raises(ValueError, match=wrong_std_msg): + make_blobs(n_samples, centers=centers, cluster_std=cluster_stds[:-1]) + wrong_type_msg = "Parameter `centers` must be array-like. Got {!r} instead".format( + 3 + ) + with pytest.raises(ValueError, match=wrong_type_msg): + make_blobs(n_samples, centers=3) + + +def test_make_friedman1(global_random_seed): + X, y = make_friedman1( + n_samples=5, n_features=10, noise=0.0, random_state=global_random_seed + ) + + assert X.shape == (5, 10), "X shape mismatch" + assert y.shape == (5,), "y shape mismatch" + + assert_array_almost_equal( + y, + 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + + 20 * (X[:, 2] - 0.5) ** 2 + + 10 * X[:, 3] + + 5 * X[:, 4], + ) + + +def test_make_friedman2(global_random_seed): + X, y = make_friedman2(n_samples=5, noise=0.0, random_state=global_random_seed) + + assert X.shape == (5, 4), "X shape mismatch" + assert y.shape == (5,), "y shape mismatch" + + assert_array_almost_equal( + y, (X[:, 0] ** 2 + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5 + ) + + +def test_make_friedman3(global_random_seed): + X, y = make_friedman3(n_samples=5, noise=0.0, random_state=global_random_seed) + + assert X.shape == (5, 4), "X shape mismatch" + assert y.shape == (5,), "y shape mismatch" + + assert_array_almost_equal( + y, np.arctan((X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) / X[:, 0]) + ) + + +def test_make_low_rank_matrix(): + X = make_low_rank_matrix( + n_samples=50, + n_features=25, + effective_rank=5, + tail_strength=0.01, + random_state=0, + ) + + assert X.shape == (50, 25), "X shape mismatch" + + from numpy.linalg import svd + + u, s, v = svd(X) + assert sum(s) - 5 < 0.1, "X rank is not approximately 5" + + +def test_make_sparse_coded_signal(global_random_seed): + Y, D, X = make_sparse_coded_signal( + n_samples=5, + n_components=8, + n_features=10, + n_nonzero_coefs=3, + random_state=global_random_seed, + ) + assert Y.shape == (5, 10), "Y shape mismatch" + assert D.shape == (8, 10), "D shape mismatch" + assert X.shape == (5, 8), "X shape mismatch" + for row in X: + assert len(np.flatnonzero(row)) == 3, "Non-zero coefs mismatch" + assert_allclose(Y, X @ D) + assert_allclose(np.sqrt((D**2).sum(axis=1)), np.ones(D.shape[0])) + + +def test_make_sparse_uncorrelated(): + X, y = make_sparse_uncorrelated(n_samples=5, n_features=10, random_state=0) + + assert X.shape == (5, 10), "X shape mismatch" + assert y.shape == (5,), "y shape mismatch" + + +def test_make_spd_matrix(global_random_seed): + X = make_spd_matrix(n_dim=5, random_state=global_random_seed) + + assert X.shape == (5, 5), "X shape mismatch" + assert_array_almost_equal(X, X.T) + + from numpy.linalg import eig + + eigenvalues, _ = eig(X) + assert np.all(eigenvalues > 0), "X is not positive-definite" + + +@pytest.mark.parametrize("norm_diag", [True, False]) +@pytest.mark.parametrize( + "sparse_format", [None, "bsr", "coo", "csc", "csr", "dia", "dok", "lil"] +) +def test_make_sparse_spd_matrix(norm_diag, sparse_format, global_random_seed): + n_dim = 5 + X = make_sparse_spd_matrix( + n_dim=n_dim, + norm_diag=norm_diag, + sparse_format=sparse_format, + random_state=global_random_seed, + ) + + assert X.shape == (n_dim, n_dim), "X shape mismatch" + if sparse_format is None: + assert not sp.issparse(X) + assert_allclose(X, X.T) + Xarr = X + else: + assert sp.issparse(X) and X.format == sparse_format + assert_allclose_dense_sparse(X, X.T) + Xarr = X.toarray() + + from numpy.linalg import eig + + # Do not use scipy.sparse.linalg.eigs because it cannot find all eigenvalues + eigenvalues, _ = eig(Xarr) + assert np.all(eigenvalues > 0), "X is not positive-definite" + + if norm_diag: + # Check that leading diagonal elements are 1 + assert_array_almost_equal(Xarr.diagonal(), np.ones(n_dim)) + + +@pytest.mark.parametrize("hole", [False, True]) +def test_make_swiss_roll(global_random_seed, hole): + X, t = make_swiss_roll( + n_samples=5, noise=0.0, random_state=global_random_seed, hole=hole + ) + + assert X.shape == (5, 3) + assert t.shape == (5,) + assert_array_almost_equal(X[:, 0], t * np.cos(t)) + assert_array_almost_equal(X[:, 2], t * np.sin(t)) + + +def test_make_s_curve(global_random_seed): + X, t = make_s_curve(n_samples=5, noise=0.0, random_state=global_random_seed) + + assert X.shape == (5, 3), "X shape mismatch" + assert t.shape == (5,), "t shape mismatch" + assert_array_almost_equal(X[:, 0], np.sin(t)) + assert_array_almost_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1)) + + +def test_make_biclusters(): + X, rows, cols = make_biclusters( + shape=(100, 100), n_clusters=4, shuffle=True, random_state=0 + ) + assert X.shape == (100, 100), "X shape mismatch" + assert rows.shape == (4, 100), "rows shape mismatch" + assert cols.shape == ( + 4, + 100, + ), "columns shape mismatch" + assert_all_finite(X) + assert_all_finite(rows) + assert_all_finite(cols) + + X2, _, _ = make_biclusters( + shape=(100, 100), n_clusters=4, shuffle=True, random_state=0 + ) + assert_array_almost_equal(X, X2) + + +def test_make_checkerboard(): + X, rows, cols = make_checkerboard( + shape=(100, 100), n_clusters=(20, 5), shuffle=True, random_state=0 + ) + assert X.shape == (100, 100), "X shape mismatch" + assert rows.shape == (100, 100), "rows shape mismatch" + assert cols.shape == ( + 100, + 100, + ), "columns shape mismatch" + + X, rows, cols = make_checkerboard( + shape=(100, 100), n_clusters=2, shuffle=True, random_state=0 + ) + assert_all_finite(X) + assert_all_finite(rows) + assert_all_finite(cols) + + X1, _, _ = make_checkerboard( + shape=(100, 100), n_clusters=2, shuffle=True, random_state=0 + ) + X2, _, _ = make_checkerboard( + shape=(100, 100), n_clusters=2, shuffle=True, random_state=0 + ) + assert_array_almost_equal(X1, X2) + + +def test_make_moons(global_random_seed): + X, y = make_moons(3, shuffle=False, random_state=global_random_seed) + for x, label in zip(X, y): + center = [0.0, 0.0] if label == 0 else [1.0, 0.5] + dist_sqr = ((x - center) ** 2).sum() + assert_almost_equal( + dist_sqr, 1.0, err_msg="Point is not on expected unit circle" + ) + + +def test_make_moons_unbalanced(): + X, y = make_moons(n_samples=(7, 5)) + assert np.sum(y == 0) == 7 and np.sum(y == 1) == 5, ( + "Number of samples in a moon is wrong" + ) + assert X.shape == (12, 2), "X shape mismatch" + assert y.shape == (12,), "y shape mismatch" + + with pytest.raises( + ValueError, + match=r"`n_samples` can be either an int or a two-element tuple.", + ): + make_moons(n_samples=(10,)) + + +def test_make_circles(): + factor = 0.3 + + for n_samples, n_outer, n_inner in [(7, 3, 4), (8, 4, 4)]: + # Testing odd and even case, because in the past make_circles always + # created an even number of samples. + X, y = make_circles(n_samples, shuffle=False, noise=None, factor=factor) + assert X.shape == (n_samples, 2), "X shape mismatch" + assert y.shape == (n_samples,), "y shape mismatch" + center = [0.0, 0.0] + for x, label in zip(X, y): + dist_sqr = ((x - center) ** 2).sum() + dist_exp = 1.0 if label == 0 else factor**2 + dist_exp = 1.0 if label == 0 else factor**2 + assert_almost_equal( + dist_sqr, dist_exp, err_msg="Point is not on expected circle" + ) + + assert X[y == 0].shape == ( + n_outer, + 2, + ), "Samples not correctly distributed across circles." + assert X[y == 1].shape == ( + n_inner, + 2, + ), "Samples not correctly distributed across circles." + + +def test_make_circles_unbalanced(): + X, y = make_circles(n_samples=(2, 8)) + + assert np.sum(y == 0) == 2, "Number of samples in inner circle is wrong" + assert np.sum(y == 1) == 8, "Number of samples in outer circle is wrong" + assert X.shape == (10, 2), "X shape mismatch" + assert y.shape == (10,), "y shape mismatch" + + with pytest.raises( + ValueError, + match="When a tuple, n_samples must have exactly two elements.", + ): + make_circles(n_samples=(10,)) diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_svmlight_format.py b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_svmlight_format.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc171a5f452bd75602143f544ca45d97cb3a888 --- /dev/null +++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/test_svmlight_format.py @@ -0,0 +1,613 @@ +import gzip +import os +import shutil +from bz2 import BZ2File +from importlib import resources +from io import BytesIO +from tempfile import NamedTemporaryFile + +import numpy as np +import pytest +import scipy.sparse as sp + +import sklearn +from sklearn.datasets import dump_svmlight_file, load_svmlight_file, load_svmlight_files +from sklearn.utils._testing import ( + assert_allclose, + assert_array_almost_equal, + assert_array_equal, + create_memmap_backed_data, +) +from sklearn.utils.fixes import CSR_CONTAINERS + +TEST_DATA_MODULE = "sklearn.datasets.tests.data" +datafile = "svmlight_classification.txt" +multifile = "svmlight_multilabel.txt" +invalidfile = "svmlight_invalid.txt" +invalidfile2 = "svmlight_invalid_order.txt" + + +def _svmlight_local_test_file_path(filename): + return resources.files(TEST_DATA_MODULE) / filename + + +def _load_svmlight_local_test_file(filename, **kwargs): + """ + Helper to load resource `filename` with `importlib.resources` + """ + data_path = _svmlight_local_test_file_path(filename) + with data_path.open("rb") as f: + return load_svmlight_file(f, **kwargs) + + +def test_load_svmlight_file(): + X, y = _load_svmlight_local_test_file(datafile) + + # test X's shape + assert X.indptr.shape[0] == 7 + assert X.shape[0] == 6 + assert X.shape[1] == 21 + assert y.shape[0] == 6 + + # test X's non-zero values + for i, j, val in ( + (0, 2, 2.5), + (0, 10, -5.2), + (0, 15, 1.5), + (1, 5, 1.0), + (1, 12, -3), + (2, 20, 27), + ): + assert X[i, j] == val + + # tests X's zero values + assert X[0, 3] == 0 + assert X[0, 5] == 0 + assert X[1, 8] == 0 + assert X[1, 16] == 0 + assert X[2, 18] == 0 + + # test can change X's values + X[0, 2] *= 2 + assert X[0, 2] == 5 + + # test y + assert_array_equal(y, [1, 2, 3, 4, 1, 2]) + + +def test_load_svmlight_file_fd(): + # test loading from file descriptor + + # GH20081: testing equality between path-based and + # fd-based load_svmlight_file + + data_path = resources.files(TEST_DATA_MODULE) / datafile + data_path = str(data_path) + X1, y1 = load_svmlight_file(data_path) + + fd = os.open(data_path, os.O_RDONLY) + try: + X2, y2 = load_svmlight_file(fd) + assert_array_almost_equal(X1.data, X2.data) + assert_array_almost_equal(y1, y2) + finally: + os.close(fd) + + +def test_load_svmlight_pathlib(): + # test loading from file descriptor + data_path = _svmlight_local_test_file_path(datafile) + X1, y1 = load_svmlight_file(str(data_path)) + X2, y2 = load_svmlight_file(data_path) + + assert_allclose(X1.data, X2.data) + assert_allclose(y1, y2) + + +def test_load_svmlight_file_multilabel(): + X, y = _load_svmlight_local_test_file(multifile, multilabel=True) + assert y == [(0, 1), (2,), (), (1, 2)] + + +def test_load_svmlight_files(): + data_path = _svmlight_local_test_file_path(datafile) + X_train, y_train, X_test, y_test = load_svmlight_files( + [str(data_path)] * 2, dtype=np.float32 + ) + assert_array_equal(X_train.toarray(), X_test.toarray()) + assert_array_almost_equal(y_train, y_test) + assert X_train.dtype == np.float32 + assert X_test.dtype == np.float32 + + X1, y1, X2, y2, X3, y3 = load_svmlight_files([str(data_path)] * 3, dtype=np.float64) + assert X1.dtype == X2.dtype + assert X2.dtype == X3.dtype + assert X3.dtype == np.float64 + + +def test_load_svmlight_file_n_features(): + X, y = _load_svmlight_local_test_file(datafile, n_features=22) + + # test X'shape + assert X.indptr.shape[0] == 7 + assert X.shape[0] == 6 + assert X.shape[1] == 22 + + # test X's non-zero values + for i, j, val in ((0, 2, 2.5), (0, 10, -5.2), (1, 5, 1.0), (1, 12, -3)): + assert X[i, j] == val + + # 21 features in file + with pytest.raises(ValueError): + _load_svmlight_local_test_file(datafile, n_features=20) + + +def test_load_compressed(): + X, y = _load_svmlight_local_test_file(datafile) + + with NamedTemporaryFile(prefix="sklearn-test", suffix=".gz") as tmp: + tmp.close() # necessary under windows + with _svmlight_local_test_file_path(datafile).open("rb") as f: + with gzip.open(tmp.name, "wb") as fh_out: + shutil.copyfileobj(f, fh_out) + Xgz, ygz = load_svmlight_file(tmp.name) + # because we "close" it manually and write to it, + # we need to remove it manually. + os.remove(tmp.name) + assert_array_almost_equal(X.toarray(), Xgz.toarray()) + assert_array_almost_equal(y, ygz) + + with NamedTemporaryFile(prefix="sklearn-test", suffix=".bz2") as tmp: + tmp.close() # necessary under windows + with _svmlight_local_test_file_path(datafile).open("rb") as f: + with BZ2File(tmp.name, "wb") as fh_out: + shutil.copyfileobj(f, fh_out) + Xbz, ybz = load_svmlight_file(tmp.name) + # because we "close" it manually and write to it, + # we need to remove it manually. + os.remove(tmp.name) + assert_array_almost_equal(X.toarray(), Xbz.toarray()) + assert_array_almost_equal(y, ybz) + + +def test_load_invalid_file(): + with pytest.raises(ValueError): + _load_svmlight_local_test_file(invalidfile) + + +def test_load_invalid_order_file(): + with pytest.raises(ValueError): + _load_svmlight_local_test_file(invalidfile2) + + +def test_load_zero_based(): + f = BytesIO(b"-1 4:1.\n1 0:1\n") + with pytest.raises(ValueError): + load_svmlight_file(f, zero_based=False) + + +def test_load_zero_based_auto(): + data1 = b"-1 1:1 2:2 3:3\n" + data2 = b"-1 0:0 1:1\n" + + f1 = BytesIO(data1) + X, y = load_svmlight_file(f1, zero_based="auto") + assert X.shape == (1, 3) + + f1 = BytesIO(data1) + f2 = BytesIO(data2) + X1, y1, X2, y2 = load_svmlight_files([f1, f2], zero_based="auto") + assert X1.shape == (1, 4) + assert X2.shape == (1, 4) + + +def test_load_with_qid(): + # load svmfile with qid attribute + data = b""" + 3 qid:1 1:0.53 2:0.12 + 2 qid:1 1:0.13 2:0.1 + 7 qid:2 1:0.87 2:0.12""" + X, y = load_svmlight_file(BytesIO(data), query_id=False) + assert_array_equal(y, [3, 2, 7]) + assert_array_equal(X.toarray(), [[0.53, 0.12], [0.13, 0.1], [0.87, 0.12]]) + res1 = load_svmlight_files([BytesIO(data)], query_id=True) + res2 = load_svmlight_file(BytesIO(data), query_id=True) + for X, y, qid in (res1, res2): + assert_array_equal(y, [3, 2, 7]) + assert_array_equal(qid, [1, 1, 2]) + assert_array_equal(X.toarray(), [[0.53, 0.12], [0.13, 0.1], [0.87, 0.12]]) + + +@pytest.mark.skip( + "testing the overflow of 32 bit sparse indexing requires a large amount of memory" +) +def test_load_large_qid(): + """ + load large libsvm / svmlight file with qid attribute. Tests 64-bit query ID + """ + data = b"\n".join( + ( + "3 qid:{0} 1:0.53 2:0.12\n2 qid:{0} 1:0.13 2:0.1".format(i).encode() + for i in range(1, 40 * 1000 * 1000) + ) + ) + X, y, qid = load_svmlight_file(BytesIO(data), query_id=True) + assert_array_equal(y[-4:], [3, 2, 3, 2]) + assert_array_equal(np.unique(qid), np.arange(1, 40 * 1000 * 1000)) + + +def test_load_invalid_file2(): + with pytest.raises(ValueError): + data_path = _svmlight_local_test_file_path(datafile) + invalid_path = _svmlight_local_test_file_path(invalidfile) + load_svmlight_files([str(data_path), str(invalid_path), str(data_path)]) + + +def test_not_a_filename(): + # in python 3 integers are valid file opening arguments (taken as unix + # file descriptors) + with pytest.raises(TypeError): + load_svmlight_file(0.42) + + +def test_invalid_filename(): + with pytest.raises(OSError): + load_svmlight_file("trou pic nic douille") + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dump(csr_container): + X_sparse, y_dense = _load_svmlight_local_test_file(datafile) + X_dense = X_sparse.toarray() + y_sparse = csr_container(np.atleast_2d(y_dense)) + + # slicing a csr_matrix can unsort its .indices, so test that we sort + # those correctly + X_sliced = X_sparse[np.arange(X_sparse.shape[0])] + y_sliced = y_sparse[np.arange(y_sparse.shape[0])] + + for X in (X_sparse, X_dense, X_sliced): + for y in (y_sparse, y_dense, y_sliced): + for zero_based in (True, False): + for dtype in [np.float32, np.float64, np.int32, np.int64]: + f = BytesIO() + # we need to pass a comment to get the version info in; + # LibSVM doesn't grok comments so they're not put in by + # default anymore. + + if sp.issparse(y) and y.shape[0] == 1: + # make sure y's shape is: (n_samples, n_labels) + # when it is sparse + y = y.T + + # Note: with dtype=np.int32 we are performing unsafe casts, + # where X.astype(dtype) overflows. The result is + # then platform dependent and X_dense.astype(dtype) may be + # different from X_sparse.astype(dtype).asarray(). + X_input = X.astype(dtype) + + dump_svmlight_file( + X_input, y, f, comment="test", zero_based=zero_based + ) + f.seek(0) + + comment = f.readline() + comment = str(comment, "utf-8") + + assert "scikit-learn %s" % sklearn.__version__ in comment + + comment = f.readline() + comment = str(comment, "utf-8") + + assert ["one", "zero"][zero_based] + "-based" in comment + + X2, y2 = load_svmlight_file(f, dtype=dtype, zero_based=zero_based) + assert X2.dtype == dtype + assert_array_equal(X2.sorted_indices().indices, X2.indices) + + X2_dense = X2.toarray() + if sp.issparse(X_input): + X_input_dense = X_input.toarray() + else: + X_input_dense = X_input + + if dtype == np.float32: + # allow a rounding error at the last decimal place + assert_array_almost_equal(X_input_dense, X2_dense, 4) + assert_array_almost_equal( + y_dense.astype(dtype, copy=False), y2, 4 + ) + else: + # allow a rounding error at the last decimal place + assert_array_almost_equal(X_input_dense, X2_dense, 15) + assert_array_almost_equal( + y_dense.astype(dtype, copy=False), y2, 15 + ) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dump_multilabel(csr_container): + X = [[1, 0, 3, 0, 5], [0, 0, 0, 0, 0], [0, 5, 0, 1, 0]] + y_dense = [[0, 1, 0], [1, 0, 1], [1, 1, 0]] + y_sparse = csr_container(y_dense) + for y in [y_dense, y_sparse]: + f = BytesIO() + dump_svmlight_file(X, y, f, multilabel=True) + f.seek(0) + # make sure it dumps multilabel correctly + assert f.readline() == b"1 0:1 2:3 4:5\n" + assert f.readline() == b"0,2 \n" + assert f.readline() == b"0,1 1:5 3:1\n" + + +def test_dump_concise(): + one = 1 + two = 2.1 + three = 3.01 + exact = 1.000000000000001 + # loses the last decimal place + almost = 1.0000000000000001 + X = [ + [one, two, three, exact, almost], + [1e9, 2e18, 3e27, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + ] + y = [one, two, three, exact, almost] + f = BytesIO() + dump_svmlight_file(X, y, f) + f.seek(0) + # make sure it's using the most concise format possible + assert f.readline() == b"1 0:1 1:2.1 2:3.01 3:1.000000000000001 4:1\n" + assert f.readline() == b"2.1 0:1000000000 1:2e+18 2:3e+27\n" + assert f.readline() == b"3.01 \n" + assert f.readline() == b"1.000000000000001 \n" + assert f.readline() == b"1 \n" + f.seek(0) + # make sure it's correct too :) + X2, y2 = load_svmlight_file(f) + assert_array_almost_equal(X, X2.toarray()) + assert_array_almost_equal(y, y2) + + +def test_dump_comment(): + X, y = _load_svmlight_local_test_file(datafile) + X = X.toarray() + + f = BytesIO() + ascii_comment = "This is a comment\nspanning multiple lines." + dump_svmlight_file(X, y, f, comment=ascii_comment, zero_based=False) + f.seek(0) + + X2, y2 = load_svmlight_file(f, zero_based=False) + assert_array_almost_equal(X, X2.toarray()) + assert_array_almost_equal(y, y2) + + # XXX we have to update this to support Python 3.x + utf8_comment = b"It is true that\n\xc2\xbd\xc2\xb2 = \xc2\xbc" + f = BytesIO() + with pytest.raises(UnicodeDecodeError): + dump_svmlight_file(X, y, f, comment=utf8_comment) + + unicode_comment = utf8_comment.decode("utf-8") + f = BytesIO() + dump_svmlight_file(X, y, f, comment=unicode_comment, zero_based=False) + f.seek(0) + + X2, y2 = load_svmlight_file(f, zero_based=False) + assert_array_almost_equal(X, X2.toarray()) + assert_array_almost_equal(y, y2) + + f = BytesIO() + with pytest.raises(ValueError): + dump_svmlight_file(X, y, f, comment="I've got a \0.") + + +def test_dump_invalid(): + X, y = _load_svmlight_local_test_file(datafile) + + f = BytesIO() + y2d = [y] + with pytest.raises(ValueError): + dump_svmlight_file(X, y2d, f) + + f = BytesIO() + with pytest.raises(ValueError): + dump_svmlight_file(X, y[:-1], f) + + +def test_dump_query_id(): + # test dumping a file with query_id + X, y = _load_svmlight_local_test_file(datafile) + X = X.toarray() + query_id = np.arange(X.shape[0]) // 2 + f = BytesIO() + dump_svmlight_file(X, y, f, query_id=query_id, zero_based=True) + + f.seek(0) + X1, y1, query_id1 = load_svmlight_file(f, query_id=True, zero_based=True) + assert_array_almost_equal(X, X1.toarray()) + assert_array_almost_equal(y, y1) + assert_array_almost_equal(query_id, query_id1) + + +def test_load_with_long_qid(): + # load svmfile with longint qid attribute + data = b""" + 1 qid:0 0:1 1:2 2:3 + 0 qid:72048431380967004 0:1440446648 1:72048431380967004 2:236784985 + 0 qid:-9223372036854775807 0:1440446648 1:72048431380967004 2:236784985 + 3 qid:9223372036854775807 0:1440446648 1:72048431380967004 2:236784985""" + X, y, qid = load_svmlight_file(BytesIO(data), query_id=True) + + true_X = [ + [1, 2, 3], + [1440446648, 72048431380967004, 236784985], + [1440446648, 72048431380967004, 236784985], + [1440446648, 72048431380967004, 236784985], + ] + + true_y = [1, 0, 0, 3] + trueQID = [0, 72048431380967004, -9223372036854775807, 9223372036854775807] + assert_array_equal(y, true_y) + assert_array_equal(X.toarray(), true_X) + assert_array_equal(qid, trueQID) + + f = BytesIO() + dump_svmlight_file(X, y, f, query_id=qid, zero_based=True) + f.seek(0) + X, y, qid = load_svmlight_file(f, query_id=True, zero_based=True) + assert_array_equal(y, true_y) + assert_array_equal(X.toarray(), true_X) + assert_array_equal(qid, trueQID) + + f.seek(0) + X, y = load_svmlight_file(f, query_id=False, zero_based=True) + assert_array_equal(y, true_y) + assert_array_equal(X.toarray(), true_X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_load_zeros(csr_container): + f = BytesIO() + true_X = csr_container(np.zeros(shape=(3, 4))) + true_y = np.array([0, 1, 0]) + dump_svmlight_file(true_X, true_y, f) + + for zero_based in ["auto", True, False]: + f.seek(0) + X, y = load_svmlight_file(f, n_features=4, zero_based=zero_based) + assert_array_almost_equal(y, true_y) + assert_array_almost_equal(X.toarray(), true_X.toarray()) + + +@pytest.mark.parametrize("sparsity", [0, 0.1, 0.5, 0.99, 1]) +@pytest.mark.parametrize("n_samples", [13, 101]) +@pytest.mark.parametrize("n_features", [2, 7, 41]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_load_with_offsets(sparsity, n_samples, n_features, csr_container): + rng = np.random.RandomState(0) + X = rng.uniform(low=0.0, high=1.0, size=(n_samples, n_features)) + if sparsity: + X[X < sparsity] = 0.0 + X = csr_container(X) + y = rng.randint(low=0, high=2, size=n_samples) + + f = BytesIO() + dump_svmlight_file(X, y, f) + f.seek(0) + + size = len(f.getvalue()) + + # put some marks that are likely to happen anywhere in a row + mark_0 = 0 + mark_1 = size // 3 + length_0 = mark_1 - mark_0 + mark_2 = 4 * size // 5 + length_1 = mark_2 - mark_1 + + # load the original sparse matrix into 3 independent CSR matrices + X_0, y_0 = load_svmlight_file( + f, n_features=n_features, offset=mark_0, length=length_0 + ) + X_1, y_1 = load_svmlight_file( + f, n_features=n_features, offset=mark_1, length=length_1 + ) + X_2, y_2 = load_svmlight_file(f, n_features=n_features, offset=mark_2) + + y_concat = np.concatenate([y_0, y_1, y_2]) + X_concat = sp.vstack([X_0, X_1, X_2]) + assert_array_almost_equal(y, y_concat) + assert_array_almost_equal(X.toarray(), X_concat.toarray()) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_load_offset_exhaustive_splits(csr_container): + rng = np.random.RandomState(0) + X = np.array( + [ + [0, 0, 0, 0, 0, 0], + [1, 2, 3, 4, 0, 6], + [1, 2, 3, 4, 0, 6], + [0, 0, 0, 0, 0, 0], + [1, 0, 3, 0, 0, 0], + [0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0], + ] + ) + X = csr_container(X) + n_samples, n_features = X.shape + y = rng.randint(low=0, high=2, size=n_samples) + query_id = np.arange(n_samples) // 2 + + f = BytesIO() + dump_svmlight_file(X, y, f, query_id=query_id) + f.seek(0) + + size = len(f.getvalue()) + + # load the same data in 2 parts with all the possible byte offsets to + # locate the split so has to test for particular boundary cases + for mark in range(size): + f.seek(0) + X_0, y_0, q_0 = load_svmlight_file( + f, n_features=n_features, query_id=True, offset=0, length=mark + ) + X_1, y_1, q_1 = load_svmlight_file( + f, n_features=n_features, query_id=True, offset=mark, length=-1 + ) + q_concat = np.concatenate([q_0, q_1]) + y_concat = np.concatenate([y_0, y_1]) + X_concat = sp.vstack([X_0, X_1]) + assert_array_almost_equal(y, y_concat) + assert_array_equal(query_id, q_concat) + assert_array_almost_equal(X.toarray(), X_concat.toarray()) + + +def test_load_with_offsets_error(): + with pytest.raises(ValueError, match="n_features is required"): + _load_svmlight_local_test_file(datafile, offset=3, length=3) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_multilabel_y_explicit_zeros(tmp_path, csr_container): + """ + Ensure that if y contains explicit zeros (i.e. elements of y.data equal to + 0) then those explicit zeros are not encoded. + """ + save_path = str(tmp_path / "svm_explicit_zero") + rng = np.random.RandomState(42) + X = rng.randn(3, 5).astype(np.float64) + indptr = np.array([0, 2, 3, 6]) + indices = np.array([0, 2, 2, 0, 1, 2]) + # The first and last element are explicit zeros. + data = np.array([0, 1, 1, 1, 1, 0]) + y = csr_container((data, indices, indptr), shape=(3, 3)) + # y as a dense array would look like + # [[0, 0, 1], + # [0, 0, 1], + # [1, 1, 0]] + + dump_svmlight_file(X, y, save_path, multilabel=True) + + _, y_load = load_svmlight_file(save_path, multilabel=True) + y_true = [(2.0,), (2.0,), (0.0, 1.0)] + assert y_load == y_true + + +def test_dump_read_only(tmp_path): + """Ensure that there is no ValueError when dumping a read-only `X`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/28026 + """ + rng = np.random.RandomState(42) + X = rng.randn(5, 2) + y = rng.randn(5) + + # Convert to memmap-backed which are read-only + X, y = create_memmap_backed_data([X, y]) + + save_path = str(tmp_path / "svm_read_only") + dump_svmlight_file(X, y, save_path)